Esempio n. 1
0
def AttachInterfaceKit(databasepath, serialNumber):
    def inputChangeHandler(event):
        conn = sqlite3.connect(databasepath)
        conn.execute(
            "INSERT INTO INTERFACEKIT_INPUTCHANGE VALUES(NULL, DateTime('now'), ?, ?, ?)",
            (event.device.getSerialNum(), event.index, event.state))
        conn.commit()
        conn.close()

    def outputChangeHandler(event):
        conn = sqlite3.connect(databasepath)
        conn.execute(
            "INSERT INTO INTERFACEKIT_OUTPUTCHANGE VALUES(NULL, DateTime('now'), ?, ?, ?)",
            (event.device.getSerialNum(), event.index, event.state))
        conn.commit()
        conn.close()

    def sensorChangeHandler(event):
        conn = sqlite3.connect(databasepath)
        conn.execute(
            "INSERT INTO INTERFACEKIT_SENSORCHANGE VALUES(NULL, DateTime('now'), ?, ?, ?)",
            (event.device.getSerialNum(), event.index, event.value))
        conn.commit()
        conn.close()

    try:
        ik = InterfaceKit()
        ik.setOnInputChangeHandler(inputChangeHandler)
        ik.setOnOutputChangeHandler(outputChangeHandler)
        ik.setOnSensorChangeHandler(sensorChangeHandler)
        ik.openPhidget(serialNumber)
    except PhidgetException as e:
        print("Phidget Exception %i: %s" % (e.code, e.details))
        print("Exiting...")
        exit(1)
Esempio n. 2
0
 def __init__(self, master, stage, sphere, lakeshore, bk):
     self.stop_exposures = False
     self.master = master
     self.stage = stage
     self.sphere = sphere
     self.bk = bk
     self.lakeshore = lakeshore
     self.vbb = 0.0
     CfgFile = "/sandbox/lsst/lsst/GUI/UCDavis.cfg"
     if self.CheckIfFileExists(CfgFile):
         self.CfgFile = CfgFile
     else:
         print "Configuration file %s not found. Exiting.\n"%CfgFile
         sys.exit()
         return
     self.edtsaodir = eolib.getCfgVal(self.CfgFile,"EDTSAO_DIR")
     self.EDTdir = eolib.getCfgVal(self.CfgFile,"EDT_DIR")
     self.vendor = eolib.getCfgVal(self.CfgFile,"CCD_MANU").strip()
     self.ccd_sern = eolib.getCfgVal(self.CfgFile,"CCD_SERN").strip()
     if not (self.vendor == "ITL" or self.vendor == "E2V"):
         print "Vendor not recognized.  Exiting."
         sys.exit()
     self.fitsfilename = "dummy.fits" # Just a dummy - not really used
     self.relay = InterfaceKit()
     return
Esempio n. 3
0
class cycleForever(threading.Thread):
    def __init__(
        self,
        behavior_setup_name,
        interfaceKitIPAddress,
        pumpIPAddress,
        interfaceKitPort=5001,
        pumpPort=100,
        pump_channels=["01", "02"]
        ):
        threading.Thread.__init__(self)
        self.setup_name = behavior_setup_name
        self.interfaceKitIPAddress = interfaceKitIPAddress
        self.interfaceKitPort = interfaceKitPort
        self.controller = InterfaceKit()
        self.controller.openRemoteIP(self.interfaceKitIPAddress, self.interfaceKitPort)
        self.pumpIPAddress = pumpIPAddress
        self.pumpPort = pumpPort
        self.pumpsConn = newPumpConnection(self.pumpIPAddress, self.pumpPort)
        self.pump_channels = pump_channels

    def run(self):
        while True:
            infuse = infuseFully(self.setup_name, self.controller, self.pumpsConn, pump_channels=self.pump_channels)
            infuse.start()
            infuse.join()
            withdraw = withdrawFully(self.setup_name, self.controller, self.pumpsConn, pump_channels=self.pump_channels)
            withdraw.start()
            withdraw.join()
Esempio n. 4
0
class InterfaceSource(Source):
    def __init__(self):
        Source.__init__(self)
        
        try:
            self._device = InterfaceKit()
        except RuntimeError as e:
            print("Runtime Error: %s" % e.message)
            
        try:
            self._device.openPhidget()
        except PhidgetException as e:
            print("Phidget Exception %i: %s" % (e.code, e.detail))
        
        self._device.setOnSensorChangeHandler(self.sensor_changed)
        
        print("Phidget: Waiting for Connection")
        self._device.waitForAttach(10000)
        
        self._device.setSensorChangeTrigger(0, 0)
        self._device.setDataRate(0, 1)
        
        print("Phidget: Connected")
    
    def sensor_changed(self, e):
        if self.sink is not None:
            self.sink([e.value])
Esempio n. 5
0
    def __init__(self):
        # Create an interfacekit object
        try:
            self.__interfaceKit = InterfaceKit()
        except RuntimeError as e:
            print('Runtime Exception: %s' % e.details)
            return 1

        try:
            # logging example, uncomment to generate a log file
            #self.__interfaceKit.enableLogging(PhidgetLogLevel.PHIDGET_LOG_VERBOSE, 'phidgetlog.log')

            self.__interfaceKit.setOnAttachHandler(self.__interfaceKitAttached)
            self.__interfaceKit.setOnDetachHandler(self.__interfaceKitDetached)
            self.__interfaceKit.setOnErrorhandler(self.__interfaceKitError)
            self.__interfaceKit.setOnInputChangeHandler(
                self.__interfaceKitInputChanged)
            self.__interfaceKit.setOnOutputChangeHandler(
                self.__interfaceKitOutputChanged)
            self.__interfaceKit.setOnSensorChangeHandler(
                self.__interfaceKitSensorChanged)
        except PhidgetException as e:
            print('[ERROR] Phidget Exception %i: %s' % (e.code, e.details))
            return 1

        print('[INFO] [InterfaceKitHelper] Opening phidget object....')

        try:
            self.__interfaceKit.openPhidget()
        except PhidgetException as e:
            print('[ERROR] Phidget Exception %i: %s' % (e.code, e.details))
            return 1

        print('[INFO] [InterfaceKitHelper] Waiting for attach....')

        try:
            self.__interfaceKit.waitForAttach(10000)
        except PhidgetException as e:
            print('[ERROR] Phidget Exception %i: %s' % (e.code, e.details))
            try:
                self.__interfaceKit.closePhidget()
            except PhidgetException as e:
                print('[ERROR] Phidget Exception %i: %s' % (e.code, e.details))
                return 1
            return 1
        else:
            # self.__displayDeviceInfo()
            pass

        print(
            '[INFO] [InterfaceKitHelper] Setting the data rate for each sensor index to 4ms....'
        )
        for i in range(self.__interfaceKit.getSensorCount()):
            try:
                self.__interfaceKit.setDataRate(i, 4)
            except PhidgetException as e:
                print('[ERROR] Phidget Exception %i: %s' % (e.code, e.details))

        self.led = LED(self)
Esempio n. 6
0
 def __init__(self, master):
     self.master = master
     self.fill_log_name='/sandbox/lsst/lsst/GUI/particles/fill_log.dat'
     self.valve = InterfaceKit()
     self.comm_status = False
     self.ov_temp = 999.0
     self.valve_state = "Closed"
     return
Esempio n. 7
0
 def __init__(self, **kwargs):
     log.debug("Acquiring InterfaceKit")
     self.ik = InterfaceKit()
     log.debug("Registering Handlers")
     self.ik.setOnAttachHandler(self._onAttach)
     self.ik.setOnDetachHandler(self._onDetach)
     self.ik.setOnErrorhandler(self._onError)
     self.ik.setOnOutputChangeHandler(self._onOutput)
     self.ik.setOnInputChangeHandler(self._onInput)
     self.ik.setOnSensorChangeHandler(self._onSensor)
Esempio n. 8
0
class Phidget(Relay):
    
    def __init__(self, **kwargs):
        super(Phidget,self).__init__(**kwargs)
        self.use_sqllog = True
    
    def get_port(self, port):
        rval = -1
        if self.connect():
            try:
                rval = self.interfaceKit.getOutputState(port)
            except PhidgetException as e:
                self.logger.error("Phidget Exception %i: %s" % (e.code, e.details))
                raise e
            finally:
                self.disconnect()
        return rval
    
    def set_port(self, port, state):
        if self.connect():
            try:
                self.interfaceKit.setOutputState(port, state)
            except PhidgetException as e:
                self.logger.error("Phidget Exception %i: %s" % (e.code, e.details))
                raise e
            finally:
                self.disconnect()
            return True
        else:
            return False            
            
    def connect(self):
        #Create an interfacekit object
        try:
            self.interfaceKit = InterfaceKit()
            self.interfaceKit.openPhidget()
            self.interfaceKit.waitForAttach(10000)
            
        except RuntimeError as e:
            self.logger.error("Runtime error: %s" % e.message)
            raise e
            
        except PhidgetException as e:
            self.logger.error("Phidget Exception %i: %s" % (e.code, e.details))
            try:
                self.interfaceKit.closePhidget()
            except PhidgetException as e:
                self.logger.error("Phidget Exception %i: %s" % (e.code, e.details))
            raise e
            
        return True
    
    def disconnect(self):
        try:
            self.interfaceKit.closePhidget()
        except PhidgetException as e:
            self.logger.error("Phidget Exception %i: %s" % (e.code, e.details))
            raise e
