Exemple #1
0
    def __init__(self):
        # make sure this baudrate matches the baudrate True the Arduino
        self.running = False
        self.led_state = False
        self.baud = 115200
        self.commands = [
            'set_led',
            'status',
        ]

        try:
            # gets the first available USB port
            self.port_name = self.list_usb_ports()[0][0]
            self.serial_port = serial.Serial(self.port_name,
                                             self.baud,
                                             timeout=0)
        except (serial.SerialException, IndexError):
            raise SystemExit('Could not open serial port.')
        else:
            print 'Serial port sucessfully opened.'
            self.messenger = CmdMessenger(self.serial_port)
            # attach callbacks
            self.messenger.attach(func=self.on_unknown_command)
            self.messenger.attach(func=self.on_status,
                                  msgid=self.commands.index('status'))
Exemple #2
0
    def __init__(self):
        # make sure this baudrate matches the baudrate on the Arduino
        self.running = False
        self.baud = 115200
        self.commands = [
            'acknowledge',
            'error',
            'float_addition',
            'float_addition_result',
        ]

        try:
            # try to open the first available usb port
            self.port_name = self.list_usb_ports()[0][0]
            self.serial_port = serial.Serial(self.port_name,
                                             self.baud,
                                             timeout=0)
        except (serial.SerialException, IndexError):
            raise SystemExit('Could not open serial port.')
        else:
            print 'Serial port sucessfully opened.'
            self.messenger = CmdMessenger(self.serial_port)
            # attach callbacks
            self.messenger.attach(func=self.on_error,
                                  msgid=self.commands.index('error'))
            self.messenger.attach(
                func=self.on_float_addition_result,
                msgid=self.commands.index('float_addition_result'))

            # send a command that the arduino will acknowledge
            self.messenger.send_cmd(self.commands.index('acknowledge'))
            # Wait until the arduino sends and acknowledgement back
            self.messenger.wait_for_ack(
                ackid=self.commands.index('acknowledge'))
            print 'Arduino Ready'
    def __init__(self, port, baudrate):
        # Initialize the serial / command messenger connection
        self.ser = serial.Serial(port=port, baudrate=baudrate, timeout=0)
        self.cm = CmdMessenger(self.ser)

        # attach callbacks
        self.cm.attach(self._onUnknownCommand)

        # Start monitoring
        self.cmm = CmdMessengerMonitor(self.cm)
        self.cmm.start()
    def __init__(self):
        # make sure this baudrate matches the baudrate on the Arduino
        self.running = False
        self.baud = 115200
        self.commands = ['acknowledge',
                         'error',
                         'float_addition',
                         'float_addition_result',
                         ]

        try:
            # try to open the first available usb port
            self.port_name = self.list_usb_ports()[0][0]
            self.serial_port = serial.Serial(self.port_name, self.baud, timeout=0)
        except (serial.SerialException, IndexError):
            raise SystemExit('Could not open serial port.')
        else:
            print 'Serial port sucessfully opened.'
            self.messenger = CmdMessenger(self.serial_port)
            # attach callbacks
            self.messenger.attach(func=self.on_error, msgid=self.commands.index('error'))
            self.messenger.attach(func=self.on_float_addition_result,
                                  msgid=self.commands.index('float_addition_result'))

            # send a command that the arduino will acknowledge
            self.messenger.send_cmd(self.commands.index('acknowledge'))
            # Wait until the arduino sends and acknowledgement back
            self.messenger.wait_for_ack(ackid=self.commands.index('acknowledge'))
            print 'Arduino Ready'
Exemple #5
0
    def __init__(self):
        self.running = False
        self.led_state = False
        # make sure this baudrate matches the baudrate on the Arduino
        self.baud = 115200
        self.commands = ['set_led']

        try:
            # gets the first available USB port
            self.port_name = self.list_usb_ports()[0][0]
            self.serial_port = serial.Serial(self.port_name, self.baud, timeout=0)
        except (serial.SerialException, IndexError):
            raise SystemExit('Could not open serial port.')
        else:
            print 'Serial port sucessfully opened.'
            self.messenger = CmdMessenger(self.serial_port)
Exemple #6
0
    def __init__(self, port=None):
        # make sure this baudrate matches the baudrate on the Arduino
        self.running = False
        # this method list is matched with the enumerator type on the Arduino sketch
        # always make sure to have them in the same order.
        self.commands = [
            "acknowledge",
            "error",
            "pin_set_state",
            "command_result",
            "lcd_print",
            "identify",
            "motor_start",
        ]

        try:
            if port is None:
                print "Ensure that the right firmware is loaded to the webot"
                print "Select Serial Interface (USB=1,BLUETOOTH=2) >",
                selinterface = raw_input()
                if selinterface == "1":
                    print "Set Baud=115200, readtimeout=0.1"
                    self.baud = 115200
                    self.readtimeout = 0.1
                    print "USB interface selected"
                    # try to open the first available usb port
                    self.port_name = self.list_usb_ports()[0][0]
                elif selinterface == "2":
                    print "Set Baud=57600, readtimeout=0.5"
                    self.baud = 57600
                    self.readtimeout = 0.5
                    print "Bluetooth interface selected (/dev/rfcomm0)"
                    self.port_name = "/dev/rfcomm0"
                else:
                    print "Defaulting to USB interface"
                    # try to open the first available usb port
                    self.port_name = self.list_usb_ports()[0][0]
            else:
                print "Setting up bluetooth courier configuration"
                self.baud = 57600
                self.readtimeout = 0.5
                self.port_name = port
            self.serial_port = serial.Serial(self.port_name, self.baud, timeout=0)
        except (serial.SerialException, IndexError):
            raise SystemExit("Could not open serial port.")
        else:
            time.sleep(5)
            print "Serial port sucessfully opened."
            self.messenger = CmdMessenger(self.serial_port)
            # attach callbacks
            self.messenger.attach(func=self.on_error, msgid=self.commands.index("error"))
            self.messenger.attach(func=self.on_command_result, msgid=self.commands.index("command_result"))
            self.messenger.attach(func=self.on_identify, msgid=self.commands.index("identify"))

            # send a command that the arduino will acknowledge
            self.messenger.send_cmd(self.commands.index("acknowledge"))
            # Wait until the arduino sends an acknowledgement back
            self.messenger.wait_for_ack(ackid=self.commands.index("acknowledge"))
            print "Edubot Ready"
