def main(settings): """ Main function for the communicatior, loops here """ if settings.transport == "websocket": pebble = PebbleConnection(WebsocketTransport(settings.device), log_packet_level=logging.DEBUG) else: # No elif, for compatibility with older configs pebble = PebbleConnection(SerialTransport(settings.device), log_packet_level=logging.DEBUG) pebble.connect() # For some reason it seems to timeout for the first time, with "somebody is eating our input" error, # replying seems to help. for loop in range(5): try: pebble.run_async() break except libpebble2.exceptions.TimeoutError: logging.info("Pebble timeouted, retrying..") continue # Register service for app messages appservice = AppMessageService(pebble) handler = CommandHandler(settings) commwatch = CommunicationKeeper(settings, appservice) appservice.register_handler("nack", commwatch.nack_received) appservice.register_handler("ack", commwatch.ack_received) # Start the watchapp pebble.send_packet(AppRunState(command = 0x01, data=AppRunStateStart(uuid = uuid.UUID(settings.uuid)))) # Send our current config for (id_key, id_type) in get_button_ids(): id_full = id_key[0] + "," + id_type[0] if id_full in settings.key_mappings: status = "T" else: status = "F" data = id_key[0] + id_type[0] + status commwatch.send_message({COMMUNICATION_KEY_CONFIG: CString(data)}) # Wait for all for loop in range(10): if len(commwatch.pending) == 0: break if commwatch.error: raise PebbleConnectionException("Commwatch:" + commwatch.error) time.sleep(0.1) else: raise PebbleConnectionException("Pebble not respoding to config") logging.info("Connection ok, entering to active state..") appservice.register_handler("appmessage", handler.message_received_event) while True: commwatch.send_message({COMMUNICATION_KEY_PING: Uint8(0)}) time.sleep(10)
class PebbleManager(object): def __init__(self, qemu): self.qemu = qemu.split(":") print self.qemu self.pebble = PebbleConnection(QemuTransport(*self.qemu), log_packet_level=logging.DEBUG) self.handle_start = None self.handle_stop = None self.blobdb = None self.launcher = None def connect(self): self.pebble.connect() greenlet = gevent.spawn(self.pebble.run_sync) self.pebble.fetch_watch_info() self.register_endpoints() self.pebble.transport.send_packet(QemuBluetoothConnection(connected=True), target=MessageTargetQemu()) self.blobdb = BlobDBClient(self.pebble) self.request_running_app() logger.info("connected to %s", self.qemu) return greenlet def disconnect(self): if self.launcher is not None: self.launcher.shutdown() def register_endpoints(self): self.pebble.register_endpoint(AppRunState, self.handle_lifecycle) self.launcher = AppMessageService(self.pebble, message_type=LegacyAppLaunchMessage) self.launcher.register_handler("appmessage", self.handle_launcher) def request_running_app(self): if self.pebble.firmware_version.major >= 3: self.pebble.send_packet(AppRunState(data=AppRunStateRequest())) else: self.launcher.send_message(uuid.UUID(int=0), {LegacyAppLaunchMessage.Keys.StateFetch: Uint8(1)}) def handle_lifecycle(self, packet): if isinstance(packet.data, AppRunStateStart): if callable(self.handle_start): self.handle_start(packet.data.uuid) elif isinstance(packet.data, AppRunStateStop): if callable(self.handle_stop): self.handle_stop(packet.data.uuid) def handle_launcher(self, txid, uuid, message): state = message[LegacyAppLaunchMessage.Keys.RunState] if state == LegacyAppLaunchMessage.States.Running: if callable(self.handle_start): self.handle_start(uuid) elif state == LegacyAppLaunchMessage.States.NotRunning: if callable(self.handle_stop): self.handle_stop(uuid) @property def timeline_is_supported(self): return self.pebble.firmware_version.major >= 3
def meminiSense(startDateTime,hostIP,BASE_PORT,streaming=True,logging=True): global meminifilename #logging.basicConfig(level=logging.INFO) #file_path = "/media/card/memini/" #if file_path is None: # print("DID NOT FIND PEBBLE_DATA_LOC") # #print(os.environ) # exit(1) #if not os.path.exists(file_path): # os.mkdir(file_path) # #filename = str(file_path) + "memini_data.csv" running = True #pebble = PebbleConnection(SerialTransport("/dev/rfcomm0")) #pebble.connect() while True: try: pebble = PebbleConnection(SerialTransport("/dev/rfcomm0")) pebble.connect() #print "connection try 0!" appUUID = APP_UUID[:] while running: try: print "Attempt to Connect" #logging.info("Attempting to connect to pebble") pebble.run_async() print "Connection Success" #logging.info("Pebble connection success") break except libpebble2.exceptions.TimeoutError: print "Pebble timeouted, retrying.." continue #print "Opening file!" #with open(meminifilename,'a') as dataFile: # dataFile.write("message,timestamp,button_id,click_type,battery_charge\n") if pebble.connected: restart_app_on_watch(pebble,appUUID) with open(meminifilename,'a') as dataFile: dataFile.write("message,timestamp,button_id,click_type,battery_charge\n") # Register service for app messages mainMsgService = AppMessageService(pebble) mainCommHandler = CommunicationKeeper(appUUID, mainMsgService) mainMsgService.register_handler("nack", mainCommHandler.nack_received) mainMsgService.register_handler("ack", mainCommHandler.ack_received) mainMsgHandler = AppMsgHandler(appUUID) mainMsgService.register_handler("appmessage", mainMsgHandler.message_received_event) while pebble.connected: # time.sleep(10) memini_main(mainMsgService,mainCommHandler,mainMsgHandler) except SerialException: print("Error: Pebble Disconnected!") time.sleep(30) exit(2)
def _connect_phone(self, phone): parts = phone.split(':') ip = parts[0] if len(parts) == 2: port = int(parts[1]) else: port = 9000 connection = PebbleConnection(WebsocketTransport("ws://{}:{}/".format(ip, port)), **self._get_debug_args()) connection.connect() connection.run_async() return connection
def _connect_emulator(self, platform, sdk): connection = PebbleConnection(ManagedEmulatorTransport(platform, sdk), **self._get_debug_args()) connection.connect() connection.run_async() # Make sure the timezone is set usefully. if connection.firmware_version.major >= 3: ts = time.time() tz_offset = -time.altzone if time.localtime(ts).tm_isdst and time.daylight else -time.altzone tz_offset_minutes = tz_offset // 60 tz_name = "UTC%+d" % (tz_offset_minutes / 60) connection.send_packet(TimeMessage(message=SetUTC(unix_time=ts, utc_offset=tz_offset_minutes, tz_name=tz_name))) return connection
def _connect_emulator(self, platform, sdk): connection = PebbleConnection(ManagedEmulatorTransport(platform, sdk), **self._get_debug_args()) connection.connect() connection.run_async() # Make sure the timezone is set usefully. if connection.firmware_version.major >= 3: ts = time.time() tz_offset = -time.altzone if time.localtime(ts).tm_isdst and time.daylight else -time.timezone tz_offset_minutes = tz_offset // 60 tz_name = "UTC%+d" % (tz_offset_minutes / 60) connection.send_packet(TimeMessage(message=SetUTC(unix_time=ts, utc_offset=tz_offset_minutes, tz_name=tz_name))) return connection
def _connect_qemu(self, qemu): parts = qemu.split(':') ip = parts[0] if not ip: ip = '127.0.0.1' if len(parts) == 2: port = int(parts[1]) else: port = 12344 connection = PebbleConnection(QemuTransport(ip, port), **self._get_debug_args()) connection.connect() connection.run_async() return connection
def main(self, args, app): port = self.device.get('port') fails = 0 while True: try: pebble = PebbleConnection(SerialTransport(port)) pebble.connect() pebble.run_async() return self.perform(pebble, args, app) except TimeoutError: fails += 1 if fails < MAX_FAILS: time.sleep(SLEEP_LENGTH) continue else: raise
class Sinker: def __init__(self): # Set bgthread to a finished thread so we never # have to check if it is None. self.bgthread = threading.Thread() self.bgthread.start() self.pebble = PebbleConnection(SerialTransport("/dev/rfcomm0")) # FIXME: hardcoded self.pebble.connect() self.pebble.run_async() def get_serial(self): if self.bgthread.is_alive(): return self.bgthread = threading.Thread(target=get_serial_function) self.bgthread.start()
def _connect(self, args): self._set_debugging(args.v) for handler_impl in self.valid_connection_handlers(): if handler_impl.is_selected(args): break else: # No selected transport, fallback to a running emulator if available if PebbleTransportEmulator.get_running_emulators(): handler_impl = PebbleTransportEmulator else: raise ToolError("No pebble connection specified.") transport = handler_impl.get_transport(args) connection = PebbleConnection(transport, **self._get_debug_args()) connection.connect() connection.run_async() handler_impl.post_connect(connection) return connection
def main(settings): """ Main function for the communicator, loops here """ if settings.transport == "websocket": pebble = PebbleConnection(WebsocketTransport(settings.device), log_packet_level=logging.DEBUG) else: # No elif, for compatibility with older configs pebble = PebbleConnection(SerialTransport(settings.device), log_packet_level=logging.DEBUG) pebble.connect() if (pebble.connected): print("Pebble successfully connected.") try: pebble.run_async() except libpebble2.exceptions.TimeoutError: print("Pebble timeouted") logging.info("Pebble timeouted") # Install app AppInstaller(pebble, "../hotpebble.pbw").install() # Register service for app messages appservice = AppMessageService(pebble) handler = CommandHandler(settings) commwatch = CommunicationKeeper(settings, appservice) appservice.register_handler("nack", commwatch.nack_received) appservice.register_handler("ack", commwatch.ack_received) # Start the watchapp pebble.send_packet( AppRunState(command=0x01, data=AppRunStateStart(uuid=uuid.UUID(settings.uuid)))) logging.info("Connection ok, entering to active state...") appservice.register_handler("appmessage", handler.message_received_event) while True: commwatch.send_message({COMMUNICATION_KEY_PING: Uint8(0)}) time.sleep(10)
def main(self, args, app): params = self.get_params(args) port = self.device.get('port') fails = 0 while True: try: pebble = PebbleConnection(SerialTransport(port)) pebble.connect() pebble.run_async() Notifications(pebble).send_notification(params['subject'], params['message']) return { 'subject': params['subject'], 'message': params['message'], 'received': True, } except TimeoutError: fails += 1 if fails < MAX_FAILS: time.sleep(SLEEP_LENGTH) continue else: raise
def main(self, args, app): params = self.get_params(args) port = self.device.get('port') fails = 0 while True: try: pebble = PebbleConnection(SerialTransport(port)) pebble.connect() pebble.run_async() Notifications(pebble).send_notification( params['subject'], params['message']) return { 'subject': params['subject'], 'message': params['message'], 'received': True, } except TimeoutError: fails += 1 if fails < MAX_FAILS: time.sleep(SLEEP_LENGTH) continue else: raise
def meminiSense(startDateTime,hostIP,BASE_PORT,streaming=True,logging=True): global meminifilename global agiType global agiIndx global agiStatus global server_address server_address = (hostIP, BASE_PORT) startTimeDT = rNTPTime.stripDateTime(startDateTime) #logging.basicConfig(level=logging.INFO) #file_path = "/media/card/memini/" #if file_path is None: # print("DID NOT FIND PEBBLE_DATA_LOC") # #print(os.environ) # exit(1) #if not os.path.exists(file_path): # os.mkdir(file_path) # #filename = str(file_path) + "memini_data.csv" running = True #pebble = PebbleConnection(SerialTransport("/dev/rfcomm0")) #pebble.connect() while True: try: pebble = PebbleConnection(SerialTransport("/dev/rfcomm0")) pebble.connect() pebble.pump_reader() #print "connection try 0!" appUUID = APP_UUID[:] print "initializing Pebble connection.." # print pebble.send_and_read(AppRunState(data=AppRunStateRequest()), AppRunState).data.uuid while running: try: print "Attempt to Connect" #logging.info("Attempting to connect to pebble") pebble.run_async() print "Connection Success" #logging.info("Pebble connection success") break except libpebble2.exceptions.TimeoutError: print "Pebble timeouted, retrying.." continue while pebble.connected: try: print "Pebble Connected.." restart_app_on_watch(pebble,appUUID) with open(meminifilename,'a') as dataFile: dataFile.write("message,timestamp,button_id,click_type,battery_charge\n") # Register service for app messages print "initializing Services..." mainMsgService = AppMessageService(pebble) mainCommHandler = CommunicationKeeper(appUUID, mainMsgService) mainMsgService.register_handler("nack", mainCommHandler.nack_received) mainMsgService.register_handler("ack", mainCommHandler.ack_received) mainMsgHandler = AppMsgHandler(appUUID) mainMsgService.register_handler("appmessage", mainMsgHandler.message_received_event) break except Exception as err: print err print "Error Initializing Services, retrying.." pebble.run_async() continue while pebble.connected: # time.sleep(10) is_app_on(pebble,appUUID) pebbleMessage = [] pebbleMessage.append("checkNoti") #check for notiFlag from basestation pebbleMessage.append(str(BASE_PORT)) temp = rNTPTime.checkNoti(hostIP, pebbleMessage, 5) # if True: #for testing if int(rNTPTime.notiFlag) == 1: memini_main(mainMsgService,mainCommHandler,mainMsgHandler) # print("sending Message") else: #print "NO NOTIFICATION" time.sleep(NOTI_CHECK_DELAY) except SerialException: print("Pebble Disconnected!") time.sleep(30) continue except Exception as err: print err pass
def _connect_serial(self, device): connection = PebbleConnection(SerialTransport(device), **self._get_debug_args()) connection.connect() connection.run_async() return connection
def _connect_cloudpebble(self): connection = PebbleConnection(CloudPebbleTransport(), **self._get_debug_args()) connection.connect() connection.run_async() return connection
START_PRESS = 7 # Pebble app properties pebble_app_uuid = uuid.UUID("7f1e9122-6a6b-4b58-8e1a-484d5c51e861") # Instantiate game objects and game variables flying_toaster = game_objects.Ship(init_position,ship_speed,init_direction,init_rate,ship_x_dim,ship_y_dim) the_canyon = game_objects.Map(map_file,num_cells,map_dimensions) the_lulz = lulzbot_interface.Lulzbot(lulz_x,lulz_y,lulz_z,offset,flight_feedrate,fast_feedrate) game_time = 0.0 collision_status = 0 # Establish connection with Pebble app pebble = PebbleConnection(SerialTransport(parser.parse_args().serial)) pebble.connect() pebble.run_async() print "Connection established to:", parser.parse_args().serial # Bind handlers to specific AppMessages def handler(self, uuid, data): if data[PebbleKeys.BUTTON_PRESS_KEY.value] == PebbleKeys.LEFT_PRESS.value: print PebbleKeys.LEFT_PRESS.name flying_toaster.turn(1.0) if data[PebbleKeys.BUTTON_PRESS_KEY.value] == PebbleKeys.RIGHT_PRESS.value: print PebbleKeys.RIGHT_PRESS.name flying_toaster.turn(-1.0) if data[PebbleKeys.BUTTON_PRESS_KEY.value] == PebbleKeys.RESET_PRESS.value: print PebbleKeys.RESET_PRESS.name
type=argparse.FileType("rb")) parser.add_argument("--resources", metavar="FILE", help="System resources pack", required=True, type=argparse.FileType("rb")) group = parser.add_mutually_exclusive_group(required=True) group.add_argument("--serial", metavar="DEVICE", dest="transport", type=SerialTransport) args = parser.parse_args() pebble = PebbleConnection(args.transport) pebble.connect() pebble.run_async() pebble.send_and_read( SystemMessage(message_type=SystemMessage.Type.FirmwareUpdateStart), SystemMessage) PutBytes(pebble, PutBytesType.Firmware, args.firmware.read(), bank=0).send() PutBytes(pebble, PutBytesType.SystemResources, args.resources.read(), bank=0).send() pebble.send_packet( SystemMessage(message_type=SystemMessage.Type.FirmwareUpdateComplete))
class PebbleManager(object): def __init__(self, qemu): self.qemu = qemu.split(':') print self.qemu self.pebble = PebbleConnection(QemuTransport(*self.qemu), log_packet_level=logging.DEBUG) self.handle_start = None self.handle_stop = None self.blobdb = None self.launcher = None def connect(self): self.pebble.connect() greenlet = gevent.spawn(self.pebble.run_sync) self.pebble.fetch_watch_info() self.register_endpoints() self.pebble.transport.send_packet( QemuBluetoothConnection(connected=True), target=MessageTargetQemu()) self.blobdb = BlobDBClient(self.pebble) self.request_running_app() logger.info('connected to %s', self.qemu) return greenlet def disconnect(self): if self.launcher is not None: self.launcher.shutdown() def register_endpoints(self): self.pebble.register_endpoint(AppRunState, self.handle_lifecycle) self.launcher = AppMessageService(self.pebble, message_type=LegacyAppLaunchMessage) self.launcher.register_handler("appmessage", self.handle_launcher) def request_running_app(self): if self.pebble.firmware_version.major >= 3: self.pebble.send_packet(AppRunState(data=AppRunStateRequest())) else: self.launcher.send_message( uuid.UUID(int=0), {LegacyAppLaunchMessage.Keys.StateFetch: Uint8(1)}) def handle_lifecycle(self, packet): if isinstance(packet.data, AppRunStateStart): if callable(self.handle_start): self.handle_start(packet.data.uuid) elif isinstance(packet.data, AppRunStateStop): if callable(self.handle_stop): self.handle_stop(packet.data.uuid) def handle_launcher(self, txid, uuid, message): state = message[LegacyAppLaunchMessage.Keys.RunState] if state == LegacyAppLaunchMessage.States.Running: if callable(self.handle_start): self.handle_start(uuid) elif state == LegacyAppLaunchMessage.States.NotRunning: if callable(self.handle_stop): self.handle_stop(uuid) @property def timeline_is_supported(self): return self.pebble.firmware_version.major >= 3