Esempio n. 9
0
    def __init__(self):
        print ("Initiating pumps")
        try:
            self.interfaceKit = InterfaceKit()
        except RuntimeError as e:
            print ("Runtime Exception a: %s" % e.details)
            print ("Exiting....")
            exit(1)
        try:
            self.interfaceKit.openPhidget()
        except PhidgetException as e:
            print ("Phidget Exception b %i: %s" % (e.code, e.details))
            print ("Exiting....")
            exit(1)

        try:
            self.interfaceKit.waitForAttach(1000)
        except PhidgetException as e:
            print ("Phidget Exception c %i: %s" % (e.code, e.details))
            raise Exception("Timeout")
            try:
                self.interfaceKit.closePhidget()
            except PhidgetException as e:
                print ("Phidget Exception d %i: %s" % (e.code, e.details))
                print ("Exiting....")
                exit(1)
        self.pumplist = []
        for i in range(0, 4):
            self.pumplist.append(onePump(self.interfaceKit, i))
        print ("Pumps ready")
Esempio n. 10
0
 def _try_init(self):
     if all([self._data_rate, self._attach_timeout, self._sensors]):
         try:
             from Phidgets.Devices.InterfaceKit import InterfaceKit
             from Phidgets.PhidgetException import PhidgetException
             self.interface_kit = InterfaceKit()
             self.interface_kit.setOnAttachHandler(lambda e: self._attach(e))
             self.interface_kit.setOnDetachHandler(lambda e: self._detach(e))
             self.interface_kit.setOnErrorhandler(lambda e: self._error(e))
             self.interface_kit.setOnSensorChangeHandler(lambda e: self._sensor_change(e))
             self.interface_kit.openPhidget()
             self.interface_kit.waitForAttach(self._attach_timeout)
             for i in range(self.interface_kit.getSensorCount()):
                 self.interface_kit.setDataRate(i, self._data_rate)
             logging.info("Phidget Sensor Handler Initalized")
             for s in self._sensors:
                 if s.port_num is not None:
                     s.current_data = self.interface_kit.getSensorValue(s.port_num)
                     logging.debug("Setting Initial Value for Sensor {} to {}".format(s.port_num, s.current_data))
                 else:
                     logging.warn("Cannot set Initial Value for Sensor {}".format(s.port_num))
         except ImportError:
             self.interface_kit = None
             logging.error('Phidget Python Module not found. Did you install python-phidget?')
         except PhidgetException as e:
             self.interface_kit = None
             logging.error("Could not Initalize Phidget Kit: {}".format(e.details))
Esempio n. 11
0
    def __init__(self):     
        try:
            self.interfaceKit = InterfaceKit()
        except RuntimeError as e:
            print("Runtime Exception: %s" % e.details)
            exit(1)

        print("Connecting to Phidget.")

        try:
            self.interfaceKit.openPhidget()
        except PhidgetException as e:
            print("Phidget Exception %i: %s" % (e.code, e.details))
            exit(1)

        print("Connection opened.")

        try:
            self.interfaceKit.waitForAttach(10000)
        except PhidgetException as e:
            try:
                self.interfaceKit.closePhidget()
            except PhidgetException as e:
                exit(1)
            exit(1)
        print("Attached to phidget interface.")
Esempio n. 12
0
 def __init__(self, name, *args, **kwargs):
     self.name = name
     self.initializing = True
     if LIVE: self.interface_kit = InterfaceKit()
     self.manager = PubSub(self, pub_port=settings.NODE_PUB, sub_port=settings.NODE_SUB, sub_filter=self.name)
     self.logger = util.get_logger("%s.%s" % (self.__module__, self.__class__.__name__))
     self.initialize()    
     self.run()
Esempio n. 13
0
    def run(self):
        try:
            self.interfaceKit = InterfaceKit(
            )  #instanzio la classe per interfacciarmi con la scheda di acquisizione
            self.monitoring = sm.SensorMonitoring(
            )  #tabella dove sono memorizzati i valori dei sensori collegati
            self.monitoring.open()
            self.monitoring.create()
        except RuntimeError as e:
            print("Runtime Exception: %s" % e.details)
            print("Exiting....")
            exit(1)

        try:
            self.interfaceKit.setOnSensorChangeHandler(
                self.interfaceKitSensorChanged)
        except PhidgetException as e:
            print("Exiting....")
            exit(1)

        try:
            self.interfaceKit.openPhidget()
        except PhidgetException as e:
            print("Exiting....")
            exit(1)

        try:
            self.interfaceKit.waitForAttach(10000)
        except PhidgetException as e:
            try:
                self.interfaceKit.closePhidget()
            except PhidgetException as e:
                exit(1)
            print(
                "Assicurarsi di aver collegato la scheda di acquisizione Phidget 1019 al PC. Exiting...."
            )
            exit(1)
        else:
            print "Scheda di acquisizione rilevata."

        for i in range(self.interfaceKit.getSensorCount()):
            try:
                self.interfaceKit.setDataRate(i, 4)
            except PhidgetException as e:
                pass
Esempio n. 14
0
    def __init__(self):
        """Open InterfaceKit and Encoder devices and initialize ros node"""
        rospy.init_node("phidgets_node")
        #rospy.init_node("phidgets_node", log_level=rospy.DEBUG)

        # Call base class initializer, which starts a ros node with a name and log_level
        # It then opens and attaches Phidget device
        self.interfaceKit = InterfaceKit()
        self.encoder = Encoder()
        # self.bridge = Bridge()

        # initialize this to nan to indicate we haven't homed the location
        self.sled_pos = float('nan')  # position of sled in millimeters
        self.encoder_rear_offset = 0
        self.encoder_front_offset = 0

        # Open the devices and wait for them to attach
        self._attachPhidget(self.interfaceKit, "Interface Kit")
        self._attachPhidget(self.encoder, "Encoder board")
        # self._attachPhidget(self.bridge, "Wheatstone Bridge")

        self.params = rospy.get_param("/phidgets")
        self.sled_params = self.params["sled"]

        self.sensor_pub = rospy.Publisher("/actuator_states/raw/",
                                          ActuatorStates,
                                          queue_size=10)
        self.sensor_processed_pub = rospy.Publisher("/actuator_states/proc",
                                                    ActuatorStatesProcessed,
                                                    queue_size=10)
        self.limit_sub = rospy.Subscriber("/pololu/limit_switch",
                                          LimitSwitch,
                                          self.limit_callback,
                                          queue_size=10)
        self.sled_is_homed = False

        # enable both the sled encoders
        self.encoder.setEnabled(self.sled_params["encoder_index"]["left"],
                                True)
        self.encoder.setEnabled(self.sled_params["encoder_index"]["right"],
                                True)

        # Display info of the devices
        self._displayDeviceInfo(self.encoder)
        self.displayInterfaceKitInfo()
Esempio n. 15
0
    def open_phidget(self):
        self.log.debug("Attempting to open phidget")

        self.interface = InterfaceKit()

        if self._serial != None:
            self.log.debug("Attempt to open serial: %s" % self._serial)
            self.interface.openPhidget(self._serial)
        else:
            self.log.debug("Attempt to open first found")
            self.interface.openPhidget()

        wait_interval = 10300
        self.log.debug("Wait for attach %sms" % wait_interval)
        self.interface.waitForAttach(wait_interval)

        self.log.info("Opened phidget")
        return 1
Esempio n. 16
0
 def __init__(
     self,
     behavior_setup_name,
     interfaceKitIPAddress,
     pumpIPAddress,
     interfaceKitPort=5001,
     pumpPort=100,
     pump_channels=["01", "02"]
     ):
     threading.Thread.__init__(self)
     self.setup_name = behavior_setup_name
     self.interfaceKitIPAddress = interfaceKitIPAddress
     self.interfaceKitPort = interfaceKitPort
     self.controller = InterfaceKit()
     self.controller.openRemoteIP(self.interfaceKitIPAddress, self.interfaceKitPort)
     self.pumpIPAddress = pumpIPAddress
     self.pumpPort = pumpPort
     self.pumpsConn = newPumpConnection(self.pumpIPAddress, self.pumpPort)
     self.pump_channels = pump_channels