Exemple #7
0
class Receive(object):

    def __init__(self):
        self.running = False
        self.led_state = False
        # make sure this baudrate matches the baudrate on the Arduino
        self.baud = 115200
        self.commands = ['set_led']

        try:
            # gets the first available USB port
            self.port_name = self.list_usb_ports()[0][0]
            self.serial_port = serial.Serial(self.port_name, self.baud, timeout=0)
        except (serial.SerialException, IndexError):
            raise SystemExit('Could not open serial port.')
        else:
            print 'Serial port sucessfully opened.'
            self.messenger = CmdMessenger(self.serial_port)

    def list_usb_ports(self):
        """Use the grep generator to get a list of all USB ports.
        """
        ports =  [port for port in list_ports.grep('usb')]
        return ports

    def stop(self):
        """Stops the main run loop
        """
        self.running = False

    def run(self):
        """Main loop to send data to the Arduino
        """
        self.running = True
        timeout = 1
        t0 = time.time()
        while self.running:
            # Update the led state once every second
            if time.time() - t0 > timeout:
                t0 = time.time()
                if self.led_state == True:
                    self.messenger.send_cmd(self.commands.index('set_led'), False)
                    self.led_state = False
                else:
                    self.messenger.send_cmd(self.commands.index('set_led'), True)
                    self.led_state = True
    def __init__(self, port, baudrate):
        # Initialize the serial / command messenger connection
        self.ser = serial.Serial(port=port, baudrate=baudrate, timeout=0)
        self.cm = CmdMessenger(self.ser)

        # attach callbacks
        self.cm.attach(self._onUnknownCommand)

        # Start monitoring
        self.cmm = CmdMessengerMonitor(self.cm)
        self.cmm.start()
    def __init__(self):

        # make sure this baudrate matches the baudrate on the Arduino
        self.running = False
        self.baud = 9600
        self.temperature = {}
        self.temperature["Hot"]  = 100
        self.temperature["Mash"] = 100
        self.temperature["Boil"] = 100

        self.flow_level_current = 0
        self.flow_level_target  = 0

        self.commands = ['acknowledge',
                         'error',
                         'ping',
                         'SetPin',
                         'PwmPin',
                         'ReadTemperature',
                         'ReadFlow',
                         'Resistor'
                         ]

        if (MyGlobals.args['hardware_disconnected'] is False):
            try:
                # try to open the first available usb port
                self.port_name = self.list_usb_ports()[0][0]
                self.serial_port = serial.Serial(self.port_name, self.baud, timeout=0, rtscts=True)
            except (serial.SerialException, IndexError):
                raise SystemExit('Could not open serial port.')
            else:
                time.sleep(2)
                self.messenger = CmdMessenger(self.serial_port)

            # send a command that the arduino will acknowledge
            self.messenger.send_cmd(self.commands.index('acknowledge'))
            # Wait until the arduino sends and acknowledgement back
            status = self.messenger.wait_for_ack(ackid=self.commands.index('acknowledge'), timeout=5)
            if (status is None):
                print('Arduino timeout')
                sys.exit(255)

            # attach callbacks
            self.messenger.attach(func=self.on_error, msgid=self.commands.index('error'))
            self.messenger.attach(func=self.on_read_temperature,
                                  msgid=self.commands.index('ReadTemperature'))
            self.messenger.attach(func=self.on_read_flow,
                                  msgid=self.commands.index('ReadFlow'))


            thread = threading.Thread(target=self.run, args=())
            thread.daemon = True                            # Daemonize thread
            thread.start()                                  # Start the execution
