def require(self, mnemonicsList):
        """Download a list of Hardware Objects in one go"""
        self.requiredHardwareObjects = {}

        if not self.server:
            return

        try:
            t0 = time.time()
            mnemonics = ",".join([repr(mne) for mne in mnemonicsList])
            if len(mnemonics) > 0:
                self.requiredHardwareObjects = SpecWaitObject.waitReply(
                    self.server,
                    "send_msg_cmd_with_return",
                    ("xml_getall(%s)" % mnemonics,),
                    timeout=3,
                )
                logging.getLogger("HWR").debug(
                    "Getting %s hardware objects took %s ms."
                    % (len(self.requiredHardwareObjects), (time.time() - t0) * 1000)
                )
        except SpecClientError.SpecClientTimeoutError:
            logging.getLogger("HWR").error("Timeout loading Hardware Objects")
        except BaseException:
            logging.getLogger("HWR").exception(
                "Could not execute 'require' on Hardware Repository server"
            )
    def require(self, mnemonicsList):
        """Download a list of Hardware Objects in one go"""
        self.requiredHardwareObjects = {}

        if not self.server:
            return

        try:
            t0 = time.time()
            mnemonics = ",".join([repr(mne) for mne in mnemonicsList])
            if len(mnemonics) > 0:
                self.requiredHardwareObjects = SpecWaitObject.waitReply(
                    self.server,
                    "send_msg_cmd_with_return",
                    ("xml_getall(%s)" % mnemonics, ),
                    timeout=3,
                )
                logging.getLogger("HWR").debug(
                    "Getting %s hardware objects took %s ms." %
                    (len(self.requiredHardwareObjects),
                     (time.time() - t0) * 1000))
        except SpecClientError.SpecClientTimeoutError:
            logging.getLogger("HWR").error("Timeout loading Hardware Objects")
        except Exception:
            logging.getLogger("HWR").exception(
                "Could not execute 'require' on Hardware Repository server")
예제 #3
0
    def getHardwareRepositoryFiles(self, startdir = '/'):
        #TODO: when server is not used
        if not self.server:
            return

        try:
            completeFilesList = SpecWaitObject.waitReply(self.server, 'send_msg_chan_read', ('readDirectory()', ), timeout = 3)
        except:
            logging.getLogger('HWR').error('Cannot retrieve Hardware Repository files list')
        else:
            if '__error__' in completeFilesList:
                logging.getLogger('HWR').error('Error while doing Hardware Repository files list')
                return
            else:
                for name, filename in completeFilesList.items():
                    if name.startswith(startdir):
                        yield (name, filename)
    def getHardwareRepositoryFiles(self, startdir="/"):
        # TODO: when server is not used
        if not self.server:
            return

        try:
            completeFilesList = SpecWaitObject.waitReply(
                self.server, "send_msg_chan_read", ("readDirectory()",), timeout=3
            )
        except:
            logging.getLogger("HWR").error("Cannot retrieve Hardware Repository files list")
        else:
            if "__error__" in completeFilesList:
                logging.getLogger("HWR").error("Error while doing Hardware Repository files list")
                return
            else:
                for name, filename in completeFilesList.items():
                    if name.startswith(startdir):
                        yield (name, filename)
    def getHardwareRepositoryFiles(self, startdir="/"):
        # TODO: when server is not used
        if not self.server:
            return

        try:
            completeFilesList = SpecWaitObject.waitReply(self.server,
                                                         "send_msg_chan_read",
                                                         ("readDirectory()", ),
                                                         timeout=3)
        except Exception:
            logging.getLogger("HWR").error(
                "Cannot retrieve Hardware Repository files list")
        else:
            if "__error__" in completeFilesList:
                logging.getLogger("HWR").error(
                    "Error while doing Hardware Repository files list")
                return
            else:
                for name, filename in completeFilesList.items():
                    if name.startswith(startdir):
                        yield (name, filename)