Esempio n. 17
0
 def __init__(self, **kwargs):
     log.debug("Acquiring InterfaceKit")
     self.ik = InterfaceKit()
     log.debug("Registering Handlers")
     self.ik.setOnAttachHandler(self._onAttach)
     self.ik.setOnDetachHandler(self._onDetach)
     self.ik.setOnErrorhandler(self._onError)
     self.ik.setOnOutputChangeHandler(self._onOutput)
     self.ik.setOnInputChangeHandler(self._onInput)
     self.ik.setOnSensorChangeHandler(self._onSensor)
Esempio n. 18
0
 def connect(self):
     #Create an interfacekit object
     try:
         self.interfaceKit = InterfaceKit()
         self.interfaceKit.openPhidget()
         self.interfaceKit.waitForAttach(10000)
         
     except RuntimeError as e:
         self.logger.error("Runtime error: %s" % e.message)
         raise e
         
     except PhidgetException as e:
         self.logger.error("Phidget Exception %i: %s" % (e.code, e.details))
         try:
             self.interfaceKit.closePhidget()
         except PhidgetException as e:
             self.logger.error("Phidget Exception %i: %s" % (e.code, e.details))
         raise e
         
     return True
Esempio n. 19
0
    def open_phidget(self):
        ''' Based on the InterfaceKit-simple.py example from Phidgets, create an
        relay object, attach the handlers, open it and wait for the attachment.
        This function's primarily purpose is to replace the prints with log
        statements.  '''
        try:
            self.interface = InterfaceKit()
        except RuntimeError as e:
            log.critical("Phidget runtime exception: %s" % e.details)
            return 0


        try:
            self.interface.setOnAttachHandler( self.interfaceAttached )
            self.interface.setOnDetachHandler( self.interfaceDetached )
            self.interface.setOnErrorhandler(  self.interfaceError    )
        except PhidgetException as e:
            log.critical("Phidget Exception %i: %s" % (e.code, e.details))
            return 0


        try:
	    #print "Force open relay serial: 290968"
            self.interface.openPhidget()
        except PhidgetException as e:
            log.critical("Phidget Exception %i: %s" % (e.code, e.details))
            return 0


        #log.info("Waiting for attach....")
        try:
            self.interface.waitForAttach(100)
        except PhidgetException as e:
            log.critical("Phidget Exception %i: %s" % (e.code, e.details))
            try:
                self.interface.closePhidget()
            except PhidgetException as e:
                log.critical("Close Exc. %i: %s" % (e.code, e.details))
            return 0
   
        return 1
Esempio n. 20
0
    def __init__(self):
        #Create an interfacekit object
        try:
            self.interfaceKit = InterfaceKit()
        except RuntimeError as e:
            print("Runtime Exception: %s" % e.details)
            print("Exiting....")
            exit(1)

        try:
            self.interfaceKit.openPhidget()
            self.interfaceKit.waitForAttach(10000)
            self.interfaceKit.setDataRate(self.__sensorPort, self.__sampleRate)
        except PhidgetException as e:
            print("Phidget Exception %i: %s" % (e.code, e.details))
            try:
                self.interfaceKit.closePhidget()
            except PhidgetException as e:
                print("Phidget Exception %i: %s" % (e.code, e.details))
                print("Exiting....")
                exit(1)
Esempio n. 21
0
    def __init__(self, n_sensors=2, n_inputs=1):
        '''
        Docstring

        Parameters
        ----------

        Returns
        -------
        '''
        self.n_sensors = n_sensors
        self.n_inputs = n_inputs
        self.interval = 1. / self.update_freq

        self.sensordat = np.zeros((n_sensors,))
        self.inputdat = np.zeros((n_inputs,), dtype=np.bool)
        self.data = np.zeros((1,), dtype=self.dtype)

        self.kit = InterfaceKit()
        self.kit.openPhidget()
        self.kit.waitForAttach(2000)
    def __init__(self, log_file):
        self.interfaceKit = InterfaceKit()
        self.log_file = log_file
        try:
            self.interfaceKit.setOnAttachHandler(self.interfaceKitAttached)
            self.interfaceKit.setOnDetachHandler(self.interfaceKitDetached)
            self.interfaceKit.setOnErrorhandler(self.interfaceKitError)
            self.interfaceKit.setOnSensorChangeHandler(self.interfaceKitSensorChanged)
        except PhidgetException as e:
            print("Phidget Exception %i: %s" % (e.code, e.details))
            print("Exiting....")
            exit(1)

        print("Turning on glove....")

        try:
            self.interfaceKit.openPhidget()
        except PhidgetException as e:
            print("Phidget Exception %i: %s" % (e.code, e.details))
            print("Exiting....")
            exit(1)

        print("Waiting for glove to attach....")

        try:
            self.interfaceKit.waitForAttach(10000)
        except PhidgetException as e:
            print("Phidget Exception %i: %s" % (e.code, e.details))
            try:
                self.interfaceKit.closePhidget()
            except PhidgetException as e:
                print("Phidget Exception %i: %s" % (e.code, e.details))
                print("Exiting....")
                exit(1)
            print("Exiting....")
            exit(1)
        else:
            print "Glove connected..."
            # self.displayDeviceInfo()
        return
Esempio n. 23
0
 def instanciarIK (self, nroSerie):
     """
     Método utilizado para instanciar un objeto de tipo InterfaceKit de la API de Phidgets, que permite interactuar con la placa controladora y sus puertos"""
     try:
         ik= InterfaceKit()
         ik.openRemoteIP(self.__ipWS, self.__puertoWS, nroSerie)
         ik.waitForAttach(5000)
         return ik
     except :
         ik.closePhidget()
         return None
Esempio n. 24
0
 def _try_init(self):
     if all([self._data_rate, self._attach_timeout, self._sensors]):
         try:
             from Phidgets.Devices.InterfaceKit import InterfaceKit
             from Phidgets.PhidgetException import PhidgetException
             self.interface_kit = InterfaceKit()
             self.interface_kit.setOnAttachHandler(
                 lambda e: self._attach(e))
             self.interface_kit.setOnDetachHandler(
                 lambda e: self._detach(e))
             self.interface_kit.setOnErrorhandler(lambda e: self._error(e))
             self.interface_kit.setOnSensorChangeHandler(
                 lambda e: self._sensor_change(e))
             self.interface_kit.openPhidget()
             self.interface_kit.waitForAttach(self._attach_timeout)
             for i in range(self.interface_kit.getSensorCount()):
                 self.interface_kit.setDataRate(i, self._data_rate)
             logging.info("Phidget Sensor Handler Initalized")
             for s in self._sensors:
                 if s.port_num is not None:
                     s.current_data = self.interface_kit.getSensorValue(
                         s.port_num)
                     logging.debug(
                         "Setting Initial Value for Sensor {} to {}".format(
                             s.port_num, s.current_data))
                 else:
                     logging.warn(
                         "Cannot set Initial Value for Sensor {}".format(
                             s.port_num))
         except ImportError:
             self.interface_kit = None
             logging.error(
                 'Phidget Python Module not found. Did you install python-phidget?'
             )
         except PhidgetException as e:
             self.interface_kit = None
             logging.error("Could not Initalize Phidget Kit: {}".format(
                 e.details))
Esempio n. 25
0
class cycleFor(threading.Thread):
    def __init__(
        self,
        numCycles,
        behavior_setup_name,
        interfaceKitIPAddress,
        pumpIPAddress,
        interfaceKitPort=5001,
        primeForBehavior=True,
        pumpPort=100,
        pump_channels=["01", "02"]
        ):
        threading.Thread.__init__(self)
        self.controller = InterfaceKit()
        self.controller.openRemoteIP(interfaceKitIPAddress, interfaceKitPort)
        self.pumpsConn = newPumpConnection(pumpIPAddress, pumpPort)
        self.numCycles = numCycles
        self.behavior_setup_name = behavior_setup_name
        self.interfaceKitIPAddress = interfaceKitIPAddress
        self.pumpIPAddress = pumpIPAddress
        self.interfaceKitPort = interfaceKitPort
        self.primeForBehavior = primeForBehavior
        self.pumpPort = pumpPort
        self.pump_channels = pump_channels
    def run(self):
        #infuse fully then withdraw fully for numCycles
        for i in xrange(self.numCycles):
            infuse = infuseFully(self.behavior_setup_name, self.controller, self.pumpsConn, pump_channels=self.pump_channels)
            infuse.start()
            infuse.join()
            withdraw = withdrawFully(self.behavior_setup_name, self.controller, self.pumpsConn, pump_channels=self.pump_channels)
            withdraw.start()
            withdraw.join()
        if self.primeForBehavior:
            prime = primeForBehaviorSession(self.behavior_setup_name, self.controller, self.pumpsConn, pump_channels=self.pump_channels)
            prime.start()
            prime.join()
        self.pumpsConn.close()
