simplesync/src/python_module.cpp
2024-01-15 18:19:56 +01:00

86 lines
3.5 KiB
C++

#include <chrono>
#include <functional>
#include <pybind11/cast.h>
#include <pybind11/chrono.h>
#include <pybind11/functional.h>
#include <pybind11/pybind11.h>
#include <pybind11/pytypes.h>
#include "simplesync.hpp"
namespace py = pybind11;
typedef simplesync::SimpleSync<std::chrono::time_point<std::chrono::steady_clock>,
std::chrono::nanoseconds, 1024, true>
SimpleS;
PYBIND11_MODULE(pysimplesync, m) {
py::class_<SimpleS>(m, "SimpleSync")
.def(py::init([](const std::function<void(py::bytes)> &write) {
return std::unique_ptr<SimpleS>(new SimpleS(
[write](uint8_t *buf, unsigned int buf_size) {
std::string sbuf;
sbuf.assign((char *)buf, buf_size);
write(py::bytes(sbuf));
// py::print(py::bytes((char *)buf, buf_size));
return 0;
},
[]() { return (std::chrono::steady_clock::now()); }));
}))
.def("request_all_interfaces", &SimpleS::request_all_interfaces)
.def(
"__getitem__",
[](SimpleS &s, const std::string &key) -> py::object {
auto ni = s.get_number(key.c_str());
if (ni) return py::int_(*ni);
auto si = s.get_string(key.c_str());
if (si) return py::str(*si);
throw pybind11::key_error();
},
py::is_operator())
.def(
"__getitem__",
[](SimpleS &s, unsigned int i) -> py::tuple {
if (i < s.interfaces.size()) {
auto &interface = s.interfaces[i];
if (!interface) throw pybind11::index_error();
switch (interface->type) {
case 0x01:
return py::make_tuple(py::str(interface->key),
py::int_(*s.get_number(interface->key.c_str())));
case 0x02:
return py::make_tuple(py::str(interface->key),
py::str(*s.get_string(interface->key.c_str())));
}
}
throw pybind11::index_error();
},
py::is_operator())
.def(
"__setitem__",
[](SimpleS &s, const std::string &key, py::object value) {
if (py::isinstance<py::int_>(value)) {
auto ni = s.get_or_create_interface(0x01, key.c_str());
if (ni) {
*(int *)ni->data = value.cast<int>();
ni->send_requested = true;
return;
}
} else if (py::isinstance<py::str>(value)) {
auto ni = s.get_or_create_interface(0x02, key.c_str());
if (ni) {
*(std::string *)ni->data = value.cast<std::string>();
ni->send_requested = true;
return;
}
} else
throw pybind11::type_error();
throw pybind11::key_error();
},
py::is_operator())
.def("update", &SimpleS::update)
.def("handle_stream", [](SimpleS &s, const std::string &buf_new) {
/* handle_stream(b'\x06\x01\x74\x65\x73\x74\x04\x6d\x21\x97\x00') */
s.handle_stream((const uint8_t *)buf_new.data(), buf_new.length());
});
}