def open_relay(channel): relay = DigitalOutput() relay.setOnAttachHandler(relayAttachHandler) relay.setOnDetachHandler(relayDetachHandler) relay.setOnErrorHandler(relayErrorHandler) try: relay.setDeviceSerialNumber(352936) relay.setChannel(channel) print('Wait for relay to attach...') relay.openWaitForAttachment(5000) except PhidgetException as e: print("Program Terminated: Relay Open Failed") return return relay
def init_interface(interfaceKit_serial, hubPort, isHubPortDevice): if with_interface: try: print("Connecting Output Channels (%s): %s" % (interfaceKit_serial, output_channels)) for ich, this_channel in enumerate(output_channels): print("... %s: %s" % (ich, this_channel)) ch = DigitalOutput() ch.setDeviceSerialNumber(interfaceKit_serial) ch.setHubPort(hubPort) ch.setIsHubPortDevice(isHubPortDevice) ch.setChannel(df_params.loc[1, this_channel]) ch.setOnAttachHandler(onAttachHandler) ch.setOnDetachHandler(onDetachHandler) ch.setOnErrorHandler(onErrorHandler) ch.openWaitForAttachment(5000) interfaceKit_output[ich] = ch interfaceKit_output[ich].setState(False) #init off print("Connecting Input Channels %s: %s" % (interfaceKit_serial, input_channels)) for ich, this_channel in enumerate(input_channels): ch = DigitalInput() if ich == 1: # 'input_zLimitSwitch', 'input_fLimitSwitch'] ch.linkedOutput = f_stepper ch.linkedOutput.setOnPositionChangeHandler( fpositionChangeHandler) ch.setOnStateChangeHandler(fonStateChangeHandler) else: ch.linkedOutput = z_stepper ch.linkedOutput.setOnPositionChangeHandler( zpositionChangeHandler) ch.setOnStateChangeHandler(zonStateChangeHandler) ch.setDeviceSerialNumber(interfaceKit_serial) ch.setHubPort(hubPort) ch.setIsHubPortDevice(isHubPortDevice) ch.setChannel(df_params.loc[1, this_channel]) ch.setOnAttachHandler(onAttachHandler) ch.setOnDetachHandler(onDetachHandler) ch.setOnErrorHandler(onErrorHandler) ch.openWaitForAttachment(5000) interfaceKit_input[ich] = ch except PhidgetException as e: print("Attachment Terminated: Open Failed", e) print("Cleaning up...") for ch in interfaceKit_output: ch.close() return False except RuntimeError as e: print("Attachment Terminated: RunTimeError", e) sys.stderr.write("Runtime Error: \t") return False return [interfaceKit_output, interfaceKit_input]
def main(): try: # Create your Phidget channels digitalOutput0 = DigitalOutput() digitalOutput1 = DigitalOutput() digitalOutput2 = DigitalOutput() digitalOutput3 = DigitalOutput() # Set addressing parameters to specify which channel to open (if any) digitalOutput0.setChannel(0) digitalOutput1.setChannel(1) digitalOutput2.setChannel(2) digitalOutput3.setChannel(3) # Assign any event handlers you need before calling open so that no events are missed. digitalOutput0.setOnAttachHandler(onAttach) digitalOutput0.setOnDetachHandler(onDetach) digitalOutput0.setOnErrorHandler(onError) digitalOutput1.setOnAttachHandler(onAttach) digitalOutput1.setOnDetachHandler(onDetach) digitalOutput1.setOnErrorHandler(onError) digitalOutput2.setOnAttachHandler(onAttach) digitalOutput2.setOnDetachHandler(onDetach) digitalOutput2.setOnErrorHandler(onError) digitalOutput3.setOnAttachHandler(onAttach) digitalOutput3.setOnDetachHandler(onDetach) digitalOutput3.setOnErrorHandler(onError) # Open your Phidgets and wait for attachment digitalOutput0.openWaitForAttachment(5000) digitalOutput1.openWaitForAttachment(5000) digitalOutput2.openWaitForAttachment(5000) digitalOutput3.openWaitForAttachment(5000) # Do stuff with your Phidgets here or in your event handlers. digitalOutput0.setDutyCycle(1) digitalOutput1.setDutyCycle(1) digitalOutput2.setDutyCycle(1) digitalOutput3.setDutyCycle(1) with open("keys.txt", "r") as timing_file: try: state_str = timing_file.read(2) last_state = False elapsed_time = Decimal("0.00") while state_str: state = bool(int(state_str[-1:])) if state != last_state: if state: digitalOutput0.setDutyCycle(1) digitalOutput1.setDutyCycle(1) digitalOutput2.setDutyCycle(1) digitalOutput3.setDutyCycle(1) else: digitalOutput0.setDutyCycle(0) digitalOutput1.setDutyCycle(0) digitalOutput2.setDutyCycle(0) digitalOutput3.setDutyCycle(0) print(" ", end="\r") print(f"State: {state}\tTime: {elapsed_time}", end="\r") time.sleep(0.02) elapsed_time += Decimal("0.02") state_str = timing_file.read(2) last_state = state except (Exception, KeyboardInterrupt): pass # Close your Phidgets once the program is done. digitalOutput0.close() digitalOutput1.close() digitalOutput2.close() digitalOutput3.close() except PhidgetException as ex: # We will catch Phidget Exceptions here, and print the error informaiton. traceback.print_exc() print("") print("PhidgetException " + str(ex.code) + " (" + ex.description + "): " + ex.details)
def main(): # Relay Phidget setup try: relay = DigitalOutput() except RuntimeError as e: print("Runtime Exception: %s" % e.details) print("Exiting....") exit(1) def relayAttachHandler(e): ph = relay try: #If you are unsure how to use more than one Phidget channel with this event, we recommend going to #www.phidgets.com/docs/Using_Multiple_Phidgets for information print("\nAttach Event:") """ * Get device information and display it. """ serialNumber = ph.getDeviceSerialNumber() channelClass = ph.getChannelClassName() channel = ph.getChannel() deviceClass = ph.getDeviceClass() if (deviceClass != DeviceClass.PHIDCLASS_VINT): print("\n\t-> Channel Class: " + channelClass + "\n\t-> Serial Number: " + str(serialNumber) + "\n\t-> Channel " + str(channel) + "\n") else: hubPort = ph.getHubPort() print("\n\t-> Channel Class: " + channelClass + "\n\t-> Serial Number: " + str(serialNumber) + "\n\t-> Hub Port: " + str(hubPort) + "\n\t-> Channel " + str(channel) + "\n") except PhidgetException as e: print("\nError in Attach Event:") DisplayError(e) traceback.print_exc() return def relayDetachHandler(e): ph = relay try: #If you are unsure how to use more than one Phidget channel with this event, we recommend going to #www.phidgets.com/docs/Using_Multiple_Phidgets for information print("\nDetach Event:") """ * Get device information and display it. """ serialNumber = ph.getDeviceSerialNumber() channelClass = ph.getChannelClassName() channel = ph.getChannel() deviceClass = ph.getDeviceClass() if (deviceClass != DeviceClass.PHIDCLASS_VINT): print("\n\t-> Channel Class: " + channelClass + "\n\t-> Serial Number: " + str(serialNumber) + "\n\t-> Channel " + str(channel) + "\n") else: hubPort = ph.getHubPort() print("\n\t-> Channel Class: " + channelClass + "\n\t-> Serial Number: " + str(serialNumber) + "\n\t-> Hub Port: " + str(hubPort) + "\n\t-> Channel " + str(channel) + "\n") except PhidgetException as e: print("\nError in Detach Event:") DisplayError(e) traceback.print_exc() return def relayErrorHandler(button, errorCode, errorString): sys.stderr.write("[Phidget Error Event] -> " + errorString + " (" + str(errorCode) + ")\n") try: relay.setOnAttachHandler(relayAttachHandler) relay.setOnDetachHandler(relayDetachHandler) relay.setOnErrorHandler(relayErrorHandler) except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) print("Exiting....") exit(1) try: relay.setDeviceSerialNumber(120683) relay.setChannel(0) relay.open() relay.openWaitForAttachment(5000) except PhidgetException as e: PrintOpenErrorMessage(e, ch) raise EndProgramSignal("Program Terminated: Digital Input Open Failed") total_time = sys.argv[1] interval = sys.argv[2] camera_ports = [] ports_strings = subprocess.check_output(["gphoto2", "--auto-detect"]) ports_strings_split = ports_strings.split() for item in ports_strings_split: item = item.decode('utf-8') if item[0] == 'u': camera_ports.append(item) number_of_cameras = len(camera_ports) number_of_photos = str(math.ceil(int(total_time) / int(interval))) processes = [] i = 0 x = 0 while x < int(number_of_photos): i = 0 time.sleep(int(interval)) while i < number_of_cameras: print(i) process = subprocess.Popen([ "python3", "/home/ryan/Documents/full_circle/timelapse/capture.py", str(i), number_of_photos, interval, str(x) ]) processes.append(process) i = i + 1 x = x + 1 relay.setDutyCycle(1.0) time.sleep(3) relay.setDutyCycle(0.0) for proc in processes: os.killpg(os.getpgid(proc.pid), signal.SIGTERM) try: relay.close() exit(0) except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) print("Exiting....") exit(1)
def main(): try: """ * Allocate a new Phidget Channel object """ ch = DigitalOutput() """ * Set matching parameters to specify which channel to open """ #You may remove this line and hard-code the addressing parameters to fit your application channelInfo = AskForDeviceParameters(ch) ch.setDeviceSerialNumber(channelInfo.deviceSerialNumber) ch.setHubPort(channelInfo.hubPort) ch.setIsHubPortDevice(channelInfo.isHubPortDevice) ch.setChannel(channelInfo.channel) if (channelInfo.netInfo.isRemote): ch.setIsRemote(channelInfo.netInfo.isRemote) if (channelInfo.netInfo.serverDiscovery): try: Net.enableServerDiscovery( PhidgetServerType.PHIDGETSERVER_DEVICEREMOTE) except PhidgetException as e: PrintEnableServerDiscoveryErrorMessage(e) raise EndProgramSignal( "Program Terminated: EnableServerDiscovery Failed") else: Net.addServer("Server", channelInfo.netInfo.hostname, channelInfo.netInfo.port, channelInfo.netInfo.password, 0) """ * Add event handlers before calling open so that no events are missed. """ print("\n--------------------------------------") print("\nSetting OnAttachHandler...") ch.setOnAttachHandler(onAttachHandler) print("Setting OnDetachHandler...") ch.setOnDetachHandler(onDetachHandler) print("Setting OnErrorHandler...") ch.setOnErrorHandler(onErrorHandler) """ * Open the channel with a timeout """ print("\nOpening and Waiting for Attachment...") try: ch.openWaitForAttachment(5000) except PhidgetException as e: PrintOpenErrorMessage(e, ch) raise EndProgramSignal("Program Terminated: Open Failed") print( "--------------------\n" "\n | The output of a DigitalOutput channel can be controlled by setting its Duty Cycle.\n" " | The Duty Cycle can be a number from 0.0 or 1.0\n" " | Some devices only accept Duty Cycles of 0 and 1.\n" "\nInput a desired duty cycle from 0.0 or 1.0 and press ENTER\n" "Input Q and press ENTER to quit\n") end = False state = False while (end != True): buf = sys.stdin.readline(100) if not buf: continue if (buf[0] == 'Q' or buf[0] == 'q'): end = True continue try: dutyCycle = float(buf) except ValueError as e: print("Input must be a number, or Q to quit.") continue if (dutyCycle > 1.0 or dutyCycle < 0.0): print("Duty Cycle must be between 0.0 and 1.0") continue print("Setting DigitalOutput DutyCycle to " + str(dutyCycle)) ch.setDutyCycle(dutyCycle) print("Cleaning up...") ch.close() print("\nExiting...") return 0 except PhidgetException as e: sys.stderr.write("\nExiting with error(s)...") DisplayError(e) traceback.print_exc() print("Cleaning up...") ch.close() return 1 except EndProgramSignal as e: print(e) print("Cleaning up...") ch.close() return 1 except RuntimeError as e: sys.stderr.write("Runtime Error: \n\t" + e) traceback.print_exc() return 1 finally: print("Press ENTER to end program.") readin = sys.stdin.readline()
class PhidgetController: def __init__(self, channel: int): self.io = DigitalOutput() self.queue = asyncio.Queue() self._io_handler_task: Optional[asyncio.Task] = None # Set addressing parameters to specify which channel to open (if any) self.io.setChannel(channel) # Assign any event handlers you need before calling open so that no events are missed. self.io.setOnAttachHandler(self.onAttach) self.io.setOnDetachHandler(self.onDetach) self.io.setOnErrorHandler(self.onError) # Open your Phidgets and wait for attachment self.io.openWaitForAttachment(5000) async def start(self): try: while True: command = await self.queue.get() if self._io_handler_task: self._io_handler_task.cancel() if command["mode"] == "end": break self._io_handler_task = asyncio.get_event_loop().create_task( self._io_handler(command)) finally: print("Closing phidget") try: self.io.setDutyCycle(0) self.io.close() except PhidgetException: print("device not connected") # if self._io_handler_task: # self._io_handler_task.cancel() async def _io_handler(self, command: dict): print(command) try: if command["mode"] == "wave": phase_s = (1 / command["frequency_hz"]) / 2 while True: self.io.setDutyCycle(0) await asyncio.sleep(phase_s) self.io.setDutyCycle(1) await asyncio.sleep(phase_s) if command["mode"] == "pwm": period_s = 1 / command["frequency_hz"] on_phase_s = command["duty_cycle"] * period_s off_phase_s = period_s - on_phase_s while True: self.io.setDutyCycle(0) await asyncio.sleep(on_phase_s) self.io.setDutyCycle(1) await asyncio.sleep(off_phase_s) if command["mode"] == "off": self.io.setDutyCycle(0) while True: await asyncio.sleep(3600) if command["mode"] == "on": self.io.setDutyCycle(1) while True: await asyncio.sleep(3600) except asyncio.CancelledError: pass @staticmethod def onAttach(io): print("Attach [" + str(io.getChannel()) + "]!") @staticmethod def onDetach(io): print("Detach [" + str(io.getChannel()) + "]!") @staticmethod def onError(io, code, description): print("Code [" + str(io.getChannel()) + "]: " + ErrorEventCode.getName(code)) print("Description [" + str(io.getChannel()) + "]: " + str(description)) print("----------")