Esempio n. 26
0
def grabInterfaceKit():
    try:
        interface_kit = InterfaceKit()
        interface_kit.openPhidget()
        interface_kit.waitForAttach(0)
    except PhidgetException as e:
        print("Phidget Exception %i: %s" % (e.code, e.details))
        try:
            interface_kit.closePhidget()
        except PhidgetException as e:
            print("Phidget Exception %i: %s" % (e.code, e.details))
            print("Exiting....")
            exit(1)
        print("Exiting....")
        exit(1)
    return interface_kit
Esempio n. 27
0
 def __init__(
     self,
     numCycles,
     behavior_setup_name,
     interfaceKitIPAddress,
     pumpIPAddress,
     interfaceKitPort=5001,
     primeForBehavior=True,
     pumpPort=100,
     pump_channels=["01", "02"]
     ):
     threading.Thread.__init__(self)
     self.controller = InterfaceKit()
     self.controller.openRemoteIP(interfaceKitIPAddress, interfaceKitPort)
     self.pumpsConn = newPumpConnection(pumpIPAddress, pumpPort)
     self.numCycles = numCycles
     self.behavior_setup_name = behavior_setup_name
     self.interfaceKitIPAddress = interfaceKitIPAddress
     self.pumpIPAddress = pumpIPAddress
     self.interfaceKitPort = interfaceKitPort
     self.primeForBehavior = primeForBehavior
     self.pumpPort = pumpPort
     self.pump_channels = pump_channels
Esempio n. 28
0
 def __openIF(self):
     try:
         self._interfaceKit = InterfaceKit()
     except RuntimeError as e:
         print("IF Kit - Runtime Exception: %s" % e.details)
         return False
     try:
         self._interfaceKit.setOnAttachHandler(self.__onAttachedIF)
         self._interfaceKit.setOnDetachHandler(self.__onDetachedIF)
         self._interfaceKit.setOnErrorhandler(self.__onErrorIF)
         self._interfaceKit.setOnInputChangeHandler(self.__onInputChangedIF)
         self._interfaceKit.setOnSensorChangeHandler(
             self.__onSensorChangedIF)
     except PhidgetException as e:
         print("IF Kit - Phidget Exception %i: %s" % (e.code, e.details))
         return False
     try:
         self._interfaceKit.openPhidget()
     except PhidgetException as e:
         print("IF Kit - Phidget Exception %i: %s" % (e.code, e.details))
         return False
     self._openIF = True
     return True
Esempio n. 29
0
def set_bbias(state):
    """Set back bias to state"""

    state_dict = {"On" : True,
                  "Off" : False}
    setting = state_dict[state]

    ## Attach to Phidget controller
    relay = InterfaceKit()
    relay.openPhidget()
    relay.waitForAttach(10000)

    ## Check if successful
    if relay.isAttached():
        print "Done!"
    else:
        print "Failed to connect to Phidget controller"

    ## Set output to 0 and close
    relay.setOutputState(0, setting)
    print "BSS is now {0}".format(state)
    relay.closePhidget()

    return
Esempio n. 30
0
def run():  
    kit = InterfaceKit()
    try:
        try:
            kit.openPhidget()
            kit.setOnAttachHandler(attached)
            kit.setOnDetachHandler(detached)
            if not kit.isAttached():
                print "Please attach the interface kit!"
            raw_input()
        except PhidgetException as e:
            print ("Phidget exception %i: %s" % (e.code,e.detail))
    except RuntimeError as e:
        print ("Runtime error: %s" % e.message)
    except Exception as e:
        print ("Unknown error: %s" % (e.message))
        
    stop(kit)
Esempio n. 31
0
    def __init__(self, serialNumber=None, waitForAttach=1000, **kargs):

        self.interfaceKit = InterfaceKit()

        if 'remoteHost' in kargs:
            self.interfaceKit.openRemote(kargs['remoteHost'], serialNumber)
        else:
            self.interfaceKit.openPhidget(serialNumber)
    
        self.ratiometric = 1
        if 'ratiometric' in kargs:
            self.ratiometric = kargs['ratiometric'] 

        h = [
            'onAttachHandler',
            'onDetachHandler',
            'onErrorhandler',
            'onInputChangeHandler',
            'onOutputChangeHandler',
            'onSensorChangeHandler'
            ]

        for event in h:
            self.__dict__[event] = None
            if event in kargs:
                self.__dict__[event] = kargs[event]

        self.interfaceKit.setOnAttachHandler(self.attached)
        self.interfaceKit.setOnDetachHandler(self.detached)
        self.interfaceKit.setOnErrorhandler(self.error)
        self.interfaceKit.setOnInputChangeHandler(self.inputChanged)
        self.interfaceKit.setOnOutputChangeHandler(self.outputChanged)
        self.interfaceKit.setOnSensorChangeHandler(self.sensorChanged)


        if waitForAttach > 0:
            try:
                self.interfaceKit.waitForAttach(waitForAttach)
            except PhidgetException as e:
                #print("Phidget Exception %i: %s" % (e.code, e.details))
                try:
                    self.interfaceKit.closePhidget()
                except PhidgetException as e2:
                    pass
                raise e
Esempio n. 32
0
    def open_phidget(self):
        self.log.debug("Attempting to open phidget")

        self.interface = InterfaceKit()

        if self._serial != None:
            self.log.debug("Attempt to open serial: %s" % self._serial)
            self.interface.openPhidget(self._serial)
        else:
            self.log.debug("Attempt to open first found")
            self.interface.openPhidget()

        wait_interval = 10300
        self.log.debug("Wait for attach %sms" % wait_interval)           
        self.interface.waitForAttach(wait_interval)
  
        self.log.info("Opened phidget") 
        return 1
Esempio n. 33
0
    def __init__(self):

        rospy.loginfo("Initializing PhidgetInterface")

        self.batteryVoltage = 0
        self.forwardRange = 1
        self.aftRange = 2

        self.interfaceKit = InterfaceKit()
        
        self.forwardRangeMessage = Range()
        self.forwardRangeMessage.header.frame_id = 'infrared_forward'
        self.forwardRangeMessage.radiation_type = Range.INFRARED
        self.forwardRangeMessage.field_of_view = 0.018
        self.forwardRangeMessage.min_range = 0.2
        self.forwardRangeMessage.max_range = 0.8
        self.forwardRangeMessage.range = 0.0

        self.aftRangeMessage = Range()
        self.aftRangeMessage.header.frame_id = 'infrared_aft'
        self.aftRangeMessage.radiation_type = Range.INFRARED
        self.aftRangeMessage.field_of_view = 0.018
        self.aftRangeMessage.min_range = 0.2
        self.aftRangeMessage.max_range = 0.8
        self.aftRangeMessage.range = 0.0

        self.sensorPublisher = rospy.Publisher('bogies', Range)

        self.interfaceKit.setOnAttachHandler(self.interfaceKitAttached)
        self.interfaceKit.setOnDetachHandler(self.interfaceKitDetached)
        self.interfaceKit.setOnErrorhandler(self.interfaceKitError)
        self.interfaceKit.setOnInputChangeHandler(self.interfaceKitInputChanged)
        self.interfaceKit.setOnOutputChangeHandler(self.interfaceKitOutputChanged)
        self.interfaceKit.setOnSensorChangeHandler(self.interfaceKitSensorChanged)

        try:
            self.interfaceKit.openPhidget()

        except PhidgetException, e:
            rospy.logerror("openPhidget() failed")
            rospy.logerror("code: %d" % e.code)
            rospy.logerror("message", e.message)

            raise
Esempio n. 34
0
class pumpUSB:  # pragma: no cover
    def __init__(self):
        print ("Initiating pumps")
        try:
            self.interfaceKit = InterfaceKit()
        except RuntimeError as e:
            print ("Runtime Exception a: %s" % e.details)
            print ("Exiting....")
            exit(1)
        try:
            self.interfaceKit.openPhidget()
        except PhidgetException as e:
            print ("Phidget Exception b %i: %s" % (e.code, e.details))
            print ("Exiting....")
            exit(1)

        try:
            self.interfaceKit.waitForAttach(1000)
        except PhidgetException as e:
            print ("Phidget Exception c %i: %s" % (e.code, e.details))
            raise Exception("Timeout")
            try:
                self.interfaceKit.closePhidget()
            except PhidgetException as e:
                print ("Phidget Exception d %i: %s" % (e.code, e.details))
                print ("Exiting....")
                exit(1)
        self.pumplist = []
        for i in range(0, 4):
            self.pumplist.append(onePump(self.interfaceKit, i))
        print ("Pumps ready")

    def getPump(self, index):
        return self.pumplist[index]

    def getSwitch(self, index):
        """ yes it is the same as getPump, standard name use """
        return self.pumplist[index]

    def close(self):
        self.interfaceKit.closePhidget()
