def main(): from fabtotum.fabui.config import ConfigService dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) # SETTING EXPECTED ARGUMENTS parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("-n", "--name", help="Look for name", default="PRISM") parser.add_argument("-m", "--mac", help="Mac address", default="") parser.add_argument("-v", "--verbose", action="store_true", help="Show verbose") # GET ARGUMENTS args = parser.parse_args() name = args.name mac = args.mac verbose = args.verbose config = ConfigService() # Ensure bluetooth is enabled p = subprocess.Popen(['connmanctl', 'enable', 'bluetooth'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if 'Enabled bluetooth' == out.strip(): # Give bluetoothd some time to bring up the hci device time.sleep(3) if (verbose): print "Bluetooth enabled" adapter = Adapter() if not adapter.Powered: if (verbose): print "Powering up bluetooth..." adapter.Powered = True master_bt_address = adapter.Address devices = adapter.discoverDevices(look_for_name=name, timeout=30, verbose=verbose) paired = False already_paired = False for addr in devices: dev = devices[addr] if (verbose): print addr, dev.Name, dev.Paired, dev.Trusted, dev.Adapter if not dev.Paired: if (verbose): print "Pairing..." dev.Pair() dev.Trusted = True paired = True mac = addr if (verbose): print "Paired" # Store PRISM bt mac address config.set('bluetooth', 'prism_bt_address', str(addr)) config.save('bluetooth') # Make PRISM trust us ;) send_command('trust', [master_bt_address], addr, verbose=verbose) else: paired = True mac = addr already_paired = True send_command('trust', [master_bt_address], addr, verbose=verbose) if (verbose): print "Already paired" response = { 'name': name, 'mac': mac, 'paired': paired, 'already_paired': already_paired } print json.dumps(response)
class BTFactory(): def __init__(self, verbose=False): ## init attr self.verbose = verbose self._adapter = None self.controller_address = None self.config = ConfigService() self.status = None ## init adapater self._init_adapter() ####################### ## INIT BLUETOOTH ADAPTER ####################### def _init_adapter(self): dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) ## get bluetooth status self.status = bluetooth_status() ## enable bluetooth if is necessary if (self.status['powered'] == False): self.enable_bluetooth() self._adapter = Adapter(verbose=self.verbose) ## power adapter if necessary if not self._adapter.Powered: self._adapter.Powered = True self.controller_address = self._adapter.Address ####################### ## ENABLE BLUETOOTH ####################### def enable_bluetooth(self): if (self.verbose): print "Enabling bluetooth" enable_bluetooth() ## give time to bluetooth time.sleep(2) self.status = bluetooth_status() ####################### ## PAIR ####################### def pair(self, mac_address=None, look_for_name="PRISM"): if (self.status['paired'] != False): if (self.status['paired']['mac_address'] == mac_address or self.status['paired']['name'] == look_for_name): if (self.verbose): print "Already paired, skip pairing" return { 'paired': True, 'mac_address': self.status['paired']['mac_address'], 'name': self.status['paired']['name'] } if (self.verbose): print "trying to pair with: {0} [{1}]".format( look_for_name, mac_address) if (self.status['powered'] == False): self.enable_bluetooth() paired = False ## start pairing devices = self._adapter.discoverDevices(look_for_address=mac_address, timeout=60, verbose=self.verbose) for addrees in devices: device = devices[addrees] paired = True # mac_address = addrees if (self.verbose): print addrees, device.Name, device.Paired, device.Trusted, device.Adapter # mac_address = addrees if not device.Paired: if (self.verbose): print "Pairing.." device.Pair() device.Trusted = True if paired: if (self.verbose): print "Paired with {0} [{1}]".format(look_for_name, mac_address) ## save to config file self.config.set('bluetooth', 'prism_bt_address', str(mac_address)) self.config.set('bluetooth', 'prism_bt_name', str(look_for_name)) self.config.save('bluetooth') ### trust us ## give time to bluetooth time.sleep(2) send_command('trust', [self.controller_address], mac_address, verbose=self.verbose) return { 'paired': paired, 'mac_address': mac_address, 'name': look_for_name } ####################### ## UNPAIR ####################### def unpair(self, mac_address): try: self._adapter.RemoveDevice(mac_address) ### tell also device to unpair send_command('disconnect', [self.controller_address], mac_address, verbose=self.verbose) # send_command('unpair', [self.controller_address], mac_address, verbose=self.verbose) ## save to config file self.config.set('bluetooth', 'prism_bt_address', '') self.config.set('bluetooth', 'prism_bt_name', '') self.config.set('bluetooth', 'prism_bt_network_address', '') self.config.save('bluetooth') except Exception as e: pass return True ####################### ## SCAN ####################### def scan(self): if (self.verbose): print "Scan for devices..." return scan('list') ################################### ## AUTO PAIR AND CONNECT TO PRISM ################################### def auto_connection(self, name="PRISM", mac_address=None): if (self.status['paired'] == False): if (mac_address == None or mac_address == ""): devices = self.scan() for device in devices: if (device['name'] == name): mac_address = device['mac'] else: if (mac_address == None or mac_address == ""): mac_address = self.status['paired']['mac_address'] if (self.verbose): print "Autoconnection to {0} [{1}]".format(name, mac_address) pairing_result = self.pair(mac_address=mac_address, look_for_name=name) mac_address = pairing_result['mac_address'] paired = pairing_result['paired'] connection = None if (paired): connection = self.send_command('connect', [], mac_address) return {'connection': connection, 'paired': paired} ################################### ## SEN COMMAND TO PRISM ################################### def send_command(self, command, args=[], mac_address=None, port=0x1001): if (mac_address == None or mac_address == ""): if self.status['paired'] != False: if "mac_address" in self.status['paired']: mac_address = self.status['paired']['mac_address'] else: return {'error': _("No connected device")} socket = bluetooth.BluetoothSocket(bluetooth.L2CAP) socket.settimeout(3) if (self.verbose): print "Trying to connect to {0} on port {1}".format( mac_address, port) try: socket.connect((mac_address, port)) #bluetooth.set_packet_timeout(mac_address, 0) if command in ['connect', 'disconnect', 'trust', 'untrust']: args.append(self._adapter.Address) if command in ['connect', 'rpc']: tether_address = get_ip_address('tether') if (tether_address != 'n.a'): args.append(tether_address) args.append(self.config.get('xmlrpc', 'xmlrpc_port')) data = json.dumps({'cmd': command, 'args': args}) if self.verbose: print "Data sent {0}".format(data) ## send data socket.send(data) # get data reply = socket.recv(1024) # close socket socket.close() if self.verbose: print "Data received:".format(reply) response = json.loads(reply) ## save network address if (command in ['connect', 'network-address']): self.config.set('bluetooth', 'prism_bt_network_address', response['reply']) self.config.save('bluetooth') if (command == 'disconnect'): self.config.set('bluetooth', 'prism_bt_network_address', '') self.config.save('bluetooth') return {'command': command, 'response': response['reply']} except Exception as e: if self.verbose: print "Error: {0}".format(e) return {'error': str(e)}
def hardwareBootstrap(gcs, config = None, logger = None): if not config: config = ConfigService() if logger: log = logger else: log = logging.getLogger('GCodeService') ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter("%(levelname)s : %(message)s") ch.setFormatter(formatter) log.addHandler(ch) config.reload() try: color = config.get('settings', 'color') except KeyError: color = { 'r' : 255, 'g' : 255, 'b' : 255, } try: safety_door = config.get('settings', 'safety.door') except KeyError: safety_door = 0 try: switch = config.get('settings', 'switch') except KeyError: switch = 0 try: collision_warning = config.get('settings', 'safety.collision_warning') except KeyError: collision_warning = 0 try: wire_end = config.get('settings', 'wire_end', 0) except KeyError: wire_end = 0 probe = {} probe['extend'] = config.get('settings', 'probe.e', 127) probe['retract'] = config.get('settings', 'probe.r', 25) ## MANDATORY - AFTER THAT LINE YOU CAN SEND COMMANDS gcs.atomic_begin(group='bootstrap') # read EEPROM eeprom = read_eeprom(gcs) # reset EEPROM (to prevent any mysterious bug) log.info("Reset EEPROM") gcs.send('M502', group='bootstrap') # read Factory settings factory = None if os.path.exists('/mnt/live/mnt/boot/factory/settings/settings.json'): try: with open('/mnt/live/mnt/boot/factory/settings/settings.json') as json_f: factory = json.load(json_f) except: # Continue if the file is not there pass try: hardwareID = eeprom['batch_number'] except Exception as e: log.error("cannot read batch number") hardwareID = str(config.get('settings', 'hardware.id', 1)) log.error("batch number set to {0}".format(hardwareID)) if config.is_firstboot(): log.info("First Boot") if factory: probe['extend'] = factory['probe']['e'] probe['retract'] = factory['probe']['r'] probe['length'] = factory['probe']['length'] hardwareID = factory['hardware']['id'] wire_end = factory['wire_end'] log.info("Factory settings applied") config.set('settings', 'probe.e', probe['extend']) config.set('settings', 'probe.r', probe['retract']) config.set('settings', 'probe.length', probe['length']) config.set('settings', 'hardware.id', hardwareID) config.set('settings', 'wire_end', wire_end) config.save('settings') # Raise probe gcs.send('M402', group='bootstrap') # Send ALIVE gcs.send('M728', group='bootstrap') #enable homing check gcs.send('M733 S1', group='bootstrap') # Set ambient colors gcs.send("M701 S{0}".format(color['r']), group='bootstrap') gcs.send("M702 S{0}".format(color['g']), group='bootstrap') gcs.send("M703 S{0}".format(color['b']), group='bootstrap') # Set safety door open warnings: enabled/disabled gcs.send("M732 S{0}".format(safety_door), group='bootstrap') # Set collision warning: enabled/disabled gcs.send("M734 S{0}".format(collision_warning), group='bootstrap') # Set homing preferences gcs.send("M714 S{0}".format(switch), group='bootstrap') #set wire_end enabled/disabled gcs.send("M805 S{0}".format(wire_end), group='bootstrap') #set probe extend angle gcs.send("M711 S{0}".format(probe['extend']), group='bootstrap') #set probe retract angle gcs.send("M712 S{0}".format(probe['retract']), group='bootstrap') # Execute version specific intructions if config.get('settings', 'settings_type') == 'custom': PRESET_MAP["custom"](gcs, config, log, eeprom, factory) elif hardwareID in PRESET_MAP: PRESET_MAP[hardwareID](gcs, config, log, eeprom, factory) else: log.error("Unsupported hardware version: %s", hardwareID) log.error("Forced to hardware1") PRESET_MAP["1"](gcs, config, log, eeprom, factory) config.reload() configure_head(gcs, config, log) configure_feeder(gcs, config, log) configure_4thaxis(gcs, config, log) gcs.atomic_end()