Exemple #10
0
    def __init__(self):
        # make sure this baudrate matches the baudrate on the Arduino
        self.running = False
        self.baud = 57600
        self.commands = [
            'acknowledge',
            'error',
            'drive_robot',
            'robot_status',
        ]

        try:
            # try to open the first available usb port
            self.port_name = self.list_usb_ports()[0][0]
            # Initialize an ArduinoBoard instance.  This is where you specify baud rate and
            # serial timeout.  If you are using a non ATmega328 board, you might also need
            # to set the data sizes (bytes for integers, longs, floats, and doubles).
            #arduino = PyCmdMessenger.ArduinoBoard("/dev/ttyACM0",baud_rate=9600)
            self.serial_port = serial.Serial(self.port_name,
                                             self.baud,
                                             timeout=0)
        except (serial.SerialException, IndexError):
            raise SystemExit('Could not open serial port.')
        else:
            print('Serial port sucessfully opened.')
            # Initialize the messenger
            self.messenger = CmdMessenger(self.serial_port)

            # attach callbacks
            self.messenger.attach(func=self.on_error,
                                  msgid=self.commands.index('error'))
            self.messenger.attach(func=self.on_robot_status,
                                  msgid=self.commands.index('robot_status'))

            # send a command that the arduino will acknowledge
            self.messenger.send_cmd(self.commands.index('acknowledge'))
            # Wait until the arduino sends and acknowledgement back
            self.messenger.wait_for_ack(
                ackid=self.commands.index('acknowledge'))
            print('Arduino Ready')
    def __init__(self):
        # make sure this baudrate matches the baudrate True the Arduino
        self.running = False
        self.led_state = False
        self.baud = 115200
        self.commands = ['set_led',
                         'status',
                         ]

        try:
            # gets the first available USB port
            self.port_name = self.list_usb_ports()[0][0]
            self.serial_port = serial.Serial(self.port_name, self.baud, timeout=0)
        except (serial.SerialException, IndexError):
            raise SystemExit('Could not open serial port.')
        else:
            print 'Serial port sucessfully opened.'
            self.messenger = CmdMessenger(self.serial_port)
            # attach callbacks
            self.messenger.attach(func=self.on_unknown_command)
            self.messenger.attach(func=self.on_status, msgid=self.commands.index('status'))
class SendAndReceive(object):

    def __init__(self):
        # make sure this baudrate matches the baudrate True the Arduino
        self.running = False
        self.led_state = False
        self.baud = 115200
        self.commands = ['set_led',
                         'status',
                         ]

        try:
            # gets the first available USB port
            self.port_name = self.list_usb_ports()[0][0]
            self.serial_port = serial.Serial(self.port_name, self.baud, timeout=0)
        except (serial.SerialException, IndexError):
            raise SystemExit('Could not open serial port.')
        else:
            print 'Serial port sucessfully opened.'
            self.messenger = CmdMessenger(self.serial_port)
            # attach callbacks
            self.messenger.attach(func=self.on_unknown_command)
            self.messenger.attach(func=self.on_status, msgid=self.commands.index('status'))

    def list_usb_ports(self):
        """Use the grep generator to get a list of all USB ports.
        """
        ports =  [port for port in list_ports.grep('usb')]
        return ports

    def on_unknown_command(self, received_command, *args, **kwargs):
        """Handle when an unknown command has been received.
        """
        print "Command without attached callback received"

    def on_status(self, received_command, *args, **kwargs):
        """Callback function that prints the Arduino status to the console
        """
        print "Status: ",  args[0][0]

    def stop(self):
        """ Stops the main run loop
        """
        self.running = False

    def run(self):
        """Main loop to send and receive data from the Arduino
        """
        self.running = True
        timeout = 1
        t0 = time.time()
        while self.running:
            # Update the led state once every second
            if time.time() - t0 > timeout:
                t0 = time.time()
                if self.led_state == True:
                    self.messenger.send_cmd(self.commands.index('set_led'), False)
                    self.led_state = False
                else:
                    self.messenger.send_cmd(self.commands.index('set_led'), True)
                    self.led_state = True

            # Check to see if any data has been received
            self.messenger.feed_in_data()
class Petduino(object):

    # Actions
    SET_STATE_ACTION = 0
    GET_STATE_ACTION = 1
    SET_LED_ACTION = 2
    TOGGLE_LED_ACTION = 3
    GET_LED_ACTION = 4
    GET_TEMPERATURE_ACTION = 5
    GET_LIGHT_LEVEL_ACTION = 6
    SET_DATA_ACTION = 7

    # Events
    STATE_EVENT = 0
    LED_EVENT = 1
    TEMPERATURE_EVENT = 2
    LIGHT_LEVEL_EVENT = 3
    BUTTON_1_EVENT = 4
    BUTTON_2_EVENT = 5

    # Private
    _callbacks = {}

    # Constructor
    def __init__(self, port, baudrate):
        # Initialize the serial / command messenger connection
        self.ser = serial.Serial(port=port, baudrate=baudrate, timeout=0)
        self.cm = CmdMessenger(self.ser)

        # attach callbacks
        self.cm.attach(self._onUnknownCommand)

        # Start monitoring
        self.cmm = CmdMessengerMonitor(self.cm)
        self.cmm.start()

    def close(self):
        # Stop the monitoring
        self.cmm.stop()

        # Close the command messenger connection
        self.cm.close()

    # Actions
    def setState(self, val):
        self.cm.send_cmd(self.SET_STATE_ACTION, val)

    def getState(self):
        self.cm.send_cmd(self.GET_STATE_ACTION)

    def setLed(self, val):
        self.cm.send_cmd(self.SET_LED_ACTION, val)

    def toggleLed(self):
        self.cm.send_cmd(self.TOGGLE_LED_ACTION)

    def getLed(self, val):
        self.cm.send_cmd(self.GET_LED_ACTION, val)

    def getTemperature(self):
        self.cm.send_cmd(self.GET_TEMPERATURE_ACTION)

    def getLightLevel(self):
        self.cm.send_cmd(self.GET_LIGHT_LEVEL_ACTION)

    def setData(self, val):
        self.cm.send_cmd(self.SET_DATA_ACTION, val)

    # Events
    def _onUnknownCommand(self, received_command, *args, **kwargs):
        print "Command without attached callback received: ", received_command

    def onState(self, callback):
        self._setCallback(callback, self._onIntArgCmd, self.STATE_EVENT)

    def onLed(self, callback):
        self._setCallback(callback, self._onIntArgCmd, self.LED_EVENT)

    def onTemperature(self, callback):
        self._setCallback(callback, self._onFloatArgCmd,
                          self.TEMPERATURE_EVENT)

    def onLightLevel(self, callback):
        self._setCallback(callback, self._onIntArgCmd, self.LIGHT_LEVEL_EVENT)

    def onBtn1(self, callback):
        self._setCallback(callback, self._onBoolArgCmd, self.BUTTON_1_EVENT)

    def onBtn2(self, callback):
        self._setCallback(callback, self._onBoolArgCmd, self.BUTTON_2_EVENT)

    # Private event handlers
    def _onIntArgCmd(self, received_command, *args, **kwargs):
        if received_command in self._callbacks:
            self._callbacks[received_command](int(args[0][0]))

    def _onFloatArgCmd(self, received_command, *args, **kwargs):
        if received_command in self._callbacks:
            self._callbacks[received_command](float(args[0][0]))

    def _onBoolArgCmd(self, received_command, *args, **kwargs):
        if received_command in self._callbacks:
            self._callbacks[received_command](args[0][0] in ['true', '1', 'y'])

    # TODO: Maybe make attach / detach explicit?
    def _setCallback(self, callback, callbackProxy, evt):
        if (callback is None):
            if evt in self._callbacks:
                self.cm.detach(evt)
                self._callbacks.pop(evt)
        else:
            self._callbacks[evt] = callback
            self.cm.attach(callbackProxy, evt)
