def try_weight_sensor(self): print("Try Weight Sensor") try: # Allocate a new Phidget Channel object self.ch = VoltageRatioInput() self.do = DigitalOutput() self.ch.setChannel(0) self.do.setChannel(6) self.ch.setOnAttachHandler(onAttachHandler) self.ch.setOnDetachHandler(onDetachHandler) self.ch.setOnErrorHandler(onErrorHandler) self.ch.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler) self.ch.setOnSensorChangeHandler(onSensorChangeHandler) # Open the channel with a timeout try: self.ch.openWaitForAttachment(5000) self.do.openWaitForAttachment(5000) except PhidgetException as e: # PrintOpenErrorMessage(e, self.ch) raise EndProgramSignal("Program Terminated: Open Failed") print("THREAD STARTING") weight_thread = threading.Thread( target=self.start_getting_weight_value) weight_thread.daemon = True weight_thread.start() except Exception as e: self.ch.close() self.try_conneting_again()
class DigitalOutputChannel(): ''' Class used to set high or low voltages on Digital Output channels on IO boards ''' def __init__(self, deviceSN,channelNo): ''' Constructor for Digital Output channels. ''' #Attempt to attach tochannel self.deviceSN = deviceSN self.channelNo = channelNo self.attachChannel() def attachChannel(self): ''' Connect to Digital output channel testing ''' self.channel = DigitalOutput() self.channel.setDeviceSerialNumber(self.deviceSN) self.channel.setChannel(self.channelNo) self.channel.openWaitForAttachment(100) self.channel.setState(False) def setState(self,state): ''' Changes the output state of the channel between high and low using True and False ''' self.channel.setState(state)
def attachChannel(self): ''' Connect to Digital output channel testing ''' self.channel = DigitalOutput() self.channel.setDeviceSerialNumber(self.deviceSN) self.channel.setChannel(self.channelNo) self.channel.openWaitForAttachment(100) self.channel.setState(False)
def __init__(self, hub_serial, hub_port, relay_channel): self.updated_n = 0 self.relay = DigitalOutput() self.relay.setChannel(relay_channel) self.relay.setHubPort(hub_port) self.relay.setDeviceSerialNumber(hub_serial) self.relay_channel = relay_channel self.relay.openWaitForAttachment(5000) self.previous_duty_cycle = 100
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)
def __init__(self, serial_num): logging.debug("Opening Phidget") self.popper_pump = DigitalOutput() self.popper_pump.setChannel(0) self.popper_pump.setDeviceSerialNumber(serial_num) self.popper_pump.openWaitForAttachment(5000) self.program_lock = threading.Lock() self.program_queue = queue.Queue() self.run_time = runMin self.sleep_time = sleepMin # Required for Kontroller self.kontrol = None self.channel = None
def __init__(self, provider, channel, defaultState): self._defaultState = defaultState self.do = DigitalOutput() self.do.setDeviceSerialNumber(provider) self.do.setChannel(channel) self.do.setOnAttachHandler(self._attached) self.do.openWaitForAttachment(1000)
from Phidget22.Phidget import * from Phidget22.Devices.DigitalOutput import * from Phidget22.Devices.DigitalInput import * import time serial_number = 95358 digitalOutput = DigitalOutput() digitalOutput.setChannel(4) digitalOutput.openWaitForAttachment(5000) digitalOutput.setState(0) digitalOutput.setDeviceSerialNumber(serial_number) while True: res = input() if (res == "on"): digitalOutput.setState(1) elif (res == "off"): digitalOutput.setState(0) elif (res == "quit"): break digitalOutput.close()
fstepper_accelleration = 1000 zstepper_accelleration = 1000 output_channels = [ 'output_filterDARK', 'output_filterGFP', 'output_filterRFP', 'output_filterCFP', 'output_filterYFP', 'output_camera', 'output_incubator', 'output_humidity' ] input_channels = ['input_zLimitSwitch', 'input_fLimitSwitch'] ########################## Initialize InterfaceKit f_stepper = Stepper() z_stepper = Stepper() interfaceKit_output = [DigitalOutput() for i in range(0, len(output_channels))] interfaceKit_input = [DigitalInput() for i in range(0, len(input_channels))] ########################## USER-DEFINED PARAMETERS #MODIFY TO DEFINE SERIAL NUMBERS!! z_stepper_serial = '506023' f_stepper_serial = '522559' interfaceKit_serial = '313877' arduino_usbport = '/dev/ttyUSB0' #DEFAULT VALUES fpos_filterBRIGHT = -3250 fpos_filterDARK = -3250 fpos_filterGFP = -4994 fpos_filterRFP = -6555
def __init__(self, master, initial_name, top_name, color, sol, reg_pwr, reg_set, reg_get, PSI): self.frame = Frame(master, borderwidth=2, relief=SUNKEN, bg=color) self.frame.pack() self.master = master self.frame_name = StringVar() self.frame_name.set(initial_name) self.state = 0 self.fontType = "Comic Sans" self.activeColor = 'SpringGreen4' self.frameColor = color self.pressure = IntVar() self.lock_flag = IntVar() self.pressure.set("") self.power = Button(self.frame, text="PWR", activebackground=self.activeColor, command=lambda: self.toggle_pwr()) self.set_label = Button(self.frame, text="SET LABEL", font=(self.fontType, 7), command=lambda: self.get_label_input()) self.observed_pressure = Entry(self.frame, width=5, state="readonly", textvariable=self.pressure) if self.frame_name.get() == "Hydro": self.set_pressure_scale = Scale(self.frame, orient=HORIZONTAL, from_=0, to=92, resolution=0.5, bg=color, label="Set Pressure (PSI)", highlightthickness=0, command=self.set_pressure) else: self.set_pressure_scale = Scale(self.frame, orient=HORIZONTAL, from_=0, to=50, resolution=0.5, bg=color, label="Set Pressure (PSI)", highlightthickness=0, command=self.set_pressure) self.custom_label = Label(self.frame, textvariable=self.frame_name, font=(self.fontType, 14), bg=color) self.label = Label(self.frame, text=initial_name, bg=color) self.lock = Checkbutton(self.frame, text="LOCK", bg=color, variable=self.lock_flag, command=self.lock) self.frame_name.set(top_name) # Init the pressure scale to the default value. self.set_pressure_scale.set(PSI) # Lock hydo at startup if initial_name == "Hydro": self.lock.select() self.set_pressure_scale.config(state="disabled") self.power.config(state="disable") self.frame.rowconfigure(0, minsize=30) self.custom_label.grid(row=0, column=0, columnspan=2, sticky=S) self.set_label.grid(column=0, row=1, columnspan=2) self.frame.rowconfigure(2, minsize=50) self.power.grid(column=0, row=2) self.observed_pressure.grid(column=1, row=2) self.set_pressure_scale.grid(column=0, row=3, columnspan=2, padx=20) self.frame.rowconfigure(4, minsize=5) self.label.grid(column=0, row=5) self.lock.grid(column=1, row=5) # Connect to Phidget Solid State Relay for solinoid control if self.frame_name.get() == "Hydro": self.solenoid_switch = DigitalOutput() self.solenoid_switch.setDeviceSerialNumber(sol[0]) self.solenoid_switch.setIsHubPortDevice(False) self.solenoid_switch.setHubPort(sol[1]) self.solenoid_switch.setChannel(sol[2]) self.solenoid_switch.openWaitForAttachment(5000) #Connect to Phidget Solid State Relay for regulator power control self.reg_switch = DigitalOutput() self.reg_switch.setDeviceSerialNumber(reg_pwr[0]) self.reg_switch.setIsHubPortDevice(False) self.reg_switch.setHubPort(reg_pwr[1]) self.reg_switch.setChannel(reg_pwr[2]) self.reg_switch.openWaitForAttachment(5000) #Connect to Phidget Voltage Ouptut for pressure control self.pressure_ctrl = VoltageOutput() self.pressure_ctrl.setDeviceSerialNumber(reg_set[0]) self.pressure_ctrl.setIsHubPortDevice(False) self.pressure_ctrl.setHubPort(reg_set[1]) self.pressure_ctrl.setChannel(reg_set[2]) self.pressure_ctrl.openWaitForAttachment(5000) #Connect to Phidget Analog Input for pressure reading self.pressure_reading = VoltageRatioInput() self.pressure_reading.setDeviceSerialNumber(reg_get[0]) #One of the VINT Hubs on the SBC is used and needs special configuration if reg_get[0] == SBCH: self.pressure_reading.setIsHubPortDevice(True) self.pressure_reading.setHubPort(0) self.pressure_reading.setChannel(reg_get[1]) self.pressure_reading.openWaitForAttachment(5000)
def __init__(self, master, colorArray): frame1 = Frame(master, borderwidth=2, relief=SUNKEN) frame2 = Frame(master, borderwidth=2, relief=SUNKEN) frame3 = Frame(master, borderwidth=2, relief=SUNKEN) frame4 = Frame(master, borderwidth=2, relief=SUNKEN) frame5 = Frame(master, borderwidth=2, relief=SUNKEN) frame6 = Frame(master, borderwidth=2, relief=SUNKEN) frame7 = Frame(master, borderwidth=2, relief=SUNKEN) camera_frame = Frame(master, borderwidth=2, relief=SUNKEN) frame1.grid(row=1, column=0) frame2.grid(row=1, column=1) frame3.grid(row=1, column=2) frame4.grid(row=1, column=3) frame5.grid(row=1, column=4) frame6.grid(row=1, column=5) frame7.grid(row=1, column=6) camera_frame.grid(row=3, column=0, columnspan=7, sticky=W) self.out1 = AxisFrame(frame1, "BASE CIRC", "VESSEL RIGHT", "VESSEL LEFT", HUB1, 5, colorArray[0], 3.3, 0.55) self.out2 = AxisFrame(frame2, "BASE AUX", "CW/IN", "CCW/OUT", HUB2, 0, colorArray[1], 2.2, 0.11) self.out3 = AxisFrame(frame3, "VARD ROT", "CW", "CCW", HUB1, 3, colorArray[2], 2.2, 0.15) self.out4 = AxisFrame(frame4, "VARD VERT", "UP", "DOWN", HUB1, 4, colorArray[3], 7.8, 0.54) self.out5 = AxisFrame(frame5, "DA MAST", "UP", "DOWN", HUB1, 0, colorArray[4], 8, 0.86) self.out6 = AxisFrame(frame6, "DA PAN", "CW", "CCW", HUB1, 2, colorArray[5], 3.0, 0.30) self.out7 = AxisFrame(frame7, "DA TILT", "UP", "DOWN", HUB1, 1, colorArray[6], 3.6, 0.57) #RJ Camera Control Code self.invert_tilt = BooleanVar() self.invert_pan = BooleanVar() self.btn_power = Button(camera_frame, text="PWR", font="Courier, 12", command=self.toggle_power) self.btn_near = Button(camera_frame, text="NEAR", font="Courier, 12", width=7) self.btn_far = Button(camera_frame, text="FAR", font="Courier, 12", width=7) self.btn_wide = Button(camera_frame, text="WIDE", font="Courier, 12", width=7) self.btn_tele = Button(camera_frame, text="TELE", font="Courier, 12", width=7) self.btn_ms = Button(camera_frame, text="MS", font="Courier, 12", width=7) self.left_light_scale = Scale(camera_frame, orient=VERTICAL, from_=0, to=0.45, resolution=0.01, command=self.update_left_intensity) self.right_light_scale = Scale(camera_frame, orient=VERTICAL, from_=0, to=0.45, resolution=0.01, command=self.update_right_intensity) self.label_lights = Label(camera_frame, text=" Light Intensity") self.btn_tilt_up = Button(camera_frame, text="TILT UP", font="Courier, 12", width=10) self.btn_tilt_down = Button(camera_frame, text="TILT DOWN", font="Courier, 12", width=10) self.btn_pan_right = Button(camera_frame, text="PAN RIGHT", font="Courier, 12", width=10) self.btn_pan_left = Button(camera_frame, text="PAN LEFT", font="Courier, 12", width=10) self.tilt_speed = Scale(camera_frame, orient=HORIZONTAL, from_=0.01, to=.5, resolution=0.01) self.pan_speed = Scale(camera_frame, orient=HORIZONTAL, from_=0.01, to=.5, resolution=0.01) self.ckbx_invert_tilt = Checkbutton(camera_frame, text="Invert Tilt", variable=self.invert_tilt) self.ckbx_invert_pan = Checkbutton(camera_frame, text="Invert Pan", variable=self.invert_pan) self.activeColor = 'SpringGreen4' self.tilt_speed.set(0.15) self.pan_speed.set(0.15) self.btn_power.grid(row=0, column=0, padx=60) self.btn_ms.grid(row=1, column=0, padx=5, pady=5) self.btn_near.grid(row=0, column=2, padx=20, pady=10) self.btn_far.grid(row=1, column=2, padx=20, pady=10) self.btn_tele.grid(row=0, column=3, padx=20, pady=10) self.btn_wide.grid(row=1, column=3, padx=20, pady=10) self.left_light_scale.grid(row=0, column=4, rowspan=3, padx=20, pady=5) self.right_light_scale.grid(row=0, column=5, rowspan=3, padx=45, pady=5) self.label_lights.grid(row=3, column=4, columnspan=2, padx=45, sticky=N) self.btn_tilt_up.grid(row=0, column=6, padx=20, pady=5) self.btn_tilt_down.grid(row=1, column=6, padx=20, pady=5) self.btn_pan_right.grid(row=0, column=8, padx=20, pady=5, rowspan=2) self.btn_pan_left.grid(row=0, column=7, padx=20, pady=5, rowspan=2) self.tilt_speed.grid(row=2, column=6) self.pan_speed.grid(row=2, column=7, columnspan=2) self.ckbx_invert_tilt.grid(row=3, column=6) self.ckbx_invert_pan.grid(row=3, column=7, columnspan=2) #Connect to Phidget Devices self.power = DigitalOutput() self.power.setDeviceSerialNumber(HUB2) self.power.setIsHubPortDevice(False) self.power.setHubPort(1) self.power.setChannel(0) self.power.openWaitForAttachment(5000) self.manual_select = DigitalOutput() self.manual_select.setDeviceSerialNumber(HUB2) self.manual_select.setIsHubPortDevice(False) self.manual_select.setHubPort(1) self.manual_select.setChannel(1) self.manual_select.openWaitForAttachment(5000) self.near = DigitalOutput() self.near.setDeviceSerialNumber(HUB2) self.near.setIsHubPortDevice(False) self.near.setHubPort(1) self.near.setChannel(2) self.near.openWaitForAttachment(5000) self.far = DigitalOutput() self.far.setDeviceSerialNumber(HUB2) self.far.setIsHubPortDevice(False) self.far.setHubPort(1) self.far.setChannel(3) self.far.openWaitForAttachment(5000) self.wide = DigitalOutput() self.wide.setDeviceSerialNumber(HUB2) self.wide.setIsHubPortDevice(False) self.wide.setHubPort(1) self.wide.setChannel(4) self.wide.openWaitForAttachment(5000) self.tele = DigitalOutput() self.tele.setDeviceSerialNumber(HUB2) self.tele.setIsHubPortDevice(False) self.tele.setHubPort(1) self.tele.setChannel(5) self.tele.openWaitForAttachment(5000) self.left_light = VoltageOutput() self.left_light.setDeviceSerialNumber(HUB2) self.left_light.setIsHubPortDevice(False) self.left_light.setHubPort(2) self.left_light.setChannel(0) self.left_light.openWaitForAttachment(5000) self.right_light = VoltageOutput() self.right_light.setDeviceSerialNumber(HUB2) self.right_light.setIsHubPortDevice(False) self.right_light.setHubPort(3) self.right_light.setChannel(0) self.right_light.openWaitForAttachment(5000) self.pan = VoltageOutput() self.pan.setDeviceSerialNumber(HUB2) self.pan.setIsHubPortDevice(False) self.pan.setHubPort(5) self.pan.setChannel(0) self.pan.openWaitForAttachment(5000) self.tilt = VoltageOutput() self.tilt.setDeviceSerialNumber(HUB2) self.tilt.setIsHubPortDevice(False) self.tilt.setHubPort(4) self.tilt.setChannel(0) self.tilt.openWaitForAttachment(5000) self.btn_near.bind('<ButtonPress-1>', lambda event: self.focus("+")) self.btn_near.bind('<ButtonRelease-1>', lambda event: self.focus("0")) self.btn_far.bind('<ButtonPress-1>', lambda event: self.focus("-")) self.btn_far.bind('<ButtonRelease-1>', lambda event: self.focus("0")) self.btn_wide.bind('<ButtonPress-1>', lambda event: self.zoom("-")) self.btn_wide.bind('<ButtonRelease-1>', lambda event: self.zoom("0")) self.btn_tele.bind('<ButtonPress-1>', lambda event: self.zoom("+")) self.btn_tele.bind('<ButtonRelease-1>', lambda event: self.zoom("0")) self.btn_ms.bind('<ButtonPress-1>', lambda event: self.focus_type("ON")) self.btn_ms.bind('<ButtonRelease-1>', lambda event: self.focus_type("OFF")) self.btn_tilt_up.bind('<ButtonPress-1>', lambda event: self.tilt_move("-")) self.btn_tilt_up.bind('<ButtonRelease-1>', lambda event: self.tilt_move("0")) self.btn_tilt_down.bind('<ButtonPress-1>', lambda event: self.tilt_move("+")) self.btn_tilt_down.bind('<ButtonRelease-1>', lambda event: self.tilt_move("0")) self.btn_pan_right.bind('<ButtonPress-1>', lambda event: self.pan_move("R")) self.btn_pan_right.bind('<ButtonRelease-1>', lambda event: self.pan_move("0")) self.btn_pan_left.bind('<ButtonPress-1>', lambda event: self.pan_move("L")) self.btn_pan_left.bind('<ButtonRelease-1>', lambda event: self.pan_move("0"))
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(): digitalOutput0 = DigitalOutput() digitalOutput1 = DigitalOutput() digitalOutput2 = DigitalOutput() digitalOutput3 = DigitalOutput() digitalOutput4 = DigitalOutput() digitalOutput5 = DigitalOutput() digitalOutput6 = DigitalOutput() digitalOutput7 = DigitalOutput() digitalOutput0.setChannel(0) digitalOutput1.setChannel(1) digitalOutput2.setChannel(2) digitalOutput3.setChannel(3) digitalOutput4.setChannel(4) digitalOutput5.setChannel(5) digitalOutput6.setChannel(6) digitalOutput7.setChannel(7) digitalOutput0.openWaitForAttachment(5000) digitalOutput1.openWaitForAttachment(5000) digitalOutput2.openWaitForAttachment(5000) digitalOutput3.openWaitForAttachment(5000) digitalOutput4.openWaitForAttachment(5000) digitalOutput5.openWaitForAttachment(5000)
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()
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
class WeightSensor: def __init__(self): self.weight_value = -1 self.has_ended = False self.try_weight_sensor() def try_weight_sensor(self): print("Try Weight Sensor") try: # Allocate a new Phidget Channel object self.ch = VoltageRatioInput() self.do = DigitalOutput() self.ch.setChannel(0) self.do.setChannel(6) self.ch.setOnAttachHandler(onAttachHandler) self.ch.setOnDetachHandler(onDetachHandler) self.ch.setOnErrorHandler(onErrorHandler) self.ch.setOnVoltageRatioChangeHandler(onVoltageRatioChangeHandler) self.ch.setOnSensorChangeHandler(onSensorChangeHandler) # Open the channel with a timeout try: self.ch.openWaitForAttachment(5000) self.do.openWaitForAttachment(5000) except PhidgetException as e: # PrintOpenErrorMessage(e, self.ch) raise EndProgramSignal("Program Terminated: Open Failed") print("THREAD STARTING") weight_thread = threading.Thread( target=self.start_getting_weight_value) weight_thread.daemon = True weight_thread.start() except Exception as e: self.ch.close() self.try_conneting_again() def start_getting_weight_value(self): while not self.has_ended: try: self.weight_value = self.ch.getVoltageRatio() except: self.ch.close() break time.sleep(0.25) self.try_conneting_again() def try_conneting_again(self): self.has_ended = True print( "Weight sensor failed! Trying to connect to the weight sensor again in 3 2 1..." ) time.sleep(3) self.ch = None self.do = None self.has_ended = False self.weight_value = -1 self.try_weight_sensor() def get_weight_value(self): return self.weight_value
class jigOutput(object): '''generic digital output on the jig''' def __init__(self, provider, channel, defaultState): self._defaultState = defaultState self.do = DigitalOutput() self.do.setDeviceSerialNumber(provider) self.do.setChannel(channel) self.do.setOnAttachHandler(self._attached) self.do.openWaitForAttachment(1000) def _attached(self, event): self.set(self._defaultState) @property def state(self): return self.do.getState() def set(self, state): self.do.setState(state) def reset(self): self.set(self._defaultState)
from Phidget22.Devices.DigitalInput import * number_of_inputs = 4 number_of_outputs = 4 timeout_duration = 5 * 1000 # its in miliseconds serial_number = 96781 # create input pins input_pins = [DigitalInput() for each_index in range(number_of_inputs)] for each_index, each in enumerate(input_pins): each.setChannel(each_index) each.setDeviceSerialNumber(serial_number) each.openWaitForAttachment(timeout_duration) # create ouput pins output_pins = [DigitalOutput() for each_index in range(number_of_outputs)] for each_index, each in enumerate(output_pins): each.setChannel(each_index) each.setDeviceSerialNumber(serial_number) each.openWaitForAttachment(timeout_duration) def which_key(input_pin, index_of_input): key_values = [["1", "2", "3", "A"], ["4", "5", "6", "B"], ["7", "8", "9", "C"], ["*", "0", "#", "D"]] return_value = None # do trial-and-error to find which output pin for index_of_output, each_output in enumerate(output_pins): each_output.setState(1) time.sleep(0.05)
sys.stderr.write("[Phidget Error Event] -> " + errorString + " (" + str(errorCode) + ")\n") def configChannel(phi, serial, channel): phi.setDeviceSerialNumber(serial) phi.setHubPort(-1) phi.setIsHubPortDevice(0) phi.setChannel(channel) phi.setOnAttachHandler(onAttachHandler) phi.setOnDetachHandler(onDetachHandler) phi.setOnErrorHandler(onErrorHandler) try: phi.openWaitForAttachment(5000) except PhidgetException as e: PrintOpenErrorMessage(e, phi) raise EndProgramSignal("Program Terminated: Open Failed") if __name__ == "__main__": Phidget_serial = 383808 Phidget_channel = 0 phidget = DigitalOutput() configChannel(phidget, Phidget_serial, Phidget_channel) phidget.setDutyCycle(1) while True: time.sleep(5) phidget.setDutyCycle(0) time.sleep(5) phidget.setDutyCycle(1)
class Multiplexer: def __init__(self): print('init mp') try: self.ch0 = DigitalOutput() self.ch1 = DigitalOutput() self.ch2 = DigitalOutput() self.ch3 = DigitalOutput() self.ch4 = DigitalOutput() self.ch5 = DigitalOutput() self.ch6 = DigitalOutput() self.ch7 = DigitalOutput() except RuntimeError as e: print("Runtime Exception %s" % e.details) print("Press Enter to Exit...\n") raise def ErrorEvent(self, e, eCode, description): print("Error %i : %s" % (eCode, description)) try: self.ch0.setOnErrorHandler(ErrorEvent) self.ch1.setOnErrorHandler(ErrorEvent) self.ch2.setOnErrorHandler(ErrorEvent) self.ch3.setOnErrorHandler(ErrorEvent) self.ch4.setOnErrorHandler(ErrorEvent) self.ch5.setOnErrorHandler(ErrorEvent) self.ch6.setOnErrorHandler(ErrorEvent) self.ch7.setOnErrorHandler(ErrorEvent) self.ch0.setChannel(0) self.ch1.setChannel(1) self.ch2.setChannel(2) self.ch3.setChannel(3) self.ch4.setChannel(4) self.ch5.setChannel(5) self.ch6.setChannel(6) self.ch7.setChannel(7) print( "Waiting for the Phidget DigitalOutput Objects to be attached..." ) self.ch0.openWaitForAttachment(5000) self.ch1.openWaitForAttachment(5000) self.ch2.openWaitForAttachment(5000) self.ch3.openWaitForAttachment(5000) self.ch4.openWaitForAttachment(5000) self.ch5.openWaitForAttachment(5000) self.ch6.openWaitForAttachment(5000) self.ch7.openWaitForAttachment(5000) except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) print("Press Enter to Exit...\n") raise def SelectChannel(self, channel): self.ch0.setState(0) self.ch1.setState(0) self.ch2.setState(0) self.ch3.setState(0) self.ch4.setState(0) self.ch5.setState(0) self.ch6.setState(0) self.ch7.setState(0) if channel < 0: return if channel == 0: self.ch0.setState(1) if channel == 1: self.ch1.setState(1) if channel == 2: self.ch2.setState(1) if channel == 3: self.ch3.setState(1) if channel == 4: self.ch4.setState(1) if channel == 5: self.ch5.setState(1) if channel == 6: self.ch6.setState(1) if channel == 7: self.ch7.setState(1) time.sleep(10) def ChannelsOff(self): self.SelectChannel(-1) def close(self): try: self.ch0.close() self.ch1.close() self.ch2.close() self.ch3.close() self.ch4.close() self.ch5.close() self.ch6.close() self.ch7.close() except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) print("Press Enter to Exit...\n") raise print("Closed DigitalOutput device")
class MyRelay: def __init__(self, hub_serial, hub_port, relay_channel): self.updated_n = 0 self.relay = DigitalOutput() self.relay.setChannel(relay_channel) self.relay.setHubPort(hub_port) self.relay.setDeviceSerialNumber(hub_serial) self.relay_channel = relay_channel self.relay.openWaitForAttachment(5000) self.previous_duty_cycle = 100 def set_state(self, state): self.relay.setState(state) def set_duty_cycle(self, duty_cycle): try: diff = math.fabs(self.previous_duty_cycle - duty_cycle) if diff > 0.05: self.relay.setDutyCycle(duty_cycle) self.previous_duty_cycle = duty_cycle self.updated_n = self.updated_n + 1 except PhidgetException as exception: print('Error on relay channel', self.relay_channel, exception) self.reconnect() def __del__(self): self.relay.close()
def __init__(self): print('init mp') try: self.ch0 = DigitalOutput() self.ch1 = DigitalOutput() self.ch2 = DigitalOutput() self.ch3 = DigitalOutput() self.ch4 = DigitalOutput() self.ch5 = DigitalOutput() self.ch6 = DigitalOutput() self.ch7 = DigitalOutput() except RuntimeError as e: print("Runtime Exception %s" % e.details) print("Press Enter to Exit...\n") raise def ErrorEvent(self, e, eCode, description): print("Error %i : %s" % (eCode, description)) try: self.ch0.setOnErrorHandler(ErrorEvent) self.ch1.setOnErrorHandler(ErrorEvent) self.ch2.setOnErrorHandler(ErrorEvent) self.ch3.setOnErrorHandler(ErrorEvent) self.ch4.setOnErrorHandler(ErrorEvent) self.ch5.setOnErrorHandler(ErrorEvent) self.ch6.setOnErrorHandler(ErrorEvent) self.ch7.setOnErrorHandler(ErrorEvent) self.ch0.setChannel(0) self.ch1.setChannel(1) self.ch2.setChannel(2) self.ch3.setChannel(3) self.ch4.setChannel(4) self.ch5.setChannel(5) self.ch6.setChannel(6) self.ch7.setChannel(7) print( "Waiting for the Phidget DigitalOutput Objects to be attached..." ) self.ch0.openWaitForAttachment(5000) self.ch1.openWaitForAttachment(5000) self.ch2.openWaitForAttachment(5000) self.ch3.openWaitForAttachment(5000) self.ch4.openWaitForAttachment(5000) self.ch5.openWaitForAttachment(5000) self.ch6.openWaitForAttachment(5000) self.ch7.openWaitForAttachment(5000) except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) print("Press Enter to Exit...\n") raise
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 __init__(self, master, colorArray): frame1 = Frame(master, borderwidth=2, relief=SUNKEN) frame2 = Frame(master, borderwidth=2, relief=SUNKEN) frame3 = Frame(master, borderwidth=2, relief=SUNKEN) frame4 = Frame(master, borderwidth=2, relief=SUNKEN) frame5 = Frame(master, borderwidth=2, relief=SUNKEN) frame6 = Frame(master, borderwidth=2, relief=SUNKEN) frame7 = Frame(master, borderwidth=2, relief=SUNKEN) camera_frame_1 = Frame(master, borderwidth=2, relief=SUNKEN, bg='LightSkyBlue2') camera_frame_2 = Frame(master, borderwidth=2, relief=SUNKEN, bg='light goldenrod yellow') frame1.grid(row=1, column=0) frame2.grid(row=1, column=1) frame3.grid(row=1, column=2) frame4.grid(row=1, column=3) frame5.grid(row=1, column=4) frame6.grid(row=1, column=5) frame7.grid(row=1, column=6) camera_frame_1.grid(row=3, column=0, columnspan=7, sticky=NSEW) camera_frame_2.grid(row=4, column=0, columnspan=7, sticky=NSEW) self.out1 = AxisFrame(frame1, "BASE CIRC", "VESSEL RIGHT", "VESSEL LEFT", HUB1, 5, colorArray[0], 3.3, 0.55) self.out2 = AxisFrame(frame2, "BASE AUX", "CW/IN", "CCW/OUT", HUB2, 0, colorArray[1], 2.2, 0.11) self.out3 = AxisFrame(frame3, "VARD ROT", "CW", "CCW", HUB1, 3, colorArray[2], 2.2, 0.15) self.out4 = AxisFrame(frame4, "VARD VERT", "UP", "DOWN", HUB1, 4, colorArray[3], 7.8, 0.54) self.out5 = AxisFrame(frame5, "DA MAST", "UP", "DOWN", HUB1, 0, colorArray[4], 8, 0.86) self.out6 = AxisFrame(frame6, "DA PAN", "CW", "CCW", HUB1, 2, colorArray[5], 3.0, 0.30) self.out7 = AxisFrame(frame7, "DA TILT", "UP", "DOWN", HUB1, 1, colorArray[6], 3.6, 0.57) # RJ Camera Control: Code Tool Camera self.invert_tilt_1 = BooleanVar() self.invert_pan_1 = BooleanVar() self.btn_power_1 = Button(camera_frame_1, text="PWR", font="Courier, 12", command=self.toggle_power_1) self.btn_near_1 = Button(camera_frame_1, text="NEAR", font="Courier, 12", width=7) self.btn_far_1 = Button(camera_frame_1, text="FAR", font="Courier, 12", width=7) self.btn_wide_1 = Button(camera_frame_1, text="WIDE", font="Courier, 12", width=7) self.btn_tele_1 = Button(camera_frame_1, text="TELE", font="Courier, 12", width=7) self.btn_ms_1 = Button(camera_frame_1, text="MS", font="Courier, 12", width=7) self.left_light_scale_1 = Scale(camera_frame_1, orient=VERTICAL, from_=0, to=0.45, resolution=0.01, command=self.update_left_intensity_1, bg='LightSkyBlue2', highlightthickness=0) self.right_light_scale_1 = Scale(camera_frame_1, orient=VERTICAL, from_=0, to=0.45, resolution=0.01, command=self.update_right_intensity_1, bg='LightSkyBlue2', highlightthickness=0) self.label_lights_1 = Label(camera_frame_1, text=" Light Intensity", bg='LightSkyBlue2') self.label_camera_type_1 = Label(camera_frame_1, text="TOOL CAMERA", font=("TkDefaultFont", 14), bg='LightSkyBlue2') self.btn_tilt_up_1 = Button(camera_frame_1, text="TILT UP", font="Courier, 12", width=10) self.btn_tilt_down_1 = Button(camera_frame_1, text="TILT DOWN", font="Courier, 12", width=10) self.btn_pan_right_1 = Button(camera_frame_1, text="PAN RIGHT", font="Courier, 12", width=10) self.btn_pan_left_1 = Button(camera_frame_1, text="PAN LEFT", font="Courier, 12", width=10) self.tilt_speed_1 = Scale(camera_frame_1, orient=HORIZONTAL, from_=0.01, to=.5, resolution=0.01, bg='LightSkyBlue2', highlightthickness=0) self.pan_speed_1 = Scale(camera_frame_1, orient=HORIZONTAL, from_=0.01, to=.5, resolution=0.01, bg='LightSkyBlue2', highlightthickness=0) self.ckbx_invert_tilt_1 = Checkbutton(camera_frame_1, text="Invert Tilt", variable=self.invert_tilt_1, bg='LightSkyBlue2') self.ckbx_invert_pan_1 = Checkbutton(camera_frame_1, text="Invert Pan", variable=self.invert_pan_1, bg='LightSkyBlue2') self.activeColor_1 = 'SpringGreen4' self.tilt_speed_1.set(0.15) self.pan_speed_1.set(0.15) # RJ Camera Control: Overview Camera self.invert_tilt_2 = BooleanVar() self.invert_pan_2 = BooleanVar() self.btn_power_2 = Button(camera_frame_2, text="PWR", font="Courier, 12", command=self.toggle_power_2) self.btn_near_2 = Button(camera_frame_2, text="NEAR", font="Courier, 12", width=7) self.btn_far_2 = Button(camera_frame_2, text="FAR", font="Courier, 12", width=7) self.btn_wide_2 = Button(camera_frame_2, text="WIDE", font="Courier, 12", width=7) self.btn_tele_2 = Button(camera_frame_2, text="TELE", font="Courier, 12", width=7) self.btn_ms_2 = Button(camera_frame_2, text="MS", font="Courier, 12", width=7) self.left_light_scale_2 = Scale(camera_frame_2, orient=VERTICAL, from_=0, to=0.45, resolution=0.01, command=self.update_left_intensity_2, bg='light goldenrod yellow', highlightthickness=0) self.right_light_scale_2 = Scale(camera_frame_2, orient=VERTICAL, from_=0, to=0.45, resolution=0.01, command=self.update_right_intensity_2, bg='light goldenrod yellow', highlightthickness=0) self.label_lights_2 = Label(camera_frame_2, text=" Light Intensity", bg='light goldenrod yellow') self.label_camera_type_2 = Label(camera_frame_2, text="OVERVIEW CAMERA", font=("TkDefaultFont", 14), bg='light goldenrod yellow') self.btn_tilt_up_2 = Button(camera_frame_2, text="TILT UP", font="Courier, 12", width=10) self.btn_tilt_down_2 = Button(camera_frame_2, text="TILT DOWN", font="Courier, 12", width=10) self.btn_pan_right_2 = Button(camera_frame_2, text="PAN RIGHT", font="Courier, 12", width=10) self.btn_pan_left_2 = Button(camera_frame_2, text="PAN LEFT", font="Courier, 12", width=10) self.tilt_speed_2 = Scale(camera_frame_2, orient=HORIZONTAL, from_=0.01, to=.5, resolution=0.01, bg='light goldenrod yellow', highlightthickness=0) self.pan_speed_2 = Scale(camera_frame_2, orient=HORIZONTAL, from_=0.01, to=.5, resolution=0.01, bg='light goldenrod yellow', highlightthickness=0) self.ckbx_invert_tilt_2 = Checkbutton(camera_frame_2, text="Invert Tilt", variable=self.invert_tilt_2, bg='light goldenrod yellow') self.ckbx_invert_pan_2 = Checkbutton(camera_frame_2, text="Invert Pan", variable=self.invert_pan_2, bg='light goldenrod yellow') self.activeColor_2 = 'SpringGreen4' self.tilt_speed_2.set(0.15) self.pan_speed_2.set(0.15) # Grid the Tool Camera Controls self.btn_power_1.grid(row=0, column=0, padx=60) self.btn_ms_1.grid(row=1, column=0, padx=5, pady=5) self.btn_near_1.grid(row=0, column=2, padx=20, pady=10) self.btn_far_1.grid(row=1, column=2, padx=20, pady=10) self.btn_tele_1.grid(row=0, column=3, padx=20, pady=10) self.btn_wide_1.grid(row=1, column=3, padx=20, pady=10) self.label_camera_type_1.grid(row=2, column=0, columnspan=4) self.left_light_scale_1.grid(row=0, column=4, rowspan=3, padx=20, pady=5) self.right_light_scale_1.grid(row=0, column=5, rowspan=3, padx=45, pady=5) self.label_lights_1.grid(row=3, column=4, columnspan=2, padx=45, sticky=N) self.btn_tilt_up_1.grid(row=0, column=6, padx=20, pady=5) self.btn_tilt_down_1.grid(row=1, column=6, padx=20, pady=5) self.btn_pan_right_1.grid(row=0, column=8, padx=20, pady=5, rowspan=2) self.btn_pan_left_1.grid(row=0, column=7, padx=20, pady=5, rowspan=2) self.tilt_speed_1.grid(row=2, column=6) self.pan_speed_1.grid(row=2, column=7, columnspan=2) self.ckbx_invert_tilt_1.grid(row=3, column=6) self.ckbx_invert_pan_1.grid(row=3, column=7, columnspan=2) # Grid the Overview Camera Controls self.btn_power_2.grid(row=0, column=0, padx=60) self.btn_ms_2.grid(row=1, column=0, padx=5, pady=5) self.btn_near_2.grid(row=0, column=2, padx=20, pady=10) self.btn_far_2.grid(row=1, column=2, padx=20, pady=10) self.btn_tele_2.grid(row=0, column=3, padx=20, pady=10) self.btn_wide_2.grid(row=1, column=3, padx=20, pady=10) self.label_camera_type_2.grid(row=2, column=0, columnspan=4) self.left_light_scale_2.grid(row=0, column=4, rowspan=3, padx=20, pady=5) self.right_light_scale_2.grid(row=0, column=5, rowspan=3, padx=45, pady=5) self.label_lights_2.grid(row=3, column=4, columnspan=2, padx=45, sticky=N) self.btn_tilt_up_2.grid(row=0, column=6, padx=20, pady=5) self.btn_tilt_down_2.grid(row=1, column=6, padx=20, pady=5) self.btn_pan_right_2.grid(row=0, column=8, padx=20, pady=5, rowspan=2) self.btn_pan_left_2.grid(row=0, column=7, padx=20, pady=5, rowspan=2) self.tilt_speed_2.grid(row=2, column=6) self.pan_speed_2.grid(row=2, column=7, columnspan=2) self.ckbx_invert_tilt_2.grid(row=3, column=6) self.ckbx_invert_pan_2.grid(row=3, column=7, columnspan=2) # Connect to Phidget Devices for Tool Camera self.power_1 = DigitalOutput() self.power_1.setDeviceSerialNumber(HUB2) self.power_1.setIsHubPortDevice(False) self.power_1.setHubPort(1) self.power_1.setChannel(0) try: self.power_1.openWaitForAttachment(1000) except PhidgetException as e: print("Failed to open (CAM POWER): " + e.details) self.manual_select_1 = DigitalOutput() self.manual_select_1.setDeviceSerialNumber(HUB2) self.manual_select_1.setIsHubPortDevice(False) self.manual_select_1.setHubPort(1) self.manual_select_1.setChannel(1) try: self.manual_select_1.openWaitForAttachment(1000) except PhidgetException as e: print("Failed to open (Manual Select): " + e.details) self.near_1 = DigitalOutput() self.near_1.setDeviceSerialNumber(HUB2) self.near_1.setIsHubPortDevice(False) self.near_1.setHubPort(1) self.near_1.setChannel(2) try: self.near_1.openWaitForAttachment(1000) except PhidgetException as e: print("Failed to open (NEAR): " + e.details) self.far_1 = DigitalOutput() self.far_1.setDeviceSerialNumber(HUB2) self.far_1.setIsHubPortDevice(False) self.far_1.setHubPort(1) self.far_1.setChannel(3) try: self.far_1.openWaitForAttachment(1000) except PhidgetException as e: print("Failed to open (FAR): " + e.details) self.wide_1 = DigitalOutput() self.wide_1.setDeviceSerialNumber(HUB2) self.wide_1.setIsHubPortDevice(False) self.wide_1.setHubPort(1) self.wide_1.setChannel(4) try: self.wide_1.openWaitForAttachment(1000) except PhidgetException as e: print("Failed to open (WIDE): " + e.details) self.tele_1 = DigitalOutput() self.tele_1.setDeviceSerialNumber(HUB2) self.tele_1.setIsHubPortDevice(False) self.tele_1.setHubPort(1) self.tele_1.setChannel(5) try: self.tele_1.openWaitForAttachment(1000) except PhidgetException as e: print("Failed to open (TELE): " + e.details) self.left_light_1 = VoltageOutput() self.left_light_1.setDeviceSerialNumber(HUB2) self.left_light_1.setIsHubPortDevice(False) self.left_light_1.setHubPort(2) self.left_light_1.setChannel(0) try: self.left_light_1.openWaitForAttachment(1000) except PhidgetException as e: print("Failed to open (LEFT LIGHT): " + e.details) self.right_light_1 = VoltageOutput() self.right_light_1.setDeviceSerialNumber(HUB2) self.right_light_1.setIsHubPortDevice(False) self.right_light_1.setHubPort(3) self.right_light_1.setChannel(0) try: self.right_light_1.openWaitForAttachment(1000) except PhidgetException as e: print("Failed to open (RIGHT LIGHT): " + e.details) self.pan_1 = VoltageOutput() self.pan_1.setDeviceSerialNumber(HUB2) self.pan_1.setIsHubPortDevice(False) self.pan_1.setHubPort(5) self.pan_1.setChannel(0) try: self.pan_1.openWaitForAttachment(1000) except PhidgetException as e: print("Failed to open (PAN): " + e.details) self.tilt_1 = VoltageOutput() self.tilt_1.setDeviceSerialNumber(HUB2) self.tilt_1.setIsHubPortDevice(False) self.tilt_1.setHubPort(4) self.tilt_1.setChannel(0) try: self.tilt_1.openWaitForAttachment(1000) except PhidgetException as e: print("Failed to open (TILT): " + e.details) self.btn_near_1.bind('<ButtonPress-1>', lambda event: self.focus_1("+")) self.btn_near_1.bind('<ButtonRelease-1>', lambda event: self.focus_1("0")) self.btn_far_1.bind('<ButtonPress-1>', lambda event: self.focus_1("-")) self.btn_far_1.bind('<ButtonRelease-1>', lambda event: self.focus_1("0")) self.btn_wide_1.bind('<ButtonPress-1>', lambda event: self.zoom_1("-")) self.btn_wide_1.bind('<ButtonRelease-1>', lambda event: self.zoom_1("0")) self.btn_tele_1.bind('<ButtonPress-1>', lambda event: self.zoom_1("+")) self.btn_tele_1.bind('<ButtonRelease-1>', lambda event: self.zoom_1("0")) self.btn_ms_1.bind('<ButtonPress-1>', lambda event: self.focus_type_1("ON")) self.btn_ms_1.bind('<ButtonRelease-1>', lambda event: self.focus_type_1("OFF")) self.btn_tilt_up_1.bind('<ButtonPress-1>', lambda event: self.tilt_move_1("-")) self.btn_tilt_up_1.bind('<ButtonRelease-1>', lambda event: self.tilt_move_1("0")) self.btn_tilt_down_1.bind('<ButtonPress-1>', lambda event: self.tilt_move_1("+")) self.btn_tilt_down_1.bind('<ButtonRelease-1>', lambda event: self.tilt_move_1("0")) self.btn_pan_right_1.bind('<ButtonPress-1>', lambda event: self.pan_move_1("R")) self.btn_pan_right_1.bind('<ButtonRelease-1>', lambda event: self.pan_move_1("0")) self.btn_pan_left_1.bind('<ButtonPress-1>', lambda event: self.pan_move_1("L")) self.btn_pan_left_1.bind('<ButtonRelease-1>', lambda event: self.pan_move_1("0")) # Connect to Phidget Devices for Overview Camera self.power_2 = DigitalOutput() self.power_2.setDeviceSerialNumber(HUB2) self.power_2.setIsHubPortDevice(False) self.power_2.setHubPort(1) self.power_2.setChannel(0) try: self.power_2.openWaitForAttachment(1000) except PhidgetException as e: print("Failed to open (CAM POWER): " + e.details) self.manual_select_2 = DigitalOutput() self.manual_select_2.setDeviceSerialNumber(HUB2) self.manual_select_2.setIsHubPortDevice(False) self.manual_select_2.setHubPort(1) self.manual_select_2.setChannel(1) try: self.manual_select_2.openWaitForAttachment(1000) except PhidgetException as e: print("Failed to open (Manual Select): " + e.details) self.near_2 = DigitalOutput() self.near_2.setDeviceSerialNumber(HUB2) self.near_2.setIsHubPortDevice(False) self.near_2.setHubPort(1) self.near_2.setChannel(2) try: self.near_2.openWaitForAttachment(1000) except PhidgetException as e: print("Failed to open (NEAR): " + e.details) self.far_2 = DigitalOutput() self.far_2.setDeviceSerialNumber(HUB2) self.far_2.setIsHubPortDevice(False) self.far_2.setHubPort(1) self.far_2.setChannel(3) try: self.far_2.openWaitForAttachment(1000) except PhidgetException as e: print("Failed to open (FAR): " + e.details) self.wide_2 = DigitalOutput() self.wide_2.setDeviceSerialNumber(HUB2) self.wide_2.setIsHubPortDevice(False) self.wide_2.setHubPort(1) self.wide_2.setChannel(4) try: self.wide_2.openWaitForAttachment(1000) except PhidgetException as e: print("Failed to open (WIDE): " + e.details) self.tele_2 = DigitalOutput() self.tele_2.setDeviceSerialNumber(HUB2) self.tele_2.setIsHubPortDevice(False) self.tele_2.setHubPort(1) self.tele_2.setChannel(5) try: self.tele_2.openWaitForAttachment(1000) except PhidgetException as e: print("Failed to open (TELE): " + e.details) self.left_light_2 = VoltageOutput() self.left_light_2.setDeviceSerialNumber(HUB2) self.left_light_2.setIsHubPortDevice(False) self.left_light_2.setHubPort(2) self.left_light_2.setChannel(0) try: self.left_light_2.openWaitForAttachment(1000) except PhidgetException as e: print("Failed to open (LEFT LIGHT): " + e.details) self.right_light_2 = VoltageOutput() self.right_light_2.setDeviceSerialNumber(HUB2) self.right_light_2.setIsHubPortDevice(False) self.right_light_2.setHubPort(3) self.right_light_2.setChannel(0) try: self.right_light_2.openWaitForAttachment(1000) except PhidgetException as e: print("Failed to open (RIGHT LIGHT): " + e.details) self.pan_2 = VoltageOutput() self.pan_2.setDeviceSerialNumber(HUB2) self.pan_2.setIsHubPortDevice(False) self.pan_2.setHubPort(5) self.pan_2.setChannel(0) try: self.pan_2.openWaitForAttachment(1000) except PhidgetException as e: print("Failed to open (PAN): " + e.details) self.tilt_2 = VoltageOutput() self.tilt_2.setDeviceSerialNumber(HUB2) self.tilt_2.setIsHubPortDevice(False) self.tilt_2.setHubPort(4) self.tilt_2.setChannel(0) try: self.tilt_2.openWaitForAttachment(1000) except PhidgetException as e: print("Failed to open (TILT): " + e.details)
class PneumaticFrame2: def __init__(self, master, initial_name, top_name, color, sol, reg_pwr, reg_set, reg_get, PSI): self.frame = Frame(master, borderwidth=2, relief=SUNKEN, bg=color) self.frame.pack() self.master = master self.frame_name = StringVar() self.frame_name.set(initial_name) self.state = 0 self.fontType = "Comic Sans" self.activeColor = 'SpringGreen4' self.frameColor = color self.pressure = IntVar() self.lock_flag = IntVar() self.pressure.set("") self.power = Button(self.frame, text="PWR", activebackground=self.activeColor, command=lambda: self.toggle_pwr()) self.set_label = Button(self.frame, text="SET LABEL", font=(self.fontType, 7), command=lambda: self.get_label_input()) self.observed_pressure = Entry(self.frame, width=5, state="readonly", textvariable=self.pressure) if self.frame_name.get() == "Hydro": self.set_pressure_scale = Scale(self.frame, orient=HORIZONTAL, from_=0, to=92, resolution=0.5, bg=color, label="Set Pressure (PSI)", highlightthickness=0, command=self.set_pressure) else: self.set_pressure_scale = Scale(self.frame, orient=HORIZONTAL, from_=0, to=50, resolution=0.5, bg=color, label="Set Pressure (PSI)", highlightthickness=0, command=self.set_pressure) self.custom_label = Label(self.frame, textvariable=self.frame_name, font=(self.fontType, 14), bg=color) self.label = Label(self.frame, text=initial_name, bg=color) self.lock = Checkbutton(self.frame, text="LOCK", bg=color, variable=self.lock_flag, command=self.lock) self.frame_name.set(top_name) # Init the pressure scale to the default value. self.set_pressure_scale.set(PSI) # Lock hydo at startup if initial_name == "Hydro": self.lock.select() self.set_pressure_scale.config(state="disabled") self.power.config(state="disable") self.frame.rowconfigure(0, minsize=30) self.custom_label.grid(row=0, column=0, columnspan=2, sticky=S) self.set_label.grid(column=0, row=1, columnspan=2) self.frame.rowconfigure(2, minsize=50) self.power.grid(column=0, row=2) self.observed_pressure.grid(column=1, row=2) self.set_pressure_scale.grid(column=0, row=3, columnspan=2, padx=20) self.frame.rowconfigure(4, minsize=5) self.label.grid(column=0, row=5) self.lock.grid(column=1, row=5) # Connect to Phidget Solid State Relay for solinoid control if self.frame_name.get() == "Hydro": self.solenoid_switch = DigitalOutput() self.solenoid_switch.setDeviceSerialNumber(sol[0]) self.solenoid_switch.setIsHubPortDevice(False) self.solenoid_switch.setHubPort(sol[1]) self.solenoid_switch.setChannel(sol[2]) self.solenoid_switch.openWaitForAttachment(5000) #Connect to Phidget Solid State Relay for regulator power control self.reg_switch = DigitalOutput() self.reg_switch.setDeviceSerialNumber(reg_pwr[0]) self.reg_switch.setIsHubPortDevice(False) self.reg_switch.setHubPort(reg_pwr[1]) self.reg_switch.setChannel(reg_pwr[2]) self.reg_switch.openWaitForAttachment(5000) #Connect to Phidget Voltage Ouptut for pressure control self.pressure_ctrl = VoltageOutput() self.pressure_ctrl.setDeviceSerialNumber(reg_set[0]) self.pressure_ctrl.setIsHubPortDevice(False) self.pressure_ctrl.setHubPort(reg_set[1]) self.pressure_ctrl.setChannel(reg_set[2]) self.pressure_ctrl.openWaitForAttachment(5000) #Connect to Phidget Analog Input for pressure reading self.pressure_reading = VoltageRatioInput() self.pressure_reading.setDeviceSerialNumber(reg_get[0]) #One of the VINT Hubs on the SBC is used and needs special configuration if reg_get[0] == SBCH: self.pressure_reading.setIsHubPortDevice(True) self.pressure_reading.setHubPort(0) self.pressure_reading.setChannel(reg_get[1]) self.pressure_reading.openWaitForAttachment(5000) def toggle_pwr(self): #Turn on air channel if self.state == 0: #Turn on power to regulator and show active button color self.power.config(bg=self.activeColor) self.reg_switch.setState(True) if self.frame_name.get() == "Hydro": self.solenoid_switch.setState(True) #Start monitoring air pressure self.update_pressure() #Change state of air channel self.state = 1 #Turn off air channel elif self.state == 1: remember_state = self.set_pressure_scale.get() if self.frame_name.get() != "Hydro": messagebox.showinfo( self.frame_name.get() + " Warning", "Pressure will be set to zero. Acknowledge that " + self.frame_name.get() + " is in a safe configuration") # Change pressure to zero self.set_pressure_scale.set(0) self.set_pressure(0) time.sleep(0.5) self.frame.update() self.reg_switch.setState(False) time.sleep(0.5) self.set_pressure_scale.set(remember_state) if self.frame_name.get() == "Hydro": self.solenoid_switch.setState(False) self.lock.select() self.set_pressure_scale.config(state="disabled") self.power.config(state="disable") #Turn off power to reguluator and remove active button color self.power.config(bg="SystemButtonFace") #Update air channel state self.state = 0 def get_label_input(self): self.window = popupWindow(self.master) self.set_label.config(state=DISABLED) self.master.wait_window(self.window.top) self.set_label.config(state=NORMAL) #If the user does not enter a value exception will be produced try: if len(self.window.value) > 12: self.frame_name.set("SET ERROR") else: self.frame_name.set(self.window.value) except: self.frame_name.set("SET ERROR") def set_pressure(self, val): # Pressure Range range = MAXPR - MINPR # Calculate volts/PSI ratio = 5 / range self.pressure_ctrl.setVoltage(float(val) * ratio) def update_pressure(self): if self.reg_switch.getState(): try: val = float(self.pressure_reading.getSensorValue()) PSI = val * 165.63 - 30.855 PSI = round(PSI, 2) self.pressure.set(PSI) #Low pressure check if PSI < (self.set_pressure_scale.get() - 3): if self.frame.cget('bg') == "Red": self.frame.config(bg=self.frameColor) self.set_pressure_scale.config(bg=self.frameColor) self.custom_label.config(bg=self.frameColor) self.label.config(bg=self.frameColor) self.lock.config(bg=self.frameColor) else: self.frame.config(bg='Red') self.set_pressure_scale.config(bg="Red") self.custom_label.config(bg="Red") self.label.config(bg="Red") self.lock.config(bg="Red") if PSI > (self.set_pressure_scale.get() - 3): if self.frame.cget('bg') == "Red": self.frame.config(bg=self.frameColor) self.set_pressure_scale.config(bg=self.frameColor) self.custom_label.config(bg=self.frameColor) self.label.config(bg=self.frameColor) self.lock.config(bg=self.frameColor) except: print("Init Air Pressure") root.after(200, self.update_pressure) else: self.pressure.set("") def lock(self): if self.lock_flag.get() == True: self.set_pressure_scale.config(state="disabled") self.power.config(state="disable") elif self.lock_flag.get() == False: self.set_pressure_scale.config(state="normal") self.power.config(state="normal")
def open_menu(): wait = 0.15 for x in range(3): set("ON") time.sleep(wait) set("OFF") time.sleep(wait) zoom("+") time.sleep(wait) zoom("0") #Line required to look for Phidget devices on the network Net.enableServerDiscovery(PhidgetServerType.PHIDGETSERVER_DEVICEREMOTE) #Setup Power Button power = DigitalOutput() power.setDeviceSerialNumber(540047) power.setIsHubPortDevice(False) power.setHubPort(1) power.setChannel(3) power.openWaitForAttachment(5000) #Setup Focus, Zoom, and Manual Select: focus_enable = DigitalOutput() focus_enable.setDeviceSerialNumber(540047) focus_enable.setIsHubPortDevice(False) focus_enable.setHubPort(HUB_FOCUS_ENABLE) focus_enable.setChannel(CH_FOCUS_ENABLE) focus_enable.openWaitForAttachment(5000) focus_select = DigitalOutput()
#Open the channel try: userMotor.openWaitForAttachment(5000) randomMotor.openWaitForAttachment(5000) except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) #Set both motors to a default position randomMotor.setTargetPosition(90) randomMotor.setEngaged(True) userMotor.setTargetPosition(90) userMotor.setEngaged(True) #Create a led object try: LED = DigitalOutput() except RuntimeError as e: print("Runtime Error: %s" % e.message) try: LED.setDeviceSerialNumber(437969) except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) def onAttachHandler(e): print("Phidget attached!") LED.setOnAttachHandler(onAttachHandler) LED.setChannel(0) LED.openWaitForAttachment(5000)
class PopperPump: def __init__(self, serial_num): logging.debug("Opening Phidget") self.popper_pump = DigitalOutput() self.popper_pump.setChannel(0) self.popper_pump.setDeviceSerialNumber(serial_num) self.popper_pump.openWaitForAttachment(5000) self.program_lock = threading.Lock() self.program_queue = queue.Queue() self.run_time = runMin self.sleep_time = sleepMin # Required for Kontroller self.kontrol = None self.channel = None def close(self): logging.debug("Closing Phidget") self.popper_pump.close() def program_is_running(self): return self.program_lock.locked() def set_run(self, value): if self.run_time != value: self.run_time = value logging.debug(f'PopperPump run time set to {value} seconds') def set_sleep(self, value): if self.sleep_time != value: self.sleep_time = value logging.debug(f'PopperPump sleep time set to {value} seconds') def start_program(self): threading.Thread(target=self._program, daemon=True).start() def stop_program(self): self.program_queue.put("stop") # Private Functions def _program(self): if not self.program_lock.acquire(False): logging.warning("popperpump program already running") else: logging.info("starting popperpump program") try: while True: self.popper_pump.setDutyCycle(1) self.kontrol.k_led_on(self.channel, 's') try: msg = self.program_queue.get(timeout=self.run_time) # Message Received self.popper_pump.setDutyCycle(0) self.kontrol.k_led_off(self.channel, 's') return except queue.Empty: pass self.popper_pump.setDutyCycle(0) self.kontrol.k_led_off(self.channel, 's') try: msg = self.program_queue.get(timeout=self.sleep_time) # Message Received self.popper_pump.setDutyCycle(0) self.kontrol.k_led_off(self.channel, 's') return except queue.Empty: pass finally: logging.info("popperpump program stopped") self.program_lock.release() # Kontrol Functions def k_attach(self, channel, k: Kontrol2): if self.kontrol is None: self.kontrol = k self.channel = channel logging.debug(f'PopperPump attached on channel {channel}') else: raise KontrolAlreadyAttachedError( f'cannot attach to channel {channel} already attached to {self.channel}' ) def k_button_down( self, button, ): if self.kontrol is not None: if button == 'r': if self.program_is_running(): self.stop_program() self.kontrol.k_led_off(self.channel, 'r') else: self.start_program() self.kontrol.k_led_on(self.channel, 'r') else: raise KontrolNotAttachedError( f'PopperPump not attached to Kontroller') def k_button_up(self, button): if self.kontrol is not None: pass # Unused else: raise KontrolNotAttachedError( f'PopperPump not attached to Kontroller') def k_knob(self, level): if self.kontrol is not None: scale_level = int(util.scale(level, (0, 127), (sleepMin, sleepMax))) self.set_sleep(scale_level) else: raise KontrolNotAttachedError( f'PopperPump not attached to Kontroller') def k_slider(self, level): if self.kontrol is not None: scale_level = int(util.scale(level, (0, 127), (runMin, runMax))) self.set_run(scale_level) else: raise KontrolNotAttachedError( f'PopperPump not attached to Kontroller')
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]
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("----------")