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)
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
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)
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
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 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
def setup_interfaceKit(): #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....") exit(1) print("Opening phidget object....") try: #interfaceKit.openPhidget() interfaceKit.openRemoteIP(IP, port=5001) except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) print("Exiting....") exit(1) print("Waiting for attach....") try: interfaceKit.waitForAttach(10000) except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) try: interfaceKit.closePhidget() except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) print("Exiting....") exit(1) print("Exiting....") exit(1) return interfaceKit
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 __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()
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
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 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 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
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 __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
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))
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 __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
def setupSensorHandlers(): global interfaceKit, batteryPublisher, rangePublisher global batteryVoltageChannel, batteryFullLevel, batteryDepletedLevel, batteryRange, frontRangeChannel, backRangeChannel global batteryInfo, rangeInfo try: interfaceKit = InterfaceKit() except RuntimeError as e: rospy.logfatal('Failed to create InterfaceKit: %s' % (e.details)) rospy.signal_shutdown('Failed to connect to InterfaceKit') try: interfaceKit.setOnAttachHandler(attachHandler) interfaceKit.setOnDetachHandler(detachHandler) interfaceKit.setOnErrorhandler(errorHandler) interfaceKit.setOnInputChangeHandler(inputChangeHandler) interfaceKit.setOnOutputChangeHandler(outputChangeHandler) interfaceKit.setOnSensorChangeHandler(sensorChangeHandler) except PhidgetException as e: rospy.logfatal('Failed to set handlers: %i, %s' % (e.code, e.details)) rospy.signal_shutdown('Failed to connect to InterfaceKit') try: interfaceKit.openPhidget() except PhidgetException as e: rospy.logfatal("Failed to openPhidget() %i: %s" % (e.code, e.details)) rospy.signal_shutdown('Failed to openPhidget()') try: interfaceKit.waitForAttach(10000) except PhidgetException as e: rospy.logfatal("Failed on waitForAttach() %i: %s" % (e.code, e.details)) interfaceKit.closePhidget() rospy.signal_shutdown('Failed on waitForAttach()') for sensor in range(interfaceKit.getSensorCount()): try: interfaceKit.setDataRate(sensor, 16) except PhidgetException as e: rospy.logwarn("Failed to setDateRate() %i: %s" % (e.code, e.details)) batteryPublisher = rospy.Publisher('batteryInfo', Battery) rangePublisher = rospy.Publisher('rangeInfo', Range) batteryVoltageChannel = rospy.get_param('RoverState/battery/channel') batteryFullLevel = float(rospy.get_param('RoverState/battery/fullCharge')) batteryDepletedLevel = rospy.get_param('RoverState/battery/depletedCharge') batteryRange = batteryFullLevel - batteryDepletedLevel frontRangeChannel = rospy.get_param('RoverState/range/front/channel') backRangeChannel = rospy.get_param('RoverState/range/back/channel') sendRange() sendBattery() return
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
#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.Phidget import PhidgetID #added from Phidgets.Devices.TextLCD import TextLCD, TextLCD_ScreenSize #added for LCD from Phidgets.PhidgetException import PhidgetErrorCodes, PhidgetException from Phidgets.Events.Events import AttachEventArgs, DetachEventArgs, ErrorEventArgs, CurrentChangeEventArgs, PositionChangeEventArgs, VelocityChangeEventArgs from Phidgets.Devices.AdvancedServo import AdvancedServo from Phidgets.Devices.Servo import ServoTypes from Phidgets.PhidgetException import PhidgetException from Phidgets.Devices.GPS import GPS #Create an interfacekit object try: interfaceKit = InterfaceKit() except RuntimeError as e: print("Runtime Exception: %s" % e.details) print("Exiting....") exit(1) #Create an TextLCD object try: textLCD = TextLCD() except RuntimeError as e: print("Runtime Exception: %s" % e.details) print("Exiting....") exit(1) #Information Display Function #IFkit8/8/8
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:
def connect_to_phidget(SensorChangedFunction, serial_number=None): #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())) #Event Handler Callback Functions def interfaceKitAttached(e): attached = e.device print("InterfaceKit %i Attached!" % (attached.getSerialNum())) def interfaceKitDetached(e): detached = e.device print("InterfaceKit %i Detached!" % (detached.getSerialNum())) def interfaceKitError(e): try: source = e.device print("InterfaceKit %i: Phidget Error %i: %s" % (source.getSerialNum(), e.eCode, e.description)) except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) #Main Program Code try: interfaceKit.setOnAttachHandler(interfaceKitAttached) interfaceKit.setOnDetachHandler(interfaceKitDetached) interfaceKit.setOnErrorhandler(interfaceKitError) except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) print("Exiting....") exit(1) print("Opening phidget object....") try: if serial_number is not None: interfaceKit.openPhidget(serial_number) else: interfaceKit.openPhidget() except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) print("Exiting....") exit(1) print("Waiting for attach....") try: interfaceKit.waitForAttach(10000) except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) try: interfaceKit.closePhidget() except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) print("Exiting....") exit(1) print("Exiting....") exit(1) else: displayDeviceInfo() phidget = interfaceKit return phidget
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')
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
return True from Phidgets.PhidgetException import * from Phidgets.Events.Events import * from Phidgets.Manager import Manager from Phidgets.Phidget import PhidgetLogLevel from Phidgets.Devices.MotorControl import MotorControl motorC = MotorControl() from Phidgets.Devices.AdvancedServo import AdvancedServo servoC = AdvancedServo() from Phidgets.Devices.InterfaceKit import InterfaceKit interC = InterfaceKit() def motorInpChange(e): inp = e.state print('[M] Motor Input: ' + str(inp)) def motorCurChange(e): cur = e.current print('[M] Motor Cur: ' + str(cur)) def motorVelChange(e): vel = e.velocity print('[M] Motor Velocity: ' + str(vel))
#Phidget specific imports from Phidgets.PhidgetException import PhidgetErrorCodes, PhidgetException from Phidgets.Events.Events import AttachEventArgs, DetachEventArgs, ErrorEventArgs from Phidgets.Devices.InterfaceKit import InterfaceKit import signal interupt = False def signal_handler(signum, frame): global interupt interupt = True #Create an interfacekit object try: interfaceKitHUB = InterfaceKit() #interfaceKitLCD = 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 -|" % (interfaceKitHUB.isAttached(),interfaceKitHUB.getDeviceName(), interfaceKitHUB.getSerialNum(), interfaceKitHUB.getDeviceVersion())) # print("|- %8s -|- %30s -|- %10d -|- %8d -|" % (interfaceKitLCD.isAttached(), interfaceKitLCD.getDeviceName(), interfaceKitLCD.getSerialNum(), interfaceKitLCD.getDeviceVersion())) print("|------------|----------------------------------|--------------|------------|") print("Number of Digital Inputs: %i" % (interfaceKitHUB.getInputCount()))
#AquaIntPhidget # For use with Aquaresp.com # Author: Morten Bo Soendergaard Svendsen, fishiology.dk/comparativ.com, April 2016 import sys from Phidgets.Devices.InterfaceKit import InterfaceKit ik = InterfaceKit() ik.openPhidget() ik.waitForAttach(10000) ik.setOutputState(int(sys.argv[1]),int(sys.argv[2]))