pvplot 1.4.0__tar.gz → 1.6.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pvplot-1.6.2/PKG-INFO +30 -0
- pvplot-1.6.2/README.md +15 -0
- pvplot-1.6.2/docs/peakSimulator_pvp.png +0 -0
- pvplot-1.6.2/docs/pvplotx.jpg +0 -0
- {pvplot-1.4.0/pvplot → pvplot-1.6.2/fallback}/pvplot.py +28 -15
- pvplot-1.6.2/p2plantaccess/__init__.py +2 -0
- pvplot-1.6.2/p2plantaccess/ipc.py +133 -0
- pvplot-1.6.2/p2plantaccess/p2plantaccess.py +194 -0
- pvplot-1.6.2/p2plantaccess/simulatedADCs.py +206 -0
- {pvplot-1.4.0 → pvplot-1.6.2}/pvplot/__main__.py +1 -1
- {pvplot-1.4.0 → pvplot-1.6.2}/pvplot/cad_epics.py +17 -13
- pvplot-1.6.2/pvplot/cad_pvaccess.py +154 -0
- pvplot-1.4.0/pvplot/pvplot_todo_disable_plot.py → pvplot-1.6.2/pvplot/pvplot-123a.py +26 -19
- pvplot-1.4.0/pvplot/pvplot_1.3.6.py → pvplot-1.6.2/pvplot/pvplot.py +96 -60
- {pvplot-1.4.0 → pvplot-1.6.2}/pyproject.toml +1 -1
- pvplot-1.4.0/PKG-INFO +0 -26
- pvplot-1.4.0/README.md +0 -12
- pvplot-1.4.0/config.py +0 -48
- pvplot-1.4.0/config_proposal.py +0 -40
- pvplot-1.4.0/pvplot/pvplot_tmp.py +0 -875
- {pvplot-1.4.0 → pvplot-1.6.2}/LICENSE +0 -0
- {pvplot-1.4.0 → pvplot-1.6.2}/config/peakSimulator_pvp.py +0 -0
- {pvplot-1.4.0 → pvplot-1.6.2}/pvplot/__init__.py +0 -0
- {pvplot-1.4.0 → pvplot-1.6.2}/pvplot/helptxt.py +0 -0
pvplot-1.6.2/PKG-INFO
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pvplot
|
|
3
|
+
Version: 1.6.2
|
|
4
|
+
Summary: Plotting tool for EPICS PVs, ADO and LITE parameters
|
|
5
|
+
Project-URL: Homepage, https://github.com/ASukhanov/pvplot
|
|
6
|
+
Project-URL: Bug Tracker, https://github.com/ASukhanov/pvplot/issues
|
|
7
|
+
Author-email: Andrei Sukhanov <cyxandr@gmail.com>
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Requires-Python: >=3.7
|
|
13
|
+
Requires-Dist: liteaccess
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# pvplot
|
|
17
|
+
Package for dynamic plotting of EPICS PVs (both CA and PVA) and [liteServer data objects](https://github.com/ASukhanov/liteServer).<br>
|
|
18
|
+

|
|
19
|
+
|
|
20
|
+
## Examples
|
|
21
|
+
- `python -m pvplot -cconfig -fpeakSimulator_pvp`: [Two docks](docs/peakSimulator_pvp.png) with array plot and a strip chart using native config file /operations/app_store/pvplot/peakSimulator_pvp.py. Note: The litePeakSimulator has to be running and serving localhost port 9710, it can be started like this: `python -m liteserver.device.litePeakSimulator -ilo -p9710`.
|
|
22
|
+
- Sliced array plot of EPICS Channel Access [testAsynPortDriverApp](https://epics.anl.gov/modules/soft/asyn/R4-38/asynDriver.html#testAsynPortDriverApp):<br>
|
|
23
|
+
`python -m pvplot -s0.01 -a'E:testAPD:scope1:' 'Waveform_RBV[1:500]'`
|
|
24
|
+
- Waveform of EPICS PVAccess [simScope](https://github.com/ASukhanov/p4pex):<br>
|
|
25
|
+
`python -m pvplot P:simScope1:Waveform_RBV`
|
|
26
|
+
- Fast correlation plot of a litePeakSimulator<br>
|
|
27
|
+
`python -m pvplot -s.01 -a'L:localhost;9710:dev1:' 'x,y'`
|
|
28
|
+
- Strip chart of analog inputs of a LabJack U3-HV instrument, served by liteLabjack:<br>
|
|
29
|
+
`python -m pvplot -a'L:localhost:dev1' 'tempU3 ADC_HV[0] ADC_HV[1] ADC_HV[2] ADC_HV[3] ADC_LV'`
|
|
30
|
+
- To change properties of curves: right click on a plot and select 'DataSets Options'
|
pvplot-1.6.2/README.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# pvplot
|
|
2
|
+
Package for dynamic plotting of EPICS PVs (both CA and PVA) and [liteServer data objects](https://github.com/ASukhanov/liteServer).<br>
|
|
3
|
+

|
|
4
|
+
|
|
5
|
+
## Examples
|
|
6
|
+
- `python -m pvplot -cconfig -fpeakSimulator_pvp`: [Two docks](docs/peakSimulator_pvp.png) with array plot and a strip chart using native config file /operations/app_store/pvplot/peakSimulator_pvp.py. Note: The litePeakSimulator has to be running and serving localhost port 9710, it can be started like this: `python -m liteserver.device.litePeakSimulator -ilo -p9710`.
|
|
7
|
+
- Sliced array plot of EPICS Channel Access [testAsynPortDriverApp](https://epics.anl.gov/modules/soft/asyn/R4-38/asynDriver.html#testAsynPortDriverApp):<br>
|
|
8
|
+
`python -m pvplot -s0.01 -a'E:testAPD:scope1:' 'Waveform_RBV[1:500]'`
|
|
9
|
+
- Waveform of EPICS PVAccess [simScope](https://github.com/ASukhanov/p4pex):<br>
|
|
10
|
+
`python -m pvplot P:simScope1:Waveform_RBV`
|
|
11
|
+
- Fast correlation plot of a litePeakSimulator<br>
|
|
12
|
+
`python -m pvplot -s.01 -a'L:localhost;9710:dev1:' 'x,y'`
|
|
13
|
+
- Strip chart of analog inputs of a LabJack U3-HV instrument, served by liteLabjack:<br>
|
|
14
|
+
`python -m pvplot -a'L:localhost:dev1' 'tempU3 ADC_HV[0] ADC_HV[1] ADC_HV[2] ADC_HV[3] ADC_LV'`
|
|
15
|
+
- To change properties of curves: right click on a plot and select 'DataSets Options'
|
|
Binary file
|
|
Binary file
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
|
-
"""Plotting package for EPICS PVs
|
|
2
|
+
"""Plotting package for EPICS PVs (CA and PVA), LITE and ADO parameters.
|
|
3
3
|
"""
|
|
4
|
-
__version__ = 'v1.
|
|
4
|
+
__version__ = 'v1.5.1 2025-01-08'# fix importing of cad_epics an cad_pvaccess
|
|
5
5
|
#TODO: if backend times out the gui is not responsive
|
|
6
6
|
#TODO: move Add Dataset to Dataset options
|
|
7
7
|
#TODO: add dataset arithmetics
|
|
8
|
+
#TODO: handle XCELLNAME in mon file
|
|
8
9
|
|
|
9
10
|
import sys, os, time, datetime
|
|
10
11
|
timer = time.perf_counter
|
|
@@ -64,13 +65,25 @@ def prettyDict(rDict, lineLimit=75):
|
|
|
64
65
|
return r
|
|
65
66
|
|
|
66
67
|
try: from . import cad_epics as EPICSAccess
|
|
67
|
-
except
|
|
68
|
-
|
|
69
|
-
|
|
68
|
+
except:
|
|
69
|
+
try: from cad_epics import epics as EPICSAccess
|
|
70
|
+
except: pass
|
|
71
|
+
try: print(f'EPICS Channels Access interface {EPICSAccess.__version__}')
|
|
72
|
+
except:
|
|
73
|
+
EPICSAccess = None
|
|
74
|
+
printw(f'EPICS CA devices are not supported on this host')
|
|
75
|
+
try: from . import cad_pvaccess as PVAccess
|
|
76
|
+
except:
|
|
77
|
+
try: from cad_pvaccess import pvaccess as PVAccess
|
|
78
|
+
except: pass
|
|
79
|
+
try: print(f'EPICS PVAccess interface {PVAccess.__version__}')
|
|
80
|
+
except:
|
|
81
|
+
PVAccess = None
|
|
82
|
+
printw(f'EPICS PVA devices are not supported on this host')
|
|
70
83
|
try:
|
|
71
84
|
import liteaccess as liteAccess
|
|
72
85
|
LITEAccess = liteAccess.Access
|
|
73
|
-
print(f'liteAccess {liteAccess.__version__}')
|
|
86
|
+
print(f'liteAccess interface {liteAccess.__version__}')
|
|
74
87
|
except Exception as e:
|
|
75
88
|
printw(f'LITE devices are not supported on this host: {e}')
|
|
76
89
|
LITEAccess = None
|
|
@@ -82,13 +95,13 @@ except Exception as e:
|
|
|
82
95
|
ADOAccess = None
|
|
83
96
|
|
|
84
97
|
def get_pv(adopar:str, prop='value'):
|
|
85
|
-
#print(f'>get_pv {adopar}')
|
|
98
|
+
#print(f'>pvp get_pv {adopar}')
|
|
86
99
|
adopar, vslice = split_slice(adopar)
|
|
87
100
|
try:
|
|
88
101
|
access = PVPlot.access[adopar[:2]]
|
|
89
102
|
adopar = adopar[2:]
|
|
90
103
|
except:
|
|
91
|
-
access =
|
|
104
|
+
access = ADOAccess
|
|
92
105
|
if access is None:
|
|
93
106
|
printe(f'No access method for `{adopar}`')
|
|
94
107
|
sys.exit(1)
|
|
@@ -105,7 +118,7 @@ def get_pv(adopar:str, prop='value'):
|
|
|
105
118
|
pass
|
|
106
119
|
try:
|
|
107
120
|
ts = rd['timestamp']# EPICS and LITE
|
|
108
|
-
except: # ADO
|
|
121
|
+
except: # ADO & PVA
|
|
109
122
|
ts = rd['timestampSeconds'] + rd['timestampNanoSeconds']*1.e-9
|
|
110
123
|
|
|
111
124
|
#printv(f"get_pv {adopar}: {rd['value']} {vslice}")
|
|
@@ -586,7 +599,7 @@ class MapOfDatasets():
|
|
|
586
599
|
|
|
587
600
|
def add(dockNum:int, mapOfCurves):
|
|
588
601
|
"""add new datasets, the adoPars is the space delimited string of
|
|
589
|
-
source
|
|
602
|
+
source device:parameters."""
|
|
590
603
|
printv(f'>MapOfDatasets.add({dockNum, mapOfCurves})')
|
|
591
604
|
for i, kv in enumerate(mapOfCurves.items()):
|
|
592
605
|
curveName,devList = kv
|
|
@@ -599,7 +612,7 @@ class MapOfDatasets():
|
|
|
599
612
|
pnameAndCount = []
|
|
600
613
|
for adoPar in devList:
|
|
601
614
|
adoPar = adoPar.lstrip()#remove leading whitespaces
|
|
602
|
-
|
|
615
|
+
#print(f'adoPar: {adoPar}')
|
|
603
616
|
if adoPar.startswith('device('):
|
|
604
617
|
e = adoPar.index(')')
|
|
605
618
|
rest = adoPar[e+1:]# it could be arithmetics
|
|
@@ -963,7 +976,7 @@ def add_curves(dockNum:int, curveMap:str):
|
|
|
963
976
|
docks = PVPlot.mapOfDocks.keys()
|
|
964
977
|
printv(f'>addcurves curves {curveMap} to {curves,docks}')
|
|
965
978
|
if dockNum not in docks:
|
|
966
|
-
printv(f'adding new dock{dockNum}')
|
|
979
|
+
printv(f'adding new dock{type(dockNum),dockNum}')
|
|
967
980
|
PVPlot.mapOfDocks[dockNum] = dockarea.Dock(str(dockNum),
|
|
968
981
|
size=(500,200), hideTitle=True)
|
|
969
982
|
if dockNum == 0:
|
|
@@ -991,7 +1004,7 @@ def parse_input_parameters(pargs):
|
|
|
991
1004
|
fn = pargs.file
|
|
992
1005
|
if fn:
|
|
993
1006
|
sys.path.append(pargs.configDir)
|
|
994
|
-
|
|
1007
|
+
print(f'Config file: {pargs.configDir}/{fn}')
|
|
995
1008
|
try:
|
|
996
1009
|
ConfigModule = import_module(fn)
|
|
997
1010
|
configFormat = ConfigModule.configFormat
|
|
@@ -1027,7 +1040,7 @@ class PVPlot():
|
|
|
1027
1040
|
subscribedParMap = {}
|
|
1028
1041
|
perfmon = False # option for performance monitoring
|
|
1029
1042
|
legend = {}# unfortunately we have to keep track of legends
|
|
1030
|
-
access = {'E:':EPICSAccess, 'L:':LITEAccess}
|
|
1043
|
+
access = {'E:':EPICSAccess, 'L:':LITEAccess, 'P:':PVAccess}
|
|
1031
1044
|
qWin = None
|
|
1032
1045
|
qTimer = QtCore.QTimer()
|
|
1033
1046
|
dockArea = None
|
|
@@ -1092,7 +1105,7 @@ class PVPlot():
|
|
|
1092
1105
|
for par in pargs.dock:
|
|
1093
1106
|
dockNum = par[0][0]
|
|
1094
1107
|
adopar = par[0][1:].lstrip()
|
|
1095
|
-
add_curves(dockNum, {adopar:adopar})
|
|
1108
|
+
add_curves(int(dockNum), {adopar:adopar})
|
|
1096
1109
|
else:
|
|
1097
1110
|
# plots for the main dock
|
|
1098
1111
|
if not ',' in pargs.parms:
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Simple IPC Message Queue class for Python3, using ctypes and libc.
|
|
2
|
+
"""
|
|
3
|
+
#Adopted from: https://gist.github.com/unautre/3cf4e9924ee81b762f82
|
|
4
|
+
__version__ = '1.0.0 2024-04-21'# Transport is static class
|
|
5
|
+
#TODO: Currently ftok file does not matter. Issue: if send size is bigger than recv buffer then queue will be spoiled. Ideally it should contain the max size of the receiver buffer.
|
|
6
|
+
|
|
7
|
+
"""```````````````````Usage
|
|
8
|
+
$ python3 parmhost/ipc.py -l
|
|
9
|
+
$ python3
|
|
10
|
+
from parmhost.ipc import Transport
|
|
11
|
+
msq = Transport()
|
|
12
|
+
msq.send(b'hello')
|
|
13
|
+
"""
|
|
14
|
+
import sys
|
|
15
|
+
|
|
16
|
+
from ctypes import CDLL, get_errno, create_string_buffer
|
|
17
|
+
from ctypes import c_ushort, c_int, c_uint, c_long, c_ulong
|
|
18
|
+
from ctypes import c_char_p, c_void_p, POINTER, Structure, cast
|
|
19
|
+
|
|
20
|
+
# we load the libc.
|
|
21
|
+
libc = CDLL("libc.so.6")
|
|
22
|
+
# define some consts.
|
|
23
|
+
IPC_CREAT = 0o1000
|
|
24
|
+
IPC_EXCL = 0o2000
|
|
25
|
+
IPC_NOWAIT= 0o4000
|
|
26
|
+
IPC_RMID = 0
|
|
27
|
+
IPC_SET = 1
|
|
28
|
+
IPC_STAT = 2
|
|
29
|
+
IPC_INFO = 3
|
|
30
|
+
# typedef some types
|
|
31
|
+
key_t = c_int
|
|
32
|
+
|
|
33
|
+
# Static key for IPC
|
|
34
|
+
ftok = libc.ftok
|
|
35
|
+
ftok.argtypes = [c_char_p, c_int]
|
|
36
|
+
ftkey = ftok(c_char_p(b"/tmp/ipcbor.ftok"), c_int(65))
|
|
37
|
+
if ftkey == -1:
|
|
38
|
+
print("ERR: Could not create IPC Message Key, Please do: 'touch /tmp/ipcbor.ftok'")
|
|
39
|
+
sys.exit(1);
|
|
40
|
+
print(f'IPC ftok: {ftkey}')
|
|
41
|
+
|
|
42
|
+
class ipc_perm(Structure):
|
|
43
|
+
_fields_ = [ ("__key", key_t),
|
|
44
|
+
("uid", c_uint),
|
|
45
|
+
("gid", c_uint),
|
|
46
|
+
("cuid", c_uint),
|
|
47
|
+
("cgid", c_uint),
|
|
48
|
+
("mode", c_ushort),
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
class msqid_ds(Structure):
|
|
52
|
+
_fields_ = [ ("msg_perm", ipc_perm),
|
|
53
|
+
("msg_stime", c_ulong),
|
|
54
|
+
("msg_rtime", c_ulong),
|
|
55
|
+
("msg_ctime", c_ulong),
|
|
56
|
+
("__msg_cbytes", c_ulong),
|
|
57
|
+
("msg_qnum", c_ulong), # Useful:number of messages in queue
|
|
58
|
+
("msg_qbytes", c_ulong),
|
|
59
|
+
("msg_lspid", c_int),
|
|
60
|
+
("msg_lrpid", c_int)
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
class Transport:
|
|
64
|
+
"""Static class"""
|
|
65
|
+
msgget = libc.msgget
|
|
66
|
+
msgget.argtypes = [key_t, c_int]
|
|
67
|
+
|
|
68
|
+
msgsnd = libc.msgsnd
|
|
69
|
+
msgsnd.argtypes = [c_int, c_char_p, c_ulong, c_int]
|
|
70
|
+
|
|
71
|
+
msgctl = libc.msgctl
|
|
72
|
+
msgctl.argtypes = [c_int, c_int, POINTER(msqid_ds)]
|
|
73
|
+
|
|
74
|
+
msgrcv = libc.msgrcv
|
|
75
|
+
msgrcv.argtypes = [c_int, c_char_p, c_ulong, c_ulong, c_int]
|
|
76
|
+
|
|
77
|
+
perror = libc.perror
|
|
78
|
+
perror.argtypes = [c_char_p]
|
|
79
|
+
|
|
80
|
+
def init(key=ftkey, mode=IPC_CREAT | 0o644, bitrate=None):
|
|
81
|
+
Transport.id_rcv = Transport.msgget(key+1, mode)
|
|
82
|
+
Transport.id_snd = Transport.msgget(key, mode)
|
|
83
|
+
print(f'IPC id_rcv: {Transport.id_rcv}, id_snd: {Transport.id_snd}')
|
|
84
|
+
|
|
85
|
+
def send(msg):#, msglen), msgtype=1, flag=0):
|
|
86
|
+
msgtype=1; flag=0
|
|
87
|
+
msglen = len(msg)
|
|
88
|
+
buf = create_string_buffer(msglen+8)
|
|
89
|
+
lbuf = cast(buf, POINTER(c_long))
|
|
90
|
+
lbuf[0] = msgtype
|
|
91
|
+
buf[8:] = msg[:msglen]
|
|
92
|
+
r = Transport.msgsnd(Transport.id_snd, buf, msglen, flag)
|
|
93
|
+
if r != 0:
|
|
94
|
+
raise BufferError('in Transport.send.')
|
|
95
|
+
msq.clear()
|
|
96
|
+
|
|
97
|
+
def recv(msgsize=15000):
|
|
98
|
+
msgtype=1; flag=0
|
|
99
|
+
size = msgsize+8
|
|
100
|
+
buf = create_string_buffer(size)
|
|
101
|
+
msglen = Transport.msgrcv(Transport.id_rcv, buf, size, msgtype, flag)
|
|
102
|
+
# do not return type
|
|
103
|
+
#lbuf = cast(buf, POINTER(c_long)) # for msgtype
|
|
104
|
+
#return lbuf.contents.value, buf[8:msglen+8]
|
|
105
|
+
return buf[8:msglen+8]
|
|
106
|
+
|
|
107
|
+
def clear():
|
|
108
|
+
Transport.msgctl(Transport.id_rcv, IPC_RMID, None)
|
|
109
|
+
Transport.msgctl(Transport.id_snd, IPC_RMID, None)
|
|
110
|
+
#,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
|
|
111
|
+
if __name__ == "__main__":
|
|
112
|
+
import argparse
|
|
113
|
+
parser = argparse.ArgumentParser(description=__doc__
|
|
114
|
+
,formatter_class=argparse.ArgumentDefaultsHelpFormatter
|
|
115
|
+
,epilog=f'ipc {__version__}')
|
|
116
|
+
parser.add_argument('-l','--listener', action='store_true', help=\
|
|
117
|
+
'Print incoming messages')
|
|
118
|
+
parser.add_argument('messages', nargs='*', help='Messages to send to server')
|
|
119
|
+
pargs = parser.parse_args()
|
|
120
|
+
|
|
121
|
+
msq = Transport()
|
|
122
|
+
for msg in pargs.messages:
|
|
123
|
+
msq.send(msg)
|
|
124
|
+
|
|
125
|
+
if pargs.listener:
|
|
126
|
+
print('IPC Listening')
|
|
127
|
+
msglen = 1
|
|
128
|
+
while msglen > 0:
|
|
129
|
+
msg = msq.recv()
|
|
130
|
+
print(f'IPC Received {msglen} bytes:`{msg}`')
|
|
131
|
+
msglen = len(msg)
|
|
132
|
+
msq.clear()
|
|
133
|
+
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""Access to P2Plant process variables with IPC queue link.
|
|
2
|
+
Usage:
|
|
3
|
+
$ python3
|
|
4
|
+
from p2plantaccess import Access as pa
|
|
5
|
+
pa.init(); pa.start()
|
|
6
|
+
pa.request(["info", ["*"]])
|
|
7
|
+
pa.request(["get", ['run',"version"]])
|
|
8
|
+
or:
|
|
9
|
+
pa.request('["get", ["run","version"]]')
|
|
10
|
+
pa.request(['set', [('run','stop')]])
|
|
11
|
+
"""
|
|
12
|
+
__version__ = 'v1.0.4 2025-02-17'# recv blocking is bool
|
|
13
|
+
print(f'p2plantAccess {__version__}')
|
|
14
|
+
|
|
15
|
+
import time
|
|
16
|
+
import threading
|
|
17
|
+
from collections import deque
|
|
18
|
+
import numpy as np
|
|
19
|
+
from json import loads
|
|
20
|
+
import cbor2 as cbor
|
|
21
|
+
#import cbor
|
|
22
|
+
|
|
23
|
+
dtype = {# map of CBOR tags to numpy dtype
|
|
24
|
+
72: "int8",
|
|
25
|
+
64: "uint8",
|
|
26
|
+
69: "uint16",
|
|
27
|
+
77: "int16",
|
|
28
|
+
78: "int32",
|
|
29
|
+
70: "uint32",
|
|
30
|
+
}
|
|
31
|
+
tag = {v:k for k,v in dtype.items()}# map of dtype to CBOR tag
|
|
32
|
+
|
|
33
|
+
def printi(msg): print(f'inf_p2pa: {msg}')
|
|
34
|
+
def printw(msg): print(f'WAR_p2pa: {msg}')
|
|
35
|
+
def printe(msg): print(f'ERR_p2pa: {msg}')
|
|
36
|
+
def printv(msg):
|
|
37
|
+
if (Access.DBG): print(f'dbg_p2p: {msg}')
|
|
38
|
+
|
|
39
|
+
class Access:
|
|
40
|
+
"""Static class"""
|
|
41
|
+
DBG = False
|
|
42
|
+
receivedList = []
|
|
43
|
+
commandReply = deque()# OCould keep many deliveries
|
|
44
|
+
subscriptionReply = deque()# Only one delivery could be kept here
|
|
45
|
+
started = False
|
|
46
|
+
receivedMap = {}
|
|
47
|
+
|
|
48
|
+
event_subscription_received = threading.Event()
|
|
49
|
+
event_reply_received = threading.Event()
|
|
50
|
+
|
|
51
|
+
queueAndEvents = {
|
|
52
|
+
'reply': (commandReply, event_reply_received),# event_reply_processed),
|
|
53
|
+
'subscription': (subscriptionReply, event_subscription_received),# event_subscription_processed)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
def init(transport='ipc', bitrate=7372800):
|
|
57
|
+
if transport== 'ipc':
|
|
58
|
+
from .ipc import Transport
|
|
59
|
+
Transport.init(bitrate=bitrate)
|
|
60
|
+
Access.transport = Transport
|
|
61
|
+
|
|
62
|
+
def start():
|
|
63
|
+
thread = threading.Thread(target=Access._receiver, daemon=True)
|
|
64
|
+
Access.started = True
|
|
65
|
+
thread.start()
|
|
66
|
+
|
|
67
|
+
def stop():
|
|
68
|
+
Access.started = False
|
|
69
|
+
|
|
70
|
+
def _receiver():
|
|
71
|
+
printi("Receiver started")
|
|
72
|
+
while Access.started:
|
|
73
|
+
bbuf = Access.transport.recv()
|
|
74
|
+
printv(f'Received a message[{len(bbuf)}]: {bbuf}')
|
|
75
|
+
Access.receivedList = cbor.loads(bbuf)
|
|
76
|
+
if len(Access.receivedList) > 0\
|
|
77
|
+
and Access.receivedList[0] == 'Subscription':
|
|
78
|
+
printv(f'Subscriptions: {Access.receivedList}')
|
|
79
|
+
if len(Access.subscriptionReply) > 0:
|
|
80
|
+
continue
|
|
81
|
+
Access.subscriptionReply.append(Access.receivedList[1:])
|
|
82
|
+
Access.event_subscription_received.set()
|
|
83
|
+
else:
|
|
84
|
+
Access.commandReply.append(Access.receivedList)
|
|
85
|
+
Access.event_reply_received.set();
|
|
86
|
+
printi("Receiver finished")
|
|
87
|
+
|
|
88
|
+
def send(request):
|
|
89
|
+
"""Encode object to CBOR and send it to IPC queue"""
|
|
90
|
+
if not Access.started:
|
|
91
|
+
printw("Receiver is not started")
|
|
92
|
+
return
|
|
93
|
+
#cborobj = cbor.dumps(request, canonical=True)# expect more compact output, but it is not compatible with p2plant.
|
|
94
|
+
cborobj = cbor.dumps(request)
|
|
95
|
+
#print(f'send cbor: {cborobj}')
|
|
96
|
+
Access.transport.send(cborobj)
|
|
97
|
+
#print('')
|
|
98
|
+
|
|
99
|
+
#def array(nparray):
|
|
100
|
+
# """Convert numpy array to CBORTag. For use in send()."""
|
|
101
|
+
# atag = tag[str(nparray.dtype)]
|
|
102
|
+
# return cbor.CBORTag(atag, nparray.tobytes())
|
|
103
|
+
|
|
104
|
+
def recv(what:str = 'reply', blocking=True):
|
|
105
|
+
"""Receive data, the what could be 'reply' or 'Subscription'.
|
|
106
|
+
if blocking==True, the program will be blocked until arrival of
|
|
107
|
+
new data"""
|
|
108
|
+
#print(f'recv {what}, {blocking}')
|
|
109
|
+
if not Access.started:
|
|
110
|
+
printw("Receiver is not started")
|
|
111
|
+
return
|
|
112
|
+
try:
|
|
113
|
+
queue, evRcv = Access.queueAndEvents[what]
|
|
114
|
+
except:
|
|
115
|
+
return {'ERR':f'recv supports only {Access.queueAndEvents.keys()}'}
|
|
116
|
+
if blocking:
|
|
117
|
+
evRcv.wait()
|
|
118
|
+
else:
|
|
119
|
+
if not evRcv.is_set():
|
|
120
|
+
return {}
|
|
121
|
+
l = len(queue)
|
|
122
|
+
printv(f'reply received {what}[{l}]')
|
|
123
|
+
Access.receivedMap = {}
|
|
124
|
+
if l == 0:
|
|
125
|
+
return []
|
|
126
|
+
if l == 1:# Handling last item. The flag could be cleared.
|
|
127
|
+
evRcv.clear()
|
|
128
|
+
qitem = deque(queue.pop())
|
|
129
|
+
printv(f'qitem: {qitem}')
|
|
130
|
+
if (len(qitem)%2) != 0:
|
|
131
|
+
# Received odd number of items: that happens if request was incorrect.
|
|
132
|
+
printe(f'Request was not recognized by server: {qitem[0]}')
|
|
133
|
+
return {}
|
|
134
|
+
try:
|
|
135
|
+
while par := qitem.popleft():
|
|
136
|
+
parmap = qitem.popleft()
|
|
137
|
+
if par in Access.receivedMap:
|
|
138
|
+
Access.receivedMap[par].update(parmap)
|
|
139
|
+
else:
|
|
140
|
+
Access.receivedMap[par] = parmap
|
|
141
|
+
except IndexError:
|
|
142
|
+
pass
|
|
143
|
+
#print(f'Access.receivedMap: {Access.receivedMap}')
|
|
144
|
+
return Access.receivedMap
|
|
145
|
+
|
|
146
|
+
def decode(parName='*'):
|
|
147
|
+
"""Translate reply to standard python objects"""
|
|
148
|
+
outmap = {}
|
|
149
|
+
inmap = Access.receivedMap
|
|
150
|
+
if parName != '*':
|
|
151
|
+
try:
|
|
152
|
+
inmap = {parName: Access.receivedMap[parName]}
|
|
153
|
+
except:
|
|
154
|
+
return {}
|
|
155
|
+
for par,parmap in inmap.items():
|
|
156
|
+
outmap[par] = {}
|
|
157
|
+
for key,v in parmap.items():
|
|
158
|
+
if isinstance(v, cbor.CBORTag):
|
|
159
|
+
v = np.frombuffer(v.value, dtype[v.tag])
|
|
160
|
+
if key == 'v':
|
|
161
|
+
shape = parmap.get('shape')
|
|
162
|
+
v = v.reshape(shape)
|
|
163
|
+
elif key == 't':
|
|
164
|
+
v = v[0],v[1]
|
|
165
|
+
outmap[par][key] = v
|
|
166
|
+
return outmap
|
|
167
|
+
|
|
168
|
+
def valueAndTimestamp(parName:str):
|
|
169
|
+
"""Return (value,timestamps) of a parameter"""
|
|
170
|
+
try:
|
|
171
|
+
parmap = Access.decode(parName)[parName]
|
|
172
|
+
v,t = parmap['v'],parmap['t']
|
|
173
|
+
return (v,t)
|
|
174
|
+
except:
|
|
175
|
+
return []
|
|
176
|
+
|
|
177
|
+
def request(obj):
|
|
178
|
+
"""Send object or text to IPC queue and receive/decode the reply"""
|
|
179
|
+
if isinstance(obj, str):
|
|
180
|
+
try:
|
|
181
|
+
obj = loads(obj)
|
|
182
|
+
except Exception as e:
|
|
183
|
+
printe(f"Failed to encode string '{obj}' to json: {e}")
|
|
184
|
+
return {}
|
|
185
|
+
try:
|
|
186
|
+
printv(f'Sending obj: {obj}')
|
|
187
|
+
Access.send(obj)
|
|
188
|
+
Access.recv()
|
|
189
|
+
r = Access.decode()
|
|
190
|
+
printv(f'rcv: {r}')
|
|
191
|
+
return r
|
|
192
|
+
except Exception as e:
|
|
193
|
+
printe(f'Sending {obj}: {e}')
|
|
194
|
+
return {}
|