Пример #1
0
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
Пример #2
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()
Пример #3
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()
Пример #4
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()
Пример #5
0
            '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'])
def update_digital_pin(pin_id):
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()