def stopDriver(self, icepap_name, addr):
     try:
         self._ctrl_icepap.stopDriver(icepap_name, addr)
     except:
         MessageDialogs.showWarningMessage(self._form,
                                           "StopDriver Icepap error",
                                           "Connection error")
    def writeIcepapParameters(self, icepap_name, driver_addr, par_var_list):
        values = []
        # THE CONFIGURATION VALUES SHOULD BE SENT IN A SPECIFIC ORDER
        order_list = self.icepap_cfgorder[icepap_name][driver_addr]
        params_ordered = {}
        not_found_index = []
        for (name, value) in par_var_list:
            try:
                index = order_list.index(name)
                params_ordered[index] = (name, value)
            except:
                not_found_index.append((name, value))

        keys = params_ordered.keys()
        keys.sort()
        for key in keys:
            (name, value) = params_ordered.get(key)
            try:
                self.iPaps[icepap_name].writeParameter(driver_addr, name,
                                                       value)
            except IcePAPException, iex:
                msg = 'Error writing icepap parameter %s = %s.' % (name,
                                                                   str(value))
                msg += '\n' + iex.msg
                MessageDialogs.showErrorMessage(None, 'write param', msg)
                print iex.msg
                raise iex
    def setDriverConfiguration(self,
                               icepap_name,
                               driver_addr,
                               new_values,
                               expertFlag=False):
        """ TO-DO STORM review"""
        if self.iPaps[icepap_name].getMode(driver_addr) != IcepapMode.CONFIG:
            self.iPaps[icepap_name].setConfig(driver_addr)

        # THE CONFIGURATION VALUES SHOULD BE SENT IN A SPECIFIC ORDER
        order_list = self.icepap_cfgorder[icepap_name][driver_addr]
        params_ordered = {}
        not_found_index = []
        for (name, value) in new_values:
            try:
                index = order_list.index(name)
                params_ordered[index] = (name, value)
            except:
                not_found_index.append((name, value))

        keys = params_ordered.keys()
        keys.sort()
        for key in keys:
            (name, value) = params_ordered.get(key)
            if name != "VER":
                try:
                    self.iPaps[icepap_name].setCfgParameter(
                        driver_addr, name, str(value))
                except IcePAPException, iex:
                    msg = 'Error configuring parameter %s = %s' % (name,
                                                                   str(value))
                    msg += '\n' + iex.msg
                    MessageDialogs.showErrorMessage(None, 'Driver conf', msg)
                    print iex.msg
                    raise iex
    def importMovedDriver(self, icepap_driver, from_to=False):
        """ function to import the information from a moved driver, to avoid losing historic cfgs"""
        id = icepap_driver.current_cfg.getParameter("ID", True)
        got_driver = self._db.existsDriver(icepap_driver, id)
        if from_to:
            if got_driver:
                src_driver = icepap_driver
                dst_driver = got_driver
            else:
                delete = MessageDialogs.showYesNoMessage(
                    self._form, "Driver error",
                    "Driver not present.\nRemove driver from DB?")
                if delete:
                    icepap_driver.icepap_system.removeDriver(
                        icepap_driver.addr)
                return None
        else:
            src_driver = got_driver
            dst_driver = icepap_driver

        move = MessageDialogs.showYesNoMessage(
            self._form, "Import moved driver",
            "Import all historic configurations from %s:axis %d to %s:axis %d"
            % (src_driver.icepapsystem_name, src_driver.addr,
               dst_driver.icepapsystem_name, dst_driver.addr))
        src_sys = src_driver.icepap_system
        if move:
            for cfg in src_driver.historic_cfgs:
                cfg.setDriver(dst_driver)
                dst_driver.historic_cfgs.add(cfg)
        src_driver.icepap_system.removeDriver(src_driver.addr)
        return src_sys
 def moveDriverAbsolute(self, icepap_name, addr, position):
     try:
         self._ctrl_icepap.moveDriverAbsolute(icepap_name, addr, position)
     except IcePAPException, error:
         MessageDialogs.showErrorMessage(
             self._form, "MoveDriverAbsolute Icepap error",
             "%s Connection error:%s" % (icepap_name, error.msg))
 def configDriverToDefaults(self, icepap_name, driver_addr):
     try:
         self.iPaps[icepap_name].setDefaultConfig(driver_addr)
     except IcePAPException, iex:
         msg = 'Error configuring to defaults.'
         msg += '\n' + iex.msg
         MessageDialogs.showErrorMessage(None, 'default config', msg)
         print iex.msg
         raise iex
 def setDriverMotionValues(self, icepap_name, addr, values):
     """ Sets speed and acceleration to a driver """
     try:
         return self._ctrl_icepap.setDriverMotionValues(
             icepap_name, addr, values)
     except:
         MessageDialogs.showWarningMessage(
             self._form, "SetDriverMotionValues Icepap error",
             "Connection error")
 def readIcepapParameters(self, icepap_name, addr, par_list):
     """ Gets from adriver the values of the parameters in par_list """
     try:
         return self._ctrl_icepap.readIcepapParameters(
             icepap_name, addr, par_list)
     except IcePAPException, error:
         MessageDialogs.showErrorMessage(
             self._form, "ReadIcepapParamenters Icepap error",
             "%s Connection error:%s" % (icepap_name, error.msg))
 def getDriverActiveStatus(self, icepap_name, driver_addr):
     try:
         return self.iPaps[icepap_name].getActive(driver_addr)
     except IcePAPException, iex:
         msg = 'Error reading active status.'
         msg += '\n' + iex.msg
         MessageDialogs.showErrorMessage(None, 'get active', msg)
         print iex.msg
         raise iex
 def stopIcepap(self, icepap_system):
     """ Close the connection to an icepap. And commits all the changes in the database """
     try:
         self._ctrl_icepap.closeConnection(icepap_system.name)
         self._db.commitTransaction()
     except IcePAPException, error:
         MessageDialogs.showErrorMessage(
             self._form, "Stop Icepap error",
             "%s Connection error:%s" % (icepap_name, error.msg))
 def discardDriverCfg(self, icepap_name, driver_addr):
     try:
         if self.iPaps.has_key(icepap_name):
             self.iPaps[icepap_name].signConfig(driver_addr, "")
     except IcePAPException, iex:
         msg = 'Error signing config.'
         msg += '\n' + iex.msg
         MessageDialogs.showErrorMessage(None, 'config', msg)
         print iex.msg
         raise iex
    def getDriverConfiguration(self, icepap_name, addr):
        try:
            config = self._ctrl_icepap.getDriverConfiguration(
                icepap_name, addr)
            return config

        except:
            MessageDialogs.showErrorMessage(
                self._form, "GetDriverConfiguration Icepap error",
                "%s Connection error" % icepap_name)
 def getDriverCfgInfo(self, icepap_name, driver_addr):
     try:
         cfginfo = self.iPaps[icepap_name].getCfgInfo(driver_addr)
         return cfginfo
     except IcePAPException, iex:
         msg = 'Error getting cfginfo (%s).' % (str(driver_addr))
         msg += '\n' + iex.msg
         MessageDialogs.showErrorMessage(None, 'cfg info', msg)
         print iex.msg
         raise iex
 def getDriverTestStatus(self, icepap_name, addr, pos_sel, enc_sel):
     """ Driver Status used in the System and crate view
         Returns [status register, power state, [position register value, encoder register value]"""
     try:
         return self._ctrl_icepap.getDriverTestStatus(
             icepap_name, addr, pos_sel, enc_sel)
     except IcePAPException, error:
         MessageDialogs.showErrorMessage(
             self._form, "GetDriverTestStatus Icepap error",
             "%s Connection error:%s" % (icepap_name, error.msg))
         self._form.refreshTree()
         return (-1, -1, [-1, -1])
 def undoDriverConfiguration(self, icepap_driver):
     undo_cfg = icepap_driver.getUndoList()
     new_cfg = self._ctrl_icepap.setDriverConfiguration(
         icepap_driver.icepapsystem_name, icepap_driver.addr,
         undo_cfg.toList())
     if new_cfg is None:
         MessageDialogs.showWarningMessage(self._form,
                                           "undoDriverConfig error",
                                           "Connection error")
         #self._form.checkIcepapConnection()
     else:
         icepap_driver.undo(new_cfg)
         return True
 def signDriverConfiguration(self, icepap_name, driver_addr, signature):
     try:
         if self.iPaps.has_key(icepap_name):
             if self.iPaps[icepap_name].getMode(
                     driver_addr) != IcepapMode.CONFIG:
                 self.iPaps[icepap_name].setConfig(driver_addr)
             self.iPaps[icepap_name].signConfig(driver_addr, signature)
     except IcePAPException, iex:
         msg = 'Error signing config.'
         msg += '\n' + iex.msg
         MessageDialogs.showErrorMessage(None, 'sign driver', msg)
         print iex.msg
         raise iex
 def startConfiguringDriver(self, icepap_name, driver):
     try:
         mode = self.iPaps[icepap_name].getMode(driver.addr)
         if mode == IcepapMode.PROG:
             return mode
         if mode != IcepapMode.CONFIG:
             self.iPaps[icepap_name].setConfig(driver.addr)
         driver.setMode(IcepapMode.CONFIG)
     except IcePAPException, iex:
         msg = 'Error starting config.'
         msg += '\n' + iex.msg
         MessageDialogs.showErrorMessage(None, 'config', msg)
         print iex.msg
         raise iex
    def checkFirmwareVersions(self, icepap_system):
        config = ConfigManager()
        if config._options.skipversioncheck == True:
            print "Firmware versions are not checked."
            return
        try:
            icepap_name = icepap_system.name
            master_version = self._ctrl_icepap.iPaps[icepap_name].getVersion(
                0, "DRIVER")
            master_version = str(master_version)
            mismatched_drivers = []
            for driver in icepap_system.getDrivers():
                #####################################################################
                driver_version = self._ctrl_icepap.iPaps[
                    icepap_name].getVersion(driver.addr, "DRIVER")
                # If the driver has been temporary removed, the error should
                if driver_version.count("ERROR") > 0:
                    driver_version = master_version
                if master_version != driver_version:
                    mismatched_drivers.append(
                        (driver.addr, str(driver_version)))

            if len(mismatched_drivers) > 0:
                msg = "Some drivers do not have the MASTER's firmware version (%s):\n" % (
                    master_version)
                for driver, version in mismatched_drivers:
                    msg = msg + "driver %d: %s\n" % (driver, version)
                saved_version = self._ctrl_icepap.iPaps[
                    icepap_name].getVersionSaved()
                msg = msg + "Board saved version: %s\n" % (saved_version)
                msg = msg + "Would you like to upgrade these drivers?\n"
                upgrade = MessageDialogs.showYesNoMessage(
                    self._form, "Firmware mismatch", msg)
                if upgrade:
                    progress_dialog = QtGui.QProgressDialog(self._form)
                    progress_dialog.setLabel(
                        QtGui.QLabel(
                            "Icepap: %s\nUpgrading drivers' firmware to %s" %
                            (icepap_name, saved_version)))
                    progress_dialog.setCancelButton(None)
                    progress_dialog.setMaximum(100)
                    upgrading = self._ctrl_icepap.upgradeDrivers(
                        icepap_name, progress_dialog)
                    if not upgrading:
                        progress_dialog.cancel()
                        msg = "Sorry, problems found while upgrading. Please try it manually :-("
                        MessageDialogs.showErrorMessage(
                            None, "Firmware upgrade error", msg)
        except:
            pass
    def host_in_same_subnet(self, host):
        if self._config._options.allnets:
            return True

        networks = []
        configs = None
        addr_pattern = None
        mask_pattern = None
        digits = r'[0-9]{1,3}'

        if os.name == 'posix':
            ifconfigs = [
                '/sbin/ifconfig', '/usr/sbin/ifconfig', '/bin/ifconfig',
                '/usr/bin/ifconfig'
            ]
            ifconfig = filter(os.path.exists, ifconfigs)[0]
            fp = os.popen(ifconfig + ' -a')
            configs = fp.read().split('\n\n')
            fp.close()
            addr_pattern = r'(inet addr:) *(%s\.%s\.%s\.%s)[^0-9]' % (
                (digits, ) * 4)
            mask_pattern = r'(Mask:) *(%s\.%s\.%s\.%s)[^0-9]' % (
                (digits, ) * 4)
        elif os.name == 'nt':
            fp = os.popen('ipconfig /all')
            configs = fp.read().split(':\r\n\r\n')
            fp.close()
            addr_pattern = r'(IP Address).*: (%s\.%s\.%s\.%s)[^0-9]' % (
                (digits, ) * 4)
            mask_pattern = r'(Subnet Mask).*: (%s\.%s\.%s\.%s)[^0-9]' % (
                (digits, ) * 4)

        if configs and addr_pattern and mask_pattern:
            networks = self.find_networks(configs, addr_pattern, mask_pattern)

        if len(networks) > 0:
            host_addr = socket.gethostbyname(host)
            for net in networks:
                if host_addr in net:
                    return True
            return False
        else:
            MessageDialogs.showInformationMessage(
                None, "Not posix operating system",
                "Sorry system not yet supported.\nWe allow you access to the icepap even if it is in another subnet."
            )
            return True
 def endConfiguringDriver(self, icepap_name, driver):
     try:
         if not self.iPaps.has_key(icepap_name):
             return
         mode = self.iPaps[icepap_name].getMode(driver.addr)
         if mode == IcepapMode.PROG:
             return
         if mode != IcepapMode.OPER:
             last_signature = self.iPaps[icepap_name].getConfig(driver.addr)
             self.iPaps[icepap_name].signConfig(driver.addr, last_signature)
         driver.setMode(IcepapMode.OPER)
     except IcePAPException, iex:
         msg = 'Error ending config.'
         msg += '\n' + iex.msg
         MessageDialogs.showErrorMessage(None, 'end config', msg)
         print iex.msg
         raise iex
 def openConnection(self, icepap_name, host, port):
     log_folder = None
     if self.debug:
         log_folder = self.log_folder
     if not self.host_in_same_subnet(icepap_name):
         MessageDialogs.showInformationMessage(
             None, "Host connection",
             "It is not allowed to connect to %s" % host)
         return False
     else:
         try:
             self.iPaps[icepap_name] = EthIcePAP(host,
                                                 port,
                                                 log_path=log_folder)
             self.iPaps[icepap_name].connect()
             return True
         except Exception, e:
             #print "icepapcontroller: Some exception opening connection.",e
             return False
    def readIcepapParameters(self, icepap_name, driver_addr, par_list):
        try:
            values = []
            for name in par_list:
                if type(name) == type(values):
                    value = self.iPaps[icepap_name].readParameter(
                        driver_addr, name[0], name[1])
                else:
                    value = self.iPaps[icepap_name].readParameter(
                        driver_addr, name)
                values.append([name, value])

            return values
        except IcePAPException, iex:
            msg = 'Error reading parameters for driver %s.' % (
                str(driver_addr))
            msg += '\n' + iex.msg
            MessageDialogs.showErrorMessage(None, 'read param', msg)
            print iex.msg
            raise iex
 def getDriverStatus(self, icepap_name, addr):
     """ Driver Status used in the System and crate view
         Returns [status register, power status, current ]"""
     icepap_system = self.getIcepapSystem(icepap_name)
     if icepap_system == None:
         return (-1, False, -1)
     try:
         driver = icepap_system.getDriver(addr)
         if driver is None:
             return (-1, False, -1)
         if driver.conflict == Conflict.DRIVER_NOT_PRESENT or driver.conflict == Conflict.NO_CONNECTION:
             #print "OUPS! THIS DRIVER SHOULD NOT BE SCANNED"
             return (-1, False, -1)
         status = self._ctrl_icepap.getDriverStatus(icepap_name, addr)
         return status
     except IcePAPException, error:
         MessageDialogs.showErrorMessage(
             self._form, "GetDriverStatus Icepap error",
             "%s,%d Connection timeout" % (icepap_name, addr))
         self._form.refreshTree()
         return (-1, False, -1)
    def getDriverCfgInfoDictAndList(self, icepap_name, driver_addr):
        """
            Returns a dictionary with all the Driver params cfginfo
        """
        """ TO-DO STORM review"""
        # THE AVAILABLE OPTIONS FOR EACH PARAMETER ARE ALSO GIVEN BY THE DRIVER INSTEAD OF
        # FIXED VALUES FROM THE APPLICATION
        # THE CFGINFO IS NEEDED TO POPULATE THE QComboBoxes with correct available values
        cfginfo_str = self.getDriverCfgInfo(icepap_name, driver_addr)
        cfginfo_str = cfginfo_str.replace('$\r\n', "")
        cfginfo_str = cfginfo_str.replace('\r\n$', "")
        cfginfo_list = cfginfo_str.split("\r\n")
        cfginfo_dict = {}
        order_list = []
        for param_cfg in cfginfo_list:
            split = param_cfg.split(" ", 1)
            if len(split) > 1:
                param = split[0]
                values = split[1]
                values = values.replace("{", "")
                values = values.replace("}", "")
                cfginfo_dict[split[0]] = values.split()
                order_list.append(param)
            else:
                print "THE CONTROLLER DID NOT RECEIVE ALL THE CFGINFO FOR THE DRIVER " + str(
                    driver_addr)
                print "PLEASE, TRY TO RECONNECT TO THE " + str(
                    icepap_name) + " ICEPAP SYSTEM"
                print "AND REPORT THIS OUTPUT TO THE MANTAINER\n\n\n"

                MessageDialogs.showWarningMessage(
                    None, "Driver configuration",
                    "Could not retrive all the CFGINFO for the driver " +
                    str(driver_addr) + ". Please, try to reconnect to " +
                    str(icepap_name) + ".")
                #print "ALL INFO WAS (str): "+str(cfginfo_str)
                #print "ALL INFO WAS (list): "+str(cfginfo_list)
                #print "SOME ERROR GETTING CFGINFO: "+str(param_cfg)
        return (cfginfo_dict, order_list)
 def scanIcepap(self, icepap_system):
     """ Searches for configuration conflicts.
     Returns the conflicts list. That is composed by elements of [Conflict code, icepap_system, icepap_driver_addr] """
     QtGui.QApplication.instance().setOverrideCursor(
         QtGui.QCursor(QtCore.Qt.WaitCursor))
     icepap_name = icepap_system.name
     conflictsList = []
     try:
         if self._ctrl_icepap.openConnection(icepap_name,
                                             icepap_system.host,
                                             icepap_system.port):
             driver_list = self._ctrl_icepap.scanIcepapSystem(
                 icepap_name, True)
             conflictsList = icepap_system.compareDriverList(driver_list)
         else:
             conflictsList.append(
                 [Conflict.NO_CONNECTION, icepap_system, 0])
     except IcePAPException, error:
         MessageDialogs.showErrorMessage(
             None, "Scanning Icepap Error",
             "Could not scan the '" + icepap_name +
             "' Icepap System.\nPlease make sure that the system '" +
             (icepap_name) + "' is in your subnetwork.\nException:" +
             str(error))
    def addIcepapSystem(self, host, port, description=None):
        """ Adds a new Icepap in the current location, 
        the parameters are the hostname, port and description, 
        this function checks if the icepap is available, the gets all the configuration 
        of all the driver and stores all these information in the database """
        QtGui.QApplication.instance().setOverrideCursor(
            QtGui.QCursor(QtCore.Qt.WaitCursor))
        try:
            icepap_name = host
            """ *TO-DO STORM review"""
            if self.IcepapSystemList.has_key(icepap_name):
                return None
            location = self.location.name
            try:
                icepap_system = IcepapSystem(icepap_name, host, port, location,
                                             description)

                # JUST IN CASE A USER WANTS TO RE-ADD A SYSTEM !?!?!?!?
                # A QUANTUM PROBABILITY TO BE ON TWO LOCATIONS AT THE SAME TIME... :-D
                db_icepap_system = self._db.getIcepapSystem(icepap_name)
                if db_icepap_system != None:
                    MessageDialogs.showErrorMessage(
                        self._form, "Adding Icepap System error",
                        "The icepap system is already in location: '%s'" %
                        (db_icepap_system.location_name))
                    QtGui.QApplication.instance().restoreOverrideCursor()
                    return None

                self._ctrl_icepap.openConnection(icepap_name, host, port)
                driver_list = self._ctrl_icepap.scanIcepapSystem(icepap_name)
                self._db.addIcepapSystem(icepap_system)
                self.IcepapSystemList[icepap_name] = icepap_system
                self.location.addSystem(icepap_system)
                for driver in driver_list.values():
                    icepap_system.addDriver(driver)
                    self._db.store(driver)
                self._db.commitTransaction()
                QtGui.QApplication.instance().restoreOverrideCursor()
                if len(driver_list) == 0:
                    MessageDialogs.showWarningMessage(
                        None, "Scanning Icepap Warning",
                        "The icepap system '" + icepap_name +
                        "' has ZERO drivers.\nPlease make sure that the CAN BUS TERMINATOR is connected."
                    )
                return icepap_system
            except IcePAPException, ie:
                MessageDialogs.showErrorMessage(
                    None, "Scanning Icepap Error",
                    "Could not scan the '" + icepap_name +
                    "' Icepap System.\nPlease make sure that the system '" +
                    (icepap_name) +
                    "' is in your subnetwork.\nException:\n\t" + str(ie))
            except Exception, e:
                print "Unknown exception:", e
                        self.iPaps[icepap_name].setCfgParameter(
                            driver_addr, 'NAMELOCK', 'NO')
                    self.iPaps[icepap_name].writeParameter(
                        driver_addr, name, str(value))
                    self.iPaps[icepap_name].setCfgParameter(
                        driver_addr, 'NAMELOCK', namelock)
                elif name in ["VER", "ID"]:
                    pass
                else:
                    self.iPaps[icepap_name].setCfgParameter(
                        driver_addr, name, str(value))
            except IcePAPException, iex:
                msg = 'Error configuring parameter %s = %s' % (name,
                                                               str(value))
                msg += '\n' + iex.msg
                MessageDialogs.showErrorMessage(None, 'Driver conf', msg)
                print iex.msg
                raise iex
            except Exception, e:
                print "something happened when configuring the driver", e

        try:
            if expertFlag:
                self.iPaps[icepap_name].setExpertFlag(driver_addr)
        except IcePAPException, iex:
            msg = 'Error setting expert flag.'
            msg += '\n' + iex.msg
            MessageDialogs.showErrorMessage(None, 'Expert flag', msg)
            print iex.msg
            raise iex
            if driver is None:
                return (-1, False, -1)
            if driver.conflict == Conflict.DRIVER_NOT_PRESENT or driver.conflict == Conflict.NO_CONNECTION:
                #print "OUPS! THIS DRIVER SHOULD NOT BE SCANNED"
                return (-1, False, -1)
            status = self._ctrl_icepap.getDriverStatus(icepap_name, addr)
            return status
        except IcePAPException, error:
            MessageDialogs.showErrorMessage(
                self._form, "GetDriverStatus Icepap error",
                "%s,%d Connection timeout" % (icepap_name, addr))
            self._form.refreshTree()
            return (-1, False, -1)
        except Exception, e:
            MessageDialogs.showWarningMessage(self._form,
                                              "GetDriverStatus error",
                                              "Connection error")
            self._form.checkIcepapConnection()
            #print "Unexpected error:", sys.exc_info()
            #print "error getting status : %s %d" % (icepap_name,addr)
            return (-1, False, -1)

    def getDriverTestStatus(self, icepap_name, addr, pos_sel, enc_sel):
        """ Driver Status used in the System and crate view
            Returns [status register, power state, [position register value, encoder register value]"""
        try:
            return self._ctrl_icepap.getDriverTestStatus(
                icepap_name, addr, pos_sel, enc_sel)
        except IcePAPException, error:
            MessageDialogs.showErrorMessage(
                self._form, "GetDriverTestStatus Icepap error",