Skip to content

Commit

Permalink
Merge pull request #46 from robotpy/before-after-cb
Browse files Browse the repository at this point in the history
Add wrapper for HALSIM_RegisterSimPeriodic{Before,After}Callback
  • Loading branch information
virtuald authored Dec 20, 2023
2 parents 61d4676 + fbf8482 commit f9df8ef
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 2 deletions.
32 changes: 30 additions & 2 deletions subprojects/robotpy-hal/gen/simulation/MockHooks.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
---

extra_includes:
- sim_cb.h
- pybind11/functional.h

strip_prefixes:
- HALSIM_

Expand All @@ -23,11 +27,35 @@ functions:
ignore: true

HALSIM_RegisterSimPeriodicBeforeCallback:
ignore: true
param_override:
param:
ignore: true
cpp_code: |
[](std::function<void(void)> fn) -> std::unique_ptr<SimCB> {
auto cb = std::make_unique<SimCB>(fn, HALSIM_CancelSimPeriodicBeforeCallback);
auto uid = HALSIM_RegisterSimPeriodicBeforeCallback([](void *param) {
((SimCB*)param)->m_fn();
}, cb.get());
cb->SetUID(uid);
return std::move(cb);
}
HALSIM_CancelSimPeriodicBeforeCallback:
ignore: true

HALSIM_RegisterSimPeriodicAfterCallback:
ignore: true
param_override:
param:
ignore: true
cpp_code: |
[](std::function<void(void)> fn) -> std::unique_ptr<SimCB> {
auto cb = std::make_unique<SimCB>(fn, HALSIM_CancelSimPeriodicAfterCallback);
auto uid = HALSIM_RegisterSimPeriodicAfterCallback([](void *param) {
((SimCB*)param)->m_fn();
}, cb.get());
cb->SetUID(uid);
return std::move(cb);
}
HALSIM_CancelSimPeriodicAfterCallback:
ignore: true

HALSIM_CancelAllSimPeriodicCallbacks:
8 changes: 8 additions & 0 deletions subprojects/robotpy-hal/hal/simulation/main.cpp
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@

#include <rpygen_wrapper.hpp>
#include <pybind11/functional.h>

#include "sim_cb.h"

void HALSIM_ResetGlobalHandles();

RPYBUILD_PYBIND11_MODULE(m) {

py::class_<SimCB> cls_SimCB(m, "SimCB");
cls_SimCB.doc() = "Simulation callback handle";
cls_SimCB.def("cancel", &SimCB::Cancel, py::doc("Cancel the callback"));

initWrapper(m);

m.def(
Expand Down
33 changes: 33 additions & 0 deletions subprojects/robotpy-hal/hal/simulation/sim_cb.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@

#pragma once

class SimCB {
public:

SimCB(std::function<void(void)> fn, std::function<void(int32_t)> cancel) :
m_fn(fn),
m_cancel(cancel)
{}

void SetUID(int32_t uid) {
m_uid = uid;
}

~SimCB() {
Cancel();
}

void Cancel() {
if (m_valid) {
m_cancel(m_uid);
m_valid = false;
}
}

std::function<void(void)> m_fn;

private:
bool m_valid = true;
int32_t m_uid;
std::function<void(int32_t)> m_cancel;
};

0 comments on commit f9df8ef

Please sign in to comment.