Exemple #14
0
class SendAndReceive(object):
    def __init__(self):
        # make sure this baudrate matches the baudrate True the Arduino
        self.running = False
        self.led_state = False
        self.baud = 115200
        self.commands = [
            'set_led',
            'status',
        ]

        try:
            # gets the first available USB port
            self.port_name = self.list_usb_ports()[0][0]
            self.serial_port = serial.Serial(self.port_name,
                                             self.baud,
                                             timeout=0)
        except (serial.SerialException, IndexError):
            raise SystemExit('Could not open serial port.')
        else:
            print 'Serial port sucessfully opened.'
            self.messenger = CmdMessenger(self.serial_port)
            # attach callbacks
            self.messenger.attach(func=self.on_unknown_command)
            self.messenger.attach(func=self.on_status,
                                  msgid=self.commands.index('status'))

    def list_usb_ports(self):
        """Use the grep generator to get a list of all USB ports.
        """
        ports = [port for port in list_ports.grep('usb')]
        return ports

    def on_unknown_command(self, received_command, *args, **kwargs):
        """Handle when an unknown command has been received.
        """
        print "Command without attached callback received"

    def on_status(self, received_command, *args, **kwargs):
        """Callback function that prints the Arduino status to the console
        """
        print "Status: ", args[0][0]

    def stop(self):
        """ Stops the main run loop
        """
        self.running = False

    def run(self):
        """Main loop to send and receive data from the Arduino
        """
        self.running = True
        timeout = 1
        t0 = time.time()
        while self.running:
            # Update the led state once every second
            if time.time() - t0 > timeout:
                t0 = time.time()
                if self.led_state == True:
                    self.messenger.send_cmd(self.commands.index('set_led'),
                                            False)
                    self.led_state = False
                else:
                    self.messenger.send_cmd(self.commands.index('set_led'),
                                            True)
                    self.led_state = True

            # Check to see if any data has been received
            self.messenger.feed_in_data()
class SendAndReceiveArguments(object):

    def __init__(self):
        # make sure this baudrate matches the baudrate on the Arduino
        self.running = False
        self.baud = 115200
        self.commands = ['acknowledge',
                         'error',
                         'float_addition',
                         'float_addition_result',
                         ]

        try:
            # try to open the first available usb port
            self.port_name = self.list_usb_ports()[0][0]
            self.serial_port = serial.Serial(self.port_name, self.baud, timeout=0)
        except (serial.SerialException, IndexError):
            raise SystemExit('Could not open serial port.')
        else:
            print 'Serial port sucessfully opened.'
            self.messenger = CmdMessenger(self.serial_port)
            # attach callbacks
            self.messenger.attach(func=self.on_error, msgid=self.commands.index('error'))
            self.messenger.attach(func=self.on_float_addition_result,
                                  msgid=self.commands.index('float_addition_result'))

            # send a command that the arduino will acknowledge
            self.messenger.send_cmd(self.commands.index('acknowledge'))
            # Wait until the arduino sends and acknowledgement back
            self.messenger.wait_for_ack(ackid=self.commands.index('acknowledge'))
            print 'Arduino Ready'

    def list_usb_ports(self):
        """ Use the grep generator to get a list of all USB ports.
        """
        ports =  [port for port in list_ports.grep('usb')]
        return ports

    def on_error(self, received_command, *args, **kwargs):
        """Callback function to handle errors
        """
        print 'Error:', args[0][0]

    def on_float_addition_result(self, received_command, *args, **kwargs):
        """Callback to handle the float addition response
        """
        print 'Addition Result:', args[0][0]
        print 'Subtraction Result:', args[0][1]
        print

    def stop(self):
        self.running = False

    def run(self):
        """Main loop to send and receive data from the Arduino
        """
        self.running = True
        timeout = 2
        t0 = time.time()
        while self.running:
            # Send two random integers to be added/subtracted every 2 seconds
            if time.time() - t0 > timeout:
                t0 = time.time()
                a = random.randint(0, 10)
                b = random.randint(0, 10)
                print 'Sending: {}, {}'.format(a, b)
                self.messenger.send_cmd(self.commands.index('float_addition'), a, b)

            # Check to see if any data has been received
            self.messenger.feed_in_data()