Esempio n. 35
0
    def __init__(self, parent=None):
        super(PhidgetsEventThread, self).__init__(parent)

        try:
            self.interfaceKit = InterfaceKit()
            self.interfaceKit.openPhidget()
            self.interfaceKit.setOnAttachHandler(self.interfaceKitAttachedEvent)
            self.interfaceKit.setOnDetachHandler(self.interfaceKitDetachEvent)
            self.interfaceKit.setOnErrorhandler(self.interfaceKitErrorSlot)
            self.interfaceKit.setOnInputChangeHandler(self.interfaceKitInputChangedEvent)
            self.interfaceKit.setOnOutputChangeHandler(self.interfaceKitOutputChangedEvent)
            self.interfaceKit.setOnSensorChangeHandler(self.interfaceKitSensorChangedEvent)
        except RuntimeError as e:
            print "Runtime Exception: %s" % (e.details)
            print "Exiting..."
            sys.exit(1)
            
        except PhidgetException as e:
            print "Phidget Exception %i: %s" % (e.code, e.details)
            print "Exiting..."
            sys.exit(1) 
Esempio n. 36
0
    def __init__(self):
        #Create an interfacekit object
        try:
            self.interfaceKit = InterfaceKit()
        except RuntimeError as e:
            print("Runtime Exception: %s" % e.details)
            print("Exiting....")
            exit(1)

        try:
            self.interfaceKit.openPhidget()
            self.interfaceKit.waitForAttach(10000)
            self.interfaceKit.setDataRate(self.__sensorPort, self.__sampleRate)
        except PhidgetException as e:
            print("Phidget Exception %i: %s" % (e.code, e.details))
            try:
                self.interfaceKit.closePhidget()
            except PhidgetException as e:
                print("Phidget Exception %i: %s" % (e.code, e.details))
                print("Exiting....")
                exit(1)
Esempio n. 37
0
 def run(self):
         try:
             self.interfaceKit = InterfaceKit() #instanzio la classe per interfacciarmi con la scheda di acquisizione
             self.monitoring = sm.SensorMonitoring() #tabella dove sono memorizzati i valori dei sensori collegati
             self.monitoring.open()
             self.monitoring.create()
         except RuntimeError as e:
             print("Runtime Exception: %s" % e.details)
             print("Exiting....")
             exit(1)
         
         try:
             self.interfaceKit.setOnSensorChangeHandler(self.interfaceKitSensorChanged)
         except PhidgetException as e:
             print("Exiting....")
             exit(1)
             
         try:
             self.interfaceKit.openPhidget()
         except PhidgetException as e:
             print("Exiting....")
             exit(1)
             
         try:
             self.interfaceKit.waitForAttach(10000)
         except PhidgetException as e:
             try:
                 self.interfaceKit.closePhidget()
             except PhidgetException as e:
                 exit(1)
             print("Assicurarsi di aver collegato la scheda di acquisizione Phidget 1019 al PC. Exiting....")
             exit(1)
         else:
             print "Scheda di acquisizione rilevata."
             
         for i in range(self.interfaceKit.getSensorCount()):
             try:
                 self.interfaceKit.setDataRate(i, 4)
             except PhidgetException as e:
                 pass
Esempio n. 38
0
 def __openIF(self):
     try:
         self._interfaceKit = InterfaceKit()
     except RuntimeError as e:
         print("IF Kit - Runtime Exception: %s" % e.details)
         return False
     try:
         self._interfaceKit.setOnAttachHandler(self.__onAttachedIF)
         self._interfaceKit.setOnDetachHandler(self.__onDetachedIF)
         self._interfaceKit.setOnErrorhandler(self.__onErrorIF)
         self._interfaceKit.setOnInputChangeHandler(self.__onInputChangedIF)
         self._interfaceKit.setOnSensorChangeHandler(self.__onSensorChangedIF)
     except PhidgetException as e:
         print("IF Kit - Phidget Exception %i: %s" % (e.code, e.details))
         return False
     try:
         self._interfaceKit.openPhidget()
     except PhidgetException as e:
         print("IF Kit - Phidget Exception %i: %s" % (e.code, e.details))
         return False
     self._openIF=True
     return True
Esempio n. 39
0
from ctypes import *
import sys
from time import sleep
import zmq

#Phidget specific imports
from Phidgets.Phidget import PhidgetID
from Phidgets.PhidgetException import PhidgetErrorCodes, PhidgetException
from Phidgets.Events.Events import AttachEventArgs, DetachEventArgs, ErrorEventArgs
from Phidgets.Devices.TextLCD import TextLCD, TextLCD_ScreenSize
from Phidgets.Devices.InterfaceKit import InterfaceKit

#Create an TextLCD object
try:
    interfaceKitLCD = InterfaceKit()
except RuntimeError as e:
    print("Runtime Exception: %s" % e.details)
    print("Exiting....")
    exit(1)

def InterfaceKitLCDError(e):
    try:
        source = e.device
        print("InterfaceKitLCD %i: Phidget Error %i: %s" % (source.getSerialNum(), e.eCode, e.description))
    except PhidgetException as e:
        print("Phidget Exception %i: %s" % (e.code, e.details))


#Connect the event handlers
try:
    source = e.device
    print("InterfaceKit %i: Output %i: %s" % (source.getSerialNum(), e.index, e.state))
    if (source.getSerialNum() == SERIAL_NUM) and (e.index == RELAY):
            if e.state == True:
                # Set an alarm
                signal.alarm(TIMEOUT) 
                print "Alarm set"

        
if __name__ == "__main__":
    # Set the timeout alarm signal handler
    signal.signal(signal.SIGALRM, handler)

    #Create an interfacekit object
    try:
        interfaceKit = InterfaceKit()
    except RuntimeError as e:
        print("Runtime Exception: %s" % e.details)
        print("Exiting....")
        exit(1)

    try:
        interfaceKit.setOnAttachHandler(inferfaceKitAttached)
        interfaceKit.setOnDetachHandler(interfaceKitDetached)
        interfaceKit.setOnErrorhandler(interfaceKitError)
        interfaceKit.setOnInputChangeHandler(interfaceKitInputChanged)
        interfaceKit.setOnOutputChangeHandler(interfaceKitOutputChanged)
        interfaceKit.setOnSensorChangeHandler(interfaceKitSensorChanged)
    except PhidgetException as e:
        print("Phidget Exception %i: %s" % (e.code, e.details))
        print("Exiting....")
Esempio n. 41
0
#Basic imports
import sensMonitoring as sm
from datetime import datetime

#Phidget specific imports
from Phidgets.PhidgetException import PhidgetException
from Phidgets.Devices.InterfaceKit import InterfaceKit

Wheatstone = True
V1 = 0.0
V2 = 0.0

#Create an interfacekit object
try:
    interfaceKit = InterfaceKit()
    monitoring = sm.SensorMonitoring(
    )  #tabella dove sono memorizzati i valori dei sensori collegati
    monitoring.open()
    monitoring.create()
except RuntimeError as e:
    print("Runtime Exception: %s" % e.details)
    print("Exiting....")
    exit(1)


#Information Display Function
def displayDeviceInfo():
    pass

__author__ = 'Adam Stelmack'
__version__ = '2.1.8'
__date__ = 'May 17 2010'

#Basic imports
from ctypes import *
import sys
import random
#Phidget specific imports
from Phidgets.PhidgetException import PhidgetErrorCodes, PhidgetException
from Phidgets.Events.Events import AttachEventArgs, DetachEventArgs, ErrorEventArgs, InputChangeEventArgs, OutputChangeEventArgs, SensorChangeEventArgs
from Phidgets.Devices.InterfaceKit import InterfaceKit

#Create an interfacekit object
try:
    interfaceKit = InterfaceKit()
except RuntimeError as e:
    print("Runtime Exception: %s" % e.details)
    print("Exiting....")
    exit(1)

#Information Display Function
def displayDeviceInfo():
    print("|------------|----------------------------------|--------------|------------|")
    print("|- Attached -|-              Type              -|- Serial No. -|-  Version -|")
    print("|------------|----------------------------------|--------------|------------|")
    print("|- %8s -|- %30s -|- %10d -|- %8d -|" % (interfaceKit.isAttached(), interfaceKit.getDeviceName(), interfaceKit.getSerialNum(), interfaceKit.getDeviceVersion()))
    print("|------------|----------------------------------|--------------|------------|")
    print("Number of Digital Inputs: %i" % (interfaceKit.getInputCount()))
    print("Number of Digital Outputs: %i" % (interfaceKit.getOutputCount()))
    print("Number of Sensor Inputs: %i" % (interfaceKit.getSensorCount()))
