def read_attributes(self, attrs): """ Reads attribute value, returns none in case of na error :param attr: :return: """ res = [] try: if not self.test(self.device): raise ValueError d = DeviceProxy(self.device) d.ping() self.debug("Device ({}) is online".format(self.device)) state = d.state() values = None # read value only if the state is fine if state != DevState.FAULT and state != DevState.UNKNOWN: values = d.read_attributes(attrs) for value in values: res.append(value.value) self.debug("Attributes value ({}/{}/{})".format(state, attrs, res)) except DevFailed: self.error( "There is an error with access to the device ({})".format( self.device)) except ValueError: self.error("User has not provided a valid device name") return res
def _poll_image(sleep_time, video_device, device_uri, video_mode, formats): from PyTango import DeviceProxy connected = False while not connected: try: logging.getLogger("HWR").info("Connecting to %s", device_uri) lima_tango_device = DeviceProxy(device_uri) lima_tango_device.ping() except Exception as ex: logging.getLogger("HWR").exception("") logging.getLogger("HWR").info( "Could not connect to %s, retrying ...", device_uri) connected = False time.sleep(0.2) else: connected = True while True: try: data = poll_image(lima_tango_device, video_mode, formats)[0] video_device.write(data) except Exception as ex: print(ex) finally: time.sleep(sleep_time / 2)
def poll_image(encoder_input, device_uri, debug, sleep_time): from PyTango import DeviceProxy connected = False while not connected: try: logging.getLogger("HWR").info("Connecting to %s", device_uri) lima_tango_device = DeviceProxy(device_uri) lima_tango_device.ping() except Exception as ex: logging.getLogger("HWR").exception("") logging.getLogger("HWR").info( "Could not connect to %s, retrying ...", device_uri) connected = False time.sleep(0.2) else: connected = True if isinstance(encoder_input, str): encoder_input = open(encoder_input, "wb", 0) # sleep_time = lima_tango_device.video_exposure last_frame_number = -1 dtlist = [] mean_poll_t = sleep_time while True: try: t0 = time.perf_counter() data, width, height, frame_number = get_image(lima_tango_device) if last_frame_number != frame_number: encoder_input.write(data) last_frame_number = frame_number dt = time.perf_counter() - t0 dtlist.append(dt) if len(dtlist) > 25: mean_poll_t = statistics.mean(dtlist) if debug: print("Poll took, %s(s) \n" % mean_poll_t) dtlist = [] except Exception as ex: print(ex) finally: _sleep_time = sleep_time - mean_poll_t if _sleep_time < 0: _sleep_time = 0 time.sleep(_sleep_time)
def make_test(self, attr=None): """ Performs a full test of the tango server device If the attribute is given - trying to read it as well :param attr: :return: """ #@TODO : test database res = True try: d = DeviceProxy(self.device) self.debug("Device ({}) ping value ({})".format( self.device, d.ping())) state = d.state() if state == DevState.FAULT or state == DevState.UNKNOWN: raise DevFailed if self.testString(attr): v = d.read_attribute(attr) except (DevFailed, AttributeError) as e: res = False return res
def ping_to_device(): Log('server asked to ping from device', 'd') global disable_Pytango if disable_Pytango: p = DeviceProxy("sys/tg_test/1") elapsed_time = p.ping() emit("pong from device", {'elapsed': elapsed_time}) Log('client ponged from device', 'd')
def populate_startup_nodes(self): nodes = self.db.nodes print dt.now(), ":", 'populating leaves' for i in nodes.find({'type': 'leaf'}): device = i['name'] + " - " + i['attr'] if device in self.checkedLeaves: continue proxy = DeviceProxy(i['name']) deviceFlag = 1 while deviceFlag: try: proxy.ping() deviceFlag = 0 t = threading.Thread(target=self.aggregate_data, args=([device])) t.start() self.checkedLeaves.append(device) except Exception as ex: print "Warning" + "Start the device server" + device
def run(self): """ Starts a process :return: """ self.debug("Starting a pytango runner ({}/{}/{})".format( self.device, self.attr, self.value)) try: d = DeviceProxy(self.device) d.ping() state = d.state() if state == DevState.FAULT: raise DevFailed d.write_attribute(self.attr, self.value) except DevFailed: self.error("Error with the pytango runner ({}/{}/{})".format( self.device, self.attr, self.value))
def populate_startup_nodes(self): nodes = self.db.nodes print dt.now(), ":", 'populating leaves' for i in nodes.find({'type': 'leaf'}): device = i['name'] + " - " + i['attr'] if device in self.checkedLeaves: continue proxy = DeviceProxy(i['name']) deviceFlag = 1 while deviceFlag: try: proxy.ping() deviceFlag = 0 t = threading.Thread(target=self.aggregate_data, args=([device])) t.start() self.update_tree(self.dataSourcesTreeItem, i['name'], i['attr']) self.checkedLeaves.append(device) except Exception as ex: QtGui.QMessageBox.critical(self, "Warning", "Start the device server " + device) print dt.now(), ":", 'populating branches' for i in nodes.find({'type': 'branch'}): device = i['name'] treeBranch = QtGui.QTreeWidgetItem(self.ui.treeWidget) treeBranch.setText(0, device) for j in i['children']: if '-' in j: temp = j.split(' - ') self.update_tree(treeBranch, temp[0], temp[1]) else: self.update_tree(treeBranch, j, "") t = threading.Thread( target=self.aggregate_branch_data, args=([device])) t.start()
def populate_startup_nodes(self): nodes = self.db.nodes print dt.now(), ":", 'populating leaves' for i in nodes.find({'type': 'leaf'}): device = i['name'] + " - " + i['attr'] if device in self.checkedLeaves: continue proxy = DeviceProxy(i['name']) deviceFlag = 1 while deviceFlag: try: proxy.ping() deviceFlag = 0 t = threading.Thread(target=self.aggregate_data, args=([device])) t.start() self.update_tree(self.dataSourcesTreeItem, i['name'], i['attr']) self.checkedLeaves.append(device) except Exception as ex: QtGui.QMessageBox.critical( self, "Warning", "Start the device server " + device) print dt.now(), ":", 'populating branches' for i in nodes.find({'type': 'branch'}): device = i['name'] treeBranch = QtGui.QTreeWidgetItem(self.ui.treeWidget) treeBranch.setText(0, device) for j in i['children']: if '-' in j: temp = j.split(' - ') self.update_tree(treeBranch, temp[0], temp[1]) else: self.update_tree(treeBranch, j, "") t = threading.Thread(target=self.aggregate_branch_data, args=([device])) t.start()
class TangoTestContext(object): """ Context to run a device without a database.""" nodb = "#dbase=no" command = "{0} {1} -ORBendPoint giop:tcp::{2} -file={3}" connect_time = 6.0 def __init__(self, device, device_cls=None, server_name=None, instance_name=None, device_name=None, properties={}, db=None, port=0, debug=5, daemon=False, process=False): """Inititalize the context to run a given device.""" # Argument tangoclass = device.__name__ if not server_name: server_name = tangoclass if not instance_name: instance_name = server_name.lower() if not device_name: device_name = 'test/nodb/' + server_name.lower() if not port: port = get_port() if db is None: _, db = tempfile.mkstemp() # Attributes self.db = db self.port = port self.device_name = device_name self.server_name = "/".join(("dserver", server_name, instance_name)) self.host = "{0}:{1}/".format(platform.node(), self.port) self.device = self.server = None # File self.generate_db_file(server_name, instance_name, device_name, tangoclass, properties) # Command args string = self.command.format(server_name, instance_name, port, db) string += " -v{0}".format(debug) if debug else "" cmd_args = string.split() # Target and arguments if device_cls: target = run args = ({tangoclass: (device_cls, device)}, cmd_args) elif not hasattr(device, 'run_server'): target = run args = ((device,), cmd_args) else: target = device.run_server args = (cmd_args,) # Thread cls = Process if process else Thread self.thread = cls(target=target, args=args) self.thread.daemon = daemon def generate_db_file(self, server, instance, device, tangoclass=None, properties={}): """Generate a database file corresponding to the given arguments.""" if not tangoclass: tangoclass = server # Open the file with open(self.db, 'w') as f: f.write("/".join((server, instance, "DEVICE", tangoclass))) f.write(': "' + device + '"\n') # Create database db = Database(self.db) # Patched the property dict to avoid a PyTango bug patched = dict((key, value if value != '' else ' ') for key, value in properties.items()) # Write properties db.put_device_property(device, patched) return db def get_device_access(self): """Return the full device name.""" return self.host+self.device_name+self.nodb def get_server_access(self): """Return the full server name.""" return self.host+self.server_name+self.nodb def start(self): """Run the server.""" self.thread.start() self.connect() return self @retry(connect_time, [ConnectionFailed, DevFailed]) def connect(self): self.device = DeviceProxy(self.get_device_access()) self.device.ping() self.server = DeviceProxy(self.get_server_access()) self.server.ping() def stop(self, timeout=None): """Kill the server.""" if self.server: self.server.command_inout('Kill') self.thread.join(timeout) os.unlink(self.db) def join(self, timeout=None): self.thread.join(timeout) def __enter__(self): """Enter method for context support.""" if not self.thread.is_alive(): self.start() return self.device def __exit__(self, exc_type, exception, trace): """Exit method for context support.""" self.stop()
def ping_to_device(): print('server asked to ping from device') p = DeviceProxy("sys/tg_test/1") elapsed_time = p.ping() emit("pong from device", {'elapsed': elapsed_time}) print('client ponged from device')