class MessengerController(object):

    def __init__(self):

        # make sure this baudrate matches the baudrate on the Arduino
        self.running = False
        self.baud = 9600
        self.temperature = {}
        self.temperature["Hot"]  = 100
        self.temperature["Mash"] = 100
        self.temperature["Boil"] = 100

        self.flow_level_current = 0
        self.flow_level_target  = 0

        self.commands = ['acknowledge',
                         'error',
                         'ping',
                         'SetPin',
                         'PwmPin',
                         'ReadTemperature',
                         'ReadFlow',
                         'Resistor'
                         ]

        if (MyGlobals.args['hardware_disconnected'] is False):
            try:
                # try to open the first available usb port
                self.port_name = self.list_usb_ports()[0][0]
                self.serial_port = serial.Serial(self.port_name, self.baud, timeout=0, rtscts=True)
            except (serial.SerialException, IndexError):
                raise SystemExit('Could not open serial port.')
            else:
                time.sleep(2)
                self.messenger = CmdMessenger(self.serial_port)

            # send a command that the arduino will acknowledge
            self.messenger.send_cmd(self.commands.index('acknowledge'))
            # Wait until the arduino sends and acknowledgement back
            status = self.messenger.wait_for_ack(ackid=self.commands.index('acknowledge'), timeout=5)
            if (status is None):
                print('Arduino timeout')
                sys.exit(255)

            # attach callbacks
            self.messenger.attach(func=self.on_error, msgid=self.commands.index('error'))
            self.messenger.attach(func=self.on_read_temperature,
                                  msgid=self.commands.index('ReadTemperature'))
            self.messenger.attach(func=self.on_read_flow,
                                  msgid=self.commands.index('ReadFlow'))


            thread = threading.Thread(target=self.run, args=())
            thread.daemon = True                            # Daemonize thread
            thread.start()                                  # Start the execution



    def list_usb_ports(self):
        """ Use the grep generator to get a list of all USB ports.
        """
        ports = [port for port in list_ports.grep('USB')]
        return ports

    def on_error(self, received_command, *args, **kwargs):
        """Callback function to handle errors
        """
        print(('Error:', args[0][0]))

    def on_read_temperature(self, received_command, *args, **kwargs):
        """ Callback on temperature """

        self.temperature["Hot"]  = int(args[0][0])/100
        self.temperature["Mash"] = int(args[0][1])/100
        self.temperature["Boil"] = int(args[0][2])/100

    def on_read_flow(self, received_command, *args, **kwargs):
        """ Callback on flow """

        self.flow_level_current = int(args[0][0])


    def stop(self):
        self.running = False

    def ping(self):
        """ Send a ping (blocking) """
        self.messenger.send_cmd(self.commands.index('ping'))

        self.messenger.wait_for_ack(ackid=self.commands.index('acknowledge'))

    def set_pin(self, pin, value):
        """ Set a boolean value to a pin (blocking) """
        self.messenger.send_cmd(self.commands.index('SetPin'), pin, value)

        self.messenger.wait_for_ack(ackid=self.commands.index('acknowledge'))

    def set_pwm_pin(self, pin, value):
        """ Set a pwm value to a pin (blocking)
            value is supposed to be between 0-1
        """
        self.messenger.send_cmd(self.commands.index('PwmPin'), pin, int(value*255))

        self.messenger.wait_for_ack(ackid=self.commands.index('acknowledge'))

    def set_resistors(self, mash, boil, hot):
        if (MyGlobals.args['hardware_disconnected'] is False):
            self.messenger.send_cmd(self.commands.index('Resistor'), hot, mash, boil, 100 - mash - boil - hot)


    def dump_in_water(self, valve, value):
        """ Set a pwm value to a pin (blocking)
            value is supposed to be between 0-65 liters
        """
        self.messenger.send_cmd(self.commands.index('DumpInWater'), valve, value)
        self.valve_status[valve] = True
        self.messenger.wait_for_ack(ackid=self.commands.index('acknowledge'))



    def run(self):
        """Main loop to send and receive data from the Arduino
        """
        while (True):
            self.messenger.feed_in_data()
            time.sleep(0.01)  # please do not hurt my core
Exemple #17
0
commands = ['acknowledge',
            'error',
            'set_digital_pin',
            'set_analog_pin',
            ]

# setup serial communication
try:
    # try to open the first available usb port
    ports = [port for port in list_ports.grep('usb')]
    port_name = ports[0][0]
    serial_port = serial.Serial(port_name, baud, timeout=0)
except (serial.SerialException, IndexError):
    raise SystemExit('Could not open serial port.')
else:
    messenger = CmdMessenger(serial_port)
    messenger.wait_for_ack(ackid=commands.index('acknowledge'))
    print 'Connected to Arduino'