Esempio n. 43
0
class LTCPhidget(object):
    # TODO: can the remote specific events find a disconnected usb cable?
    devserial = 0
    IP = "0.0.0.0"
    port = 0

    input = {}
    output = {}
    sensor = {}

    callback = {
        'attach': [],
        'detach': [],
        'error': [],
        'output': [],
        'input': [],
        'sensor': []
    }

    def __init__(self, **kwargs):
        log.debug("Acquiring InterfaceKit")
        self.ik = InterfaceKit()
        log.debug("Registering Handlers")
        self.ik.setOnAttachHandler(self._onAttach)
        self.ik.setOnDetachHandler(self._onDetach)
        self.ik.setOnErrorhandler(self._onError)
        self.ik.setOnOutputChangeHandler(self._onOutput)
        self.ik.setOnInputChangeHandler(self._onInput)
        self.ik.setOnSensorChangeHandler(self._onSensor)

    def start(self):
        log.verbose("Opening remote IP")
        self.ik.openRemoteIP(self.IP, self.port, self.devserial)
        log.debug("Remote IP opened")

    def close(self):
        log.verbose("Closing InterfaceKit")
        self.ik.closePhidget()
        log.debug("Interfac kit closed")

    def add_callback(self, cb, type):
        log.debug("Adding a {} type callback".format(type))
        self.callback[type].append(cb)

    def remove_callback(self, cb, type):
        log.debug("Removing a {} type callback".format(type))
        self.callback[type].remove(cb)

    def _genericCB(self, event, type):
        log.verbose("{} event received".format(type))
        for cb in self.callback[type]:
            cb(event)
        for dev in self.input.itervalues():
            for cb in dev.callback[type]:
                cb(event)
        for dev in self.output.itervalues():
            for cb in dev.callback[type]:
                cb(event)
        for dev in self.sensor.itervalues():
            for cb in dev.callback[type]:
                cb(event)

    def _onAttach(self, event):
        self._genericCB(event, 'attach')

    def _onDetach(self, event):
        self._genericCB(event, 'detach')

    def _onError(self, event):
        log.debug(event.description)
        log.verbose("{} event received".format(type))
        for cb in self.callback['error']:
            cb(event)

    def _onOutput(self, event):
        log.verbose("Output event received")
        for cb in self.callback['output']:
            cb(event)
        try:
            for cb in self.output[event.index].callback['value']:
                cb(event)
        except KeyError:
            pass

    def _onInput(self, event):
        log.verbose("Input event received")
        for cb in self.callback['input']:
            cb(event)
        try:
            for cb in self.input[event.index].callback['value']:
                cb(event)
        except KeyError:
            pass

    def _onSensor(self, event):
        log.verbose("Sensor event received")
        for cb in self.callback['sensor']:
            cb(event)
        try:
            for cb in self.sensor[event.index].callback['value']:
                cb(event)
        except KeyError:
            pass
Esempio n. 44
0
def setup_phidgets():
    global interfaceKits
    interfaceKits = InterfaceKits()

    "Print Creating phidget manager"
    try:
        manager = Manager()
    except RuntimeError as e:
        output("Runtime Exception: %s" % e.details)
        output("Exiting....")
        exit(1)

    try:
        manager.setOnAttachHandler(ManagerDeviceAttached)
        manager.setOnDetachHandler(ManagerDeviceDetached)
        manager.setOnErrorHandler(ManagerError)
    except PhidgetException as e:
        output("Phidget Exception %i: %s" % (e.code, e.details))
        output("Exiting....")
        exit(1)

    output("Opening phidget manager....")
    logging.info("Opening phidget manager....")

    try:
        manager.openManager()
        #manager.openRemote("hydropi","hydropi")
    except PhidgetException as e:
        output("Phidget Exception %i: %s" % (e.code, e.details))
        logging.error("Phidget Exception %i: %s" % (e.code, e.details))
        output("Exiting....")
        logging.error("Exiting....")
        exit(1)

    # Wait a moment for devices to attache......
    output("\nWaiting one sec for devices to attach....\n\n")
    logging.info("Waiting one sec for devices to attach....")
    time.sleep(1)

    output("Phidget manager opened.")

    attachedDevices = manager.getAttachedDevices()
    for attachedDevice in attachedDevices:
     
        output("Found %30s - SN %10d" % (attachedDevice.getDeviceName(), attachedDevice.getSerialNum()))
        if attachedDevice.getDeviceClass() == PhidgetClass.INTERFACEKIT:
            output("  %s/%d is an InterfaceKit" % ( attachedDevice.getDeviceName(),attachedDevice.getSerialNum()))
            #Create an interfacekit object
            try:
                newInterfaceKit = InterfaceKit()
            except RuntimeError as e:
                output("Runtime Exception: %s" % e.details)
                output("Exiting....")
                exit(1)

            output("  Opening...")
            try:
                newInterfaceKit.openPhidget()
            except PhidgetException as e:
                output("Phidget Exception %i: %s" % (e.code, e.details))
                output("Exiting....")

            output("  Setting handlers...")
            try:
                newInterfaceKit.setOnAttachHandler(interfaceKitAttached)
                newInterfaceKit.setOnDetachHandler(interfaceKitDetached)
                newInterfaceKit.setOnErrorhandler(interfaceKitError)
            except PhidgetException as e:
                output("Phidget Exception %i: %s" % (e.code, e.details))
                output("Exiting....")
                exit(1)

            output("  Attaching...")
            try:
                newInterfaceKit.waitForAttach(5000)
            except PhidgetException as e:
                output("Phidget Exception %i: %s" % (e.code, e.details))
                try:
                    newInterfaceKit.closePhidget()
                except PhidgetException as e:
                    output("Phidget Exception %i: %s" % (e.code, e.details))
                    output("Exiting....")
                    exit(1)
                output("Exiting....")
                exit(1)

            output("  Setting the data rate for each sensor index to 1000ms....")
            for i in range(newInterfaceKit.getSensorCount()):
                try:
                    newInterfaceKit.setDataRate(i, 1000)
                except PhidgetException as e:
                    output("Phidget Exception %i: %s" % (e.code, e.details))

            interfaceKits.kitList.append(newInterfaceKit)
            
        
    display_device_info(manager)
    return manager 
Esempio n. 45
0
__date__ = 'May 17 2010'

#Basic imports
from ctypes import *
import sys
import random
from datetime import datetime
#Phidget specific imports
from Phidgets.PhidgetException import PhidgetErrorCodes, PhidgetException
from Phidgets.Events.Events import AttachEventArgs, DetachEventArgs, ErrorEventArgs, InputChangeEventArgs, OutputChangeEventArgs, SensorChangeEventArgs
from Phidgets.Devices.InterfaceKit import InterfaceKit
from Phidgets.Devices.GPS import GPS

#Create an interfacekit object
try:
    interfaceKit = InterfaceKit()
    gps = GPS()
except RuntimeError as e:
    print("Runtime Exception: %s" % e.details)
    print("Exiting....")
    exit(1)

#Information Display Function
def displayDeviceInfo():
    print("|------------|----------------------------------|--------------|------------|")
    print("|- Attached -|-              Type              -|- Serial No. -|-  Version -|")
    print("|------------|----------------------------------|--------------|------------|")
    print("|- %8s -|- %30s -|- %10d -|- %8d -|" % (interfaceKit.isAttached(), interfaceKit.getDeviceName(), interfaceKit.getSerialNum(), interfaceKit.getDeviceVersion()))
    print("|------------|----------------------------------|--------------|------------|")
    print("Number of Digital Inputs: %i" % (interfaceKit.getInputCount()))
    print("Number of Digital Outputs: %i" % (interfaceKit.getOutputCount()))
Esempio n. 46
0
from django.shortcuts import render, HttpResponse, redirect, get_object_or_404
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.core.mail import send_mail, BadHeaderError
from django.views.decorators.cache import cache_page
from django.utils import timezone
from django.conf import settings
from .models import Plant, Photo
import json
from Phidgets.PhidgetException import PhidgetException
from Phidgets.Devices.InterfaceKit import InterfaceKit
# Create your views here.

is_phidget_connected = False
interfaceKit = InterfaceKit()
light_val = 0
try:
    interfaceKit.openRemoteIP('169.254.4.87', 5001, -1, "greenspy")
except PhidgetException as e:
    print("Phidget Exception %i: %s" % (e.code, e.details))
    print("Exiting....")
# try:
#     light_val = interfaceKit.getSensorValue(0)
# except PhidgetException as e:
#     print("Phidget Exception %i: %s" % (e.code, e.details))


