Пример #1
0
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()
Пример #2
0
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)
Пример #3
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)
Пример #4
0
    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)

Пример #5
0
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')
Пример #6
0
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()
Пример #7
0
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("----------")