def set_digital_pin(pin_id, value):
    print 'Setting digital pin:', pin_id, 'to value:', value
    messenger.send_cmd(commands.index('set_digital_pin'), pin_id, value)
    messenger.wait_for_ack(ackid=commands.index('acknowledge'))

def on_set_digital_pin(received_command, *args, **kwargs):
    pin_id = args[0][0]
    pin_value = args[0][1]
    pin_data[pin_id] = pin_value


@app.route('/arduino/digital/<int:pin_id>', methods=['PATCH'])
Exemple #18
0
class SendAndReceiveArguments(object):
    def __init__(self):
        # make sure this baudrate matches the baudrate on the Arduino
        self.running = False
        self.baud = 57600
        self.commands = [
            'acknowledge',
            'error',
            'drive_robot',
            'robot_status',
        ]

        try:
            # try to open the first available usb port
            self.port_name = self.list_usb_ports()[0][0]
            # Initialize an ArduinoBoard instance.  This is where you specify baud rate and
            # serial timeout.  If you are using a non ATmega328 board, you might also need
            # to set the data sizes (bytes for integers, longs, floats, and doubles).
            #arduino = PyCmdMessenger.ArduinoBoard("/dev/ttyACM0",baud_rate=9600)
            self.serial_port = serial.Serial(self.port_name,
                                             self.baud,
                                             timeout=0)
        except (serial.SerialException, IndexError):
            raise SystemExit('Could not open serial port.')
        else:
            print('Serial port sucessfully opened.')
            # Initialize the messenger
            self.messenger = CmdMessenger(self.serial_port)

            # attach callbacks
            self.messenger.attach(func=self.on_error,
                                  msgid=self.commands.index('error'))
            self.messenger.attach(func=self.on_robot_status,
                                  msgid=self.commands.index('robot_status'))

            # send a command that the arduino will acknowledge
            self.messenger.send_cmd(self.commands.index('acknowledge'))
            # Wait until the arduino sends and acknowledgement back
            self.messenger.wait_for_ack(
                ackid=self.commands.index('acknowledge'))
            print('Arduino Ready')

    def list_usb_ports(self):
        """ Use the grep generator to get a list of all USB ports.
        """
        ports = [port for port in list_ports.grep('USB')]
        return ports

    def on_error(self, received_command, *args, **kwargs):
        """Callback function to handle errors
        """
        print('Error:', args[0][0])

    def on_robot_status(self, received_command, *args, **kwargs):
        """Callback to handle the float addition response
        """
        print('Robot Status:', args[0][0])

    def stop(self):
        self.running = False

    def run(self):
        """Main loop to send and receive data from the Arduino
        """
        self.running = True
        timeout = 2
        pin_timeout = 2
        t0 = time.time()
        t0_pin = time.time()
        while self.running:
            if (GPIO.input(11)
                    == False) and (time.time() - t0_pin > pin_timeout):
                time.sleep(0.2)  #Delay for debounce
                t0_pin = time.time()
                # Send
                print("pin 11")
                drive_time = 1000
                self.messenger.send_cmd(self.commands.index('drive_robot'),
                                        drive_time)
                print("Sent drive command")
                time.sleep(1)
                #c.send("go_straight")
                #time.sleep (1)#Delay for go command
            if GPIO.input(12) == False:
                time.sleep(0.2)  #Delay for debounce
                print("pin 12")
                n = 2

            # Check to see if any data has been received
            self.messenger.feed_in_data()