def main_page(request):
    # Create an interface kit object
    return render(request, 'GreenSpy/index.html')
#Basic imports
from ctypes import *
import sys
import random
import socket
#Phidget specific imports
from Phidgets.PhidgetException import PhidgetErrorCodes, PhidgetException
from Phidgets.Events.Events import AttachEventArgs, DetachEventArgs, ErrorEventArgs, InputChangeEventArgs, OutputChangeEventArgs, SensorChangeEventArgs
from Phidgets.Devices.InterfaceKit import InterfaceKit




#Create an interfacekit object
try:
    interfaceKit = InterfaceKit()
except RuntimeError as e:
    print("Runtime Exception: %s" % e.details)
    print("Exiting....")
    exit(1)
    
#Information Display Function
def displayDeviceInfo():
    print("|------------|----------------------------------|--------------|------------|")
    print("|- Attached -|-              Type              -|- Serial No. -|-  Version -|")
    print("|------------|----------------------------------|--------------|------------|")
    print("|- %8s -|- %30s -|- %10d -|- %8d -|" % (interfaceKit.isAttached(), interfaceKit.getDeviceName(), interfaceKit.getSerialNum(), interfaceKit.getDeviceVersion()))
    print("|------------|----------------------------------|--------------|------------|")
    print("Number of Digital Inputs: %i" % (interfaceKit.getInputCount()))
    print("Number of Digital Outputs: %i" % (interfaceKit.getOutputCount()))
    print("Number of Sensor Inputs: %i" % (interfaceKit.getSensorCount()))
Esempio n. 48
0
    except PhidgetException as e:
        print("Phidget Exception %i: %s" % (e.code, e.details))
        print("Exiting....")
        exit(1)
    print("Exiting....")
    exit(1)

advancedServo.setPosition(0, myservoposition)
print("Servo initialized.")



#Create  an initialize an interfacekit object_______________________
print("Initialzing Interface Kit...")
try:
    interfaceKit = InterfaceKit()
except RuntimeError as e:
    print("Runtime Exception: %s" % e.details)
    print("Exiting....")
    exit(1)

try:
    interfaceKit.setOnAttachHandler(interfaceKitAttached)
    interfaceKit.setOnDetachHandler(interfaceKitDetached)
    interfaceKit.setOnErrorhandler(interfaceKitError)
    interfaceKit.setOnInputChangeHandler(interfaceKitInputChanged)
    interfaceKit.setOnOutputChangeHandler(interfaceKitOutputChanged)
    interfaceKit.setOnSensorChangeHandler(interfaceKitSensorChanged)
except PhidgetException as e:
    print("Phidget Exception %i: %s" % (e.code, e.details))
    print("Exiting....")
Esempio n. 49
0
def main():
    args = parseCommandLineArgs()
    config = getSetupInfoFromConfig()
    if args["add"]:
        saveNewSetup(
            args["<setupName>"][0],
            args["<phidgetWebServiceIPaddress>"],
            args["<StartechAdaptorIPaddress>"],
            phidget_webservice_listen_port=int(args["--phidgetPort"]),
            pump_telnet_listen_port=int(args["--startechPort"]),
        )

    elif args["rm"]:
        for setup in args["<setupName>"]:
            deleteSetup(setup)

    elif args["config"] and args["channels"]:
        updateSetupField(args["<setupName>"][0], "pump_channels", [chan for chan in args["<chans>"]])

    elif args["run"]:
        if args["cycle"]:
            threads = []
            for setup in args["<setupName>"]:
                #run pump routine for each setup in its own thread
                pump_routine = cycleFor(
                    int(args["-n"]),
                    setup,
                    config["setups"][setup]["setupIPaddr"],
                    config["setups"][setup]["pumpIPaddr"],
                    interfaceKitPort=config["setups"][setup]["phidget_webservice_listen_port"],
                    primeForBehavior=args["--primePumps"],
                    pumpPort=config["setups"][setup]["pump_telnet_listen_port"],
                    pump_channels=config["setups"][setup]["pump_channels"]
                )
                pump_routine.setDaemon(True)
                pump_routine.start()
                threads.append(pump_routine)
            print "Starting infuse/withdraw for", args["-n"], "cycles. Ctrl+c to stop pumping..."
            try:
                while threading.activeCount() > 1: #keep main thread running so it can raise KeyboardInterrupt
                    time.sleep(1)
            except KeyboardInterrupt:
                for pump_routine in threads: #TODO make this thread safe with threading.Lock in case main thread tries to access pumpConns concurrently
                    if pump_routine.isAlive():
                        for ch in pump_routine.pump_channels:
                            ch = str(ch)
                            pump_routine.pumpsConn.write(ch + " STP\r\n")
                            pump_routine.pumpsConn.read_until(ch, timeout=5)
                        pump_routine.pumpsConn.close()

        if args["forever"]:
            threads = []
            for setup in args["<setupName>"]:
                pump_routine = cycleForever(
                    setup,
                    config["setups"][setup]["setupIPaddr"],
                    config["setups"][setup]["pumpIPaddr"],
                    interfaceKitPort=config["setups"][setup]["phidget_webservice_listen_port"],
                    pumpPort=config["setups"][setup]["pump_telnet_listen_port"],
                    pump_channels=config["setups"][setup]["pump_channels"]
                )
                pump_routine.setDaemon(True)
                pump_routine.start()
                threads.append(pump_routine)
            print "Withdraw/Infuse cycling forever...happy cleaning. :-)"
            print "Protip: ctrl+c will exit the program after finishing the current cycle"
            try:
                while threading.activeCount() > 1:
                    time.sleep(1)
            except KeyboardInterrupt:
                for pump_routine in threads:
                    if pump_routine.isAlive():
                        for ch in pump_routine.pump_channels:
                            ch = str(ch)
                            pump_routine.pumpsConn.write(ch + " STP\r\n")
                            pump_routine.pumpsConn.read_until(ch, timeout=5)
                        pump_routine.pumpsConn.close()
    elif args["inf"]:
        threads = []
        for setup in args["<setupName>"]:
            controller = InterfaceKit()
            controller.openRemoteIP(config["setups"][setup]["setupIPaddr"], config["setups"][setup]["phidget_webservice_listen_port"])
            pumpsConn = newPumpConnection(config["setups"][setup]["pumpIPaddr"], port=config["setups"][setup]["pump_telnet_listen_port"])
            time.sleep(0.2) #give time to establish connections; multiple threads need extra time
            pump_routine = infuseFully(
                setup,
                controller,
                pumpsConn,
                pump_channels=config["setups"][setup]["pump_channels"]
            )
            pump_routine.setDaemon(True)
            pump_routine.start()
            threads.append(pump_routine)
        print "Infusing...press ctrl+c to cancel."
        try:
            while threading.activeCount() > 1:
                time.sleep(1)
        except KeyboardInterrupt:
            for pump_routine in threads:
                    if pump_routine.isAlive():
                        for ch in pump_routine.pump_channels:
                            ch = str(ch)
                            pump_routine.pump_conn.write(ch + " STP\r\n")
                            pump_routine.pump_conn.read_until(ch, timeout=5)
                        pump_routine.pump_conn.close()
    elif args["wdr"]:
        threads = []
        for setup in args["<setupName>"]:
            controller = InterfaceKit()
            controller.openRemoteIP(config["setups"][setup]["setupIPaddr"], config["setups"][setup]["phidget_webservice_listen_port"])
            pumpsConn = newPumpConnection(config["setups"][setup]["pumpIPaddr"], port=config["setups"][setup]["pump_telnet_listen_port"])
            time.sleep(0.2) #give time to establish connections; multiple threads need extra time
            pump_routine = withdrawFully(
                setup,
                controller,
                pumpsConn,
                pump_channels=config["setups"][setup]["pump_channels"]
            )
            pump_routine.setDaemon(True)
            pump_routine.start()
            threads.append(pump_routine)
        print "Withdrawing...press ctrl+c to cancel."
        try:
            while threading.activeCount() > 1:
                time.sleep(1)
        except KeyboardInterrupt:
            for pump_routine in threads:
                    if pump_routine.isAlive():
                        for ch in pump_routine.pump_channels:
                            ch = str(ch)
                            pump_routine.pump_conn.write(ch + " STP\r\n")
                            pump_routine.pump_conn.read_until(ch, timeout=5)
                        pump_routine.pump_conn.close()

    elif args["prime"]:
        threads = []
        for setup in args["<setupName>"]:
            controller = InterfaceKit()
            controller.openRemoteIP(config["setups"][setup]["setupIPaddr"], config["setups"][setup]["phidget_webservice_listen_port"])
            pumpsConn = newPumpConnection(config["setups"][setup]["pumpIPaddr"], port=config["setups"][setup]["pump_telnet_listen_port"])
            time.sleep(0.2) #give time to establish connections; multiple threads need extra time
            pump_routine = primeForBehaviorSession(
                setup,
                controller,
                pumpsConn,
                pump_channels=config["setups"][setup]["pump_channels"]
            )
            pump_routine.setDaemon(True)
            pump_routine.start()
            threads.append(pump_routine)
        print "Infusing 1 mL to get water flowing for a behavior session...press ctrl+c to cancel."
        try:
            while threading.activeCount() > 1:
                time.sleep(1)
        except KeyboardInterrupt:
            for pump_routine in threads:
                    if pump_routine.isAlive():
                        for ch in pump_routine.pump_channels:
                            ch = str(ch)
                            pump_routine.pump_conn.write(ch + " STP\r\n")
                            pump_routine.pump_conn.read_until(ch, timeout=5)
                        pump_routine.pump_conn.close()
    else:
        pass
