forked from msis/python-moos
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpyMOOS.cpp
More file actions
589 lines (481 loc) · 23.7 KB
/
pyMOOS.cpp
File metadata and controls
589 lines (481 loc) · 23.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
#if defined(_WIN32)
#define NOMINMAX
#endif
#include <exception>
#include "MOOS/libMOOS/Comms/MOOSMsg.h"
#include "MOOS/libMOOS/Comms/MOOSCommClient.h"
#include "MOOS/libMOOS/Comms/MOOSAsyncCommClient.h"
#include <pybind11/pybind11.h>
#include <pybind11/stl_bind.h>
#include <pybind11/stl.h>
typedef std::vector<CMOOSMsg> MsgVector;
PYBIND11_MAKE_OPAQUE(MsgVector);
typedef std::vector<MOOS::ClientCommsStatus> CommsStatusVector;
PYBIND11_MAKE_OPAQUE(CommsStatusVector);
namespace py = pybind11;
class pyMOOSException : public std::exception {
public:
explicit pyMOOSException(const char * m) : message{m} {}
virtual const char * what() const noexcept override {return message.c_str();}
private:
std::string message = "";
};
namespace MOOS {
/** this is a class which wraps MOOS::MOOSAsyncCommClient to provide
* and interface more suitable for python wrapping
*/
class AsyncCommsWrapper : public MOOS::MOOSAsyncCommClient {
private:
typedef MOOSAsyncCommClient BASE;
public:
~AsyncCommsWrapper(){
Close(true);
}
bool Run(const std::string & sServer, int Port, const std::string & sMyName) {
return BASE::Run(sServer, Port, sMyName, 0);//Comms Tick not used in Async version
}
//we can support vectors of objects by not lists so
//here we have a funtion which copies a list to vector
MsgVector FetchMailAsVector() {
MsgVector v;
MOOSMSG_LIST M;
if (Fetch(M)) {
std::copy(M.begin(), M.end(), std::back_inserter(v));
}
return v;
}
/* python strings can be binary lets make this specific*/
bool NotifyBinary(const std::string& sKey, const std::string & sData,
double dfTime) {
CMOOSMsg M(MOOS_NOTIFY, sKey, sData.size(), (void *) sData.data(),
dfTime);
return BASE::Post(M);
}
/* do a MOOSDB server request */
bool ServerRequest(const std::string& sKey, double dfTime) {
CMOOSMsg M(MOOS_SERVER_REQUEST, sKey, dfTime);
M.m_sOriginatingCommunity = GetCommunityName();
return BASE::Post(M);
}
static bool on_connect_delegate(void * pParam) {
MOOS::AsyncCommsWrapper * pMe =
static_cast<MOOS::AsyncCommsWrapper*> (pParam);
return pMe->on_connect();
}
bool SetOnConnectCallback(py::object func) {
BASE::SetOnConnectCallBack(on_connect_delegate, this);
on_connect_object_ = func;
return true;
}
static bool on_disconnect_delegate(void * pParam) {
MOOS::AsyncCommsWrapper * pMe =
static_cast<MOOS::AsyncCommsWrapper*> (pParam);
return pMe->on_disconnect();
}
bool SetOnDisconnectCallback(py::object func) {
BASE::SetOnDisconnectCallBack(on_disconnect_delegate, this);
on_disconnect_object_ = func;
return true;
}
bool Close(bool nice){
bool bResult = false;
Py_BEGIN_ALLOW_THREADS
// PyGILState_STATE gstate = PyGILState_Ensure();
closing_ = true;
bResult = BASE::Close(true);
// PyGILState_Release(gstate);
Py_END_ALLOW_THREADS
return bResult;
}
bool on_connect() {
bool bResult = false;
PyGILState_STATE gstate = PyGILState_Ensure();
try {
py::object result = on_connect_object_();
bResult = py::bool_(result);
} catch (const py::error_already_set& e) {
PyGILState_Release(gstate);
throw pyMOOSException(
"OnConnect:: caught an exception thrown in python callback");
}
PyGILState_Release(gstate);
return bResult;
}
bool on_disconnect() {
bool bResult = false;
PyGILState_STATE gstate = PyGILState_Ensure();
try {
py::object result = on_disconnect_object_();
bResult = py::bool_(result);
} catch (const py::error_already_set& e) {
PyGILState_Release(gstate);
throw pyMOOSException(
"OnDisconnect:: caught an exception thrown in python callback");
}
PyGILState_Release(gstate);
return bResult;
}
bool SetOnMailCallback(py::object func) {
BASE::SetOnMailCallBack(on_mail_delegate, this);
on_mail_object_ = func;
return true;
}
static bool on_mail_delegate(void * pParam) {
MOOS::AsyncCommsWrapper * pMe =
static_cast<MOOS::AsyncCommsWrapper*> (pParam);
return pMe->on_mail();
}
bool on_mail() {
bool bResult = false;
PyGILState_STATE gstate = PyGILState_Ensure();
try {
if(!closing_){
py::object result = on_mail_object_();
bResult = py::bool_(result);
}
} catch (const py::error_already_set& e) {
PyGILState_Release(gstate);
throw pyMOOSException(
"OnMail:: caught an exception thrown in python callback");
}
PyGILState_Release(gstate);
return bResult;
}
static bool active_queue_delegate(CMOOSMsg & M, void* pParam) {
MeAndQueue * maq = static_cast<MeAndQueue*> (pParam);
return maq->me_->OnQueue(M, maq->queue_name_);
}
bool OnQueue(CMOOSMsg & M, const std::string & sQueueName) {
std::map<std::string, MeAndQueue*>::iterator q;
{
MOOS::ScopedLock L(queue_api_lock_);
q = active_queue_details_.find(sQueueName);
if (q == active_queue_details_.end())
return false;
}
bool bResult = false;
PyGILState_STATE gstate = PyGILState_Ensure();
try {
py::object result = q->second->func_(M);
bResult = py::bool_(result);
} catch (const py::error_already_set& e) {
PyGILState_Release(gstate);
throw pyMOOSException(
"ActiveQueue:: caught an exception thrown in python callback");
}
PyGILState_Release(gstate);
return bResult;
}
virtual bool AddActiveQueue(const std::string & sQueueName, py::object func) {
MOOS::ScopedLock L(queue_api_lock_);
MeAndQueue* maq = new MeAndQueue;
maq->me_ = this;
maq->queue_name_ = sQueueName;
maq->func_ = func;
std::cerr << "adding active queue OK\n";
active_queue_details_[sQueueName] = maq;
return BASE::AddActiveQueue(sQueueName, active_queue_delegate, maq);
}
private:
/** this is a structure which is used to dispatch
* active queue callbacks
*/
struct MeAndQueue {
AsyncCommsWrapper* me_;
std::string queue_name_;
py::object func_;
};
std::map<std::string, MeAndQueue*> active_queue_details_;
CMOOSLock queue_api_lock_;
/** callback functions (stored) */
py::object on_connect_object_;
py::object on_disconnect_object_;
py::object on_mail_object_;
/** close connection flag */
bool closing_;
};
}
;//namesapce
PYBIND11_MODULE(pymoos, m) {
m.doc() = "python wrapper for MOOS";
PyEval_InitThreads();
/*********************************************************************
MOOSMsg e class
*********************************************************************/
py::class_<CMOOSMsg>(m, "moos_msg")
.def("time", &CMOOSMsg::GetTime, "Return time stamp of message.")
.def("trace",&CMOOSMsg::Trace, "Print a summary of the message.")
.def("name", &CMOOSMsg::GetKey, "Return the name of the message.")
.def("key", &CMOOSMsg::GetKey, "Return the name of the message.")
.def("is_name", &CMOOSMsg::IsName, "Returns True if name is correct"
, py::arg("name"))
.def("source", &CMOOSMsg::GetSource, "Return the name of the"
" process (as registered with the DB) who posted the"
" notification.")
.def("source_aux", &CMOOSMsg::GetSourceAux, "Return the name of the"
" process (as registered with the DB) who posted the"
" notification auxiliary field.")
.def("community", &CMOOSMsg::GetCommunity, "Return the name of the "
"MOOS community in which the orginator lives")
.def("is_double", &CMOOSMsg::IsDouble, "Check if data is double.")
.def("double", &CMOOSMsg::GetDouble, "Return double value of"
" message.")
.def("double_aux",&CMOOSMsg::GetDoubleAux, "Return second double.")
.def("is_string", &CMOOSMsg::IsString, "Check if data type is "
"string.")
.def("string", &CMOOSMsg::GetString, "Return string value of "
"message.")
.def("is_binary", &CMOOSMsg::IsBinary, "Check if data type is "
"binary.")
.def("binary_data", [](CMOOSMsg& msg) {return py::bytes(msg.GetString());},
"Return string value (as a bytes object) of the message.")
.def("binary_data_size",&CMOOSMsg::GetBinaryDataSize, "Return size"
" of binary message (0 if not binary type)/")
.def("mark_as_binary",&CMOOSMsg::MarkAsBinary, "Mark string payload"
" as binary.");
/*********************************************************************
vector of messages
*********************************************************************/
py::bind_vector<MsgVector>(m, "moos_msg_list");
/*********************************************************************
communications status class
*********************************************************************/
py::class_<MOOS::ClientCommsStatus>(m,"moos_comms_status")
.def("appraise",&MOOS::ClientCommsStatus::Appraise)
.def("print",&MOOS::ClientCommsStatus::Write);
/*********************************************************************
vector of communications status classes
*********************************************************************/
py::bind_vector<CommsStatusVector>(m, "moos_comms_status_list");
/*********************************************************************
comms base class
*********************************************************************/
py::class_<CMOOSCommObject>(m,"base_comms_object");
/*********************************************************************
synchronous comms base class
*********************************************************************/
py::class_<CMOOSCommClient, CMOOSCommObject>(m, "base_sync_comms" )
.def("register",static_cast<bool(CMOOSCommClient::*)
(const std::string&, double)> (&CMOOSCommClient::Register),
"Register for notification in changes of named variable.",
py::arg("name"), py::arg("interval") = 0)
.def("register",static_cast<bool(CMOOSCommClient::*)
(const std::string&,
const std::string&,double)> (&CMOOSCommClient::Register),
"Wild card registration",
py::arg("var_pattern"), py::arg("app_pattern"),
py::arg("interval"))
.def("is_registered_for",&CMOOSCommClient::IsRegisteredFor,
"Return True if we are registered for name variable")
.def("notify",static_cast<bool(CMOOSCommClient::*)
(const std::string&,
const std::string&, double)> (&CMOOSCommClient::Notify),
"Notify the MOOS community that something has changed.",
py::arg("name"), py::arg("value"), py::arg("time") = -1.)
.def("notify",static_cast<bool(CMOOSCommClient::*)
(const std::string&, const std::string&,
const std::string&,double)> (&CMOOSCommClient::Notify),
"Notify the MOOS community that something has changed.",
py::arg("name"), py::arg("value"), py::arg("aux_src"),
py::arg("time") = -1.)
.def("notify",static_cast<bool(CMOOSCommClient::*)
(const std::string&,
const char *, double)> (&CMOOSCommClient::Notify),
"Notify the MOOS community that something has changed.",
py::arg("name"), py::arg("value"), py::arg("time") = -1.)
.def("notify",static_cast<bool(CMOOSCommClient::*)
(const std::string&, const char *,
const std::string&, double)> (&CMOOSCommClient::Notify),
"Notify the MOOS community that something has changed.",
py::arg("name"), py::arg("value"), py::arg("aux_src"),
py::arg("time") = -1.)
.def("notify",static_cast<bool(CMOOSCommClient::*)
(const std::string&, double,
double)> (&CMOOSCommClient::Notify),
"Notify the MOOS community that something has changed.",
py::arg("name"), py::arg("value"), py::arg("time") = -1.)
.def("notify",static_cast<bool(CMOOSCommClient::*)
(const std::string&, double,
const std::string&, double)> (&CMOOSCommClient::Notify),
"Notify the MOOS community that something has changed.",
py::arg("name"), py::arg("value"), py::arg("aux_src"),
py::arg("time") = -1.)
.def("get_community_name", &CMOOSCommClient::GetCommunityName,
"Return name of community the client is attached to.")
.def("get_moos_name",&CMOOSCommClient::GetMOOSName,
"Return the name with which the client registers with the "
"MOOSDB.")
.def("close", &CMOOSCommClient::Close, "Make the client shut down.")
.def("get_published", &CMOOSCommClient::GetPublished,
"Return the list of messages names published.")
.def("get_registered",&CMOOSCommClient::GetRegistered,
"Return the list of messages registered.")
.def("get_description",&CMOOSCommClient::GetDescription,
"Describe this client in a string.")
.def("is_running", &CMOOSCommClient::IsRunning,
"Return True if client is running.")
.def("is_asynchronous",&CMOOSCommClient::IsAsynchronous,
"Return True if this clinet is Asynchronous (so can have "
"data pushed to it at any time)")
.def("is_connected",&CMOOSCommClient::IsConnected,
"Return True if this object is connected to the server.")
.def("wait_until_connected",&CMOOSCommClient::WaitUntilConnected,
"Wait for a connection. Return False if not connected "
"after n_ms ms.",
py::arg("n_ms"))
.def("get_number_of_unread_messages",
&CMOOSCommClient::GetNumberOfUnreadMessages,
"How much incoming mail is pending?")
.def("get_number_of_unsent_messages",
&CMOOSCommClient::GetNumberOfUnsentMessages,
"How much outgoing mail is pending?")
.def("get_number_bytes_sent", &CMOOSCommClient::GetNumBytesSent,
"Get total number of bytes sent.")
.def("get_number_bytes_read", &CMOOSCommClient::GetNumBytesReceived,
"Get total number of bytes received.")
.def("get_number_messages_sent", &CMOOSCommClient::GetNumMsgsSent,
"Get total number of messages sent.")
.def("get_number_message_read", &CMOOSCommClient::GetNumMsgsReceived,
"Get total number of messages received.")
.def("set_comms_control_timewarp_scale_factor",
&CMOOSCommClient::SetCommsControlTimeWarpScaleFactor,
"Set scale factor which determines how to encourage "
"messages bunching at high timewarps.",
py::arg("scale_factor"))
.def("get_comms_control_timewarp_scale_factor",
&CMOOSCommClient::GetCommsControlTimeWarpScaleFactor,
"Get scale factor which determines how to encourage "
"messages bunching at high timewarps.")
.def("do_local_time_correction",
&CMOOSCommClient::DoLocalTimeCorrection,
"Used to control whether local clock skew (used by "
"MOOSTime()) is set via the server at the other end of "
"this connection.")
.def("set_verbose_debug", &CMOOSCommClient::SetVerboseDebug,
"Used to control debug printing.")
.def("set_comms_tick", &CMOOSCommClient::SetCommsTick,
"Set the number of ms between loops of the Comms thread "
"(not relevent if Asynchronous)",
py::arg("comms_tick"))
.def("set_quiet", &CMOOSCommClient::SetQuiet,
"Used to control how verbose the connection process is.")
.def("enable_comms_status_monitoring",
&CMOOSCommClient::EnableCommsStatusMonitoring,
"Enable/disable comms status monitoring across the "
"community.",
py::arg("enable"))
.def("get_client_comms_status",&CMOOSCommClient::GetClientCommsStatus,
"Query the comms status of some other client",
py::arg("client"), py::arg("status"))
.def("get_client_comms_statuses",
&CMOOSCommClient::GetClientCommsStatuses,
"Get all client statuses",
py::arg("statuses"))
;
//
/*********************************************************************
Asynchronous comms base class
*********************************************************************/
py::class_<MOOS::MOOSAsyncCommClient,CMOOSCommClient>(m, "base_async_comms")
.def("run",&MOOS::MOOSAsyncCommClient::Run);
/*********************************************************************/
/** FINALLY HERE IS THE CLASS WE EXPECT TO BE INSTANTIATED IN PYTHON */;
// /** FINALLY HERE IS THE CLASS WE EXPECT TO BE INSTANTIATED IN PYTHON */
// /*********************************************************************/
//this is the one to use
py::class_<MOOS::AsyncCommsWrapper, MOOS::MOOSAsyncCommClient>(m, "comms")
.def(py::init<>())
.def("run", &MOOS::AsyncCommsWrapper::Run,
"Run the MOOSAsyncCommClient.",
py::arg("server"), py::arg("port"), py::arg("name"))
.def("close", &MOOS::AsyncCommsWrapper::Close,
"Make the MOOSAsyncCommClient shutdown.",
py::arg("nice"))
.def("fetch", &MOOS::AsyncCommsWrapper::FetchMailAsVector,
"Fetch incoming mail as a vector.")
.def("set_on_connect_callback",
&MOOS::AsyncCommsWrapper::SetOnConnectCallback,
"Set the user supplied on_connect callback. This callback,\n"
"when set, will be invoked when a connection to the server\n"
"is made. It is a good plan to register for notifications\n"
"of variables in this callback.",
py::arg("func"))
.def("set_on_disconnect_callback",
&MOOS::AsyncCommsWrapper::SetOnDisconnectCallback,
"Set the user supplied on_disconnect callback. This callback,\n"
"when set, will be invoked when the connection to the server\n"
"is lost. It is a good plan to register for notifications\n"
"of variables in this callback.",
py::arg("func"))
.def("set_on_mail_callback",
&MOOS::AsyncCommsWrapper::SetOnMailCallback,
"Set the user supplied on_mail callback. If you want rapid\n"
"response, use V10 active callbacks.",
py::arg("func"))
.def("notify_binary", &MOOS::AsyncCommsWrapper::NotifyBinary,
"Notify binary data. (specific to pymoos.)",
py::arg("name"), py::arg("binary_data"), py::arg("time")=-1)
.def("server_request", &MOOS::AsyncCommsWrapper::ServerRequest,
"Do a MOOSDB server request. (specific to pymoos.)",
py::arg("key"), py::arg("time")=-1)
.def("add_active_queue", &MOOS::AsyncCommsWrapper::AddActiveQueue,
"Register a custom callback for a particular message.\n"
"This will be called in it's own thread.",
py::arg("queue_name"), py::arg("func"))
.def("remove_message_route_to_active_queue",
&MOOS::AsyncCommsWrapper::RemoveMessageRouteToActiveQueue,
"Stop a message routing to active queue.",
py::arg("queue_name"), py::arg("msg_name"))
.def("remove_active_queue", &MOOS::AsyncCommsWrapper::RemoveActiveQueue,
"Remove the named active queue.",
py::arg("queue_name"))
.def("has_active_queue", &MOOS::AsyncCommsWrapper::HasActiveQueue,
"Does this named active queue exist?",
py::arg("queue_name"))
.def("print_message_to_active_queue_routing",
&MOOS::AsyncCommsWrapper::PrintMessageToActiveQueueRouting,
"Print all active queues.")
.def("add_message_route_to_active_queue",
static_cast<bool(CMOOSCommClient::*)(const std::string &,
const std::string &)>
(&MOOS::AsyncCommsWrapper::AddMessageRouteToActiveQueue),
"Make a message route to Active Queue (which will call "
"a custom callback).",
py::arg("queue_name"), py::arg("msg_name"))
;
/*********************************************************************
some MOOS Utilities
*********************************************************************/
/** here are some global help functions */
m.def("local_time", &MOOSLocalTime,
"Return time as double (time since unix in seconds). This "
"returns the time as reported by the local clock. It will *not* "
"return time at the Comms Server as time() tries to do.",
py::arg("apply_timewartping") = true);
m.def("time", &MOOSTime,
"Return time as double (time since unix in seconds). This will "
"aslo apply a skew to this time so that all processes connected "
"to a MOOSCommsServer (often in the shape of DB) will have a "
"unified time. Of course, if your process isn't using MOOSComms"
"at all, this function works just fine and returns the "
"unadulterated time as you would expect.",
py::arg("apply_timewartping") = true);
m.def("is_little_end_in", &IsLittleEndian,
"Return True if current machine is little end in.");
m.def("set_moos_timewarp", &SetMOOSTimeWarp,
"Set the rate at which time is accelerated.",
py::arg("warp"));
m.def("get_moos_timewarp", &GetMOOSTimeWarp,
"Return the current time warp factor.");
// TODO: double check that it's still needed
static py::exception<pyMOOSException> ex(m, "pyMOOSException");
py::register_exception_translator([](std::exception_ptr p) {
try {
if (p) std::rethrow_exception(p);
} catch (const pyMOOSException &e) {
// Set pyMOOSException as the active python error
// ex(e.what());
PyErr_SetString(PyExc_RuntimeError, e.what());
}
});
}