Exemplo n.º 1
0
class Arduino_Interface(object):


	##                                          ##
	##               CONSTANTS                  ##
	##                                          ##
	##                                          ##

	PING = 0x01
	TEST_DATA = 0x02






	##                                          ##
	##            Initalization                 ##
	##                                          ##
	##                                          ##



	def __init__(self, port, log_handler):
		## Initalize logging
		logging.basicConfig(level=logging.DEBUG)
		self.logger = logging.getLogger('Arduino_Interface')
		self.logger.addHandler(log_handler) # Add Tk log handler
		self.logger.debug('__init__')


		## Board Initalization
		self.board = Arduino(port)
		self.board.add_cmd_handler(pyfirmata.START_SYSEX, self.handleIncomingSysEx)
		self.board.add_cmd_handler(pyfirmata.STRING_DATA, self.handleIncomingString)

		## Data Buffer Initalization
		self.incoming_data = []

		## Callback holder
		self.callback_holder = dict()




	##                                          ##
	##           Runtime Functions              ##
	##                                          ##
	##                                          ##


	def begin_scanning(self):
		self.board.iterate()


	##                                          ##
	##              Senders                     ##
	##                                          ##
	##                                          ##


	def ping(self, pingCallback):
		self.logger.debug('----Sending Ping----')


		## Attach callback
		self.callback_holder[Arduino_Interface.PING] = pingCallback


		byte_array = bytearray()
		byte_array.append(Arduino_Interface.PING)

		self.sendSysEx(byte_array)


	def requestTestData(self, testDataCallback):
		self.logger.debug('----Requesting Test Data----')
		
		## Attach callback
		self.callback_holder[Arduino_Interface.TEST_DATA] = testDataCallback

		byte_array = bytearray()
		byte_array.append(Arduino_Interface.TEST_DATA)

		self.sendSysEx(byte_array)




	def sendSysEx(self, byteArray):
		self.logger.debug('----sendSysEx----')
		self.logger.debug('SEND Data: {}'.format(binascii.hexlify(byteArray)))
		self.board.send_sysex(pyfirmata.START_SYSEX, byteArray)

		self.begin_scanning()




	def sendString(self, stringToSend):
		pass
		#self.board.send_sysex

	
	#	for byte in dataArray:
	#		self.incoming_data.append(chr(byte))
	#	print self.incoming_data




	##                                          ##
	##              Handlers                    ##
	##                                          ##
	##                                          ##

	def handleIncomingString(self, *string):
		self.logger.debug('handling Incoming String')

		## Flush incoming_data
		self.incoming_data = []

		for byte in string:
			self.incoming_data.append(chr(byte))

		recieved_string = ''.join(self.incoming_data)
		print recieved_string



	def handleIncomingSysEx(self, *byteArray):
		self.logger.debug('----Incoming SysEx----')

		## Flush incoming_data array
		self.incoming_data = []
		self.incoming_data = self.filterSysEx(byteArray)

		## Get header
		header = byteArray[0]
		self.logger.debug('header: {}'.format(header))
		

		if (header == Arduino_Interface.PING):
			self.logger.debug('PING Response recieved')
			## Ping response recieved. Return True
			self.callback_holder[Arduino_Interface.PING](True)

		elif (header == Arduino_Interface.TEST_DATA):
			self.logger.debug('Test Data recieved')
			self.callback_holder[Arduino_Interface.TEST_DATA](self.incoming_data)




	##                                          ##
	##              Utilities                   ##
	##                                          ##
	##                                          ##


	def filterSysEx(self, byteArray):
		self.logger.debug('filterSysEx')

		incoming_data = []
		for idx, byte in enumerate(byteArray):
			if idx == 0:
				continue
			incoming_data.append(byte)

		self.logger.debug('SysEx Data:')
		self.logger.debug(incoming_data)
		return incoming_data
Exemplo n.º 2
0
# Booleans for determining stall vacancy
isOccupiedOne = False
isOccupiedTwo = False

# Sets analog pins to be able to read voltage
board.analog[5].enable_reporting()
board.analog[4].enable_reporting()

