class ArduinoBoard(object): """ Represents an Arduino board. """ def __init__(self, port): from PyMata.pymata import PyMata self._port = port self._board = PyMata(self._port, verbose=False) def set_mode(self, pin, direction, mode): """ Sets the mode and the direction of a given pin. """ if mode == 'analog' and direction == 'in': self._board.set_pin_mode(pin, self._board.INPUT, self._board.ANALOG) elif mode == 'analog' and direction == 'out': self._board.set_pin_mode(pin, self._board.OUTPUT, self._board.ANALOG) elif mode == 'digital' and direction == 'in': self._board.set_pin_mode(pin, self._board.OUTPUT, self._board.DIGITAL) elif mode == 'digital' and direction == 'out': self._board.set_pin_mode(pin, self._board.OUTPUT, self._board.DIGITAL) elif mode == 'pwm': self._board.set_pin_mode(pin, self._board.OUTPUT, self._board.PWM) def get_analog_inputs(self): """ Get the values from the pins. """ self._board.capability_query() return self._board.get_analog_response_table() def set_digital_out_high(self, pin): """ Sets a given digital pin to high. """ self._board.digital_write(pin, 1) def set_digital_out_low(self, pin): """ Sets a given digital pin to low. """ self._board.digital_write(pin, 0) def get_digital_in(self, pin): """ Gets the value from a given digital pin. """ self._board.digital_read(pin) def get_analog_in(self, pin): """ Gets the value from a given analog pin. """ self._board.analog_read(pin) def get_firmata(self): """ Return the version of the Firmata firmware. """ return self._board.get_firmata_version() def disconnect(self): """ Disconnects the board and closes the serial connection. """ self._board.reset() self._board.close()
class ArduinoBoard(object): """ Represents an Arduino board. """ def __init__(self, port): self._port = port self._board = PyMata(self._port, verbose=False) def set_mode(self, pin, direction, mode): """ Sets the mode and the direction of a given pin. """ if mode == 'analog' and direction == 'in': self._board.set_pin_mode(pin, self._board.INPUT, self._board.ANALOG) elif mode == 'analog' and direction == 'out': self._board.set_pin_mode(pin, self._board.OUTPUT, self._board.ANALOG) elif mode == 'digital' and direction == 'in': self._board.set_pin_mode(pin, self._board.OUTPUT, self._board.DIGITAL) elif mode == 'digital' and direction == 'out': self._board.set_pin_mode(pin, self._board.OUTPUT, self._board.DIGITAL) elif mode == 'pwm': self._board.set_pin_mode(pin, self._board.OUTPUT, self._board.PWM) def get_analog_inputs(self): """ Get the values from the pins. """ self._board.capability_query() return self._board.get_analog_response_table() def set_digital_out_high(self, pin): """ Sets a given digital pin to high. """ self._board.digital_write(pin, 1) def set_digital_out_low(self, pin): """ Sets a given digital pin to low. """ self._board.digital_write(pin, 0) def get_digital_in(self, pin): """ Gets the value from a given digital pin. """ self._board.digital_read(pin) def get_analog_in(self, pin): """ Gets the value from a given analog pin. """ self._board.analog_read(pin) def get_firmata(self): """ Return the version of the Firmata firmware. """ return self._board.get_firmata_version() def disconnect(self): """ Disconnects the board and closes the serial connection. """ self._board.reset() self._board.close()
def s2a_fm(): """ This is the "main" function of the program. It will instantiate PyMata for communication with an Arduino micro-controller and the command handlers class. It will the start the HTTP server to communicate with Scratch 2.0 @return : This is the main loop and should never return """ # total number of pins on arduino board total_pins_discovered = 0 # number of pins that are analog number_of_analog_pins_discovered = 0 # make sure we have a log directory and if not, create it. if not os.path.exists('log'): os.makedirs('log') # turn on logging logging.basicConfig(filename='./log/s2a_fm_debugging.log', filemode='w', level=logging.DEBUG) logging.info('s2a_fm version 1.5 Copyright(C) 2013-14 Alan Yorinks All Rights Reserved ') print 's2a_fm version 1.5 Copyright(C) 2013-14 Alan Yorinks All Rights Reserved ' # get the com_port from the command line or default if none given # if user specified the com port on the command line, use that when invoking PyMata, # else use '/dev/ttyACM0' if len(sys.argv) == 2: com_port = str(sys.argv[1]) else: com_port = '/dev/ttyACM0' logging.info('com port = %s' % com_port) try: # instantiate PyMata firmata = PyMata(com_port) # pragma: no cover except Exception: print 'Could not instantiate PyMata - is your Arduino plugged in?' logging.exception('Could not instantiate PyMata - is your Arduino plugged in?') logging.debug("Exiting s2a_fm") return # determine the total number of pins and the number of analog pins for the Arduino # get the arduino analog pin map # it will contain an entry for all the pins with non-analog set to firmata.IGNORE firmata.analog_mapping_query() capability_map = firmata.get_analog_mapping_request_results() firmata.capability_query() print "Please wait for Total Arduino Pin Discovery to complete. This can take up to 30 additional seconds." # count the pins for pin in capability_map: total_pins_discovered += 1 # non analog pins will be marked as IGNORE if pin != firmata.IGNORE: number_of_analog_pins_discovered += 1 # log the number of pins found logging.info('%d Total Pins and %d Analog Pins Found' % (total_pins_discovered, number_of_analog_pins_discovered)) # instantiate the command handler scratch_command_handler = ScratchCommandHandlers(firmata, com_port, total_pins_discovered, number_of_analog_pins_discovered) # wait for a maximum of 30 seconds to retrieve the Arduino capability query start_time = time.time() pin_capability = firmata.get_capability_query_results() while not pin_capability: if time.time() - start_time > 30: print '' print "Could not determine pin capability - exiting." firmata.close() # keep sending out a capability query until there is a response pin_capability = firmata.get_capability_query_results() time.sleep(.1) # we've got the capability, now build a dictionary with pin as the key and a list of all the capabilities # for the pin as the key's value pin_list = [] total_pins_discovered = 0 for entry in pin_capability: # bump up pin counter each time IGNORE is found if entry == firmata.IGNORE: scratch_command_handler.pin_map[total_pins_discovered] = pin_list total_pins_discovered += 1 pin_list = [] else: pin_list.append(entry) print "Arduino Total Pin Discovery completed in %d seconds" % (int(time.time() - start_time)) try: # start the server passing it the handle to PyMata and the command handler. scratch_http_server.start_server(firmata, scratch_command_handler) except Exception: logging.debug('Exception in s2a_fm.py %s' % str(Exception)) firmata.close() return except KeyboardInterrupt: # give control back to the shell that started us logging.info('s2a_fm.py: keyboard interrupt exception') firmata.close() return
def s2a_fm(): """ This is the "main" function of the program. It will instantiate PyMata for communication with an Arduino micro-controller and the command handlers class. It will the start the HTTP server to communicate with Scratch 2.0 @return : This is the main loop and should never return """ # total number of pins on arduino board total_pins_discovered = 0 # number of pins that are analog number_of_analog_pins_discovered = 0 # make sure we have a log directory and if not, create it. if not os.path.exists('log'): os.makedirs('log') # turn on logging logging.basicConfig(filename='./log/s2a_fm_debugging.log', filemode='w', level=logging.DEBUG) logging.info( 's2a_fm version 1.5 Copyright(C) 2013-14 Alan Yorinks All Rights Reserved ' ) print 's2a est la version entierement en francais de s2a_fm, une sorte de s2a_fr v1.7' print 's2a_fm version 1.5 Copyright(C) 2013-14 Alan Yorinks Tous droits reserves ' # print 'Traductions francaises : Sebastien Canet' # get the com_port from the command line or default if none given # if user specified the com port on the command line, use that when invoking PyMata, # else use '/dev/ttyACM0' if len(sys.argv) == 2: com_port = str(sys.argv[1]) else: com_port = '/dev/ttyACM0' logging.info('com port = %s' % com_port) try: # instantiate PyMata firmata = PyMata(com_port) # pragma: no cover except Exception: print 'Impossible de communiquer avec PyMata - votre carte Arduino est bien connectee ??' logging.exception( 'Could not instantiate PyMata - is your Arduino plugged in?') logging.debug("Exiting s2a_fm") return # determine the total number of pins and the number of analog pins for the Arduino # get the arduino analog pin map # it will contain an entry for all the pins with non-analog set to firmata.IGNORE firmata.analog_mapping_query() capability_map = firmata.get_analog_mapping_request_results() firmata.capability_query() print "Merci de patienter pendant la detection du nombre de pins de votre Arduino. Cela peut prendre pres de 30s de plus." # count the pins for pin in capability_map: total_pins_discovered += 1 # non analog pins will be marked as IGNORE if pin != firmata.IGNORE: number_of_analog_pins_discovered += 1 # log the number of pins found logging.info('%d Total Pins and %d Analog Pins Found' % (total_pins_discovered, number_of_analog_pins_discovered)) # instantiate the command handler scratch_command_handler = ScratchCommandHandlers( firmata, com_port, total_pins_discovered, number_of_analog_pins_discovered) # wait for a maximum of 30 seconds to retrieve the Arduino capability query start_time = time.time() pin_capability = firmata.get_capability_query_results() while not pin_capability: if time.time() - start_time > 30: print '' print "Impossible de determiner le nombre de pins - sortie du script." firmata.close() # keep sending out a capability query until there is a response pin_capability = firmata.get_capability_query_results() time.sleep(.1) # we've got the capability, now build a dictionary with pin as the key and a list of all the capabilities # for the pin as the key's value pin_list = [] total_pins_discovered = 0 for entry in pin_capability: # bump up pin counter each time IGNORE is found if entry == firmata.IGNORE: scratch_command_handler.pin_map[total_pins_discovered] = pin_list total_pins_discovered += 1 pin_list = [] else: pin_list.append(entry) print "Detection des pins de la carte Arduino faite en %d secondes" % ( int(time.time() - start_time)) try: # lance un script pour automatiser l'ouverture de Scratch pendant que le serveur se met en route # il est separe pour permettre aux utilisateurs de le modifier en direct, dans le batch, ca simplifie # os.startfile('Scratch2.bat') # start the server passing it the handle to PyMata and the command handler. scratch_http_server.start_server(firmata, scratch_command_handler) except Exception: logging.debug('Erreur dans s2a_fm.py %s' % str(Exception)) firmata.close() return except KeyboardInterrupt: # give control back to the shell that started us logging.info('s2a_fm.py: keyboard interrupt exception') firmata.close() return
def signal_handler(sig, frame): print('You pressed Ctrl+C') if board is not None: board.reset() sys.exit(0) signal.signal(signal.SIGINT, signal_handler) # Create a PyMata instance board = PyMata("/dev/ttyACM0") # Set the pin mode board.servo_config(5) board.set_pin_mode(12, board.OUTPUT, board.DIGITAL) board.set_pin_mode(0, board.INPUT, board.ANALOG) # Send query request to Arduino board.capability_query() # Some boards take a long time to respond - adjust as needed time.sleep(5) print("Pin Capability Report") print(board.get_capability_query_results()) print("PyMata Digital Response Table") print(board.get_digital_response_table()) print("PyMata Analog Response Table") print(board.get_analog_response_table())
class ArduinoFirmata(Board, AnalogInputCapable, PwmOutputCapable): def __init__(self, port=None): try: from PyMata.pymata import PyMata as PyMata # noqa except ImportError: msg = 'pingo.arduino.Arduino requires PyMata installed' raise ImportError(msg) super(ArduinoFirmata, self).__init__() self.port = port self.firmata_client = PyMata(self.port, verbose=VERBOSE) self.firmata_client.capability_query() time.sleep(10) # TODO: Find a small and safe value capability_query_results = self.firmata_client.get_capability_query_results() capability_dict = pin_list_to_board_dict(capability_query_results) self._add_pins( [DigitalPin(self, location) for location in capability_dict['digital']] + [PwmPin(self, location) for location in capability_dict['pwm']] + [AnalogPin(self, 'A%s' % location, resolution=10) for location in capability_dict['analog']] ) def cleanup(self): # self.firmata_client.close() has sys.exit(0) if hasattr(self, 'PyMata'): try: self.firmata_client.transport.close() except AttributeError: pass def __repr__(self): cls_name = self.__class__.__name__ return '<{cls_name} {self.port!r}>'.format(**locals()) def _set_digital_mode(self, pin, mode): self.firmata_client.set_pin_mode( pin.location, PIN_MODES[mode], self.firmata_client.DIGITAL ) def _set_analog_mode(self, pin, mode): pin_id = int(pin.location[1:]) self.firmata_client.set_pin_mode( pin_id, self.firmata_client.INPUT, self.firmata_client.ANALOG ) def _set_pwm_mode(self, pin, mode): pin_id = int(pin.location) self.firmata_client.set_pin_mode( pin_id, self.firmata_client.PWM, self.firmata_client.DIGITAL ) def _get_pin_state(self, pin): _state = self.firmata_client.digital_read(pin.location) if _state == self.firmata_client.HIGH: return pingo.HIGH return pingo.LOW def _set_pin_state(self, pin, state): self.firmata_client.digital_write( pin.location, PIN_STATES[state] ) def _get_pin_value(self, pin): pin_id = int(pin.location[1:]) return self.firmata_client.analog_read(pin_id) def _set_pwm_duty_cycle(self, pin, value): pin_id = int(pin.location) firmata_value = int(value * 255) return self.firmata_client.analog_write(pin_id, firmata_value) def _set_pwm_frequency(self, pin, value): raise NotImplementedError
def s2a_fm(): """ This is the "main" function of the program. It will instantiate PyMata for communication with an Arduino micro-controller and the command handlers class. It will the start the HTTP server to communicate with Scratch 2.0 @return : This is the main loop and should never return """ global s2a_fm_status # total number of pins on arduino board total_pins_discovered = 0 # number of pins that are analog number_of_analog_pins_discovered = 0 # Ethernet/WiFi autodetect autodetect = 0 print 's2a_fm version 1.5 Copyright(C) 2013-14 Alan Yorinks All Rights Reserved ' # get the com_port from the command line or default if none given # if user specified the com port on the command line, use that when invoking PyMata, # else use '/dev/ttyACM0' projectName = '86Hexapodtest' com_port = '/dev/ttyACM0' ui_server_port = 8386 if len(sys.argv) == 2: if str(sys.argv[1]) == 'autodetect': autodetect = 1 else: com_port = str(sys.argv[1]) elif len(sys.argv) == 3: if str(sys.argv[1]).find('com') == 0: com_port = str(sys.argv[1]) ui_server_port = int(sys.argv[2]) elif str(sys.argv[1]) == 'autodetect': autodetect = 1 ui_server_port = int(sys.argv[2]) else: host_ip = str(sys.argv[1]) host_port = int(sys.argv[2]) elif len(sys.argv) == 4: host_ip = str(sys.argv[1]) host_port = int(sys.argv[2]) ui_server_port = int(sys.argv[3]) try: # instantiate PyMata if autodetect == 1: firmata = PyMata(host_port=2000, ui_server_port=ui_server_port, projectName=projectName, autodetect=autodetect) elif str(sys.argv[1]).find('com') == 0: firmata = PyMata(port_id=com_port, ui_server_port=ui_server_port) # pragma: no cover elif len(sys.argv) == 3 or len(sys.argv) == 4: firmata = PyMata(host_ip=host_ip, host_port=host_port, ui_server_port=ui_server_port) # pragma: no cover except Exception: print 'Could not instantiate PyMata - is your Arduino plugged in?' return firmata.set_s2a_fm_status(5) # determine the total number of pins and the number of analog pins for the Arduino # get the arduino analog pin map # it will contain an entry for all the pins with non-analog set to firmata.IGNORE # firmata.analog_mapping_query() # time.sleep(.1) capability_map = firmata.get_analog_mapping_request_results() firmata.capability_query() print "Please wait for Total Arduino Pin Discovery to complete. This can take up to 30 additional seconds." # count the pins for pin in capability_map: total_pins_discovered += 1 # non analog pins will be marked as IGNORE if pin != firmata.IGNORE: number_of_analog_pins_discovered += 1 # instantiate the command handler scratch_command_handler = ScratchCommandHandlers( firmata, com_port, total_pins_discovered, number_of_analog_pins_discovered) firmata.set_s2a_fm_status(6) # wait for a maximum of 30 seconds to retrieve the Arduino capability query start_time = time.time() pin_capability = firmata.get_capability_query_results() while not pin_capability: firmata.set_s2a_fm_status(7) if time.time() - start_time > 30: firmata.set_s2a_fm_status(99) firmata.set_error_no(4) print '' print "Could not determine pin capability - exiting." firmata.send_error_message() firmata.close(True) return # keep sending out a capability query until there is a response pin_capability = firmata.get_capability_query_results() time.sleep(.1) firmata.set_s2a_fm_status(8) # we've got the capability, now build a dictionary with pin as the key and a list of all the capabilities # for the pin as the key's value pin_list = [] total_pins_discovered = 0 for entry in pin_capability: # bump up pin counter each time IGNORE is found if entry == firmata.IGNORE: scratch_command_handler.pin_map[total_pins_discovered] = pin_list total_pins_discovered += 1 pin_list = [] else: pin_list.append(entry) print "Arduino Total Pin Discovery completed in %d seconds" % ( int(time.time() - start_time)) firmata.set_s2a_fm_status(9) thread.start_new_thread(firmata.send_command_check_active, (firmata, )) try: # start the server passing it the handle to PyMata and the command handler. scratch_http_server.start_server(firmata, scratch_command_handler) except Exception: firmata.set_error_no(5) firmata.send_error_message() firmata.close(True) return except KeyboardInterrupt: # give control back to the shell that started us firmata.set_error_no(99) firmata.close(True) return
class ArduinoFirmata(Board, AnalogInputCapable, PwmOutputCapable): def __init__(self, port=None): try: from PyMata.pymata import PyMata as PyMata # noqa except ImportError: msg = 'pingo.arduino.Arduino requires PyMata installed' raise ImportError(msg) super(ArduinoFirmata, self).__init__() self.port = port self.firmata_client = PyMata(self.port, verbose=VERBOSE) self.firmata_client.capability_query() time.sleep(10) # TODO: Find a small and safe value capability_query_results = self.firmata_client.get_capability_query_results( ) capability_dict = pin_list_to_board_dict(capability_query_results) self._add_pins([ DigitalPin(self, location) for location in capability_dict['digital'] ] + [PwmPin(self, location) for location in capability_dict['pwm']] + [ AnalogPin(self, 'A%s' % location, resolution=10) for location in capability_dict['analog'] ]) def cleanup(self): # self.firmata_client.close() has sys.exit(0) if hasattr(self, 'PyMata'): try: self.firmata_client.transport.close() except AttributeError: pass def __repr__(self): cls_name = self.__class__.__name__ return '<{cls_name} {self.port!r}>'.format(**locals()) def _set_digital_mode(self, pin, mode): self.firmata_client.set_pin_mode(pin.location, PIN_MODES[mode], self.firmata_client.DIGITAL) def _set_analog_mode(self, pin, mode): pin_id = int(pin.location[1:]) self.firmata_client.set_pin_mode(pin_id, self.firmata_client.INPUT, self.firmata_client.ANALOG) def _set_pwm_mode(self, pin, mode): pin_id = int(pin.location) self.firmata_client.set_pin_mode(pin_id, self.firmata_client.PWM, self.firmata_client.DIGITAL) def _get_pin_state(self, pin): _state = self.firmata_client.digital_read(pin.location) if _state == self.firmata_client.HIGH: return pingo.HIGH return pingo.LOW def _set_pin_state(self, pin, state): self.firmata_client.digital_write(pin.location, PIN_STATES[state]) def _get_pin_value(self, pin): pin_id = int(pin.location[1:]) return self.firmata_client.analog_read(pin_id) def _set_pwm_duty_cycle(self, pin, value): pin_id = int(pin.location) firmata_value = int(value * 255) return self.firmata_client.analog_write(pin_id, firmata_value) def _set_pwm_frequency(self, pin, value): raise NotImplementedError
def s2a_fm(): """ This is the "main" function of the program. It will instantiate PyMata for communication with an Arduino micro-controller and the command handlers class. It will the start the HTTP server to communicate with Scratch 2.0 @return : This is the main loop and should never return """ # total number of pins on arduino board total_pins_discovered = 0 # number of pins that are analog number_of_analog_pins_discovered = 0 # make sure we have a log directory and if not, create it. if not os.path.exists('log'): os.makedirs('log') # turn on logging logging.basicConfig(filename='./log/s2a_fm_debugging.log', filemode='w', level=logging.DEBUG) logging.info( 's2a_fm version 1.5 Copyright(C) 2013-14 Alan Yorinks All Rights Reserved ' ) print 's2a_fm version 1.5 Copyright(C) 2013-14 Alan Yorinks All Rights Reserved ' # get the com_port from the command line or default if none given # if user specified the com port on the command line, use that when invoking PyMata, # else use '/dev/ttyACM0' if len(sys.argv) == 2: com_port = str(sys.argv[1]) else: com_port = '/dev/ttyACM0' logging.info('com port = %s' % com_port) try: # instantiate PyMata firmata = PyMata(com_port) # pragma: no cover except Exception: print 'Could not instantiate PyMata - is your Arduino plugged in?' logging.exception( 'Could not instantiate PyMata - is your Arduino plugged in?') logging.debug("Exiting s2a_fm") return # determine the total number of pins and the number of analog pins for the Arduino # get the arduino analog pin map # it will contain an entry for all the pins with non-analog set to firmata.IGNORE firmata.analog_mapping_query() capability_map = firmata.get_analog_mapping_request_results() firmata.capability_query() print "Please wait for Total Arduino Pin Discovery to complete. This can take up to 30 additional seconds." # count the pins for pin in capability_map: total_pins_discovered += 1 # non analog pins will be marked as IGNORE if pin != firmata.IGNORE: number_of_analog_pins_discovered += 1 # log the number of pins found logging.info('%d Total Pins and %d Analog Pins Found' % (total_pins_discovered, number_of_analog_pins_discovered)) # instantiate the command handler scratch_command_handler = ScratchCommandHandlers( firmata, com_port, total_pins_discovered, number_of_analog_pins_discovered) # wait for a maximum of 30 seconds to retrieve the Arduino capability query start_time = time.time() pin_capability = firmata.get_capability_query_results() while not pin_capability: if time.time() - start_time > 30: print '' print "Could not determine pin capability - exiting." firmata.close() # keep sending out a capability query until there is a response pin_capability = firmata.get_capability_query_results() time.sleep(.1) # we've got the capability, now build a dictionary with pin as the key and a list of all the capabilities # for the pin as the key's value pin_list = [] total_pins_discovered = 0 for entry in pin_capability: # bump up pin counter each time IGNORE is found if entry == firmata.IGNORE: scratch_command_handler.pin_map[total_pins_discovered] = pin_list total_pins_discovered += 1 pin_list = [] else: pin_list.append(entry) print "Arduino Total Pin Discovery completed in %d seconds" % ( int(time.time() - start_time)) try: # start the server passing it the handle to PyMata and the command handler. scratch_http_server.start_server(firmata, scratch_command_handler) except Exception: logging.debug('Exception in s2a_fm.py %s' % str(Exception)) firmata.close() return except KeyboardInterrupt: # give control back to the shell that started us logging.info('s2a_fm.py: keyboard interrupt exception') firmata.close() return
class s2a_fm: """ This is the "main" function of the program. It will instantiate PyMata for communication with an Arduino micro-controller and the command handlers class. It will the start the HTTP server to communicate with Scratch 2.0 @return : This is the main loop and should never return """ def __init__(self): subprocess.Popen("scratch2") # total number of pins on arduino board self.total_pins_discovered = 0 # number of pins that are analog self.number_of_analog_pins_discovered = 0 # COM-Port self.com_port = "COM1" #firmata #self.firmata ="- # make sure we have a log directory and if not, create it. if not os.path.exists('log'): os.makedirs('log') # turn on logging logging.basicConfig(filename='./log/s2a_fm_debugging.log', filemode='w', level=logging.DEBUG) logging.info('s2a_fm version 1.5 Copyright(C) 2013-14 Alan Yorinks All Rights Reserved ') print 's2a_fm version 1.5 Copyright(C) 2013-14 Alan Yorinks All Rights Reserved ' # get the com_port from the command line or default if none given # if user specified the com port on the command line, use that when invoking PyMata, # else use '/dev/ttyACM0' def search_port(self): #returns all serial COM-Ports possible_ports = serial_ports() print for com_port in possible_ports: logging.info('com port = %s' % com_port) try: # instantiate PyMata self.firmata = PyMata(com_port) # pragma: no cover self.com_port = com_port return 1 except Exception: print('Could not instantiate PyMata - is your Arduino plugged in?') logging.exception('Could not instantiate PyMata on Port %s' % com_port) return 0 #TODO: Ask if User Wants to flash Arduino on this Port def discover_arduino(self): # determine the total number of pins and the number of analog pins for the Arduino # get the arduino analog pin map # it will contain an entry for all the pins with non-analog set to self.firmata.IGNORE self.firmata.analog_mapping_query() self.capability_map = self.firmata.get_analog_mapping_request_results() self.firmata.capability_query() print("Please wait for Total Arduino Pin Discovery to complete. This can take up to 30 additional seconds.") # count the pins for pin in self.capability_map: self.total_pins_discovered += 1 # non analog pins will be marked as IGNORE if pin != self.firmata.IGNORE: self.number_of_analog_pins_discovered += 1 # log the number of pins found logging.info('%d Total Pins and %d Analog Pins Found' % (self.total_pins_discovered, self.number_of_analog_pins_discovered)) # instantiate the command handler self.scratch_command_handler = ScratchCommandHandlers(self.firmata, self.com_port, self.total_pins_discovered, self.number_of_analog_pins_discovered) # wait for a maximum of 30 seconds to retrieve the Arduino capability query start_time = time.time() pin_capability = self.firmata.get_capability_query_results() while not pin_capability: if time.time() - start_time > 30: print "Could not determine pin capability - exiting." self.firmata.close() # keep sending out a capability query until there is a response pin_capability = self.firmata.get_capability_query_results() time.sleep(.1) # we've got the capability, now build a dictionary with pin as the key and a list of all the capabilities # for the pin as the key's value pin_list = [] total_pins_discovered = 0 for entry in pin_capability: # bump up pin counter each time IGNORE is found if entry == self.firmata.IGNORE: self.scratch_command_handler.pin_map[total_pins_discovered] = pin_list total_pins_discovered += 1 pin_list = [] else: pin_list.append(entry) print "Arduino Total Pin Discovery completed in %d seconds" % (int(time.time() - start_time)) def guess_path(self): os_name = sys.plattform if os_name == "linux2": return "scratch2" elif os_name == "win32" or os_name == "cygwin": #try some if os.path.exists("C:\Program Files (x86)\Scratch 2\Scratch 2.exe"): return "C:\Program Files (x86)\Scratch 2\Scratch 2.exe" elif os_name == "darwin": return "scratch2" return -1 def start_server(self): try: # start the server passing it the handle to PyMata and the command handler. scratch_http_server.start_server(self.firmata, self.scratch_command_handler) except Exception: logging.debug('Exception in s2a_fm.py %s' % str(Exception)) self.firmata.close() return except KeyboardInterrupt: # give control back to the shell that started us logging.info('s2a_fm.py: keyboard interrupt exception') self.firmata.close() return