Esempio n. 50
0
class Phidgets:
    
    def __init__(self):
        self.V1 = 0.0
        self.V2list = [0,0,0,0,0,0,0] #lista dei valori associati alle porte analogiche, corrispondenza porta analogica posizione nella lista
        self.running = True
        
    def ponteDiWheatstone(self):
        R1 = 1000.0#1KOhm
        R2 = 1000.0#1KOhm
        R3 = 1000.0#1KOhm
        Vs = 5.0
        
        for pos, v in enumerate(self.V2list):
            if v==0:
                continue
            
            Vm = v-self.V1 #ingresso differenziale
            print Vm
            #formula per il calcolo della resistenza
            p1 = R3/(R1+R3) + (Vm/Vs)
            p2 = 1 - p1
            Rx = R2*(p1/p2);
            
            #
            date = datetime.now().strftime('%Y-%m-%d')
            time = datetime.now().strftime('%H:%M:%S')
            self.monitoring.insertValue(Rx, pos+1, date,time)
            #
            print ("la resistenza sull'input %d vale %f: " % (pos+1, Rx))

    def partitoreDiTensione(self, val):
        if val != 1:
            r1 = 1000
            Vref = 12 #5V tensione applicata al partitore
            V2 = (5.0/1023.0)*val #tensione letta ai capi della resistenza
            r2 =  r1*V2/(Vref-V2)
            print ("la resistenza vale %f: " % r2)
        
    def interfaceKitSensorChanged(self, e):
        source = e.device
        if e.value == 1:#1 indica che non sta nulla collegato e resetto anche il suo valore nella lista
            if e.index==0:
                self.V1=0
            else:
                self.V2list[e.index-1]=0
            return
        
        if e.index == 0:#V1 va collegato sempre sul pin 0
            self.V1 = (5.0/1023.0)*e.value 
            print self.V1
        else:
            val = (5.0/1023.0)*e.value
            self.V2list[e.index-1]=val #corrispondenza porta analogica posizione nella lista
            print str(self.V2list)
        
        self.ponteDiWheatstone()
            
        #if e.value != 1:
        #    self.monitoring.insertPos(e.index)
        #print("InterfaceKit %i: Sensor %i: %i" % (source.getSerialNum(), e.index, e.value))
    
    def run(self):
            try:
                self.interfaceKit = InterfaceKit() #instanzio la classe per interfacciarmi con la scheda di acquisizione
                self.monitoring = sm.SensorMonitoring() #tabella dove sono memorizzati i valori dei sensori collegati
                self.monitoring.open()
                self.monitoring.create()
            except RuntimeError as e:
                print("Runtime Exception: %s" % e.details)
                print("Exiting....")
                exit(1)
            
            try:
                self.interfaceKit.setOnSensorChangeHandler(self.interfaceKitSensorChanged)
            except PhidgetException as e:
                print("Exiting....")
                exit(1)
                
            try:
                self.interfaceKit.openPhidget()
            except PhidgetException as e:
                print("Exiting....")
                exit(1)
                
            try:
                self.interfaceKit.waitForAttach(10000)
            except PhidgetException as e:
                try:
                    self.interfaceKit.closePhidget()
                except PhidgetException as e:
                    exit(1)
                print("Assicurarsi di aver collegato la scheda di acquisizione Phidget 1019 al PC. Exiting....")
                exit(1)
            else:
                print "Scheda di acquisizione rilevata."
                
            for i in range(self.interfaceKit.getSensorCount()):
                try:
                    self.interfaceKit.setDataRate(i, 4)
                except PhidgetException as e:
                    pass
                
                 
    def close(self):
        self.running = False
        self.monitoring.close()
        print("Closing...")
        try:
            self.interfaceKit.closePhidget()
        except PhidgetException as e:
            print("Phidget Exception %i: %s" % (e.code, e.details))
            print("Exiting....")
            exit(1)
        
        print("Done.")
        exit(0)
Esempio n. 51
0
class Pot:

    __sensorPort = 1
    __sampleRate = 4 # Maybe too high?

    __potMin = 242
    __potZero = 490
    __potMax = 668


    def __init__(self):
        #Create an interfacekit object
        try:
            self.interfaceKit = InterfaceKit()
        except RuntimeError as e:
            print("Runtime Exception: %s" % e.details)
            print("Exiting....")
            exit(1)

        try:
            self.interfaceKit.openPhidget()
            self.interfaceKit.waitForAttach(10000)
            self.interfaceKit.setDataRate(self.__sensorPort, self.__sampleRate)
        except PhidgetException as e:
            print("Phidget Exception %i: %s" % (e.code, e.details))
            try:
                self.interfaceKit.closePhidget()
            except PhidgetException as e:
                print("Phidget Exception %i: %s" % (e.code, e.details))
                print("Exiting....")
                exit(1)


    def __del__(self):
        try:
            self.interfaceKit.closePhidget()
        except PhidgetException as e:
            print("Phidget Exception %i: %s" % (e.code, e.details))
            print("Exiting....")
            exit(1)

    def getRawPot(self):
        try:
            resp = self.interfaceKit.getSensorValue(self.__sensorPort)
        except PhidgetException as e:
            # suppress print (makes testing harder) #TODO restore!!
            resp = float('nan')
            #print("Skipping reading - phidget Exception %i: %s" % (e.code, e.details))
        return resp

    #def recconect(self):


    def getPot(self):
        rawSensor = self.getRawPot()
        value = 0.0

        if rawSensor > self.__potMax:
            #warnings.warn("Pot measuremens out of bounds.") 
            return 1.0
        if rawSensor < self.__potMin: 
            #warnings.warn("Pot measuremens out of bounds.")
            return -1.0

        if rawSensor >= self.__potZero:
            value = float(rawSensor - self.__potZero) / (self.__potMax - self.__potZero)
        else:
            value = float(rawSensor - self.__potZero) / (self.__potZero - self.__potMin)

        return value
Esempio n. 52
0
class System(DataSourceSystem):
    '''
    Generic DataSourceSystem interface for the Phidgets board: http://www.phidgets.com/products.php?category=0&product_id=1018_2
    '''
    update_freq = 1000

    def __init__(self, n_sensors=2, n_inputs=1):
        '''
        Docstring

        Parameters
        ----------

        Returns
        -------
        '''
        self.n_sensors = n_sensors
        self.n_inputs = n_inputs
        self.interval = 1. / self.update_freq

        self.sensordat = np.zeros((n_sensors,))
        self.inputdat = np.zeros((n_inputs,), dtype=np.bool)
        self.data = np.zeros((1,), dtype=self.dtype)

        self.kit = InterfaceKit()
        self.kit.openPhidget()
        self.kit.waitForAttach(2000)
    
    def start(self):
        '''
        Docstring

        Parameters
        ----------

        Returns
        -------
        '''
        self.tic = time.time()

    def stop(self):
        '''
        Docstring

        Parameters
        ----------

        Returns
        -------
        '''
        pass
    
    def get(self):
        '''
        Docstring

        Parameters
        ----------

        Returns
        -------
        '''
        toc = time.time() - self.tic
        if 0 < toc < self.interval:
            time.sleep(self.interval - toc)
        try:
            for i in range(self.n_sensors):
                self.sensordat[i] = self.kit.getSensorValue(i) / 1000.
            for i in range(self.n_inputs):
                self.inputdat[i] = self.kit.getInputState(i)
        except:
            print 'sensor_error'
        self.data['sensors'] = self.sensordat
        self.data['inputs'] = self.inputdat
        self.tic = time.time()
        return self.data
    
    def sendMsg(self, msg):
        '''
        Docstring

        Parameters
        ----------

        Returns
        -------
        '''
        pass

    def __del__(self):
        '''
        Docstring

        Parameters
        ----------

        Returns
        -------
        '''
        self.kit.closePhidget()