async def handle(self, msg, type=None): # print(f'%%%%%Instrument.handle: {msg.to_json()}') # handle messages from multiple sources. What ID to use? if (type == 'FromChild' and msg.type == Interface.class_type): id = msg.sender_id dt = self.parse(msg) print(f'dt = {dt}') # print(f'last_entry: {self.last_entry}') # if ( # 'DATETIME' in self.last_entry and # self.last_entry['DATETIME'] == entry['DATA']['DATETIME'] # ): # print(f'88888888888 skipped entry') # return # self.last_entry['DATETIME'] = entry['DATA']['DATETIME'] # print('entry = \n{}'.format(entry)) # TODO: how to deal with record that crosses second bound? if self.current_read_cnt == len(self.current_poll_cmds): # entry['METADATA'] = self.get_metadata() entry = self.get_data_entry(dt, add_meta=False) # print(f'entry: {entry}') data = Message( sender_id=self.get_id(), msgtype=Instrument.class_type, ) # send data to next step(s) # to controller # data.update(subject='DATA', body=entry['DATA']) data.update(subject='DATA', body=entry) # reset read count self.current_read_cnt = 0 # await self.msg_buffer.put(data) # await self.to_parent_buf.put(data) # print(f'instrument data: {data.to_json()}') # await asyncio.sleep(.1) await self.message_to_ui(data) # await PlotManager.update_data(self.plot_name, data.to_json()) # print(f'data_json: {data.to_json()}\n') # await asyncio.sleep(0.01) elif type == 'FromUI': if msg.subject == 'STATUS' and msg.body['purpose'] == 'REQUEST': print(f'msg: {msg.body}') self.send_status() elif msg.subject == 'CONTROLS' and msg.body['purpose'] == 'REQUEST': print(f'msg: {msg.body}') await self.set_control(msg.body['control'], msg.body['value']) elif msg.subject == 'RUNCONTROLS' and msg.body[ 'purpose'] == 'REQUEST': print(f'msg: {msg.body}') await self.handle_control_action(msg.body['control'], msg.body['value'])
async def handle(self, msg, type=None): # print(f'%%%%%Instrument.handle: {msg.to_json()}') # handle messages from multiple sources. What ID to use? if (type == 'FromChild' and msg.type == Interface.class_type): # print(f'aps scan: {msg.to_json()}') # id = msg.sender_id dt = self.parse(msg) if dt: entry = self.get_data_entry(dt) # print(f'entry: {entry}') data = Message( sender_id=self.get_id(), msgtype=Instrument.class_type, ) # send data to next step(s) # to controller data.update(subject='DATA', body=entry) # send data to user interface await self.message_to_ui(data) # send data to controller await self.to_parent_buf.put(data) # save data if self.datafile: await self.datafile.write_message(data) # print(f'data_json: {data.to_json()}\n') # await asyncio.sleep(0.01) # elif type == 'FromUI': # if msg.subject == 'STATUS' and msg.body['purpose'] == 'REQUEST': # # print(f'msg: {msg.body}') # self.send_status() # elif ( # msg.subject == 'CONTROLS' and # msg.body['purpose'] == 'REQUEST' # ): # # print(f'msg: {msg.body}') # await self.set_control(msg.body['control'], msg.body['value']) # elif ( # msg.subject == 'RUNCONTROLS' and # msg.body['purpose'] == 'REQUEST' # ): # # print(f'msg: {msg.body}') # await self.handle_control_action( # msg.body['control'], msg.body['value'] # ) await super().handle(msg, type)
async def poll_loop(self): print(f'polling loop started') # wait for start of next scan period # print(f'Starting scan in {time_to_next(scan_time)} seconds') await asyncio.sleep(time_to_next(self.poll_rate)) while True: # TODO: implement current_poll_cmds # cmds = self.current_poll_cmds # print(f'cmds: {cmds}') # cmds = ['read\n'] if self.iface: # meas_cmd = '#WW44022C06\n' # read_cmd = '#RR4406\n' # cmd = '{ 99RDD}\r' # send read command cmd_args = { 'command': 'write_buffer', 'address': '44', 'write_length': '02', 'data': '2C06' } msg = Message( sender_id=self.get_id(), msgtype=Instrument.class_type, subject='SEND', body=cmd_args, ) # print(f'msg: {msg.body}') await self.iface.message_from_parent(msg) await self.ready_to_read() # send read command cmd_args = { 'command': 'read_buffer', 'address': '44', 'read_length': '06' } msg = Message( sender_id=self.get_id(), msgtype=Instrument.class_type, subject='SEND', body=cmd_args, ) # print(f'msg: {msg.body}') await self.iface.message_from_parent(msg) await asyncio.sleep(time_to_next(self.poll_rate))
async def handle(self, msg, type=None): # print(f'%%%%%Instrument.handle: {msg.to_json()}') # handle messages from multiple sources. What ID to use? if type == "FromChild" and msg.type == Instrument.class_type: # id = msg.sender_id # entry = self.parse(msg) # self.last_entry = entry # print('entry = \n{}'.format(entry)) entry = self.calculate_data(msg) if entry: data = Message( sender_id=self.get_id(), msgtype=Controller.class_type, ) # send data to next step(s) # to controller # data.update(subject='DATA', body=entry['DATA']) data.update(subject="DATA", body=entry) # print(f'instrument data: {data.to_json()}') await self.message_to_ui(data) if self.datafile: await self.datafile.write_message(data) # await asyncio.sleep(.1) # await PlotManager.update_data(self.plot_name, data.to_json()) # print(f'data_json: {data.to_json()}\n') # elif type == "FromUI": # if msg.subject == "STATUS" and msg.body["purpose"] == "REQUEST": # # print(f"msg: {msg.body}") # self.send_status() # elif msg.subject == "CONTROLS" and msg.body["purpose"] == "REQUEST": # # print(f"msg: {msg.body}") # await self.set_control(msg.body["control"], msg.body["value"]) # elif msg.subject == "RUNCONTROLS" and msg.body["purpose"] == "REQUEST": # # print(f"msg: {msg.body}") # await self.handle_control_action(msg.body["control"], msg.body["value"]) # # await self.set_control(msg.body['control'], msg.body['value']) # elif msg.subject == "REGISTRATION": # print(f"reg: {msg.subject}") # if msg.body["purpose"] == "SUCCESS": # self.registration_key = msg.body["regkey"] # # if content["BODY"]["config"]: # # self.config = content["BODY"]["config"] # # self.save_current_config(json.loads(content["BODY"]["config"])) # self.status2.set_registration_status(Status.REGISTERED) # # if content["BODY"]["ui_reconfig_request"]: # # await self.resend_config_to_ui() await super().handle(msg, type)
async def poll_loop(self): print("polling loop started") await self.toggle_mcpc_power(power=1) iface = None if self.iface_components["default"]: if_id = self.iface_components["default"] dt = util.get_timestamp() cmd_list = [ f"clkyear={datetime.strftime(dt, '%y')}\n", f"clk_mon={datetime.strftime(dt, '%m')}\n", f"clk_day={datetime.strftime(dt, '%d')}\n", f"clkhour={datetime.strftime(dt, '%H')}\n", f"clk_min={datetime.strftime(dt, '%M')}\n", f"clk_sec={datetime.strftime(dt, '%S')}\n", ] for cmd in cmd_list: msg = Message( sender_id=self.get_id(), msgtype=Instrument.class_type, subject="SEND", body=cmd, ) await self.iface_map[if_id].message_from_parent(msg) await asyncio.sleep(0.1) while True: if self.do_polling: # TODO: implement current_poll_cmds # cmds = self.current_poll_cmds # print(f'cmds: {cmds}') # cmds = ['read\n'] # print("poll") # if self.iface: if self.iface_components["default"]: if_id = self.iface_components["default"] cmds = [self.poll_read_cmd+"\n"] for cmd in cmds: msg = Message( sender_id=self.get_id(), msgtype=Instrument.class_type, subject="SEND", body=cmd, ) # print(f'msg: {msg.to_json()}') await self.iface_map[if_id].message_from_parent(msg) await asyncio.sleep(time_to_next(self.poll_rate))
async def send_data(path, data): try: # message = data["message"] message = Message() message.from_json(json.dumps(data)) datafile = DataManager.get_datafile(path) if message and datafile: await datafile.write_message(message) else: print(f'DataManager.send_data: no DataFile at {path} for:\n {data}') except: print('DataManager.send_data: data does not contain a message')
async def send_data(client): while True: body = 'fake message - {}'.format( datetime.utcnow().isoformat(timespec='seconds')) msg = {'message': body} message = Message(msgtype='Test', sender_id='me', subject='test', body=msg) # print('send_data: {}'.format(msg)) print('send_data: {}'.format(message.to_json())) # await client.send(json.dumps(msg)) await client.send_message(message) await asyncio.sleep(1)
async def poll_loop(self): print(f'polling loop started') while True: # TODO: implement current_poll_cmds cmds = self.current_poll_cmds print(f'cmds: {cmds}') # cmds = ['read\n'] if self.iface: self.current_read_cnt = 0 for cmd in cmds: msg = Message( sender_id=self.get_id(), msgtype=Instrument.class_type, subject='SEND', body=cmd, ) print(f'msg: {msg}') await self.iface.message_from_parent(msg) # for k, iface in self.iface_map.items(): # for cmd in cmds: # msg = Message( # sender_id=self.get_id(), # msgtype=Instrument.class_type, # subject='SEND', # body=cmd, # ) # print(f'msg: {msg}') # await iface.message_from_parent(msg) await asyncio.sleep(time_to_next(self.poll_rate))
async def poll_loop(self): print('polling loop started') # wait for start of next scan period # print(f'Starting scan in {time_to_next(self.poll_rate)} seconds') await asyncio.sleep(time_to_next(self.poll_rate)) while True: # TODO: implement current_poll_cmds # cmds = self.current_poll_cmds # print(f'cmds: {cmds}') # cmds = ['read\n'] if self.iface: cmd = '{ 99RDD}\r' msg = Message( sender_id=self.get_id(), msgtype=Instrument.class_type, subject='SEND', body=cmd, ) # print(f'msg: {msg.body}') await self.iface.message_from_parent(msg) await asyncio.sleep(time_to_next(self.poll_rate))
async def deregister_from_UI(self): # ui_config = self.ui_config # ui_ws_address = f'ws://{ui_config["host"]}:{ui_config["port"]}/' # ui_ws_address += "ws/envdaq/daqserver/register" # self.reg_client = WSClient(uri=ui_ws_address) # while self.reg_client.isConnected() is not True: # # print(f'waiting for is_conncted {self.ui_client.isConnected()}') # # self.gui_client = WSClient(uri=gui_ws_address) # # print(f"gui client: {self.gui_client.isConnected()}") # await asyncio.sleep(1) req = Message( sender_id=self.get_id(), msgtype=Controller.class_type, subject="REGISTRATION", body={ "purpose": "REMOVE", "regkey": self.registration_key, # "id": self.daq_id, "namespace": self.namespace.to_dict(), # "config": self.config, }, ) print(f"Unregistering with UI server: {self.namespace.to_dict()}") await self.to_ui_buf.put(req) self.run_state = "UNREGISTERING" self.status2.set_run_status(Status.UNREGISTERING)
async def to_ui_loop(self): # con_msg = ConnectorMessage( # address=self.ui_address, # id='/a/b/c', # body='test', # ) # body = f'{con_msg.to_json()}\n' # test = Message( # sender_id=self.get_id(), # msgtype=Connector.class_type, # subject='SEND', # body=body, # ) # print(f'test msg: {test.to_json()}') # await self.iface.message_from_parent(test) while True: con_msg = await self.to_ui_buf.get() body = f'{con_msg.to_json()}\n' msg = Message( sender_id=self.get_id(), msgtype=Connector.class_type, subject='SEND', body=body, ) # print(f'msg: {msg.to_json()}') await self.iface.message_from_parent(msg)
async def deregister_from_UI(self): # print(f'config: {json.dumps(self.config)}') req = Message( sender_id="daq_server", msgtype="DAQServer", subject="REGISTRATION", body={ "purpose": "REMOVE", "regkey": self.registration_key, "namespace": self.namespace.to_dict(), # "id": self.daq_id, # "uri": self.uri, # "namespace": self.namespace, # "config": self.config, # "config2": json.dumps(self.config), # "status": self.status2 }, ) print( f"Deregistering FROM UI server: {self.namespace.get_namespace_sig()}" ) # self.status2.set_registration_status(Status.UNREGISTERING) await self.to_ui_buf.put(req) self.status2.set_registration_status(Status.UNREGISTERING) self.run_state = "UNREGISTERING"
async def handle_control_action(self, control, value): if control and value is not None: # print(f"msems control action: {control}, {value}") if control == "start_stop": # if value == "START": # self.start() # elif value == "STOP": # self.stop() # self.set_control_att(control, "action_state", "OK") await super(aMCPC, self).handle_control_action(control, value) else: try: # print( # f'send command to msems: {self.controls[control]["parse_label"]}={value}' # ) if self.iface_components["default"]: if_id = self.iface_components["default"] cmd = f'{self.controls[control]["parse_label"]}={value}\n' # print(f"msems control: {cmd.strip()}") # cmd = "msems_mode=2\n" msg = Message( sender_id=self.get_id(), msgtype=Instrument.class_type, subject="SEND", body=cmd, ) await self.iface_map[if_id].message_from_parent(msg) self.set_control_att(control, "action_state", "OK") except KeyError: print(f"can't set {control}") self.set_control_att(control, "action_state", "NOT_OK")
async def handle(self, msg, type=None): # print(f'%%%%%Instrument.handle: {msg.to_json()}') # handle messages from multiple sources. What ID to use? if (type == 'FromChild' and msg.type == Interface.class_type): id = msg.sender_id entry = self.parse(msg) # print(f'last_entry: {self.last_entry}') # if ( # 'DATETIME' in self.last_entry and # self.last_entry['DATETIME'] == entry['DATA']['DATETIME'] # ): # print(f'88888888888 skipped entry') # return # self.last_entry['DATETIME'] = entry['DATA']['DATETIME'] # print('entry = \n{}'.format(entry)) data = Message( sender_id=self.get_id(), msgtype=Instrument.class_type, ) # send data to next step(s) # to controller # data.update(subject='DATA', body=entry['DATA']) data.update(subject='DATA', body=entry) # await self.msg_buffer.put(data) # await self.to_parent_buf.put(data) # print(f'instrument data: {data.to_json()}') await self.message_to_ui(data) # await PlotManager.update_data(self.plot_name, data.to_json()) # print(f'data_json: {data.to_json()}\n') # await asyncio.sleep(0.01) elif type == 'FromUI': if msg.subject == 'STATUS' and msg.body['purpose'] == 'REQUEST': print(f'msg: {msg.body}') self.send_status() elif msg.subject == 'CONTROLS' and msg.body['purpose'] == 'REQUEST': print(f'msg: {msg.body}') await self.set_control(msg.body['control'], msg.body['value']) elif msg.subject == 'RUNCONTROLS' and msg.body[ 'purpose'] == 'REQUEST': print(f'msg: {msg.body}') await self.handle_control_action(msg.body['control'], msg.body['value'])
async def send_data(client): while True: body = 'read' msg = {'message': body} message = Message(msgtype='Test', sender_id='me', subject='cmd', body=msg) # print('send_data: {}'.format(msg)) print('send_data: {}'.format(message.to_json())) # await client.send(json.dumps(msg)) # await client.send('rtclck\n') await client.send('read\n') await client.send('raw=2\n') # await client.send_message(message) await asyncio.sleep(1)
async def configure_daq(self): # should check/read file every second. If no cfg_fetch_freq = 2 # seconds cfg_fetch_time = 5 # seconds cfg_fetch_current = 6 # force try on first loop print("set self.config") while not self.config: self.status2.set_config_status(Status.CONFIGURING) self.read_current_config() if False: # if self.config: # print(f"self.config: {self.config}") if not self.config and (cfg_fetch_current > cfg_fetch_time): # get config from gui print("Getting config from gui") req = Message( sender_id="daqserver", msgtype="DAQServer", subject="CONFIG", body={ "purpose": "REQUEST", "type": "ENVDAQ_CONFIG", "server_name": self.server_name, }, ) await self.to_ui_buf.put(req) cfg_fetch_current = 0 await asyncio.sleep(1) cfg_fetch_current += 1 # await asyncio.sleep(cfg_fetch_freq) # increase time between requests to avoid traffic cfg_fetch_freq += 1 if cfg_fetch_freq > 30: cfg_fetch_freq = 30 # print("Create message buffers...") # self.create_msg_buffer() # self.status2.set_config_status(Status.CONFIGURED) # print("Add controllers...") # self.add_controllers() if self.config: self.status2.set_config_status(Status.CONFIGURED) # self.run_state = "READY_TO_RUN" # reset back to original cfg_fetch_freq = 2
async def read_data(self): while True: data = await self.client.read() msg = Message(sender_id=self.get_id(), msgtype=IFDevice.class_type, subject='DATA', body={'DATA': data}) # print(f'serialportread: {data}') # await self.message_to_parent(msg) await self.message_to_parents(msg)
async def handle(self, msg, type=None): # print(f'%%%%% MAGIC210.handle: {msg.to_json()}') if type == "FromChild" and msg.type == Interface.class_type: dt = self.parse(msg) # print(f'dt = {dt}') if dt: entry = self.get_data_entry(dt) data = Message( sender_id=self.get_id(), msgtype=Instrument.class_type, ) data.update(subject="DATA", body=entry) await self.message_to_ui(data) await super().handle(msg, type)
async def handle(self, msg, type=None): # print(f'%%%%%Instrument.handle: {msg.to_json()}') # handle messages from multiple sources. What ID to use? if type == "FromChild" and msg.type == Instrument.class_type: # id = msg.sender_id # entry = self.parse(msg) # self.last_entry = entry # print('entry = \n{}'.format(entry)) entry = self.calculate_data(msg) if entry: data = Message( sender_id=self.get_id(), msgtype=Controller.class_type, ) # send data to next step(s) # to controller # data.update(subject='DATA', body=entry['DATA']) data.update(subject="DATA", body=entry) # print(f'instrument data: {data.to_json()}') await self.message_to_ui(data) if self.datafile: await self.datafile.write_message(data) # await PlotManager.update_data(self.plot_name, data.to_json()) # print(f'data_json: {data.to_json()}\n') elif type == "FromUI": if msg.subject == "STATUS" and msg.body["purpose"] == "REQUEST": print(f"msg: {msg.body}") self.send_status() elif msg.subject == "CONTROLS" and msg.body["purpose"] == "REQUEST": print(f"msg: {msg.body}") await self.set_control(msg.body["control"], msg.body["value"]) elif msg.subject == "RUNCONTROLS" and msg.body[ "purpose"] == "REQUEST": print(f"msg: {msg.body}") await self.handle_control_action(msg.body["control"], msg.body["value"])
async def send_settings_to_ui(self): if self.current_run_settings: settings = Message( sender_id=self.get_id(), msgtype=self.class_type, subject="SETTINGS", body={ "purpose": "UPDATE", "settings": self.current_run_settings, # 'note': note, }, ) await self.message_to_ui(settings)
async def send_status(self): # for now, only done by request but we could do like ping msg = Message( sender_id="DAQ_SERVER", msgtype="DAQServerStatus", subject="DAQServerStatus", body={ # "id": self.daq_id "purpose": "UPDATE", "status": self.status2.to_dict(), }, ) await self.to_ui_buf.put(msg)
def send_status(self, note=""): # print(f'send_status: {self.name}, {self.status}') status = Message( sender_id=self.get_id(), msgtype="GENERIC", subject="STATUS", body={ "purpose": "UPDATE", "status": self.status, # 'note': note, }, ) status = self.status2.to_message(sender_id=self.get_id()) # print(f'send no wait: {self.name}, {self.status}') self.message_to_ui_nowait(status)
async def handle2(self, data): # def handle2(self, data): out = {'DATA': data} # print(out) # msg = Message(subject='DATA', body=out) msg = Message(sender_id=self.get_id(), msgtype=IFDevice.class_type, subject='DATA', body=out) # print(msg.to_dict()) # print(msg.to_json()) # self.msg_send_buffer.put_nowait(msg) # print(f'to parent: {msg.to_json()}') # await self.message_to_parent(msg) await self.message_to_parents(msg)
async def to_server_loop(self): while True: con_msg = await self.from_ui_buf.get() # msg = ConnectorMessage() # msg.from_json(con_msg) # con_msg = msg.body body = f'{con_msg.to_json()}\n' msg = Message( sender_id=self.get_id(), msgtype=Connector.class_type, subject='SEND', body=body, ) # print(f'msg: {msg.to_json()}') await self.iface.message_from_parent(msg)
async def send_ready_to_ui(self): status = Message( sender_id="DAQ_SERVER", msgtype="GENERIC", subject="READY_STATE", body={ "purpose": "STATUS", "status": "READY", "namespace": self.namespace.to_dict(), # 'note': note, }, ) # print(f"_____ send no wait _____: {status.to_json()}") # print(f"** daq_server ({self.namespace['daq_server']}) ready") print(f"** daq_server ({self.namespace.get_namespace_sig()}) ready") await self.to_ui_buf.put(status)
async def ping_ui_server(self): # wait for things to get started before pinging await asyncio.sleep(5) while self.ui_client.isConnected(): msg = Message( sender_id=self.get_id(), msgtype="PING", subject="PING", body={ # "id": self.daq_id "namespace": self.namespace.to_dict() }, ) await self.to_ui_buf.put(msg) await asyncio.sleep(2)
def send_config_to_ui(self): # add namespace to metadata meta = self.get_metadata() # meta["namespace"] = self.namespace.to_dict() # tell ui to build controller msg = Message( sender_id=self.get_id(), msgtype="Controller", subject="CONFIG", body={ "purpose": "SYNC", "type": "CONTROLLER_INSTANCE", # TODO: controller needs metadata "data": meta, }, ) self.message_to_ui_nowait(msg)
def to_message(self, sender_id=None): if sender_id: # status_dict = dict() # for st in self.status_types: # status_dict[st] = self.get_status(st) msg = Message( sender_id=sender_id, msgtype='GENERIC', subject="STATUS", body={ 'purpose': 'UPDATE', 'status': self.to_dict() # 'status_object': self # 'note': note, } ) return msg
async def update_settings_loop(self): # print(f'send_status: {self.name}, {self.status}') if not self.current_run_settings: self.get_current_run_settings() while True: # while self.current_run_settings: if self.status2.get_run_status() in [Status.READY_TO_RUN, Status.STOPPED]: settings = Message( sender_id=self.get_id(), msgtype=self.class_type, subject="SETTINGS", body={ "purpose": "UPDATE", "settings": self.current_run_settings, # 'note': note, }, ) await self.message_to_ui(settings) await asyncio.sleep(2)
async def stop_logging(self): if self.iface: # if self.iface_components["default"]: # if_id = self.iface_components["default"] # self.current_read_cnt = 0 # await asyncio.sleep(0.1) # Start logging cmd = "Log,0\n" msg = Message( sender_id=self.get_id(), msgtype=Instrument.class_type, subject="SEND", body=cmd, ) # print(f'msg: {msg}') # await self.iface.message_from_parent(msg) # await self.iface_map[if_id].message_from_parent(msg) await self.iface.message_from_parent(msg)