-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathpythonWrapperV2.lua
More file actions
1686 lines (1503 loc) · 58.1 KB
/
pythonWrapperV2.lua
File metadata and controls
1686 lines (1503 loc) · 58.1 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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local startTimeout = initTimeout or 10
local sim = require('sim') -- keep here, since we have several sim-functions defined/redefined here
if _DEVMODE then
sim.addLog(sim.verbosity_warnings, 'sim-1 has been loaded from PythonWrapper')
end
local simZMQ = require('simZMQ')
local simSubprocess = require('simSubprocess')
local cbor = require('simCBOR')
if _removeLazyLoaders then _removeLazyLoaders() end
sim.callScriptFunction = wrap(sim.callScriptFunction, function(origFunc)
return function(...)
local retVal = table.pack(origFunc(...))
if #retVal == 0 then
return nil -- the remote API needs always at least a nil as return value
else
return table.unpack(retVal)
end
end
end)
function sim.setThreadSwitchTiming(switchTiming)
-- Shadow the original func
-- 0=disabled, otherwise switchTiming
threadSwitchTiming = switchTiming
end
function sim.setThreadAutomaticSwitch()
-- Shadow the original function
end
sim.setStepping = wrap(sim.setStepping, function(origFunc)
-- Shadow original function:
-- When stepping is true, CoppeliaSim ALWAYS blocks while Python runs some code
-- When stepping is false, CoppeliaSim run concurently to Python, i.e. Python is "free" (until a request from Python comes)
return function(enabled)
local retVal = 0
if currentFunction == 'sim.setStepping' then
if pythonFuncs['sysCall_thread'] then
retVal = steppingLevel
if enabled then
steppingLevel = steppingLevel + 1
else
if steppingLevel > 0 then steppingLevel = steppingLevel - 1 end
end
end
else
retVal = origFunc(enabled)
end
return retVal
end
end)
sim.acquireLock = wrap(sim.acquireLock, function(origFunc)
return function()
if currentFunction == 'sim.acquireLock' then
holdCalls = holdCalls + 1
else
origFunc()
end
end
end)
sim.releaseLock = wrap(sim.releaseLock, function(origFunc)
return function()
if currentFunction == 'sim.releaseLock' then
if holdCalls > 0 then holdCalls = holdCalls - 1 end
else
origFunc()
end
end
end)
-- Special handling of sim.yield:
originalYield = sim.yield
function sim.yield()
if sim.getSimulationState() == sim.simulation_stopped then
originalYield()
else
local st = sim.getSimulationTime()
while sim.getSimulationTime() == st do
-- stays inside here until we are ready with next simulation step. This is important since
-- other clients/scripts could too be hindering the main script to run in sysCall_beforeMainScript
originalYield()
end
end
end
function sim.step()
-- Shadow original function:
sim.yield()
end
function sim.switchThread()
-- Shadow original function:
sim.yield()
end
function sim.protectedCalls(enable)
protectedCalls = enable
end
function yieldIfAllowed()
local retVal = false
if holdCalls == 0 and doNotInterruptCommLevel == 0 and steppingLevel == 0 then
originalYield()
retVal = true
end
return retVal
end
function tobin(data)
local d = {data = data}
setmetatable(
d, {
__tocbor = function(self)
return cbor.TYPE.BIN(self.data)
end,
}
)
return d
end
function totxt(data)
local d = {data = data}
setmetatable(
d, {
__tocbor = function(self)
return cbor.TYPE.TEXT(self.data)
end,
}
)
return d
end
function toarray(data)
local d = {data = data}
setmetatable(
d, {
__tocbor = function(self)
return cbor.TYPE.ARRAY(self.data)
end,
}
)
return d
end
function tomap(data)
local d = {data = data}
setmetatable(
d, {
__tocbor = function(self)
return cbor.TYPE.MAP(self.data)
end,
}
)
return d
end
cbornil = {
__tocbor = function(self)
return cbor.SIMPLE.null()
end,
}
function tonil()
local d = {}
setmetatable(d, cbornil)
return d
end
function sysCall_init(...)
returnTypes = {}
simZMQ.__raiseErrors(true) -- so we don't need to check retval with every call
context = simZMQ.ctx_new()
replySocket = simZMQ.socket(context, simZMQ.REP)
replyPortStr = getFreePortStr()
simZMQ.bind(replySocket, replyPortStr)
local prog = pythonBoilerplate .. pythonUserCode
prog = prog:gsub("XXXconnectionAddress1XXX", replyPortStr)
prog = prog:gsub("XXXpidXXX", tostring(sim.getLongProperty(sim.handle_app, 'pid')))
local tmp = ''
if _additionalPaths then
for i = 1, #_additionalPaths, 1 do
tmp = tmp .. 'sys.path.append("' .. _additionalPaths[i] .. '"); ' -- ';' instead of '\n'! (since that would change the size of the boilerplate code)
end
end
if additionalPaths then
for i = 1, #additionalPaths, 1 do
tmp = tmp .. 'sys.path.append("' .. additionalPaths[i] .. '"); ' -- ';' instead of '\n'! (since that would change the size of the boilerplate code)
end
end
local additionalPythonPaths = {
sim.getStringParam(sim.stringparam_application_path),
sim.getStringParam(sim.stringparam_application_path) .. '/python',
sim.getStringParam(sim.stringparam_scene_path),
sim.getStringParam(sim.stringparam_additionalpythonpath)
}
for i = 1, #additionalPythonPaths, 1 do
if additionalPythonPaths[i] ~= '' then
tmp = tmp .. 'sys.path.append("' .. additionalPythonPaths[i] .. '"); ' -- ';' instead of '\n'! (since that would change the size of the boilerplate code)
end
end
prog = prog:gsub("XXXadditionalPathsXXX", tmp)
initPython(prog)
local optionalSysCallbacks = {
'sysCall_beforeMainScript', 'sysCall_suspended', 'sysCall_beforeSimulation',
'sysCall_afterSimulation', 'sysCall_sensing', 'sysCall_suspend', 'sysCall_resume',
'sysCall_realTimeIdle', 'sysCall_beforeInstanceSwitch', 'sysCall_afterInstanceSwitch',
'sysCall_beforeSave', 'sysCall_afterSave', 'sysCall_beforeCopy', 'sysCall_afterCopy',
'sysCall_afterCreate', 'sysCall_beforeDelete', 'sysCall_afterDelete',
'sysCall_addOnScriptSuspend', 'sysCall_addOnScriptResume', 'sysCall_dyn', 'sysCall_joint',
'sysCall_contact', 'sysCall_vision', 'sysCall_trigger', 'sysCall_moduleEntry',
'sysCall_msg', 'sysCall_event',
}
if subprocess then
_pythonRunning = true
corout = coroutine.create(coroutineMain)
setAutoYield(false)
threadSwitchTiming = 0.002 -- time given to service Python scripts
threadLastSwitchTime = 0
threadBusyCnt = 0
steppingLevel = 0 -- in stepping mode switching is always explicit
protectedCallErrorDepth = 0
protectedCallDepth = 0
pythonMustHaveRaisedError = false
receiveIsNext = true
holdCalls = 0
doNotInterruptCommLevel = 0
handleRequestsUntilExecutedReceived() -- handle commands from Python prior to start, e.g. initial function calls to CoppeliaSim
-- Disable optional system callbacks that are not used on Python side (nonSimulation, init, actuation, cleanup, ext and userConfig are special):
for i = 1, #optionalSysCallbacks, 1 do
local nm = optionalSysCallbacks[i]
if pythonFuncs[nm] == nil then _G[nm] = nil end
end
if pythonFuncs['sysCall_userConfig'] then
sysCall_userConfig = _sysCall_userConfig -- special
end
if pythonFuncs["sysCall_init"] == nil and pythonFuncs["sysCall_thread"] == nil then
error("can't find sysCall_init nor sysCall_thread functions")
end
auxFunc('stts', 'pythonEmbeddedScript')
return callRemoteFunction("sysCall_init", {...})
else
-- Failed initializing Python. And since we have not generated an error, we disable most funcs (want to continue with Lua only)
for i = 1, #optionalSysCallbacks, 1 do
local nm = optionalSysCallbacks[i]
_G[nm] = nil
end
sysCall_userConfig = nil
end
end
function sysCall_cleanup(...)
if subprocess ~= nil then
inCleanup = true
if receiveIsNext then -- condition added on 22.01.2025 to fix Python's sysCall_cleanup randomly not getting called
receive()
end
callRemoteFunction("sysCall_cleanup", {...})
end
cleanupPython()
simZMQ.close(replySocket)
simZMQ.ctx_term(context)
end
function coroutineMain()
callRemoteFunction("sysCall_thread", {})
end
function sysCall_ext(funcName, ...)
local args = {...}
local lang = -1 -- undef
if funcName:sub(-4) == '@lua' then
lang = 0
funcName = funcName:sub(1, -4 - 1)
elseif funcName:sub(-7) == '@python' then
lang = 1
funcName = funcName:sub(1, -7 - 1)
end
if lang == 1 or lang == -1 then -- Python takes precedence on Lua, if lang not specified
-- Python
if subprocess then
if pythonFuncs['sysCall_ext'] then
return callRemoteFunction('sysCall_ext', {funcName, args})
else
if pythonFuncs[funcName] then
return callRemoteFunction(funcName, args, true, false)
end
end
end
end
if lang == 0 or lang == -1 then
-- Lua
local fun = _G
if string.find(funcName, "%.") then
for w in funcName:gmatch("[^%.]+") do -- handle cases like sim.func or similar too
if fun[w] then fun = fun[w] end
end
else
fun = fun[funcName]
end
if type(fun) == 'function' then
local retVals = {pcall(fun, table.unpack(args))}
local status = retVals[1]
table.remove(retVals, 1)
if status == false then
return "_*runtimeError*_" -- ..retVals
else
return table.unpack(retVals)
end
end
end
return "_*funcNotFound*_"
end
function resumeCoroutine()
if coroutine.status(corout) ~= 'dead' then
protectedCallDepth = protectedCallDepth + 1
local ok, errorMsg = coroutine.resume(corout)
protectedCallDepth = protectedCallDepth - 1
if errorMsg then
error(debug.traceback(corout, errorMsg), 2) -- this error is very certainly linked to the Python wrapper itself
end
checkPythonError()
end
end
function sysCall_nonSimulation(...)
if subprocess then
if pythonFuncs['sysCall_thread'] then resumeCoroutine() end
return callRemoteFunction("sysCall_nonSimulation", {...})
end
end
function sysCall_actuation(...)
if subprocess then
if pythonFuncs['sysCall_thread'] then resumeCoroutine() end
return callRemoteFunction("sysCall_actuation", {...})
end
end
function sysCall_beforeMainScript(...)
return callRemoteFunction("sysCall_beforeMainScript", {...})
end
function sysCall_suspended(...)
return callRemoteFunction("sysCall_suspended", {...})
end
function sysCall_sensing(...)
return callRemoteFunction("sysCall_sensing", {...})
end
function sysCall_beforeSimulation(...)
return callRemoteFunction("sysCall_beforeSimulation", {...})
end
function sysCall_afterSimulation(...)
return callRemoteFunction("sysCall_afterSimulation", {...})
end
function sysCall_suspend(...)
return callRemoteFunction("sysCall_suspend", {...})
end
function sysCall_resume(...)
return callRemoteFunction("sysCall_resume", {...})
end
function sysCall_realTimeIdle(...)
return callRemoteFunction("sysCall_realTimeIdle", {...})
end
function sysCall_beforeInstanceSwitch(...)
return callRemoteFunction("sysCall_beforeInstanceSwitch", {...})
end
function sysCall_afterInstanceSwitch(...)
return callRemoteFunction("sysCall_afterInstanceSwitch", {...})
end
function sysCall_beforeSave(...)
return callRemoteFunction("sysCall_beforeSave", {...})
end
function sysCall_afterSave(...)
return callRemoteFunction("sysCall_afterSave", {...})
end
function sysCall_beforeCopy(...)
return callRemoteFunction("sysCall_beforeCopy", {...})
end
function sysCall_afterCopy(...)
return callRemoteFunction("sysCall_afterCopy", {...})
end
function sysCall_afterCreate(...)
return callRemoteFunction("sysCall_afterCreate", {...})
end
function sysCall_beforeDelete(...)
return callRemoteFunction("sysCall_beforeDelete", {...})
end
function sysCall_afterDelete(...)
return callRemoteFunction("sysCall_afterDelete", {...})
end
function sysCall_addOnScriptSuspend(...)
return callRemoteFunction("sysCall_addOnScriptSuspend", {...})
end
function sysCall_addOnScriptResume(...)
return callRemoteFunction("sysCall_addOnScriptResume", {...})
end
if dynCallback then
-- Needs to be explicitly enabled (drastic slowdown)
function sysCall_dyn(...)
return callRemoteFunction("sysCall_dyn", {...})
end
end
function sysCall_joint(...)
return callRemoteFunction("sysCall_joint", {...})
end
if contactCallback then
-- Needs to be explicitly enabled (drastic slowdown)
function sysCall_contact(...)
return callRemoteFunction("sysCall_contact", {...})
end
end
function sysCall_vision(...)
return callRemoteFunction("sysCall_vision", {...})
end
function sysCall_trigger(...)
return callRemoteFunction("sysCall_trigger", {...})
end
function _sysCall_userConfig(...) -- special
return callRemoteFunction("sysCall_userConfig", {...})
end
function sysCall_moduleEntry(...)
return callRemoteFunction("sysCall_moduleEntry", {...})
end
function sysCall_msg(...)
return callRemoteFunction("sysCall_msg", {...})
end
if eventCallback then
-- Needs to be explicitly enabled (drastic slowdown)
function sysCall_event(...)
return callRemoteFunction("sysCall_event", {...})
end
end
function sim.testCB(a, cb, b, iterations)
iterations = iterations or 99
for i = 1, iterations, 1 do cb(a, b) end
return cb(a, b)
end
function __require__(name)
local vname = name
local pos = vname:find("-")
if pos then
vname = vname:sub(1, pos - 1)
end
_G[vname] = require(name)
parseFuncsReturnTypes(vname)
end
function setPythonFuncs(data)
pythonFuncs = data
end
function __print__(str)
print(str)
end
function pyTr() -- Dummy function called by Python trace on a regular basis if in freeMode and no interaction with CoppeliaSim since a while - Allows for callbacks to be sent
end
function __getApi__(nameSpace)
str = {}
for k, v in pairs(_G) do
if type(v) == 'table' and k:find(nameSpace, 1, true) == 1 then str[#str + 1] = k end
end
return str
end
function parseFuncsReturnTypes(nameSpace)
local funcs = sim.getApiFunc(-1, '+' .. nameSpace .. '.')
for i = 1, #funcs, 1 do
local func = funcs[i]
local inf = sim.getApiInfo(-1, func)
local p = string.find(inf, '(', 1, true)
if p then
inf = string.sub(inf, 1, p - 1)
p = string.find(inf, '=')
if p then
inf = string.sub(inf, 1, p - 1)
local t = {}
local i = 1
for token in (inf .. ","):gmatch("([^,]*),") do
p = string.find(token, ' ')
if p then
token = string.sub(token, 1, p - 1)
if token == 'string' then
t[i] = 1
elseif token == 'buffer' then
t[i] = 2
elseif token == 'map' then
t[i] = 3
else
t[i] = 0
end
else
t[i] = 0
end
i = i + 1
end
returnTypes[func] = t
else
returnTypes[func] = {}
end
end
end
end
function handleRequest(req)
local resp = {}
if req['func'] ~= nil and req['func'] ~= '' then
local reqFunc = req['func']
local func = _getField(reqFunc)
local args = req['args'] or {}
if not func then
if not protectedCalls then
pythonMustHaveRaisedError = true -- actually not just yet, we still need to send a reply tp Python
end
resp['err'] = 'No such function: ' .. reqFunc
else
if reqFunc == 'sim.setThreadAutomaticSwitch' then
-- For backward compatibility with pythonWrapperV1
func = sim.setStepping
reqFunc = 'sim.setStepping'
if #args > 0 then
if not isnumber(args[1]) then args[1] = not args[1] end
end
end
currentFunction = reqFunc
-- Handle function arguments (up to a depth of 2):
for i = 1, #args, 1 do
if type(args[i]) == 'string' then
-- depth 1
if args[i]:sub(-5) == "@func" then
local nm = args[i]:sub(1, -6)
local fff = function(...) return callRemoteFunction(nm, {...}, false, true) end
args[i] = fff
if not _S.pythonCallbacks then
_S.pythonCallbacks = {}
end
_S.pythonCallbacks[fff] = true -- so that we can identify a Python callback
end
else
if type(args[i]) == 'table' then
-- depth 2
local cnt = 0
for k, v in pairs(args[i]) do
if type(v) == 'string' and v:sub(-5) == "@func" then
local nm = v:sub(1, -6)
v = function(...) return callRemoteFunction(nm, {...}, false, true) end
if not _S.pythonCallbacks then
_S.pythonCallbacks = {}
end
_S.pythonCallbacks[v] = true -- so that we can identify a Python callback
args[i][k] = v
end
cnt = cnt + 1
if cnt >= 16 then
break -- parse no more than 16 items
end
end
end
end
end
local function errHandler(err)
local trace = debug.traceback(err)
local p = string.find(trace, "\nstack traceback:")
if p then
trace = trace:sub(1, p - 1) -- strip traceback from xpcall
end
-- Make sure the string survives the passage to Python unmodified:
trace = string.gsub(trace, "\n", "_=NL=_")
trace = string.gsub(trace, "\t", "_=TB=_")
return trace
end
protectedCallDepth = protectedCallDepth + 1
doNotInterruptCommLevel = doNotInterruptCommLevel + 1
local status, retvals = xpcall(
function()
local pret = table.pack(func(table.unpack(args, 1, req.argsL)))
local ret = {}
for i = 1, pret.n do
if pret[i] ~= nil then
ret[i] = pret[i]
else
ret[i] = tonil()
end
end
--local ret = {func(table.unpack(args, 1, req.argsL))}
-- Try to assign correct types to text/buffers and arrays/maps:
local args = returnTypes[reqFunc]
if args then
local cnt = math.min(#ret, #args)
for i = 1, cnt do
if args[i] == 1 and type(ret[i]) == 'string' then
ret[i] = totxt(ret[i])
elseif args[i] == 2 and type(ret[i]) == 'string' then
ret[i] = tobin(ret[i])
elseif type(ret[i]) == 'table' then
if (not isbuffer(ret[i])) and (getmetatable(ret[i]) ~= cbornil) then
if table.isarray(ret[i]) then
ret[i] = toarray(ret[i])
else
ret[i] = tomap(ret[i])
end
end
end
end
end
return ret
end, errHandler)
doNotInterruptCommLevel = doNotInterruptCommLevel - 1
protectedCallDepth = protectedCallDepth - 1
if status == false then
if not protectedCalls then
pythonMustHaveRaisedError = true -- actually not just yet, we still need to send a reply tp Python
end
end
resp[status and 'ret' or 'err'] = retvals
end
currentFunction = nil
elseif req['eval'] ~= nil and req['eval'] ~= '' then
local status, retvals = pcall(
function()
-- cannot prefix 'return ' here, otherwise non-trivial code breaks
-- local ret={loadstring('return '..req['eval'])()}
local ret = {loadstring(req['eval'])()}
return ret
end
)
if status == false then
if not protectedCalls then
pythonMustHaveRaisedError = true -- actually not just yet, we still need to send a reply tp Python
end
end
resp[status and 'ret' or 'err'] = retvals
end
return resp
end
function __info__(obj)
if type(obj) == 'string' then obj = _getField(obj) end
if type(obj) ~= 'table' then return obj end
local ret = {}
for k, v in pairs(obj) do
if type(v) == 'table' then
if getmetatable(v) == nil or isbuffer(v) then -- other objects are not (yet) supported
ret[k] = __info__(v)
end
elseif type(v) == 'function' then
ret[k] = {func = {}}
elseif type(v) ~= 'function' then
ret[k] = {const = v}
end
end
return ret
end
function _getField(f)
local v = _G
for w in string.gmatch(f, '[%w_]+') do
v = v[w]
if not v then return nil end
end
return v
end
function receive()
-- blocking, but can switch thread
if receiveIsNext then
while simZMQ.poll({replySocket}, {simZMQ.POLLIN}, 0) <= 0 do
if threadSwitchTiming > 0 then
if sim.getSystemTime() - threadLastSwitchTime >= threadSwitchTiming or threadBusyCnt ==
0 then
if checkPythonError() then
return -- unwind xpcalls
end
yieldIfAllowed()
-- We still want to set following if not yielded:
threadLastSwitchTime = sim.getSystemTime()
threadBusyCnt = 0 -- after a switch, if the socket is idle, we switch immediately again. Otherwise we wait max. threadSwitchTiming
end
end
end
threadBusyCnt = threadBusyCnt + 1
local rc, dat = simZMQ.recv(replySocket, 0)
receiveIsNext = false
local status, req = pcall(cbor.decode, tostring(dat))
if not status then
if #dat < 2000 then
error(req .. "\n" .. sim.transformBuffer(dat, sim.buffer_uint8, 1, 0, sim.buffer_base64))
else
error('Error trying to decode received data:\n' .. req)
end
end
-- Handle non-serializable data:
if req.args and (type(req.args) == 'string') and req.args:match('^_%*baddata%*_') then
req.args = string.gsub(req.args, '_%*baddata%*_', '')
sim.addLog(sim.verbosity_warnings, "Received non-serializable data: " .. req.args)
if req.cbor_pkg == 'cbor' then
sim.addLog(sim.verbosity_warnings, "To get better support for some additional types such as numpy, install pip package 'cbor2'.")
end
end
return req
else
error('Trying to receive data from Python where a send is expected')
end
end
function send(reply)
if not receiveIsNext then
--[[
-- Make sure the data does not contain any function. If there is, convert it to string. We do that up to a depth of 2:
for i = 1, #reply do
local ob = reply[i]
if type(ob) == 'function' then
reply[i] = tostring(ob)
print("bli")
else
if type(ob) == table and not isBuffer(ob) then
local cnt = 0
for k, v in pairs(ob) do
if type(v) == 'function' then
print("bla")
ob[k] = tostring(v)
end
cnt = cnt + 1
if cnt > 16 then
break
end
end
end
end
end
--]]
local dat = reply
local status, reply = pcall(cbor.encode, reply)
if not status then
local s2, rep2 = pcall(getAsString, dat)
if s2 then
error(reply .. "\n" .. rep2)
else
error('Error while trying to encode data to send:\n' .. reply)
end
end
simZMQ.send(replySocket, reply, 0)
receiveIsNext = true
else
error('Trying to send data to Python where a receive is expected')
end
end
function handleRequestsUntilExecutedReceived()
-- Handle requests from Python, until we get a _*executed*_ message. Func is reentrant
while true do
local req = receive() -- blocking (but can switch thread (i.e. happens only with sysCall_thread))
if req == nil then
return -- unwind xpcalls
end
-- Handle buffered callbacks:
if bufferedCallbacks and #bufferedCallbacks > 0 then
local tmp = bufferedCallbacks
bufferedCallbacks = {}
for i = 1, #tmp, 1 do
callRemoteFunction(tmp[i].func, tmp[i].args)
if checkPythonError() then
return -- unwind xpcalls
end
end
end
if req['func'] == '_*executed*_' then return req.args end
-- print(req)
local resp = handleRequest(req)
if pythonMustHaveRaisedError then
if protectedCallErrorDepth == 0 then send(resp) end
protectedCallErrorDepth = protectedCallErrorDepth - 1
else
if checkPythonError() then
return -- unwind xpcalls
end
send(resp)
end
end
end
function callRemoteFunction(callbackFunc, callbackArgs, canCallAsync, possiblyLocalFunction)
-- Func is reentrant
local retVal
if checkPythonError() then
return -- unwind xpcalls
end
if pythonFuncs and pythonFuncs[callbackFunc] or possiblyLocalFunction then
if not receiveIsNext then
-- First handle buffered, async callbacks:
if bufferedCallbacks and #bufferedCallbacks > 0 then
local tmp = bufferedCallbacks
bufferedCallbacks = {}
for i = 1, #tmp, 1 do
callRemoteFunction(tmp[i].func, tmp[i].args)
if checkPythonError() then
return -- unwind xpcalls
end
end
end
-- Tell Python to run a function:
if callbackFunc ~= 'sysCall_thread' then
doNotInterruptCommLevel = doNotInterruptCommLevel + 1
end
send({func = callbackFunc, args = callbackArgs})
-- Wait for the reply from Python
retVal = handleRequestsUntilExecutedReceived()
if callbackFunc ~= 'sysCall_thread' then
doNotInterruptCommLevel = doNotInterruptCommLevel - 1
end
else
if canCallAsync then
if bufferedCallbacks == nil then bufferedCallbacks = {} end
bufferedCallbacks[#bufferedCallbacks + 1] = {
func = callbackFunc,
args = callbackArgs,
}
end
end
end
return retVal
end
function checkPythonError()
if subprocess then
if simSubprocess.isRunning(subprocess) then
while pythonErrorMsg == nil do
local r, rep = simZMQ.__noError.recv(pySocket, simZMQ.DONTWAIT)
if r >= 0 then
local rep, o, t = cbor.decode(tostring(rep))
if rep.err then
-- print(getAsString(rep.err))
local msg = getCleanErrorMsg(rep.err)
msg = '__[[__' .. msg .. '__]]__'
-- print(getAsString(msg))
pythonErrorMsg = msg
end
else
if not pythonMustHaveRaisedError then -- pythonMustHaveRaisedError: the error happened here and was transmitted to Python to raise an error there
break
end
end
end
if pythonErrorMsg then
if protectedCallDepth == 0 then
local errMsg = pythonErrorMsg
if not inCleanup then
--[[
simZMQ.close(replySocket)
replySocket = simZMQ.socket(context, simZMQ.REP)
-- simZMQ.bind(replySocket, replyPortStr) -- takes some time for the address to be free again
while true do
local bindResult = simZMQ.__noError.bind(replySocket, replyPortStr)
if bindResult == 0 then
break
elseif bindResult == -1 and simZMQ.errnum() == simZMQ.EADDRINUSE then
-- address already in use -> retry
else
simZMQ.__raise()
end
end
--]]
pythonErrorMsg = nil
protectedCallDepth = 0
protectedCallErrorDepth = 0
pythonMustHaveRaisedError = false
steppingLevel = 0
holdCalls = 0
doNotInterruptCommLevel = 0
receiveIsNext = true
simZMQ.send(
pySocket, cbor.encode(
{cmd = 'callFunc', func = '__restartClientScript__', args = {}}
), 0
)
handleRequestsUntilExecutedReceived() -- handle commands from Python prior to start, e.g. initial function calls to CoppeliaSim
end
error(errMsg)
end
end
end
end
return pythonErrorMsg
end
function getFreePortStr()
local pythonWrapperPortStart = 23259
while true do
sim.systemSemaphore('pythonWrapper', true)
local dat = sim.readCustomBufferData(sim.handle_appstorage, 'nextPythonWrapperCommPort')
if dat == nil then
dat = sim.packInt32Table({pythonWrapperPortStart})
end
local p = sim.unpackInt32Table(dat)[1]
local np = p + 1
if np >= pythonWrapperPortStart + 800 then
np = pythonWrapperPortStart
end
sim.writeCustomBufferData(sim.handle_appstorage, 'nextPythonWrapperCommPort', sim.packInt32Table({np}))
sim.systemSemaphore('pythonWrapper', false)
local tmpContext = simZMQ.ctx_new()
local tmpSocket = simZMQ.socket(tmpContext, simZMQ.REP)
if simZMQ.__noError.bind(tmpSocket, string.format('tcp://127.0.0.1:%d', p)) == 0 then
simZMQ.close(tmpSocket)
simZMQ.ctx_term(tmpContext)
return string.format('tcp://127.0.0.1:%d', p)
end
end
end
function initPython(prog)
local pyth = sim.getStringProperty(sim.handle_app, 'defaultPython')
local pyth2 = sim.getStringProperty(sim.handle_app, 'namedParam.python', {noError = true})
if pyth2 then pyth = pyth2 end
local errMsg
if pythonExecutable then
pyth = pythonExecutable
end
if #pyth > 0 then
subprocess, controlPort = startPythonClientSubprocess(pyth)
if controlPort then
pyContext = simZMQ.ctx_new()
pySocket = simZMQ.socket(pyContext, simZMQ.REQ)
simZMQ.setsockopt(pySocket, simZMQ.LINGER, sim.packUInt32Table {0})
simZMQ.connect(pySocket, controlPort)
virtualPythonFilename = sim.getStringParam(sim.stringparam_scene_path_and_name)
if virtualPythonFilename == '' then
virtualPythonFilename = 'CoppeliaSim_newScene'
else