예제 #6
0
    def loadHardwareObject(self, hoName):               
        """Load a Hardware Object
        
        Parameters :
          hoName -- string name of the Hardware Object to load, for example '/motors/m0'

        Return :
          the loaded Hardware Object, or None if it fails
        """
        if self.server:
          if self.server.isSpecConnected():
            try:
                #t0=time.time()
                if hoName in self.requiredHardwareObjects:
                    replyDict = self.requiredHardwareObjects[hoName]
                    #del self.requiredHardwareObjects[hoName]
                else:
                    replyDict = SpecWaitObject.waitReply(self.server, 'send_msg_chan_read', ('xml_get("%s")' % hoName, ), timeout = 3)
            except:
                logging.getLogger('HWR').exception('Could not load Hardware Object "%s"', hoName)
            else:
                #print 'loading %s took %s ms' % (hoName, 1000*(time.time()-t0))
                try:
                  xmldata = replyDict['xmldata']
                  mtime = int(replyDict['mtime'])
                except KeyError:
                  logging.getLogger("HWR").error("Cannot load Hardware Object %s: file does not exist.", hoName)
                  return
          else:
            logging.getLogger('HWR').error('Cannot load Hardware Object "%s" : not connected to server.', hoName)
        else:
            xmldata = ""
            for xml_files_path in self.serverAddress:
               file_name = hoName[1:] if hoName.startswith(os.path.sep) else hoName
               file_path = os.path.join(xml_files_path, file_name)+os.path.extsep+"xml"
               if os.path.exists(file_path):
                 try:
                   xmldata = open(file_path, "r").read()
                 except:
                   pass
                 break 

        if True:
                if len(xmldata) > 0:
                    try:
                        #t0 = time.time()
                        ho = self.parseXML(xmldata, hoName)
                        #print 'parsing %s took %s ms' % (hoName, (time.time()-t0)*1000)
                    except:
                        logging.getLogger("HWR").exception("Cannot parse XML file for Hardware Object %s", hoName)
                    else:
                        if ho is not None:
                            self.xml_source[hoName]=xmldata
                            dispatcher.send('hardwareObjectLoaded', hoName, self)

                            def hardwareObjectDeleted(name=ho.name()):
                                logging.getLogger("HWR").debug("%s Hardware Object has been deleted from Hardware Repository", name)
                                del self.hardwareObjects[name]

                            ho.resolveReferences()

                            try:
                                def addChannelsAndCommands(node):
                                  #import pdb; pdb.set_trace()
                                  if isinstance(node, BaseHardwareObjects.CommandContainer):
                                     node._addChannelsAndCommands()
                                  for child_node in node:
                                    addChannelsAndCommands(child_node)
                                addChannelsAndCommands(ho) 
                            except:
                                logging.getLogger('HWR').exception("Error while adding commands and/or channels to Hardware Object %s", hoName)

                            try:
                                ho._init()
                                ho.init()
                            except:
                                logging.getLogger('HWR').exception('Cannot initialize Hardware Object "%s"', hoName)

                                self.invalidHardwareObjects.add(ho.name())

                                return None
                            else:
                                if ho.name() in self.invalidHardwareObjects:
                                    self.invalidHardwareObjects.remove(ho.name())

                                self.hardwareObjects[ho.name()] = ho

                            return ho
                        else:
                            logging.getLogger("HWR").error("Failed to load Hardware Object %s", hoName)
                else:
                    logging.getLogger('HWR').error('Cannot load Hardware Object "%s" : file not found.', hoName)   
    def loadHardwareObject(self, hwobj_name=""):
        """
        Load a Hardware Object

        :param hwobj_name:  string name of the Hardware Object to load, for example '/motors/m0'
        :return: the loaded Hardware Object, or None if it fails
        """

        comment = ""
        class_name = ""
        hwobj_instance = None

        if self.server:
            if self.server.isSpecConnected():
                try:
                    if hwobj_name in self.requiredHardwareObjects:
                        reply_dict = self.requiredHardwareObjects[hwobj_name]
                    else:
                        reply_dict = SpecWaitObject.waitReply(
                            self.server,
                            "send_msg_chan_read",
                            ('xml_get("%s")' % hwobj_name,),
                            timeout=3,
                        )
                except BaseException:
                    logging.getLogger("HWR").exception(
                        'Could not load Hardware Object "%s"' % hwobj_name
                    )
                else:
                    try:
                        # TODO Both variables not used: remove?
                        xml_data = reply_dict["xmldata"]
                        mtime = int(reply_dict["mtime"])
                    except KeyError:
                        logging.getLogger("HWR").error(
                            "Cannot load Hardware Object %s: file does not exist."
                            % hwobj_name
                        )
                        return
            else:
                logging.getLogger("HWR").error(
                    'Cannot load Hardware Object "%s" : not connected to server.'
                    % hwobj_name
                )
        else:
            xml_data = ""
            for xml_files_path in self.serverAddress:
                file_name = (
                    hwobj_name[1:] if hwobj_name.startswith(os.path.sep) else hwobj_name
                )
                file_path = (
                    os.path.join(xml_files_path, file_name) + os.path.extsep + "xml"
                )
                if os.path.exists(file_path):
                    try:
                        xml_data = open(file_path, "r").read()
                    except BaseException:
                        pass
                    break

        start_time = datetime.now()

        if len(xml_data) > 0:
            try:
                hwobj_instance = self.parseXML(xml_data, hwobj_name)
                if isinstance(hwobj_instance, string_types):
                    return self.loadHardwareObject(hwobj_instance)
            except BaseException:
                comment = "Cannot parse xml"
                logging.getLogger("HWR").exception(
                    "Cannot parse XML file for Hardware Object %s", hwobj_name
                )
            else:
                if hwobj_instance is not None:
                    self.xml_source[hwobj_name] = xml_data
                    dispatcher.send("hardwareObjectLoaded", hwobj_name, self)

                    def hardwareObjectDeleted(name=hwobj_instance.name()):
                        logging.getLogger("HWR").debug(
                            "%s Hardware Object has been deleted from Hardware Repository",
                            name,
                        )
                        del self.hardwareObjects[name]

                    hwobj_instance.resolveReferences()

                    try:
                        hwobj_instance._addChannelsAndCommands()
                    except BaseException:
                        logging.getLogger("HWR").exception(
                            "Error while adding commands and/or channels to Hardware Object %s",
                            hwobj_name,
                        )
                        comment = "Failed to add all commands and/or channels"

                    try:
                        hwobj_instance._init()
                        hwobj_instance.init()
                        class_name = str(hwobj_instance.__module__)
                    except BaseException:
                        logging.getLogger("HWR").exception(
                            'Cannot initialize Hardware Object "%s"', hwobj_name
                        )
                        self.invalidHardwareObjects.add(hwobj_instance.name())
                        hwobj_instance = None
                        comment = "Failed to init class"
                    else:
                        if hwobj_instance.name() in self.invalidHardwareObjects:
                            self.invalidHardwareObjects.remove(hwobj_instance.name())

                        self.hardwareObjects[hwobj_instance.name()] = hwobj_instance
                else:
                    logging.getLogger("HWR").error(
                        "Failed to load Hardware object %s", hwobj_name
                    )
                    comment = "Loading failed"
        else:
            logging.getLogger("HWR").error(
                'Cannot load Hardware Object "%s" : file not found.', hwobj_name
            )

        end_time = datetime.now()
        time_delta = end_time - start_time

        self.hwobj_info_list.append(
            (
                hwobj_name,
                class_name,
                "%d ms" % (time_delta.microseconds / 1000),
                comment,
            )
        )

        return hwobj_instance
    def _loadHardwareObject(self, hwobj_name=""):
        """
        Load a Hardware Object. Do NOT use externally,
        as this will mess up object tracking, signals, etc.

        :param hwobj_name:  string name of the Hardware Object to load, e.g. /motors/m0
        :return: the loaded Hardware Object, or None if it fails
        """

        comment = ""
        class_name = ""
        hwobj_instance = None

        if self.server:
            if self.server.isSpecConnected():
                try:
                    if hwobj_name in self.requiredHardwareObjects:
                        reply_dict = self.requiredHardwareObjects[hwobj_name]
                    else:
                        reply_dict = SpecWaitObject.waitReply(
                            self.server,
                            "send_msg_chan_read",
                            ('xml_get("%s")' % hwobj_name, ),
                            timeout=3,
                        )
                except Exception:
                    logging.getLogger("HWR").exception(
                        'Could not load Hardware Object "%s"', hwobj_name)
                else:
                    try:
                        # TODO Both variables not used: remove?
                        xml_data = reply_dict["xmldata"]
                        mtime = int(reply_dict["mtime"])
                    except KeyError:
                        logging.getLogger("HWR").error(
                            "Cannot load Hardware Object %s: file does not exist.",
                            hwobj_name,
                        )
                        return
            else:
                logging.getLogger("HWR").error(
                    'Cannot load Hardware Object "%s" : not connected to server.',
                    hwobj_name,
                )
        else:
            xml_data = ""
            for xml_files_path in self.serverAddress:
                file_name = (hwobj_name[1:] if hwobj_name.startswith(
                    os.path.sep) else hwobj_name)
                file_path = (os.path.join(xml_files_path, file_name) +
                             os.path.extsep + "xml")
                if os.path.exists(file_path):
                    try:
                        xml_data = open(file_path, "r").read()
                    except Exception:
                        pass
                    break

        start_time = datetime.now()

        if xml_data:
            try:
                hwobj_instance = self.parseXML(xml_data, hwobj_name)
                if isinstance(hwobj_instance, string_types):
                    # We have redirection to another file
                    # Enter in dictionaries also under original names
                    result = self._loadHardwareObject(hwobj_instance)
                    if hwobj_name in self.invalidHardwareObjects:
                        self.invalidHardwareObjects.remove(hwobj_name)
                    self.hardwareObjects[hwobj_name] = result
                    return result
            except Exception:
                comment = "Cannot parse xml"
                logging.getLogger("HWR").exception(
                    "Cannot parse XML file for Hardware Object %s", hwobj_name)
            else:
                if hwobj_instance is not None:
                    self.xml_source[hwobj_name] = xml_data
                    dispatcher.send("hardwareObjectLoaded", hwobj_name, self)

                    def hardwareObjectDeleted(name=hwobj_instance.name()):
                        logging.getLogger("HWR").debug(
                            "%s Hardware Object has been deleted from Hardware Repository",
                            name,
                        )
                        del self.hardwareObjects[name]

                    hwobj_instance.resolveReferences()

                    try:
                        hwobj_instance._add_channels_and_commands()
                    except Exception:
                        logging.getLogger("HWR").exception(
                            "Error while adding commands and/or channels to Hardware Object %s",
                            hwobj_name,
                        )
                        comment = "Failed to add all commands and/or channels"

                    try:
                        hwobj_instance._init()
                        hwobj_instance.init()
                        class_name = str(hwobj_instance.__module__)
                    except Exception:
                        logging.getLogger("HWR").exception(
                            'Cannot initialize Hardware Object "%s"',
                            hwobj_name)
                        self.invalidHardwareObjects.add(hwobj_instance.name())
                        hwobj_instance = None
                        comment = "Failed to init class"
                    else:
                        if hwobj_instance.name(
                        ) in self.invalidHardwareObjects:
                            self.invalidHardwareObjects.remove(
                                hwobj_instance.name())

                        self.hardwareObjects[
                            hwobj_instance.name()] = hwobj_instance
                else:
                    logging.getLogger("HWR").error(
                        "Failed to load Hardware object %s", hwobj_name)
                    comment = "Loading failed"
        else:
            logging.getLogger("HWR").error(
                'Cannot load Hardware Object "%s" : file not found.',
                hwobj_name)

        end_time = datetime.now()
        time_delta = end_time - start_time

        self.hwobj_info_list.append((
            hwobj_name,
            class_name,
            "%d ms" % (time_delta.microseconds / 1000),
            comment,
        ))

        return hwobj_instance
    def loadHardwareObject(self, hwobj_name=""):
        """
        Load a Hardware Object

        :param hwobj_name:  string name of the Hardware Object to load, for example '/motors/m0'
        :return: the loaded Hardware Object, or None if it fails
        """

        comment = ""
        class_name = ""
        hwobj_instance = None

        if self.server:
            if self.server.isSpecConnected():
                try:
                    if hwobj_name in self.requiredHardwareObjects:
                        reply_dict = self.requiredHardwareObjects[hwobj_name]
                    else:
                        reply_dict = SpecWaitObject.waitReply(
                            self.server,
                            'send_msg_chan_read',
                            ('xml_get("%s")' % hwobj_name, ),
                            timeout=3)
                except:
                    logging.getLogger('HWR').exception(
                        'Could not load Hardware Object "%s"' % hwobj_name)
                else:
                    try:
                        #TODO Both variables not used: remove?
                        xml_data = reply_dict['xmldata']
                        mtime = int(reply_dict['mtime'])
                    except KeyError:
                        logging.getLogger("HWR").error(
                            "Cannot load Hardware Object %s: file does not exist."
                            % hwobj_name)
                        return
            else:
                logging.getLogger('HWR').error(
                    'Cannot load Hardware Object "%s" : not connected to server.'
                    % hwobj_name)
        else:
            xml_data = ""
            for xml_files_path in self.serverAddress:
                file_name = hwobj_name[1:] if hwobj_name.startswith(
                    os.path.sep) else hwobj_name
                file_path = os.path.join(xml_files_path, file_name) + \
                            os.path.extsep + \
                            "xml"
                if os.path.exists(file_path):
                    try:
                        xml_data = open(file_path, "r").read()
                    except:
                        pass
                    break

        start_time = datetime.now()

        if len(xml_data) > 0:
            try:
                hwobj_instance = self.parseXML(xml_data, hwobj_name)
                if type(hwobj_instance) == str:
                    return self.loadHardwareObject(hwobj_instance)
            except:
                comment = "Cannot parse xml"
                logging.getLogger("HWR").exception(
                    "Cannot parse XML file for Hardware Object %s", hwobj_name)
            else:
                if hwobj_instance is not None:
                    self.xml_source[hwobj_name] = xml_data
                    dispatcher.send('hardwareObjectLoaded', hwobj_name, self)

                    def hardwareObjectDeleted(name=hwobj_instance.name()):
                        logging.getLogger("HWR").debug(
                            "%s Hardware Object has been deleted from Hardware Repository",
                            name)
                        del self.hardwareObjects[name]

                    hwobj_instance.resolveReferences()

                    try:
                        hwobj_instance._addChannelsAndCommands()
                    except:
                        logging.getLogger('HWR').exception(
                            "Error while adding commands and/or channels to Hardware Object %s",
                            hwobj_name)
                        comment = "Failed to add all commands and/or channels"

                    try:
                        hwobj_instance._init()
                        hwobj_instance.init()
                        class_name = str(hwobj_instance.__module__)
                    except:
                        logging.getLogger('HWR').exception(
                            'Cannot initialize Hardware Object "%s"',
                            hwobj_name)
                        self.invalidHardwareObjects.add(hwobj_instance.name())
                        hwobj_instance = None
                        comment = "Failed to init class"
                    else:
                        if hwobj_instance.name(
                        ) in self.invalidHardwareObjects:
                            self.invalidHardwareObjects.remove(
                                hwobj_instance.name())

                        self.hardwareObjects[
                            hwobj_instance.name()] = hwobj_instance
                else:
                    logging.getLogger("HWR").error(
                        "Failed to load Hardware object %s", hwobj_name)
                    comment = "Loading failed"
        else:
            logging.getLogger('HWR').error(
                'Cannot load Hardware Object "%s" : file not found.',
                hwobj_name)

        end_time = datetime.now()
        time_delta = end_time - start_time

        self.hwobj_info_list.append(
            (hwobj_name, class_name,
             "%d ms" % (time_delta.microseconds / 1000), comment))

        return hwobj_instance