Exemple #19
0
class SendAndReceiveArguments(object):
    def __init__(self, port=None):
        # make sure this baudrate matches the baudrate on the Arduino
        self.running = False
        # this method list is matched with the enumerator type on the Arduino sketch
        # always make sure to have them in the same order.
        self.commands = [
            "acknowledge",
            "error",
            "pin_set_state",
            "command_result",
            "lcd_print",
            "identify",
            "motor_start",
        ]

        try:
            if port is None:
                print "Ensure that the right firmware is loaded to the webot"
                print "Select Serial Interface (USB=1,BLUETOOTH=2) >",
                selinterface = raw_input()
                if selinterface == "1":
                    print "Set Baud=115200, readtimeout=0.1"
                    self.baud = 115200
                    self.readtimeout = 0.1
                    print "USB interface selected"
                    # try to open the first available usb port
                    self.port_name = self.list_usb_ports()[0][0]
                elif selinterface == "2":
                    print "Set Baud=57600, readtimeout=0.5"
                    self.baud = 57600
                    self.readtimeout = 0.5
                    print "Bluetooth interface selected (/dev/rfcomm0)"
                    self.port_name = "/dev/rfcomm0"
                else:
                    print "Defaulting to USB interface"
                    # try to open the first available usb port
                    self.port_name = self.list_usb_ports()[0][0]
            else:
                print "Setting up bluetooth courier configuration"
                self.baud = 57600
                self.readtimeout = 0.5
                self.port_name = port
            self.serial_port = serial.Serial(self.port_name, self.baud, timeout=0)
        except (serial.SerialException, IndexError):
            raise SystemExit("Could not open serial port.")
        else:
            time.sleep(5)
            print "Serial port sucessfully opened."
            self.messenger = CmdMessenger(self.serial_port)
            # attach callbacks
            self.messenger.attach(func=self.on_error, msgid=self.commands.index("error"))
            self.messenger.attach(func=self.on_command_result, msgid=self.commands.index("command_result"))
            self.messenger.attach(func=self.on_identify, msgid=self.commands.index("identify"))

            # send a command that the arduino will acknowledge
            self.messenger.send_cmd(self.commands.index("acknowledge"))
            # Wait until the arduino sends an acknowledgement back
            self.messenger.wait_for_ack(ackid=self.commands.index("acknowledge"))
            print "Edubot Ready"

    def on_identify(self, received_command, *args, **kwargs):
        print "Identity:", args[0][0]

    def list_usb_ports(self):
        """ Use the grep generator to get a list of all USB ports.
        """
        ports = [port for port in list_ports.grep("usb")]
        return ports

    def on_error(self, received_command, *args, **kwargs):
        """Callback function to handle errors
        """
        print "Error:", args[0][0]

    def on_command_result(self, received_command, *args, **kwargs):
        """Callback to handle the Pin State Change success state
        """
        print "Echo Received:", args[0]
        print

    def stop(self):
        self.running = False

    def run(self):
        """Main loop to send and receive data from the Arduino        
        """
        print "Determining device identity"
        self.messenger.send_cmd(self.commands.index("identify"))
        time.sleep(self.readtimeout)
        self.messenger.feed_in_data()
        self.running = True
        while self.running:
            print "Which command would you like to test? (1-Pin Set, 2-LCD Print) ",
            userchoice = raw_input()
            if userchoice == "1":
                print "Enter Pin Number > ",
                a = raw_input()
                print "Enter State > ",
                b = raw_input()
                print "Sending: {}, {}".format(a, b)
                self.messenger.send_cmd(self.commands.index("pin_set_state"), a, b)
            if userchoice == "2":
                print "Enter LCD String > ",
                c = raw_input()
                print "Enter LCD Color hexcode >",
                d = raw_input()
                if d != "":
                    if c != "":
                        e = self.hex_to_rgb(d)
                        print "Sending: {}, {}".format(c, e)
                        self.messenger.send_cmd(self.commands.index("lcd_print"), c, *e)
                    else:
                        e = self.hex_to_rgb(d)
                        print "Sending: {}, {}".format("None", e)
                        self.messenger.send_cmd(self.commands.index("lcd_print"), "None", *e)
                else:
                    print "Sending: {}".format(c)
                    self.messenger.send_cmd(self.commands.index("lcd_print"), c)

            # Check to see if any data has been received
            time.sleep(self.readtimeout)
            self.messenger.feed_in_data()

    def hex_to_rgb(self, hexvalue):
        value = hexvalue.lstrip("#")
        lv = len(value)
        return list(int(value[i : i + lv // 3], 16) for i in range(0, lv, lv // 3))

    def relay(self, blocklycommands):
        commandlist = []
        commandlist = blocklycommands.split(";")
        self.messenger.send_cmd(self.commands.index("identify"))
        time.sleep(self.readtimeout)
        self.messenger.feed_in_data()
        commax = len(commandlist)
        # for some reason the last element is an empty string, the following
        # statements clean that out
        validcommandlist = [validcommand for validcommand in commandlist[0 : commax - 1]]
        # print validcommandlist
        for commandset in validcommandlist:
            command = []
            command = commandset.split(",")
            print command[0]

            if command[0] == "lcd_print":
                print "Working with", command[1], command[2]
                if command[2] != "None":
                    print "Hex color codes received"
                    rgblist = self.hex_to_rgb(command[2])
                    command.pop(2)
                    command = command + rgblist
                if command[1] == "None":
                    print "No LCD String received"
                    command[1] = "None"

            print command
            self.messenger.send_cmd(self.commands.index(command[0]), *command[1:])
            time.sleep(self.readtimeout)
            self.messenger.feed_in_data()
Exemple #20
0
class SendAndReceiveArguments(object):
    def __init__(self):
        # make sure this baudrate matches the baudrate on the Arduino
        self.running = False
        self.baud = 115200
        self.commands = [
            'acknowledge',
            'error',
            'float_addition',
            'float_addition_result',
        ]

        try:
            # try to open the first available usb port
            self.port_name = self.list_usb_ports()[0][0]
            self.serial_port = serial.Serial(self.port_name,
                                             self.baud,
                                             timeout=0)
        except (serial.SerialException, IndexError):
            raise SystemExit('Could not open serial port.')
        else:
            print 'Serial port sucessfully opened.'
            self.messenger = CmdMessenger(self.serial_port)
            # attach callbacks
            self.messenger.attach(func=self.on_error,
                                  msgid=self.commands.index('error'))
            self.messenger.attach(
                func=self.on_float_addition_result,
                msgid=self.commands.index('float_addition_result'))

            # send a command that the arduino will acknowledge
            self.messenger.send_cmd(self.commands.index('acknowledge'))
            # Wait until the arduino sends and acknowledgement back
            self.messenger.wait_for_ack(
                ackid=self.commands.index('acknowledge'))
            print 'Arduino Ready'

    def list_usb_ports(self):
        """ Use the grep generator to get a list of all USB ports.
        """
        ports = [port for port in list_ports.grep('usb')]
        return ports

    def on_error(self, received_command, *args, **kwargs):
        """Callback function to handle errors
        """
        print 'Error:', args[0][0]

    def on_float_addition_result(self, received_command, *args, **kwargs):
        """Callback to handle the float addition response
        """
        print 'Addition Result:', args[0][0]
        print 'Subtraction Result:', args[0][1]
        print

    def stop(self):
        self.running = False

    def run(self):
        """Main loop to send and receive data from the Arduino
        """
        self.running = True
        timeout = 2
        t0 = time.time()
        while self.running:
            # Send two random integers to be added/subtracted every 2 seconds
            if time.time() - t0 > timeout:
                t0 = time.time()
                a = random.randint(0, 10)
                b = random.randint(0, 10)
                print 'Sending: {}, {}'.format(a, b)
                self.messenger.send_cmd(self.commands.index('float_addition'),
                                        a, b)

            # Check to see if any data has been received
            self.messenger.feed_in_data()
class Petduino(object):

    # Actions
    SET_STATE_ACTION             = 0
    GET_STATE_ACTION             = 1
    SET_LED_ACTION               = 2
    TOGGLE_LED_ACTION            = 3
    GET_LED_ACTION               = 4
    GET_TEMPERATURE_ACTION       = 5
    GET_LIGHT_LEVEL_ACTION       = 6
    SET_DATA_ACTION              = 7

    # Events
    STATE_EVENT                  = 0
    LED_EVENT                    = 1
    TEMPERATURE_EVENT            = 2
    LIGHT_LEVEL_EVENT            = 3
    BUTTON_1_EVENT               = 4
    BUTTON_2_EVENT               = 5

    # Private
    _callbacks = {}

    # Constructor
    def __init__(self, port, baudrate):
        # Initialize the serial / command messenger connection
        self.ser = serial.Serial(port=port, baudrate=baudrate, timeout=0)
        self.cm = CmdMessenger(self.ser)

        # attach callbacks
        self.cm.attach(self._onUnknownCommand)

        # Start monitoring
        self.cmm = CmdMessengerMonitor(self.cm)
        self.cmm.start()

    def close(self):
        # Stop the monitoring
        self.cmm.stop()

        # Close the command messenger connection
        self.cm.close()

    # Actions
    def setState(self, val):
        self.cm.send_cmd(self.SET_STATE_ACTION, val)

    def getState(self):
        self.cm.send_cmd(self.GET_STATE_ACTION)

    def setLed(self, val):
        self.cm.send_cmd(self.SET_LED_ACTION, val)

    def toggleLed(self):
        self.cm.send_cmd(self.TOGGLE_LED_ACTION)

    def getLed(self, val):
        self.cm.send_cmd(self.GET_LED_ACTION, val)

    def getTemperature(self):
        self.cm.send_cmd(self.GET_TEMPERATURE_ACTION)

    def getLightLevel(self):
        self.cm.send_cmd(self.GET_LIGHT_LEVEL_ACTION)

    def setData(self, val):
        self.cm.send_cmd(self.SET_DATA_ACTION, val)

    # Events
    def _onUnknownCommand(self, received_command, *args, **kwargs):
        print "Command without attached callback received: ", received_command

    def onState(self, callback):
        self._setCallback(callback, self._onIntArgCmd, self.STATE_EVENT)

    def onLed(self, callback):
        self._setCallback(callback, self._onIntArgCmd, self.LED_EVENT)

    def onTemperature(self, callback):
        self._setCallback(callback, self._onFloatArgCmd, self.TEMPERATURE_EVENT)

    def onLightLevel(self, callback):
        self._setCallback(callback, self._onIntArgCmd, self.LIGHT_LEVEL_EVENT)

    def onBtn1(self, callback):
        self._setCallback(callback, self._onBoolArgCmd, self.BUTTON_1_EVENT)

    def onBtn2(self, callback):
        self._setCallback(callback, self._onBoolArgCmd, self.BUTTON_2_EVENT)

    # Private event handlers
    def _onIntArgCmd(self, received_command, *args, **kwargs):
        if received_command in self._callbacks:
            self._callbacks[received_command](int(args[0][0]))

    def _onFloatArgCmd(self, received_command, *args, **kwargs):
        if received_command in self._callbacks:
            self._callbacks[received_command](float(args[0][0]))

    def _onBoolArgCmd(self, received_command, *args, **kwargs):
        if received_command in self._callbacks:
            self._callbacks[received_command](args[0][0] in ['true', '1', 'y'])

    # TODO: Maybe make attach / detach explicit?
    def _setCallback(self, callback, callbackProxy, evt):
        if(callback is None):
            if evt in self._callbacks:
                self.cm.detach(evt)
                self._callbacks.pop(evt)
        else:
            self._callbacks[evt] = callback;
            self.cm.attach(callbackProxy, evt)
Exemple #22
0
import time

from cmdmessenger import CmdMessenger
from serial.tools import list_ports

DEV = '/dev/tty.wchusbserialfd12410'

CMD_ACK = 0
CMD_INFO = 1
CMD_ERROR = 2
CMD_SET_SPEED = 3

port = serial.Serial(DEV, 9600)
print('connected to', port.name)

msgr = CmdMessenger(port)

print('waiting for arduino...')
#msgr.send_cmd(CMD_ACK)
#msgr.wait_for_ack(CMD_ACK)
print("arduino ready")


def on_error(received_command, *args, **kwargs):
    print('Error: ', args[0][0])

def on_info(received_command, *args, **kwargs):
    print('Info: ', args[0][0])

def on_unknown_cmd(received_command, *args, **kwargs):
    print('unknown cmd')