pvplot 1.5.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pvplot
3
- Version: 1.5.0
3
+ Version: 1.6.2
4
4
  Summary: Plotting tool for EPICS PVs, ADO and LITE parameters
5
5
  Project-URL: Homepage, https://github.com/ASukhanov/pvplot
6
6
  Project-URL: Bug Tracker, https://github.com/ASukhanov/pvplot/issues
@@ -14,18 +14,17 @@ Requires-Dist: liteaccess
14
14
  Description-Content-Type: text/markdown
15
15
 
16
16
  # pvplot
17
- Package for dynamic plotting of EPICS PVs (both CA and PVA) and [liteServer data objects](https://github.com/ASukhanov/liteServer).
17
+ Package for dynamic plotting of EPICS PVs (both CA and PVA) and [liteServer data objects](https://github.com/ASukhanov/liteServer).<br>
18
+ ![litePeakSimulator](docs/pvplotx.jpg)
18
19
 
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`.
20
22
  - Sliced array plot of EPICS Channel Access [testAsynPortDriverApp](https://epics.anl.gov/modules/soft/asyn/R4-38/asynDriver.html#testAsynPortDriverApp):<br>
21
23
  `python -m pvplot -s0.01 -a'E:testAPD:scope1:' 'Waveform_RBV[1:500]'`
22
- - Waveform from EPICS PVaccess [simScope](https://github.com/ASukhanov/p4pex):<br>
24
+ - Waveform of EPICS PVAccess [simScope](https://github.com/ASukhanov/p4pex):<br>
23
25
  `python -m pvplot P:simScope1:Waveform_RBV`
24
- - Time-series plot (stripchart) of analog inputs of a LabJack U3-HV instrument, served by liteLabjack:<br>
25
- `python -m pvplot -a'L:localhost:dev1' 'tempU3 ADC_HV[0] ADC_HV[1] ADC_HV[2] ADC_HV[3] ADC_LV'`
26
26
  - Fast correlation plot of a litePeakSimulator<br>
27
- `python -m pvplot -s.01 -a'L:localhost:dev1' 'x,y'`
28
- - Multiple docks. For example, to plot two scrolling plots in lower dock and a
29
- correlation plot in upper dock:<br>
30
- `python -m pvplot -a'L:localhost:dev1:' -#0'yMax yMin' -#1'yMax,yMin'`
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'`
31
30
  - To change properties of curves: right click on a plot and select 'DataSets Options'
@@ -1,16 +1,15 @@
1
1
  # pvplot
2
- Package for dynamic plotting of EPICS PVs (both CA and PVA) and [liteServer data objects](https://github.com/ASukhanov/liteServer).
2
+ Package for dynamic plotting of EPICS PVs (both CA and PVA) and [liteServer data objects](https://github.com/ASukhanov/liteServer).<br>
3
+ ![litePeakSimulator](docs/pvplotx.jpg)
3
4
 
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`.
5
7
  - Sliced array plot of EPICS Channel Access [testAsynPortDriverApp](https://epics.anl.gov/modules/soft/asyn/R4-38/asynDriver.html#testAsynPortDriverApp):<br>
6
8
  `python -m pvplot -s0.01 -a'E:testAPD:scope1:' 'Waveform_RBV[1:500]'`
7
- - Waveform from EPICS PVaccess [simScope](https://github.com/ASukhanov/p4pex):<br>
9
+ - Waveform of EPICS PVAccess [simScope](https://github.com/ASukhanov/p4pex):<br>
8
10
  `python -m pvplot P:simScope1:Waveform_RBV`
9
- - Time-series plot (stripchart) of analog inputs of a LabJack U3-HV instrument, served by liteLabjack:<br>
10
- `python -m pvplot -a'L:localhost:dev1' 'tempU3 ADC_HV[0] ADC_HV[1] ADC_HV[2] ADC_HV[3] ADC_LV'`
11
11
  - Fast correlation plot of a litePeakSimulator<br>
12
- `python -m pvplot -s.01 -a'L:localhost:dev1' 'x,y'`
13
- - Multiple docks. For example, to plot two scrolling plots in lower dock and a
14
- correlation plot in upper dock:<br>
15
- `python -m pvplot -a'L:localhost:dev1:' -#0'yMax yMin' -#1'yMax,yMin'`
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'`
16
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
2
  """Plotting package for EPICS PVs (CA and PVA), LITE and ADO parameters.
3
3
  """
4
- __version__ = 'v1.5.0 2024-12-31'# added EPICS PVAccess support using p4p
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,17 +65,25 @@ def prettyDict(rDict, lineLimit=75):
64
65
  return r
65
66
 
66
67
  try: from . import cad_epics as EPICSAccess
67
- except Exception as e:
68
- EPICSAccess = None
69
- printw(f'EPICS devices are not supported on this host: {e}')
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')
70
75
  try: from . import cad_pvaccess as PVAccess
71
- except Exception as e:
72
- PVAccess = None
73
- printw(f'EPICS PVA devices are not supported on this host: {e}')
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')
74
83
  try:
75
84
  import liteaccess as liteAccess
76
85
  LITEAccess = liteAccess.Access
77
- print(f'liteAccess {liteAccess.__version__}')
86
+ print(f'liteAccess interface {liteAccess.__version__}')
78
87
  except Exception as e:
79
88
  printw(f'LITE devices are not supported on this host: {e}')
80
89
  LITEAccess = None
@@ -92,7 +101,7 @@ def get_pv(adopar:str, prop='value'):
92
101
  access = PVPlot.access[adopar[:2]]
93
102
  adopar = adopar[2:]
94
103
  except:
95
- access = PVPlot.ADOAccess
104
+ access = ADOAccess
96
105
  if access is None:
97
106
  printe(f'No access method for `{adopar}`')
98
107
  sys.exit(1)
@@ -967,7 +976,7 @@ def add_curves(dockNum:int, curveMap:str):
967
976
  docks = PVPlot.mapOfDocks.keys()
968
977
  printv(f'>addcurves curves {curveMap} to {curves,docks}')
969
978
  if dockNum not in docks:
970
- printv(f'adding new dock{dockNum}')
979
+ printv(f'adding new dock{type(dockNum),dockNum}')
971
980
  PVPlot.mapOfDocks[dockNum] = dockarea.Dock(str(dockNum),
972
981
  size=(500,200), hideTitle=True)
973
982
  if dockNum == 0:
@@ -995,7 +1004,7 @@ def parse_input_parameters(pargs):
995
1004
  fn = pargs.file
996
1005
  if fn:
997
1006
  sys.path.append(pargs.configDir)
998
- printv(f'importing {fn}')
1007
+ print(f'Config file: {pargs.configDir}/{fn}')
999
1008
  try:
1000
1009
  ConfigModule = import_module(fn)
1001
1010
  configFormat = ConfigModule.configFormat
@@ -1096,7 +1105,7 @@ class PVPlot():
1096
1105
  for par in pargs.dock:
1097
1106
  dockNum = par[0][0]
1098
1107
  adopar = par[0][1:].lstrip()
1099
- add_curves(dockNum, {adopar:adopar})
1108
+ add_curves(int(dockNum), {adopar:adopar})
1100
1109
  else:
1101
1110
  # plots for the main dock
1102
1111
  if not ',' in pargs.parms:
@@ -0,0 +1,2 @@
1
+ from .p2plantaccess import __version__, Access
2
+
@@ -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 {}
@@ -0,0 +1,206 @@
1
+ """Example of communication with P2Plant simulatedADCs.
2
+ """
3
+ __version__ = 'v1.0.3 2025-02-16'#input is working now, cleanup, time.sleep(.000001)#ISSUE,
4
+ print(f'Version {__version__}')
5
+ import sys, time, os
6
+ import threading
7
+ import numpy as np
8
+ import pprint
9
+ from json import loads
10
+ import pyqtgraph as pg
11
+ from pyqtgraph.Qt import QtCore
12
+
13
+ from .p2plantaccess import Access as PA
14
+
15
+ UpArrow = b'\x1b[A' #Up arrow sequence
16
+ LastCmd = ''
17
+
18
+ def printTime(): return time.strftime("%m%d:%H%M%S")
19
+ def croppedText(txt, limit=200):
20
+ if len(txt) > limit:
21
+ txt = txt[:limit]+'...'
22
+ return txt
23
+
24
+ def printi(msg, end=''): print(f'INF@{printTime()}: {msg}', end=end)
25
+
26
+ def printw(msg):
27
+ msg = croppedText(msg)
28
+ print(f'WRN@{printTime()}: {msg}')
29
+
30
+ def printe(msg):
31
+ msg = croppedText(msg)
32
+ print(f'ERR@{printTime()}: {msg}')
33
+
34
+ def _printv(msg, level=0):
35
+ if pargs.verbose >= level: print(f'DBG{level}: {msg}')
36
+ def printv(msg): _printv(msg, 1)
37
+ def printvv(msg): _printv(msg, 2)
38
+
39
+ curves = []
40
+ lasttime = time.time()
41
+ fps = 0
42
+ def receive_subscription():
43
+ global lasttime,fps
44
+ ct = time.time()
45
+ printInterval = 10#s
46
+ if ct - lasttime >= printInterval:
47
+ lasttime = ct
48
+ txt = ''
49
+ if pargs.keep_alive:
50
+ # request something to inform server that I am alive
51
+ r = PA.request('["get", ["perf"]]');
52
+ txt += f'Perf: {str(r["perf"]["v"])}.'
53
+ txt += f' Frame rate: {round(fps/printInterval,3)} Hz.'
54
+ if not pargs.graph == '':
55
+ TextItem.setText(txt)
56
+ if not pargs.quiet:
57
+ printi(txt, end='\n>')
58
+ fps = 0
59
+ r = PA.recv('subscription','nonblocking')
60
+ if len(r) == 0:
61
+ #printv(f'no data, fps: {fps}')
62
+ time.sleep(.000001)#ISSUE: if return without any system call, then the cycle rate is slow, same as with -g and CPU=100%. Is this QT issue? With this microsleep the CPU=26% and trig rate=frame.
63
+ return
64
+ try:
65
+ # data received
66
+ fps += 1
67
+ printv(f'data received, fps: {fps}')
68
+ decoded = PA.decode()
69
+ if pargs.verbose >= 2:
70
+ printv(f'decoded: {decoded}')
71
+ try: data = decoded['adcs']['v']
72
+ except KeyError:
73
+ printe(f'PV not delivered: adcs')
74
+ sys.exit(1)
75
+ lx = len(data[0])
76
+ #x = np.arange(lx)/adc_srate
77
+ x= np.arange(lx)
78
+ #printv(f'Data:[{len(data)}]:\n{data}')
79
+ if pargs.graph == '':
80
+ return
81
+ if len(curves) == 0:
82
+ for idx,row in enumerate(data):
83
+ if pargs.graph is None or str(idx+1) in pargs.graph:
84
+ curve = pg.PlotCurveItem(pen=(idx,len(data)*1.3))
85
+ printv(f'adding curve ADC{idx+1}')
86
+ plot.addItem(curve)
87
+ curves.append(curve)
88
+ legend.addItem(curve, f'ADC{idx+1}')
89
+ plot.resize(900,600)
90
+ for idx,curvrow in enumerate(zip(curves,data)):
91
+ #print(f'idx {idx} {pargs.graph is None or str(idx+1) in pargs.graph}')
92
+ if pargs.graph is None or str(idx+1) in pargs.graph:
93
+ curve,row = curvrow
94
+ curve.setData(x, row*pargs.yscale)
95
+
96
+ except KeyboardInterrupt:
97
+ print(' Interrupted')
98
+ sys.exit(1)
99
+
100
+ def input_thread():
101
+ global LastCmd
102
+ print(( 'Example commands:\n'
103
+ '````````````````````````\n'
104
+ '["info",["*"]]\n'
105
+ '["set",[["run","stop"]]]\n'
106
+ '["set",[["debug",2]]]\n'
107
+ ',,,,,,,,,,,,,,,,,,,,,,,,'))
108
+ while(1):
109
+ msg = input()
110
+ if msg.encode() == UpArrow:
111
+ msg = LastCmd
112
+ else:
113
+ LastCmd = msg
114
+ print(f'requested: {msg}')
115
+ r = PA.request(msg)
116
+ print(f'replied: {r}')
117
+ print('>',end='')
118
+ #,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
119
+ #``````````````````Main function``````````````````````````````````````````````
120
+ def main():
121
+ import argparse
122
+ global pargs, plot, TextItem, legend
123
+ parser = argparse.ArgumentParser(description=__doc__
124
+ ,formatter_class=argparse.ArgumentDefaultsHelpFormatter
125
+ ,epilog=f'{sys.argv[0]}: {__version__}')
126
+ parser.add_argument('-b','--bitrate', type=int, default=7372800, help=
127
+ 'Optional, bitrate')
128
+ parser.add_argument('-B','--black', action='store_true', help=
129
+ 'Black background, white foreground for all graphics')
130
+ parser.add_argument('-g', '--graph', default='', nargs='?', help=\
131
+ 'Show waveforms on a graph, for example, -g: show all, -g123: only show waveforms 1,2 and 3')
132
+ parser.add_argument('-k', '--keep_alive', action='store_true', help=\
133
+ 'Periodically send request to server to keep it alive')
134
+ parser.add_argument('-q', '--quiet', action='store_true', help=\
135
+ 'Do not print frame statistics')
136
+ parser.add_argument('-t','--transport', default='ipc', choices=['uart','ipc'], help=
137
+ 'Transport interface')
138
+ parser.add_argument('-u', '--yunits', default='', help=\
139
+ 'Units for Y-axis')
140
+ parser.add_argument('-v', '--verbose', action='count', default=0, help=\
141
+ 'Show more log messages (-vv: show even more)')
142
+ parser.add_argument('-y', '--yscale', type=float, default=1., help=\
143
+ 'Y scale')
144
+ parser.add_argument('-z', '--zoomin', help=\
145
+ 'Zoom the application window by a factor')
146
+ pargs = parser.parse_args()
147
+ #breakpoint()
148
+
149
+ PA.init(pargs.transport, pargs.bitrate)
150
+ PA.start()
151
+
152
+ r = PA.request('["get", ["version"]]');
153
+ print(f'P2Plant {r["version"]["v"]}')
154
+ PA.request('["set", [["run", "start"]]]')
155
+
156
+ #```````````````The P2Plant seems to be alive`````````````````````````````````
157
+ threading.Thread(target=input_thread, daemon=True).start()
158
+ if pargs.graph == '':
159
+ # No plotting.
160
+ while(1):
161
+ receive_subscription()
162
+ else:
163
+ if not pargs.black:
164
+ pg.setConfigOption('background', 'w')
165
+ pg.setConfigOption('foreground', 'k')
166
+ # the --zoom should be handled prior to QtWidgets.QApplication
167
+ try:
168
+ #print(f'argv: {sys.argv}')
169
+ idx = sys.argv.index('-z')
170
+ zoom = sys.argv[idx+1]
171
+ print(f'Zoom is set to {zoom}')
172
+ os.environ["QT_SCALE_FACTOR"] = zoom
173
+ except Exception as e:
174
+ #print(f'zoom option is not provided: {e}')
175
+ pass
176
+ app = pg.mkQApp()
177
+ plot = pg.plot()
178
+ plot.setWindowTitle('Simulated ADC')
179
+ #print(f'ADC sampling rate: {adc_srate} Hz')
180
+ adc_srate = 1.
181
+ if adc_srate == .9999:
182
+ printw(f'Fail to read ADC sampling rate. It can be recovered using `get adc_srate` command.')
183
+ plot.setLabel('bottom', 'Sample')
184
+ else:
185
+ plot.setLabel('bottom', 'Time', units='S')
186
+ plot.setLabel('left','', units=pargs.yunits)
187
+
188
+ legend = pg.LegendItem((80,60), offset=(70,20))
189
+ legend.setParentItem(plot.graphicsItem())
190
+
191
+ #text = pg.TextItem(html='<div style="text-align: center"><span style="color: #FFF;">This is the</span><br><span style="color: #FF0; font-size: 16pt;">PEAK</span></div>', anchor=(-0.3,0.5), angle=45, border='w', fill=(0, 0, 255, 100))
192
+ TextItem = pg.TextItem('Acquisition started', color='darkBlue', anchor=(0,1))#, ensureInBounds=True)
193
+ TextItem.setParentItem(plot.graphicsItem())
194
+ #plot.addItem(TextItem)
195
+ #width = plot.size().width()
196
+ #print(f'width: {width}')
197
+ TextItem.setPos(40, 20)
198
+
199
+ timer = QtCore.QTimer()
200
+ timer.timeout.connect(receive_subscription)
201
+ timer.start(1)
202
+ app.exec_()
203
+
204
+ if __name__ == "__main__":
205
+ main()
206
+