# Sets pins 11 and 13 to HIGH
board.digital[11].write(1)
board.digital[13].write(1)

# Continuously loop
while True:

    board.iterate()  # Makes the board cycle to refresh analog readings

    # Setting some preconditions
    occupiedStatusOne = isOccupiedOne
    occupiedStatusTwo = isOccupiedTwo

    # If the analog for latch one reads LOW, set pin 12 to HIGH, the stall is vacant
    # If the analog for latch one reads HIGH, set pin 12 to LOW, the stall is occupied
    if board.analog[4].read() == 0.0 or board.analog[4].read() == 0.001:
        board.digital[12].write(1)
        isOccupiedOne = False
    else:
        board.digital[12].write(0)
        isOccupiedOne = True

    # If the analog for latch two reads LOW, set pin 10 to HIGH, the stall is vacant
Exemplo n.º 3
0
class Controls(object):
    iterator = ''
    board = ''
    servos = None
    digitalouts = None
    buttons = None
    subsock = None

    def __init__(self, session):

        monkey.patch_socket() 
        import gevent_zeromq
        gevent_zeromq.monkey_patch()
         #we do use greenlets, but only patch sock stuff
        #other stuff messes up the

        config = session.arduino 
        boardglob = config['board']
        boards = glob(boardglob)
        if not len(boards):
              raise Exception("No Arduino found")
        
        self.board = Arduino(boards[0])
        #self.iterator = util.Iterator(self.board)
        #self.iterator.daemon = True
        #self.iterator.start()

        #initialize servo objects
        self.servos = {}
        if "servos" in config:
            for servo in config["servos"]:
                self.servos[servo['name']] = Servo(servo['pin'], self.board)

        #initialize light objects
        self.digitalouts = {}
        if "digitalouts" in config:
            for do in config["digitalouts"]:
                self.digitalouts[do['name']] = DigitalOut(do['pin'], self.board)

        if "digitalouts" in config or "servos" in config:
            self.subsock = ChannelManager().subscribe("ControlOutput/")

        self.buttons = []
        if "buttons" in config:
            for button in config["buttons"]:
                self.buttons.append(Button(button['pin'], button['message'], self.board))

        self.potentiometers = []
        if "potentiometers" in config:
            for pot in config["potentiometers"]:
                self.buttons.append(Potentiometer(pot['pin'], pot['name'], self.board))                

    def checkSubscription(self):
        if not self.subsock:
            return
            
        while True:
            channel = self.subsock.recv()
            message = self.subsock.recv()            
            message = jsondecode(message)
            
            for name,value in message.items():
                if name in self.servos:
                    self.servos[name].moveTo(value)
                elif name in self.digitalouts:
                    self.digitalouts[name].write(value)
            gevent.sleep(0)

    def run(self):
        if self.subsock and len(self.buttons):
            gevent.spawn_link_exception(Controls.checkSubscription, self)
        elif self.subsock:
            self.checkSubscription()
            return
        
        while True:
            while self.board.bytes_available():
                self.board.iterate()
            #make sure we have a clean buffer before bouncing the buttons    
            for b in self.buttons:
                b.read()
                
            for p in self.potentiometers:
                p.read()
                
            gevent.sleep(0)
Exemplo n.º 4
0
from pyfirmata import Arduino, util
import pyfirmata
from time import sleep

from mqtt_lib import Communicator

board = Arduino('/dev/serial/by-id/usb-1a86_USB2.0-Serial-if00-port0')  # Nano
#board = Arduino('/dev/serial/by-id/usb-Arduino__www.arduino.cc__0043_55432333038351E0F022-if00') # Uno
print('Connected')

value = board.get_pin('d:4:i')  # type: pyfirmata.Pin

it = util.Iterator(board)
it.start()
board.iterate()

PIN_MODE_PULLUP = 0x0B

msg = bytearray([pyfirmata.SET_PIN_MODE, value.pin_number, PIN_MODE_PULLUP])
value.board.sp.write(msg)

c = Communicator()

while True:
    input = value.read()
    if input == True:
        print('Switch is High')
        c.send_message(True, True)
    else:
        print('Switch is Low')
        c.send_message(False, False)
Exemplo n.º 5
0
class Arduino_Interface(object):

    ##                                          ##
    ##               CONSTANTS                  ##
    ##                                          ##
    ##                                          ##

    PING = 0x01
    TEST_DATA = 0x02

    ##                                          ##
    ##            Initalization                 ##
    ##                                          ##
    ##                                          ##

    def __init__(self, port, log_handler):
        ## Initalize logging
        logging.basicConfig(level=logging.DEBUG)
        self.logger = logging.getLogger('Arduino_Interface')
        self.logger.addHandler(log_handler)  # Add Tk log handler
        self.logger.debug('__init__')

        ## Board Initalization
        self.board = Arduino(port)
        self.board.add_cmd_handler(pyfirmata.START_SYSEX,
                                   self.handleIncomingSysEx)
        self.board.add_cmd_handler(pyfirmata.STRING_DATA,
                                   self.handleIncomingString)

        ## Data Buffer Initalization
        self.incoming_data = []

        ## Callback holder
        self.callback_holder = dict()

    ##                                          ##
    ##           Runtime Functions              ##
    ##                                          ##
    ##                                          ##

    def begin_scanning(self):
        self.board.iterate()

    ##                                          ##
    ##              Senders                     ##
    ##                                          ##
    ##                                          ##

    def ping(self, pingCallback):
        self.logger.debug('----Sending Ping----')

        ## Attach callback
        self.callback_holder[Arduino_Interface.PING] = pingCallback

        byte_array = bytearray()
        byte_array.append(Arduino_Interface.PING)

        self.sendSysEx(byte_array)

    def requestTestData(self, testDataCallback):
        self.logger.debug('----Requesting Test Data----')

        ## Attach callback
        self.callback_holder[Arduino_Interface.TEST_DATA] = testDataCallback

        byte_array = bytearray()
        byte_array.append(Arduino_Interface.TEST_DATA)

        self.sendSysEx(byte_array)

    def sendSysEx(self, byteArray):
        self.logger.debug('----sendSysEx----')
        self.logger.debug('SEND Data: {}'.format(binascii.hexlify(byteArray)))
        self.board.send_sysex(pyfirmata.START_SYSEX, byteArray)

        self.begin_scanning()

    def sendString(self, stringToSend):
        pass
        #self.board.send_sysex

    #	for byte in dataArray:
    #		self.incoming_data.append(chr(byte))
    #	print self.incoming_data

    ##                                          ##
    ##              Handlers                    ##
    ##                                          ##
    ##                                          ##

    def handleIncomingString(self, *string):
        self.logger.debug('handling Incoming String')

        ## Flush incoming_data
        self.incoming_data = []

        for byte in string:
            self.incoming_data.append(chr(byte))

        recieved_string = ''.join(self.incoming_data)
        print recieved_string

    def handleIncomingSysEx(self, *byteArray):
        self.logger.debug('----Incoming SysEx----')

        ## Flush incoming_data array
        self.incoming_data = []
        self.incoming_data = self.filterSysEx(byteArray)

        ## Get header
        header = byteArray[0]
        self.logger.debug('header: {}'.format(header))

        if (header == Arduino_Interface.PING):
            self.logger.debug('PING Response recieved')
            ## Ping response recieved. Return True
            self.callback_holder[Arduino_Interface.PING](True)

        elif (header == Arduino_Interface.TEST_DATA):
            self.logger.debug('Test Data recieved')
            self.callback_holder[Arduino_Interface.TEST_DATA](
                self.incoming_data)

    ##                                          ##
    ##              Utilities                   ##
    ##                                          ##
    ##                                          ##

    def filterSysEx(self, byteArray):
        self.logger.debug('filterSysEx')

        incoming_data = []
        for idx, byte in enumerate(byteArray):
            if idx == 0:
                continue
            incoming_data.append(byte)

        self.logger.debug('SysEx Data:')
        self.logger.debug(incoming_data)
        return incoming_data