From 57589e0b43809c16290dd4dbda882799e0f9a77a Mon Sep 17 00:00:00 2001 From: Gulsah Kose Date: Sat, 17 Jan 2015 16:37:41 +0200 Subject: Directory structure was changed --- pebble/MANIFEST.in | 16 + pebble/libpebble/LICENSE | 7 + pebble/libpebble/LightBluePebble.py | 176 +++++++ pebble/libpebble/MANIFEST.in | 16 - pebble/libpebble/__init__.py | 6 + pebble/libpebble/p.py | 150 ++++++ pebble/libpebble/pebble.py | 539 +++++++++++++++++++++ pebble/libpebble/pebble/LICENSE | 7 - pebble/libpebble/pebble/LightBluePebble.py | 176 ------- pebble/libpebble/pebble/__init__.py | 6 - pebble/libpebble/pebble/data/LICENCE | 159 ------ .../data/i18n/ca/LC_MESSAGES/pebble-remote.mo | Bin 813 -> 0 bytes .../data/i18n/es/LC_MESSAGES/pebble-remote.mo | Bin 784 -> 0 bytes .../data/i18n/it/LC_MESSAGES/pebble-remote.mo | Bin 858 -> 0 bytes .../data/i18n/tr/LC_MESSAGES/pebble-remote.mo | Bin 754 -> 0 bytes .../libpebble/pebble/data/man/pebble-remote.1.gz | Bin 572 -> 0 bytes .../libpebble/pebble/data/mimetype/pebble-remote | 5 - .../pebble/data/mimetype/pebble-remote.desktop | 33 -- .../pebble/data/mimetype/pebble-remote.png | Bin 1316 -> 0 bytes pebble/libpebble/pebble/data/scripts/exit_click.sh | 3 - pebble/libpebble/pebble/data/scripts/pebble-remote | 25 - pebble/libpebble/pebble/i18n.py | 43 -- pebble/libpebble/pebble/p.py | 151 ------ pebble/libpebble/pebble/pebble.py | 539 --------------------- pebble/libpebble/pebble/stm32_crc.py | 37 -- pebble/libpebble/setup.py | 34 -- pebble/libpebble/stm32_crc.py | 37 ++ pebble/pebble_remote/LICENCE | 159 ++++++ pebble/pebble_remote/__init__.py | 1 + .../data/i18n/ca/LC_MESSAGES/pebble-remote.mo | Bin 0 -> 813 bytes .../data/i18n/es/LC_MESSAGES/pebble-remote.mo | Bin 0 -> 784 bytes .../data/i18n/it/LC_MESSAGES/pebble-remote.mo | Bin 0 -> 858 bytes .../data/i18n/tr/LC_MESSAGES/pebble-remote.mo | Bin 0 -> 754 bytes pebble/pebble_remote/data/man/pebble-remote.1.gz | Bin 0 -> 572 bytes pebble/pebble_remote/data/mimetype/pebble-remote | 5 + .../data/mimetype/pebble-remote.desktop | 33 ++ .../pebble_remote/data/mimetype/pebble-remote.png | Bin 0 -> 1316 bytes pebble/pebble_remote/data/scripts/exit_click.sh | 3 + pebble/pebble_remote/data/scripts/pebble-remote | 25 + pebble/pebble_remote/i18n.py | 43 ++ pebble/setup.py | 34 ++ 41 files changed, 1234 insertions(+), 1234 deletions(-) create mode 100644 pebble/MANIFEST.in create mode 100644 pebble/libpebble/LICENSE create mode 100644 pebble/libpebble/LightBluePebble.py delete mode 100644 pebble/libpebble/MANIFEST.in create mode 100644 pebble/libpebble/__init__.py create mode 100755 pebble/libpebble/p.py create mode 100755 pebble/libpebble/pebble.py delete mode 100644 pebble/libpebble/pebble/LICENSE delete mode 100644 pebble/libpebble/pebble/LightBluePebble.py delete mode 100644 pebble/libpebble/pebble/__init__.py delete mode 100644 pebble/libpebble/pebble/data/LICENCE delete mode 100644 pebble/libpebble/pebble/data/i18n/ca/LC_MESSAGES/pebble-remote.mo delete mode 100644 pebble/libpebble/pebble/data/i18n/es/LC_MESSAGES/pebble-remote.mo delete mode 100644 pebble/libpebble/pebble/data/i18n/it/LC_MESSAGES/pebble-remote.mo delete mode 100644 pebble/libpebble/pebble/data/i18n/tr/LC_MESSAGES/pebble-remote.mo delete mode 100644 pebble/libpebble/pebble/data/man/pebble-remote.1.gz delete mode 100644 pebble/libpebble/pebble/data/mimetype/pebble-remote delete mode 100644 pebble/libpebble/pebble/data/mimetype/pebble-remote.desktop delete mode 100644 pebble/libpebble/pebble/data/mimetype/pebble-remote.png delete mode 100755 pebble/libpebble/pebble/data/scripts/exit_click.sh delete mode 100755 pebble/libpebble/pebble/data/scripts/pebble-remote delete mode 100644 pebble/libpebble/pebble/i18n.py delete mode 100755 pebble/libpebble/pebble/p.py delete mode 100755 pebble/libpebble/pebble/pebble.py delete mode 100644 pebble/libpebble/pebble/stm32_crc.py delete mode 100644 pebble/libpebble/setup.py create mode 100644 pebble/libpebble/stm32_crc.py create mode 100644 pebble/pebble_remote/LICENCE create mode 100644 pebble/pebble_remote/__init__.py create mode 100644 pebble/pebble_remote/data/i18n/ca/LC_MESSAGES/pebble-remote.mo create mode 100644 pebble/pebble_remote/data/i18n/es/LC_MESSAGES/pebble-remote.mo create mode 100644 pebble/pebble_remote/data/i18n/it/LC_MESSAGES/pebble-remote.mo create mode 100644 pebble/pebble_remote/data/i18n/tr/LC_MESSAGES/pebble-remote.mo create mode 100644 pebble/pebble_remote/data/man/pebble-remote.1.gz create mode 100644 pebble/pebble_remote/data/mimetype/pebble-remote create mode 100644 pebble/pebble_remote/data/mimetype/pebble-remote.desktop create mode 100644 pebble/pebble_remote/data/mimetype/pebble-remote.png create mode 100755 pebble/pebble_remote/data/scripts/exit_click.sh create mode 100755 pebble/pebble_remote/data/scripts/pebble-remote create mode 100644 pebble/pebble_remote/i18n.py create mode 100644 pebble/setup.py diff --git a/pebble/MANIFEST.in b/pebble/MANIFEST.in new file mode 100644 index 0000000..498b433 --- /dev/null +++ b/pebble/MANIFEST.in @@ -0,0 +1,16 @@ +#Language Files + +include pebble_remote/data/i18n/ca/LC_MESSAGES/pebble-remote.mo +include pebble_remote/data/i18n/tr/LC_MESSAGES/pebble-remote.mo +include pebble_remote/data/i18n/es/LC_MESSAGES/pebble-remote.mo +include pebble_remote/data/i18n/it/LC_MESSAGES/pebble-remote.mo + +#Manual page + +include pebble_remote/data/man/pebble-remote.1.gz + +#Mimetype files + +include pebble_remote/data/mimetype/pebble-remote +include pebble_remote/data/mimetype/pebble-remote.desktop +include pebble_remote/data/mimetype/pebble-remote.png diff --git a/pebble/libpebble/LICENSE b/pebble/libpebble/LICENSE new file mode 100644 index 0000000..7fc0b12 --- /dev/null +++ b/pebble/libpebble/LICENSE @@ -0,0 +1,7 @@ +Copyright (C) 2013 Liam McLoughlin + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/pebble/libpebble/LightBluePebble.py b/pebble/libpebble/LightBluePebble.py new file mode 100644 index 0000000..db743f5 --- /dev/null +++ b/pebble/libpebble/LightBluePebble.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python +import logging +import multiprocessing +import os +import Queue +import re +import socket +from multiprocessing import Process +from struct import unpack + +log = logging.getLogger() +logging.basicConfig(format='[%(levelname)-8s] %(message)s') +log.setLevel(logging.DEBUG) + +class LightBluePebbleError(Exception): + def __init__(self, id, message): + self._id = id + self._message = message + + def __str__(self): + return "%s ID:(%s) on LightBlue API" % (self._message, self._id) + +class LightBluePebble(object): + """ a wrapper for LightBlue that provides Serial-style read, write and close""" + + def __init__(self, id, should_pair, debug_protocol=False, connection_process_timeout=5): + + self.mac_address = id + self.debug_protocol = debug_protocol + self.should_pair = should_pair + + manager = multiprocessing.Manager() + self.send_queue = manager.Queue() + self.rec_queue = manager.Queue() + + self.bt_teardown = multiprocessing.Event() + self.bt_message_sent = multiprocessing.Event() + self.bt_connected = multiprocessing.Event() + + self.bt_socket_proc = Process(target=self.run) + self.bt_socket_proc.daemon = True + self.bt_socket_proc.start() + + # wait for a successful connection from child process before returning to main process + self.bt_connected.wait(connection_process_timeout) + if not self.bt_connected.is_set(): + raise LightBluePebbleError(id, "Connection timed out, LightBlueProcess was provided %d seconds to complete connecting" % connection_process_timeout) + + def write(self, message): + """ send a message to the LightBlue processs""" + try: + self.send_queue.put(message) + self.bt_message_sent.wait() + except: + self.bt_teardown.set() + if self.debug_protocol: + log.debug("LightBlue process has shutdown (queue write)") + + def read(self): + """ read a pebble message from the LightBlue processs""" + try: + return self.rec_queue.get() + except Queue.Empty: + return (None, None, '') + except: + self.bt_teardown.set() + if self.debug_protocol: + log.debug("LightBlue process has shutdown (queue read)") + return (None, None, '') + + def close(self): + """ close the LightBlue connection process""" + self.bt_teardown.set() + + def is_alive(self): + return self.bt_socket_proc.is_alive() + + def run(self): + """ create bluetooth process paired to mac_address, must be run as a process""" + from lightblue import pair, socket as lb_socket, finddevices, selectdevice + + def autodetect(self): + list_of_pebbles = list() + + if self.mac_address is not None and len(self.mac_address) is 4: + # we have the friendly name, let's get the full mac address + log.warn("Going to get full address for device %s, ensure device is broadcasting." % self.mac_address) + # scan for active devices + devices = finddevices(timeout=8) + + for device in devices: + if re.search(r'Pebble ' + self.mac_address, device[1], re.IGNORECASE): + log.debug("Found Pebble: %s @ %s" % (device[1], device[0])) + list_of_pebbles.append(device) + + if len(list_of_pebbles) is 1: + return list_of_pebbles[0][0] + else: + raise LightBluePebbleError(self.mac_address, "Failed to find Pebble") + else: + # no pebble id was provided... give them the GUI selector + try: + return selectdevice()[0] + except TypeError: + log.warn("failed to select a device in GUI selector") + self.mac_address = None + + # notify that the process has started + log.debug("LightBlue process has started on pid %d" % os.getpid()) + + # do we need to autodetect? + if self.mac_address is None or len(self.mac_address) is 4: + self.mac_address = autodetect(self) + + # create the bluetooth socket from the mac address + if self.should_pair and self.mac_address is not None: + pair(self.mac_address) + try: + self._bts = lb_socket() + self._bts.connect((self.mac_address, 1)) # pebble uses RFCOMM port 1 + self._bts.setblocking(False) + except: + raise LightBluePebbleError(self.mac_address, "Failed to connect to Pebble") + + # give them the mac address for using in faster connections + log.debug("Connection established to " + self.mac_address) + + # Tell our parent that we have a pebble connected now + self.bt_connected.set() + + send_data = e = None + while not self.bt_teardown.is_set(): + # send anything in the send queue + try: + send_data = self.send_queue.get_nowait() + self._bts.send(send_data) + if self.debug_protocol: + log.debug("LightBlue Send: %r" % send_data) + self.bt_message_sent.set() + except Queue.Empty: + pass + except (IOError, EOFError): + self.bt_teardown.set() + e = "Queue Error while sending data" + + # if anything is received relay it back + rec_data = None + try: + rec_data = self._bts.recv(4) + except (socket.timeout, socket.error): + # Exception raised from timing out on nonblocking + pass + + if (rec_data is not None) and (len(rec_data) == 4): + # check the Stream Multiplexing Layer message and get the length of the data to read + size, endpoint = unpack("!HH", rec_data) + resp = '' + while len(resp) < size: + try: + resp += self._bts.recv(size-len(resp)) + except (socket.timeout, socket.error): + # Exception raised from timing out on nonblocking + # TODO: Should probably have some kind of timeout here + pass + try: + self.rec_queue.put((endpoint, resp, rec_data)) + except (IOError, EOFError): + self.BT_TEARDOWN.set() + e = "Queue Error while recieving data" + pass + if self.debug_protocol: + log.debug("LightBlue Read: %r " % resp) + + # just let it die silent whenever the parent dies and it throws an EOFERROR + if e is not None and self.debug_protocol: + raise LightBluePebbleError(self.mac_address, "LightBlue polling loop closed due to " + e) diff --git a/pebble/libpebble/MANIFEST.in b/pebble/libpebble/MANIFEST.in deleted file mode 100644 index 3953107..0000000 --- a/pebble/libpebble/MANIFEST.in +++ /dev/null @@ -1,16 +0,0 @@ -#Language Files - -include pebble/data/i18n/ca/LC_MESSAGES/pebble-remote.mo -include pebble/data/i18n/tr/LC_MESSAGES/pebble-remote.mo -include pebble/data/i18n/es/LC_MESSAGES/pebble-remote.mo -include pebble/data/i18n/it/LC_MESSAGES/pebble-remote.mo - -#Manual page - -include pebble/data/man/pebble-remote.1.gz - -#Mimetype files - -include pebble/data/mimetype/pebble-remote -include pebble/data/mimetype/pebble-remote.desktop -include pebble/data/mimetype/pebble-remote.png diff --git a/pebble/libpebble/__init__.py b/pebble/libpebble/__init__.py new file mode 100644 index 0000000..96a407d --- /dev/null +++ b/pebble/libpebble/__init__.py @@ -0,0 +1,6 @@ +__title__ = 'libpebble' +__version__ = '0.0.1' +__build__ = 0x01 +__license__ = 'MIT' + +from .pebble import Pebble, PebbleError, PutBytesClient diff --git a/pebble/libpebble/p.py b/pebble/libpebble/p.py new file mode 100755 index 0000000..328ac11 --- /dev/null +++ b/pebble/libpebble/p.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python + +import argparse +import os +import pebble as libpebble +import time +import pexpect +import tkMessageBox +from pebble_remote import i18n + +from Tkinter import * +_ = i18n.language.gettext + +MAX_ATTEMPTS = 5 + +window = Tk() +window.wm_withdraw() +window.geometry("1x1+200+200") #remember its .geometry("WidthxHeight(+or-)X(+or-)Y") + +LightBluePebbleError = libpebble.LightBluePebble.LightBluePebbleError +PebbleError = libpebble.pebble.PebbleError + +def cmd_remote(pebble, args): + path=args.odp_file_path + runodp = args.app_name+" --impress "+path + pebble.set_nowplaying_metadata(_("LibreOffice Remote Control "), _("Next"), _("Previous")) + + try: + pexpect.run(runodp, timeout=5) + window_id = pexpect.run("xdotool search --sync --onlyvisible --class \"libreoffice\"") + fullscreen = "xdotool key --window " +window_id+" F5" + pexpect.run(fullscreen) + except Exception: + print _("Something's wrong") + return False + + def libreoffice_event_handler(event): + right_click = "xdotool key --window "+ window_id + "Right" + left_click = "xdotool key --window "+ window_id + "Left" + + if event == "next": + pexpect.run(right_click) + + if event == "previous": + pexpect.run(left_click) + + if event == "exit": + try: + window_ids = pexpect.run("xdotool search --sync --onlyvisible --name \"libreoffice\"").split("\r\n") + window_ids.pop() + window_ids.reverse() + if len(window_ids)>=2: + window_ids[0:2] + altf4_presentation = "xdotool windowactivate --sync "+window_ids[0]+" key --clearmodifiers --delay 100 alt+F4" + altf4_edit = "xdotool windowactivate --sync "+window_ids[1]+" key --clearmodifiers --delay 100 alt+F4" + pexpect.run(altf4_presentation) + pexpect.run(altf4_edit) + if len(window_ids)<2: + altf4_edit = "xdotool windowactivate --sync "+window_ids[0]+" key --clearmodifiers --delay 100 alt+F4" + pexpect.run(altf4_edit) + pexpect.run("exit_click.sh") + except Exception as e: + raise e + print event + + + def music_control_handler(endpoint, resp): + events = { + "PLAYPAUSE": "exit", + "PREVIOUS": "previous", + "NEXT": "next" + } + + libreoffice_event_handler(events[resp]) + + print _("waiting for events") + while True: + try: + pebble.register_endpoint("MUSIC_CONTROL", music_control_handler) + time.sleep(5) + except LightBluePebbleError as e: + tkMessageBox.showerror(title="Error", message=e._message, parent=window) + raise e + raise KeyboardInterrupt + except PebbleError as e: + tkMessageBox.showerror(title="Error", message=e._message, parent=window) + raise e + raise KeyboardInterrupt + except KeyboardInterrupt: + return + +def main(): + parser = argparse.ArgumentParser(description='a utility belt for pebble development') + parser.add_argument('--pebble_id', type=str, help='the last 4 digits of the target Pebble\'s MAC address. \nNOTE: if \ + --lightblue is set, providing a full MAC address (ex: "A0:1B:C0:D3:DC:93") won\'t require the pebble \ + to be discoverable and will be faster') + + parser.add_argument('--lightblue', action="store_true", help='use LightBlue bluetooth API') + parser.add_argument('--pair', action="store_true", help='pair to the pebble from LightBlue bluetooth API before connecting.') + + subparsers = parser.add_subparsers(help='commands', dest='which') + + remote_parser = subparsers.add_parser('remote', help='control LibreOffice Impress app with music app on Pebble') + remote_parser.add_argument('app_name', type=str, help='title of application to be controlled') + remote_parser.add_argument('odp_file_path', type=str, help='path for libreoffice impress presentation file') + remote_parser.set_defaults(func=cmd_remote) + + + args = parser.parse_args() + + attempts = 0 + while True: + if attempts > MAX_ATTEMPTS: + raise _('Could not connect to Pebble') + try: + pebble_id = args.pebble_id + if pebble_id is None and "PEBBLE_ID" in os.environ: + pebble_id = os.environ["PEBBLE_ID"] + pebble = libpebble.Pebble(pebble_id, args.lightblue, args.pair) + break + except LightBluePebbleError as e: + tkMessageBox.showerror(title="Error", message=_("Bluetooth connection error"), parent=window) + raise KeyboardInterrupt + except PebbleError as e: + tkMessageBox.showerror(title="Error", message=e._message, parent=window) + raise e + raise KeyboardInterrupt + except: + time.sleep(5) + attempts += 1 + + try: + args.func(pebble, args) + except LightBluePebbleError as e: + tkMessageBox.showerror(title="Error", message=e._message, parent=window) + raise e + raise KeyboardInterrupt + except PebbleError as e: + tkMessageBox.showerror(title="Error", message=e._message, parent=window) + raise e + raise KeyboardInterrupt + except Exception as e: + pebble.disconnect() + raise e + return + + pebble.disconnect() + +if __name__ == '__main__': + main() diff --git a/pebble/libpebble/pebble.py b/pebble/libpebble/pebble.py new file mode 100755 index 0000000..2496f6d --- /dev/null +++ b/pebble/libpebble/pebble.py @@ -0,0 +1,539 @@ +#!/usr/bin/env python + +import binascii +import glob +import itertools +import json +import logging +import os +import serial +import signal +import stm32_crc +import struct +import threading +import time +import traceback +import uuid +import zipfile + +from collections import OrderedDict +from LightBluePebble import LightBluePebble +from struct import pack, unpack + +log = logging.getLogger() +logging.basicConfig(format='[%(levelname)-8s] %(message)s') +log.setLevel(logging.DEBUG) + +DEFAULT_PEBBLE_ID = None #Triggers autodetection on unix-like systems +DEBUG_PROTOCOL = False + +class EndpointSync(): + timeout = 10 + + def __init__(self, pebble, endpoint): + pebble.register_endpoint(endpoint, self.callback) + self.marker = threading.Event() + + def callback(self, *args): + self.data = args + self.marker.set() + + def get_data(self): + try: + self.marker.wait(timeout=self.timeout) + return self.data[1] + except: + return False + +class PebbleError(Exception): + def __init__(self, id, message): + self._id = id + self._message = message + + def __str__(self): + return "%s (ID:%s)" % (self._message, self._id) + +class Pebble(object): + + """ + A connection to a Pebble watch; data and commands may be sent + to the watch through an instance of this class. + """ + + endpoints = { + "TIME": 11, + "VERSION": 16, + "PHONE_VERSION": 17, + "SYSTEM_MESSAGE": 18, + "MUSIC_CONTROL": 32, + "PHONE_CONTROL": 33, + "APPLICATION_MESSAGE": 48, + "LAUNCHER": 49, + "LOGS": 2000, + "PING": 2001, + "LOG_DUMP": 2002, + "RESET": 2003, + "APP": 2004, + "APP_LOGS": 2006, + "NOTIFICATION": 3000, + "RESOURCE": 4000, + "APP_MANAGER": 6000, + "PUTBYTES": 48879 + } + + log_levels = { + 0: "*", + 1: "E", + 50: "W", + 100: "I", + 200: "D", + 250: "V" + } + + + @staticmethod + def AutodetectDevice(): + if os.name != "posix": #i.e. Windows + raise NotImplementedError("Autodetection is only implemented on UNIX-like systems.") + + pebbles = glob.glob("/dev/tty.Pebble????-SerialPortSe") + + if len(pebbles) == 0: + raise PebbleError(None, "Autodetection could not find any Pebble devices") + elif len(pebbles) > 1: + log.warn("Autodetect found %d Pebbles; using most recent" % len(pebbles)) + #NOTE: Not entirely sure if this is the correct approach + pebbles.sort(key=lambda x: os.stat(x).st_mtime, reverse=True) + + id = pebbles[0][15:19] + log.info("Autodetect found a Pebble with ID %s" % id) + return id + + def __init__(self, id = None, using_lightblue = True, pair_first = False): + if id is None and not using_lightblue: + id = Pebble.AutodetectDevice() + self.id = id + self.using_lightblue = using_lightblue + self._alive = True + self._endpoint_handlers = {} + self._internal_endpoint_handlers = { + self.endpoints["TIME"]: self._get_time_response, + self.endpoints["VERSION"]: self._version_response, + self.endpoints["PHONE_VERSION"]: self._phone_version_response, + self.endpoints["SYSTEM_MESSAGE"]: self._system_message_response, + self.endpoints["MUSIC_CONTROL"]: self._music_control_response, + self.endpoints["APPLICATION_MESSAGE"]: self._application_message_response, + self.endpoints["LAUNCHER"]: self._application_message_response, + self.endpoints["LOGS"]: self._log_response, + self.endpoints["PING"]: self._ping_response, + self.endpoints["APP_LOGS"]: self._app_log_response, + self.endpoints["APP_MANAGER"]: self._appbank_status_response + } + + try: + if using_lightblue: + self._ser = LightBluePebble(self.id, pair_first) + signal.signal(signal.SIGINT, self._exit_signal_handler) + else: + devicefile = "/dev/tty.Pebble"+id+"-SerialPortSe" + log.debug("Attempting to open %s as Pebble device %s" % (devicefile, id)) + self._ser = serial.Serial(devicefile, 115200, timeout=1) + + log.debug("Initializing reader thread") + self._read_thread = threading.Thread(target=self._reader) + self._read_thread.setDaemon(True) + self._read_thread.start() + log.debug("Reader thread loaded on tid %s" % self._read_thread.name) + except PebbleError: + raise PebbleError(id, "Failed to connect to Pebble") + except: + raise + + def _exit_signal_handler(self, signum, frame): + print "Disconnecting before exiting..." + self.disconnect() + time.sleep(1) + os._exit(0) + + def __del__(self): + try: + self._ser.close() + except: + pass + + def _reader(self): + try: + while self._alive: + endpoint, resp = self._recv_message() + if resp == None: + continue + + if endpoint in self._internal_endpoint_handlers: + resp = self._internal_endpoint_handlers[endpoint](endpoint, resp) + + if endpoint in self._endpoint_handlers and resp: + self._endpoint_handlers[endpoint](endpoint, resp) + except: + traceback.print_exc() + raise PebbleError(self.id, "Lost connection to Pebble") + self._alive = False + + def _pack_message_data(self, lead, parts): + pascal = map(lambda x: x[:255], parts) + d = pack("b" + reduce(lambda x,y: str(x) + "p" + str(y), map(lambda x: len(x) + 1, pascal)) + "p", lead, *pascal) + return d + + def _build_message(self, endpoint, data): + return pack("!HH", len(data), endpoint)+data + + def _send_message(self, endpoint, data, callback = None): + if endpoint not in self.endpoints: + raise PebbleError(self.id, "Invalid endpoint specified") + + msg = self._build_message(self.endpoints[endpoint], data) + + if DEBUG_PROTOCOL: + log.debug('>>> ' + msg.encode('hex')) + self._ser.write(msg) + + def _recv_message(self): + if self.using_lightblue: + try: + endpoint, resp, data = self._ser.read() + if resp is None: + return None, None + except TypeError: + # the lightblue process has likely shutdown and cannot be read from + self.alive = False + return None, None + else: + data = self._ser.read(4) + if len(data) == 0: + return (None, None) + elif len(data) < 4: + raise PebbleError(self.id, "Malformed response with length "+str(len(data))) + size, endpoint = unpack("!HH", data) + resp = self._ser.read(size) + + if DEBUG_PROTOCOL: + log.debug("Got message for endpoint %s of length %d" % (endpoint, len(resp))) + log.debug('<<< ' + (data + resp).encode('hex')) + + return (endpoint, resp) + + def register_endpoint(self, endpoint_name, func): + if endpoint_name not in self.endpoints: + raise PebbleError(self.id, "Invalid endpoint specified") + + endpoint = self.endpoints[endpoint_name] + self._endpoint_handlers[endpoint] = func + + def set_nowplaying_metadata(self, track, album, artist): + + """Update the song metadata displayed in Pebble's music app.""" + + parts = [artist[:30], album[:30], track[:30]] + self._send_message("MUSIC_CONTROL", self._pack_message_data(16, parts)) + + def system_message(self, command): + + """ + Send a 'system message' to the watch. + + These messages are used to signal important events/state-changes to the watch firmware. + """ + + commands = { + "FIRMWARE_AVAILABLE": 0, + "FIRMWARE_START": 1, + "FIRMWARE_COMPLETE": 2, + "FIRMWARE_FAIL": 3, + "FIRMWARE_UP_TO_DATE": 4, + "FIRMWARE_OUT_OF_DATE": 5, + "BLUETOOTH_START_DISCOVERABLE": 6, + "BLUETOOTH_END_DISCOVERABLE": 7 + } + if command not in commands: + raise PebbleError(self.id, "Invalid command \"%s\"" % command) + data = pack("!bb", 0, commands[command]) + log.debug("Sending command %s (code %d)" % (command, commands[command])) + self._send_message("SYSTEM_MESSAGE", data) + + def disconnect(self): + + """Disconnect from the target Pebble.""" + + self._alive = False + self._ser.close() + + def _ping_response(self, endpoint, data): + restype, retcookie = unpack("!bL", data) + return retcookie + + def _get_time_response(self, endpoint, data): + restype, timestamp = unpack("!bL", data) + return timestamp + + def _system_message_response(self, endpoint, data): + if len(data) == 2: + log.info("Got system message %s" % repr(unpack('!bb', data))) + else: + log.info("Got 'unknown' system message...") + + def _log_response(self, endpoint, data): + if (len(data) < 8): + log.warn("Unable to decode log message (length %d is less than 8)" % len(data)) + return + + timestamp, level, msgsize, linenumber = unpack("!IBBH", data[:8]) + filename = data[8:24].decode('utf-8') + message = data[24:24+msgsize].decode('utf-8') + + str_level = self.log_levels[level] if level in self.log_levels else "?" + + print timestamp, str_level, filename, linenumber, message + + def _app_log_response(self, endpoint, data): + if (len(data) < 8): + log.warn("Unable to decode log message (length %d is less than 8)" % len(data)) + return + + app_uuid = uuid.UUID(bytes=data[0:16]) + timestamp, level, msgsize, linenumber = unpack("!IBBH", data[16:24]) + filename = data[24:40].decode('utf-8') + message = data[40:40+msgsize].decode('utf-8') + + str_level = self.log_levels[level] if level in self.log_levels else "?" + + print timestamp, str_level, app_uuid, filename, linenumber, message + + def _appbank_status_response(self, endpoint, data): + apps = {} + restype, = unpack("!b", data[0]) + + app_install_message = { + 0: "app available", + 1: "app removed", + 2: "app updated" + } + + if restype == 1: + apps["banks"], apps_installed = unpack("!II", data[1:9]) + apps["apps"] = [] + + appinfo_size = 78 + offset = 9 + for i in xrange(apps_installed): + app = {} + try: + app["id"], app["index"], app["name"], app["company"], app["flags"], app["version"] = \ + unpack("!II32s32sIH", data[offset:offset+appinfo_size]) + app["name"] = app["name"].replace("\x00", "") + app["company"] = app["company"].replace("\x00", "") + apps["apps"] += [app] + except: + if offset+appinfo_size > len(data): + log.warn("Couldn't load bank %d; remaining data = %s" % (i,repr(data[offset:]))) + else: + raise + offset += appinfo_size + + return apps + + elif restype == 2: + message_id = unpack("!I", data[1:]) + message_id = int(''.join(map(str, message_id))) + return app_install_message[message_id] + + def _version_response(self, endpoint, data): + fw_names = { + 0: "normal_fw", + 1: "recovery_fw" + } + + resp = {} + for i in xrange(2): + fwver_size = 47 + offset = i*fwver_size+1 + fw = {} + fw["timestamp"],fw["version"],fw["commit"],fw["is_recovery"], \ + fw["hardware_platform"],fw["metadata_ver"] = \ + unpack("!i32s8s?bb", data[offset:offset+fwver_size]) + + fw["version"] = fw["version"].replace("\x00", "") + fw["commit"] = fw["commit"].replace("\x00", "") + + fw_name = fw_names[i] + resp[fw_name] = fw + + resp["bootloader_timestamp"],resp["hw_version"],resp["serial"] = \ + unpack("!L9s12s", data[95:120]) + + resp["hw_version"] = resp["hw_version"].replace("\x00","") + + btmac_hex = binascii.hexlify(data[120:126]) + resp["btmac"] = ":".join([btmac_hex[i:i+2].upper() for i in reversed(xrange(0, 12, 2))]) + + return resp + + def _application_message_response(self, endpoint, data): + app_messages = { + b'\x01': "PUSH", + b'\x02': "REQUEST", + b'\xFF': "ACK", + b'\x7F': "NACK" + } + + if len(data) > 1: + rest = data[1:] + else: + rest = '' + if data[0] in app_messages: + return app_messages[data[0]] + rest + + + def _phone_version_response(self, endpoint, data): + session_cap = { + "GAMMA_RAY" : 0x80000000, + } + remote_cap = { + "TELEPHONY" : 16, + "SMS" : 32, + "GPS" : 64, + "BTLE" : 128, + "CAMERA_REAR" : 256, + "ACCEL" : 512, + "GYRO" : 1024, + "COMPASS" : 2048, + } + os = { + "UNKNOWN" : 0, + "IOS" : 1, + "ANDROID" : 2, + "OSX" : 3, + "LINUX" : 4, + "WINDOWS" : 5, + } + + # Then session capabilities, android adds GAMMA_RAY and it's + # the only session flag so far + session = session_cap["GAMMA_RAY"] + + # Then phone capabilities, android app adds TELEPHONY and SMS, + # and the phone type (we know android works for now) + remote = remote_cap["TELEPHONY"] | remote_cap["SMS"] | os["ANDROID"] + + msg = pack("!biII", 1, -1, session, remote) + self._send_message("PHONE_VERSION", msg); + + def _music_control_response(self, endpoint, data): + event, = unpack("!b", data) + + event_names = { + 1: "PLAYPAUSE", + 4: "NEXT", + 5: "PREVIOUS", + } + + return event_names[event] if event in event_names else None + +class PutBytesClient(object): + states = { + "NOT_STARTED": 0, + "WAIT_FOR_TOKEN": 1, + "IN_PROGRESS": 2, + "COMMIT": 3, + "COMPLETE": 4, + "FAILED": 5 + } + + transfer_types = { + "FIRMWARE": 1, + "RECOVERY": 2, + "SYS_RESOURCES": 3, + "RESOURCES": 4, + "BINARY": 5 + } + + def __init__(self, pebble, index, transfer_type, buffer): + self._pebble = pebble + self._state = self.states["NOT_STARTED"] + self._transfer_type = self.transfer_types[transfer_type] + self._buffer = buffer + self._index = index + self._done = False + self._error = False + + def init(self): + data = pack("!bIbb", 1, len(self._buffer), self._transfer_type, self._index) + self._pebble._send_message("PUTBYTES", data) + self._state = self.states["WAIT_FOR_TOKEN"] + + def wait_for_token(self, resp): + res, = unpack("!b", resp[0]) + if res != 1: + log.error("init failed with code %d" % res) + self._error = True + return + self._token, = unpack("!I", resp[1:]) + self._left = len(self._buffer) + self._state = self.states["IN_PROGRESS"] + self.send() + + def in_progress(self, resp): + res, = unpack("!b", resp[0]) + if res != 1: + self.abort() + return + if self._left > 0: + self.send() + log.debug("Sent %d of %d bytes" % (len(self._buffer)-self._left, len(self._buffer))) + else: + self._state = self.states["COMMIT"] + self.commit() + + def commit(self): + data = pack("!bII", 3, self._token & 0xFFFFFFFF, stm32_crc.crc32(self._buffer)) + self._pebble._send_message("PUTBYTES", data) + + def handle_commit(self, resp): + res, = unpack("!b", resp[0]) + if res != 1: + self.abort() + return + self._state = self.states["COMPLETE"] + self.complete() + + def complete(self): + data = pack("!bI", 5, self._token & 0xFFFFFFFF) + self._pebble._send_message("PUTBYTES", data) + + def handle_complete(self, resp): + res, = unpack("!b", resp[0]) + if res != 1: + self.abort() + return + self._done = True + + def abort(self): + msgdata = pack("!bI", 4, self._token & 0xFFFFFFFF) + self._pebble.send_message("PUTBYTES", msgdata) + self._error = True + + def send(self): + datalen = min(self._left, 2000) + rg = len(self._buffer)-self._left + msgdata = pack("!bII", 2, self._token & 0xFFFFFFFF, datalen) + msgdata += self._buffer[rg:rg+datalen] + self._pebble._send_message("PUTBYTES", msgdata) + self._left -= datalen + + def handle_message(self, endpoint, resp): + if self._state == self.states["WAIT_FOR_TOKEN"]: + self.wait_for_token(resp) + elif self._state == self.states["IN_PROGRESS"]: + self.in_progress(resp) + elif self._state == self.states["COMMIT"]: + self.handle_commit(resp) + elif self._state == self.states["COMPLETE"]: + self.handle_complete(resp) diff --git a/pebble/libpebble/pebble/LICENSE b/pebble/libpebble/pebble/LICENSE deleted file mode 100644 index 7fc0b12..0000000 --- a/pebble/libpebble/pebble/LICENSE +++ /dev/null @@ -1,7 +0,0 @@ -Copyright (C) 2013 Liam McLoughlin - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/pebble/libpebble/pebble/LightBluePebble.py b/pebble/libpebble/pebble/LightBluePebble.py deleted file mode 100644 index db743f5..0000000 --- a/pebble/libpebble/pebble/LightBluePebble.py +++ /dev/null @@ -1,176 +0,0 @@ -#!/usr/bin/env python -import logging -import multiprocessing -import os -import Queue -import re -import socket -from multiprocessing import Process -from struct import unpack - -log = logging.getLogger() -logging.basicConfig(format='[%(levelname)-8s] %(message)s') -log.setLevel(logging.DEBUG) - -class LightBluePebbleError(Exception): - def __init__(self, id, message): - self._id = id - self._message = message - - def __str__(self): - return "%s ID:(%s) on LightBlue API" % (self._message, self._id) - -class LightBluePebble(object): - """ a wrapper for LightBlue that provides Serial-style read, write and close""" - - def __init__(self, id, should_pair, debug_protocol=False, connection_process_timeout=5): - - self.mac_address = id - self.debug_protocol = debug_protocol - self.should_pair = should_pair - - manager = multiprocessing.Manager() - self.send_queue = manager.Queue() - self.rec_queue = manager.Queue() - - self.bt_teardown = multiprocessing.Event() - self.bt_message_sent = multiprocessing.Event() - self.bt_connected = multiprocessing.Event() - - self.bt_socket_proc = Process(target=self.run) - self.bt_socket_proc.daemon = True - self.bt_socket_proc.start() - - # wait for a successful connection from child process before returning to main process - self.bt_connected.wait(connection_process_timeout) - if not self.bt_connected.is_set(): - raise LightBluePebbleError(id, "Connection timed out, LightBlueProcess was provided %d seconds to complete connecting" % connection_process_timeout) - - def write(self, message): - """ send a message to the LightBlue processs""" - try: - self.send_queue.put(message) - self.bt_message_sent.wait() - except: - self.bt_teardown.set() - if self.debug_protocol: - log.debug("LightBlue process has shutdown (queue write)") - - def read(self): - """ read a pebble message from the LightBlue processs""" - try: - return self.rec_queue.get() - except Queue.Empty: - return (None, None, '') - except: - self.bt_teardown.set() - if self.debug_protocol: - log.debug("LightBlue process has shutdown (queue read)") - return (None, None, '') - - def close(self): - """ close the LightBlue connection process""" - self.bt_teardown.set() - - def is_alive(self): - return self.bt_socket_proc.is_alive() - - def run(self): - """ create bluetooth process paired to mac_address, must be run as a process""" - from lightblue import pair, socket as lb_socket, finddevices, selectdevice - - def autodetect(self): - list_of_pebbles = list() - - if self.mac_address is not None and len(self.mac_address) is 4: - # we have the friendly name, let's get the full mac address - log.warn("Going to get full address for device %s, ensure device is broadcasting." % self.mac_address) - # scan for active devices - devices = finddevices(timeout=8) - - for device in devices: - if re.search(r'Pebble ' + self.mac_address, device[1], re.IGNORECASE): - log.debug("Found Pebble: %s @ %s" % (device[1], device[0])) - list_of_pebbles.append(device) - - if len(list_of_pebbles) is 1: - return list_of_pebbles[0][0] - else: - raise LightBluePebbleError(self.mac_address, "Failed to find Pebble") - else: - # no pebble id was provided... give them the GUI selector - try: - return selectdevice()[0] - except TypeError: - log.warn("failed to select a device in GUI selector") - self.mac_address = None - - # notify that the process has started - log.debug("LightBlue process has started on pid %d" % os.getpid()) - - # do we need to autodetect? - if self.mac_address is None or len(self.mac_address) is 4: - self.mac_address = autodetect(self) - - # create the bluetooth socket from the mac address - if self.should_pair and self.mac_address is not None: - pair(self.mac_address) - try: - self._bts = lb_socket() - self._bts.connect((self.mac_address, 1)) # pebble uses RFCOMM port 1 - self._bts.setblocking(False) - except: - raise LightBluePebbleError(self.mac_address, "Failed to connect to Pebble") - - # give them the mac address for using in faster connections - log.debug("Connection established to " + self.mac_address) - - # Tell our parent that we have a pebble connected now - self.bt_connected.set() - - send_data = e = None - while not self.bt_teardown.is_set(): - # send anything in the send queue - try: - send_data = self.send_queue.get_nowait() - self._bts.send(send_data) - if self.debug_protocol: - log.debug("LightBlue Send: %r" % send_data) - self.bt_message_sent.set() - except Queue.Empty: - pass - except (IOError, EOFError): - self.bt_teardown.set() - e = "Queue Error while sending data" - - # if anything is received relay it back - rec_data = None - try: - rec_data = self._bts.recv(4) - except (socket.timeout, socket.error): - # Exception raised from timing out on nonblocking - pass - - if (rec_data is not None) and (len(rec_data) == 4): - # check the Stream Multiplexing Layer message and get the length of the data to read - size, endpoint = unpack("!HH", rec_data) - resp = '' - while len(resp) < size: - try: - resp += self._bts.recv(size-len(resp)) - except (socket.timeout, socket.error): - # Exception raised from timing out on nonblocking - # TODO: Should probably have some kind of timeout here - pass - try: - self.rec_queue.put((endpoint, resp, rec_data)) - except (IOError, EOFError): - self.BT_TEARDOWN.set() - e = "Queue Error while recieving data" - pass - if self.debug_protocol: - log.debug("LightBlue Read: %r " % resp) - - # just let it die silent whenever the parent dies and it throws an EOFERROR - if e is not None and self.debug_protocol: - raise LightBluePebbleError(self.mac_address, "LightBlue polling loop closed due to " + e) diff --git a/pebble/libpebble/pebble/__init__.py b/pebble/libpebble/pebble/__init__.py deleted file mode 100644 index 96a407d..0000000 --- a/pebble/libpebble/pebble/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -__title__ = 'libpebble' -__version__ = '0.0.1' -__build__ = 0x01 -__license__ = 'MIT' - -from .pebble import Pebble, PebbleError, PutBytesClient diff --git a/pebble/libpebble/pebble/data/LICENCE b/pebble/libpebble/pebble/data/LICENCE deleted file mode 100644 index 735331f..0000000 --- a/pebble/libpebble/pebble/data/LICENCE +++ /dev/null @@ -1,159 +0,0 @@ -Mozilla Public License -Version 2.0 -1. Definitions - -1.1. “Contributor” - - means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. -1.2. “Contributor Version” - - means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor’s Contribution. -1.3. “Contribution” - - means Covered Software of a particular Contributor. -1.4. “Covered Software” - - means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. -1.5. “Incompatible With Secondary Licenses” - - means - - that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or - - that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. - -1.6. “Executable Form” - - means any form of the work other than Source Code Form. -1.7. “Larger Work” - - means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. -1.8. “License” - - means this document. -1.9. “Licensable” - - means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. -1.10. “Modifications” - - means any of the following: - - any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or - - any new file in Source Code Form that contains any Covered Software. - -1.11. “Patent Claims” of a Contributor - - means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. -1.12. “Secondary License” - - means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. -1.13. “Source Code Form” - - means the form of the work preferred for making modifications. -1.14. “You” (or “Your”) - - means an individual or a legal entity exercising rights under this License. For legal entities, “You” includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, “control” means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. - -2. License Grants and Conditions -2.1. Grants - -Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: - - under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and - - under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. - -2.2. Effective Date - -The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. -2.3. Limitations on Grant Scope - -The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: - - for any code that a Contributor has removed from Covered Software; or - - for infringements caused by: (i) Your and any other third party’s modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or - - under Patent Claims infringed by Covered Software in the absence of its Contributions. - -This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). -2.4. Subsequent Licenses - -No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). -2.5. Representation - -Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. -2.6. Fair Use - -This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. -2.7. Conditions - -Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. -3. Responsibilities -3.1. Distribution of Source Form - -All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients’ rights in the Source Code Form. -3.2. Distribution of Executable Form - -If You distribute Covered Software in Executable Form then: - - such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and - - You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients’ rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - -You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). -3.4. Notices - -You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. -3.5. Application of Additional Terms - -You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. -4. Inability to Comply Due to Statute or Regulation - -If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. -5. Termination - -5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. -6. Disclaimer of Warranty - -Covered Software is provided under this License on an “as is” basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer. -7. Limitation of Liability - -Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such party’s negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You. -8. Litigation - -Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party’s ability to bring cross-claims or counter-claims. -9. Miscellaneous - -This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. -10. Versions of the License -10.1. New Versions - -Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. -10.2. Effect of New Versions - -You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. -10.3. Modified Versions - -If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). -10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses - -If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. - -You may add additional accurate notices of copyright ownership. -Exhibit B - “Incompatible With Secondary Licenses” Notice - - This Source Code Form is “Incompatible With Secondary Licenses”, as defined by the Mozilla Public License, v. 2.0. - diff --git a/pebble/libpebble/pebble/data/i18n/ca/LC_MESSAGES/pebble-remote.mo b/pebble/libpebble/pebble/data/i18n/ca/LC_MESSAGES/pebble-remote.mo deleted file mode 100644 index e7ee00a..0000000 Binary files a/pebble/libpebble/pebble/data/i18n/ca/LC_MESSAGES/pebble-remote.mo and /dev/null differ diff --git a/pebble/libpebble/pebble/data/i18n/es/LC_MESSAGES/pebble-remote.mo b/pebble/libpebble/pebble/data/i18n/es/LC_MESSAGES/pebble-remote.mo deleted file mode 100644 index 0f3a4b1..0000000 Binary files a/pebble/libpebble/pebble/data/i18n/es/LC_MESSAGES/pebble-remote.mo and /dev/null differ diff --git a/pebble/libpebble/pebble/data/i18n/it/LC_MESSAGES/pebble-remote.mo b/pebble/libpebble/pebble/data/i18n/it/LC_MESSAGES/pebble-remote.mo deleted file mode 100644 index 5139aec..0000000 Binary files a/pebble/libpebble/pebble/data/i18n/it/LC_MESSAGES/pebble-remote.mo and /dev/null differ diff --git a/pebble/libpebble/pebble/data/i18n/tr/LC_MESSAGES/pebble-remote.mo b/pebble/libpebble/pebble/data/i18n/tr/LC_MESSAGES/pebble-remote.mo deleted file mode 100644 index d2c966b..0000000 Binary files a/pebble/libpebble/pebble/data/i18n/tr/LC_MESSAGES/pebble-remote.mo and /dev/null differ diff --git a/pebble/libpebble/pebble/data/man/pebble-remote.1.gz b/pebble/libpebble/pebble/data/man/pebble-remote.1.gz deleted file mode 100644 index 08bb9a8..0000000 Binary files a/pebble/libpebble/pebble/data/man/pebble-remote.1.gz and /dev/null differ diff --git a/pebble/libpebble/pebble/data/mimetype/pebble-remote b/pebble/libpebble/pebble/data/mimetype/pebble-remote deleted file mode 100644 index fabdc8b..0000000 --- a/pebble/libpebble/pebble/data/mimetype/pebble-remote +++ /dev/null @@ -1,5 +0,0 @@ -?package(pebble-remote):needs="X11" section="Applications/Office"\ - title="Pebble Remote" command="/usr/bin/pebble-remote"\ - hints="Presentation"\ - kderemove="y"\ - icon="/usr/share/icons/hicolor/32x32/apps/libreoffice-impress.xpm" diff --git a/pebble/libpebble/pebble/data/mimetype/pebble-remote.desktop b/pebble/libpebble/pebble/data/mimetype/pebble-remote.desktop deleted file mode 100644 index e3c0335..0000000 --- a/pebble/libpebble/pebble/data/mimetype/pebble-remote.desktop +++ /dev/null @@ -1,33 +0,0 @@ -# -# This file is part of the LibreOffice project. -# -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this -# file, You can obtain one at http://mozilla.org/MPL/2.0/. -# -# This file incorporates work covered by the following license notice: -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed -# with this work for additional information regarding copyright -# ownership. The ASF licenses this file to you under the Apache -# License, Version 2.0 (the "License"); you may not use this file -# except in compliance with the License. You may obtain a copy of -# the License at http://www.apache.org/licenses/LICENSE-2.0 . -# -[Desktop Entry] -Version=2.0 -Terminal=false -Icon=/usr/share/pixmaps/pebble-remote.png -Type=Application -Categories=Office;Presentation;X-Red-Hat-Base;X-MandrivaLinux-Office-Presentations; -Exec=pebble-remote %U -MimeType=application/vnd.oasis.opendocument.presentation;application/vnd.oasis.opendocument.presentation-template;application/vnd.sun.xml.impress;application/vnd.sun.xml.impress.template;application/mspowerpoint;application/vnd.ms-powerpoint;application/vnd.openxmlformats-officedocument.presentationml.presentation;application/vnd.ms-powerpoint.presentation.macroenabled.12;application/vnd.openxmlformats-officedocument.presentationml.template;application/vnd.ms-powerpoint.template.macroenabled.12;application/vnd.openxmlformats-officedocument.presentationml.slide;application/vnd.openxmlformats-officedocument.presentationml.slideshow;application/vnd.ms-powerpoint.slideshow.macroEnabled.12;application/vnd.oasis.opendocument.presentation-flat-xml;application/x-iwork-keynote-sffkey; -Name=Pebble Remote -GenericName=Presentation -Comment=Pebble remote control for LibreOffice Impress. -StartupNotify=true -Keywords=Slideshow;Slides;OpenDocument Presentation;Microsoft PowerPoint;Microsoft Works;OpenOffice Impress;odp;ppt;pptx; -InitialPreference=5 -StartupWMClass=libreoffice-impress -X-KDE-Protocols=file,http,smb,ftp,webdav diff --git a/pebble/libpebble/pebble/data/mimetype/pebble-remote.png b/pebble/libpebble/pebble/data/mimetype/pebble-remote.png deleted file mode 100644 index 0f2090a..0000000 Binary files a/pebble/libpebble/pebble/data/mimetype/pebble-remote.png and /dev/null differ diff --git a/pebble/libpebble/pebble/data/scripts/exit_click.sh b/pebble/libpebble/pebble/data/scripts/exit_click.sh deleted file mode 100755 index bbfb104..0000000 --- a/pebble/libpebble/pebble/data/scripts/exit_click.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash - -ps aux | grep p.py | sed 's/\s\+/ /g' | cut -d' ' -f2 | xargs kill diff --git a/pebble/libpebble/pebble/data/scripts/pebble-remote b/pebble/libpebble/pebble/data/scripts/pebble-remote deleted file mode 100755 index 83a0599..0000000 --- a/pebble/libpebble/pebble/data/scripts/pebble-remote +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/bash - -export PEBBLE_ID=`bt-device -l | grep Pebble | cut -d ' ' -f3 | cut -c2-18` -export PARAMETERS=--lightblue -export SUBCOMMAND=remote -export APP_NAME=libreoffice - -if [ "$1" == "-h" ] || [ "$1" == "--help" ]; -then - - echo "Usage: `basename $0` [path_to_odp_file]" - exit 0 - -elif [ "$1" == "-v" ] || [ "$1" == "--version" ]; -then - - echo "2.0" - exit 0 - -else - - p.py --pebble_id $PEBBLE_ID $PARAMETERS $SUBCOMMAND $APP_NAME $1 - -fi - diff --git a/pebble/libpebble/pebble/i18n.py b/pebble/libpebble/pebble/i18n.py deleted file mode 100644 index 272ccbf..0000000 --- a/pebble/libpebble/pebble/i18n.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: utf-8 -*- - -import os, sys -import locale -import gettext - -# Change this variable to your app name! -# The translation files will be under -# @LOCALE_DIR@/@LANGUAGE@/LC_MESSAGES/@APP_NAME@.mo -APP_NAME = "pebble-remote" - -# This is ok for maemo. Not sure in a regular desktop: -APP_DIR = os.path.dirname(os.path.abspath("/opt/pebble/i18n")) #APP_DIR returns pebble-rmeote project path on your system -LOCALE_DIR = os.path.join(APP_DIR, 'i18n') # .mo files will then be located in APP_Dir/i18n/LANGUAGECODE/LC_MESSAGES/ - -# Now we need to choose the language. We will provide a list, and gettext -# will use the first translation available in the list -# -# In maemo it is in the LANG environment variable -# (on desktop is usually LANGUAGES) -DEFAULT_LANGUAGES = os.environ.get('LANG', '').split('.') -DEFAULT_LANGUAGES += ['en_US'] - -lc, encoding = locale.getdefaultlocale() -if lc: - languages = [lc] - -# Concat all languages (env + default locale), -# and here we have the languages and location of the translations -languages += DEFAULT_LANGUAGES -mo_location = LOCALE_DIR - -# Lets tell those details to gettext -# (nothing to change here for you) -gettext.install(True, localedir=None, unicode=1) - -gettext.find(APP_NAME, mo_location) - -gettext.textdomain (APP_NAME) - -gettext.bind_textdomain_codeset(APP_NAME, "UTF-8") - -language = gettext.translation(APP_NAME, mo_location, languages=languages, fallback=True) diff --git a/pebble/libpebble/pebble/p.py b/pebble/libpebble/pebble/p.py deleted file mode 100755 index da05a9b..0000000 --- a/pebble/libpebble/pebble/p.py +++ /dev/null @@ -1,151 +0,0 @@ -#!/usr/bin/env python - -import argparse -import os -import pebble as libpebble -import time -import pexpect -import tkMessageBox - -from Tkinter import * -from pebble import i18n - -_ = i18n.language.gettext - -MAX_ATTEMPTS = 5 - -window = Tk() -window.wm_withdraw() -window.geometry("1x1+200+200") #remember its .geometry("WidthxHeight(+or-)X(+or-)Y") - -LightBluePebbleError = libpebble.LightBluePebble.LightBluePebbleError -PebbleError = libpebble.pebble.PebbleError - -def cmd_remote(pebble, args): - path=args.odp_file_path - runodp = args.app_name+" --impress "+path - pebble.set_nowplaying_metadata(_("LibreOffice Remote Control "), _("Next"), _("Previous")) - - try: - pexpect.run(runodp, timeout=5) - window_id = pexpect.run("xdotool search --sync --onlyvisible --class \"libreoffice\"") - fullscreen = "xdotool key --window " +window_id+" F5" - pexpect.run(fullscreen) - except Exception: - print _("Something's wrong") - return False - - def libreoffice_event_handler(event): - right_click = "xdotool key --window "+ window_id + "Right" - left_click = "xdotool key --window "+ window_id + "Left" - - if event == "next": - pexpect.run(right_click) - - if event == "previous": - pexpect.run(left_click) - - if event == "exit": - try: - window_ids = pexpect.run("xdotool search --sync --onlyvisible --name \"libreoffice\"").split("\r\n") - window_ids.pop() - window_ids.reverse() - if len(window_ids)>=2: - window_ids[0:2] - altf4_presentation = "xdotool windowactivate --sync "+window_ids[0]+" key --clearmodifiers --delay 100 alt+F4" - altf4_edit = "xdotool windowactivate --sync "+window_ids[1]+" key --clearmodifiers --delay 100 alt+F4" - pexpect.run(altf4_presentation) - pexpect.run(altf4_edit) - if len(window_ids)<2: - altf4_edit = "xdotool windowactivate --sync "+window_ids[0]+" key --clearmodifiers --delay 100 alt+F4" - pexpect.run(altf4_edit) - pexpect.run("exit_click.sh") - except Exception as e: - raise e - print event - - - def music_control_handler(endpoint, resp): - events = { - "PLAYPAUSE": "exit", - "PREVIOUS": "previous", - "NEXT": "next" - } - - libreoffice_event_handler(events[resp]) - - print _("waiting for events") - while True: - try: - pebble.register_endpoint("MUSIC_CONTROL", music_control_handler) - time.sleep(5) - except LightBluePebbleError as e: - tkMessageBox.showerror(title="Error", message=e._message, parent=window) - raise e - raise KeyboardInterrupt - except PebbleError as e: - tkMessageBox.showerror(title="Error", message=e._message, parent=window) - raise e - raise KeyboardInterrupt - except KeyboardInterrupt: - return - -def main(): - parser = argparse.ArgumentParser(description='a utility belt for pebble development') - parser.add_argument('--pebble_id', type=str, help='the last 4 digits of the target Pebble\'s MAC address. \nNOTE: if \ - --lightblue is set, providing a full MAC address (ex: "A0:1B:C0:D3:DC:93") won\'t require the pebble \ - to be discoverable and will be faster') - - parser.add_argument('--lightblue', action="store_true", help='use LightBlue bluetooth API') - parser.add_argument('--pair', action="store_true", help='pair to the pebble from LightBlue bluetooth API before connecting.') - - subparsers = parser.add_subparsers(help='commands', dest='which') - - remote_parser = subparsers.add_parser('remote', help='control LibreOffice Impress app with music app on Pebble') - remote_parser.add_argument('app_name', type=str, help='title of application to be controlled') - remote_parser.add_argument('odp_file_path', type=str, help='path for libreoffice impress presentation file') - remote_parser.set_defaults(func=cmd_remote) - - - args = parser.parse_args() - - attempts = 0 - while True: - if attempts > MAX_ATTEMPTS: - raise _('Could not connect to Pebble') - try: - pebble_id = args.pebble_id - if pebble_id is None and "PEBBLE_ID" in os.environ: - pebble_id = os.environ["PEBBLE_ID"] - pebble = libpebble.Pebble(pebble_id, args.lightblue, args.pair) - break - except LightBluePebbleError as e: - tkMessageBox.showerror(title="Error", message=_("Bluetooth connection error"), parent=window) - raise KeyboardInterrupt - except PebbleError as e: - tkMessageBox.showerror(title="Error", message=e._message, parent=window) - raise e - raise KeyboardInterrupt - except: - time.sleep(5) - attempts += 1 - - try: - args.func(pebble, args) - except LightBluePebbleError as e: - tkMessageBox.showerror(title="Error", message=e._message, parent=window) - raise e - raise KeyboardInterrupt - except PebbleError as e: - tkMessageBox.showerror(title="Error", message=e._message, parent=window) - raise e - raise KeyboardInterrupt - except Exception as e: - pebble.disconnect() - raise e - return - - pebble.disconnect() - -if __name__ == '__main__': - main() diff --git a/pebble/libpebble/pebble/pebble.py b/pebble/libpebble/pebble/pebble.py deleted file mode 100755 index 2496f6d..0000000 --- a/pebble/libpebble/pebble/pebble.py +++ /dev/null @@ -1,539 +0,0 @@ -#!/usr/bin/env python - -import binascii -import glob -import itertools -import json -import logging -import os -import serial -import signal -import stm32_crc -import struct -import threading -import time -import traceback -import uuid -import zipfile - -from collections import OrderedDict -from LightBluePebble import LightBluePebble -from struct import pack, unpack - -log = logging.getLogger() -logging.basicConfig(format='[%(levelname)-8s] %(message)s') -log.setLevel(logging.DEBUG) - -DEFAULT_PEBBLE_ID = None #Triggers autodetection on unix-like systems -DEBUG_PROTOCOL = False - -class EndpointSync(): - timeout = 10 - - def __init__(self, pebble, endpoint): - pebble.register_endpoint(endpoint, self.callback) - self.marker = threading.Event() - - def callback(self, *args): - self.data = args - self.marker.set() - - def get_data(self): - try: - self.marker.wait(timeout=self.timeout) - return self.data[1] - except: - return False - -class PebbleError(Exception): - def __init__(self, id, message): - self._id = id - self._message = message - - def __str__(self): - return "%s (ID:%s)" % (self._message, self._id) - -class Pebble(object): - - """ - A connection to a Pebble watch; data and commands may be sent - to the watch through an instance of this class. - """ - - endpoints = { - "TIME": 11, - "VERSION": 16, - "PHONE_VERSION": 17, - "SYSTEM_MESSAGE": 18, - "MUSIC_CONTROL": 32, - "PHONE_CONTROL": 33, - "APPLICATION_MESSAGE": 48, - "LAUNCHER": 49, - "LOGS": 2000, - "PING": 2001, - "LOG_DUMP": 2002, - "RESET": 2003, - "APP": 2004, - "APP_LOGS": 2006, - "NOTIFICATION": 3000, - "RESOURCE": 4000, - "APP_MANAGER": 6000, - "PUTBYTES": 48879 - } - - log_levels = { - 0: "*", - 1: "E", - 50: "W", - 100: "I", - 200: "D", - 250: "V" - } - - - @staticmethod - def AutodetectDevice(): - if os.name != "posix": #i.e. Windows - raise NotImplementedError("Autodetection is only implemented on UNIX-like systems.") - - pebbles = glob.glob("/dev/tty.Pebble????-SerialPortSe") - - if len(pebbles) == 0: - raise PebbleError(None, "Autodetection could not find any Pebble devices") - elif len(pebbles) > 1: - log.warn("Autodetect found %d Pebbles; using most recent" % len(pebbles)) - #NOTE: Not entirely sure if this is the correct approach - pebbles.sort(key=lambda x: os.stat(x).st_mtime, reverse=True) - - id = pebbles[0][15:19] - log.info("Autodetect found a Pebble with ID %s" % id) - return id - - def __init__(self, id = None, using_lightblue = True, pair_first = False): - if id is None and not using_lightblue: - id = Pebble.AutodetectDevice() - self.id = id - self.using_lightblue = using_lightblue - self._alive = True - self._endpoint_handlers = {} - self._internal_endpoint_handlers = { - self.endpoints["TIME"]: self._get_time_response, - self.endpoints["VERSION"]: self._version_response, - self.endpoints["PHONE_VERSION"]: self._phone_version_response, - self.endpoints["SYSTEM_MESSAGE"]: self._system_message_response, - self.endpoints["MUSIC_CONTROL"]: self._music_control_response, - self.endpoints["APPLICATION_MESSAGE"]: self._application_message_response, - self.endpoints["LAUNCHER"]: self._application_message_response, - self.endpoints["LOGS"]: self._log_response, - self.endpoints["PING"]: self._ping_response, - self.endpoints["APP_LOGS"]: self._app_log_response, - self.endpoints["APP_MANAGER"]: self._appbank_status_response - } - - try: - if using_lightblue: - self._ser = LightBluePebble(self.id, pair_first) - signal.signal(signal.SIGINT, self._exit_signal_handler) - else: - devicefile = "/dev/tty.Pebble"+id+"-SerialPortSe" - log.debug("Attempting to open %s as Pebble device %s" % (devicefile, id)) - self._ser = serial.Serial(devicefile, 115200, timeout=1) - - log.debug("Initializing reader thread") - self._read_thread = threading.Thread(target=self._reader) - self._read_thread.setDaemon(True) - self._read_thread.start() - log.debug("Reader thread loaded on tid %s" % self._read_thread.name) - except PebbleError: - raise PebbleError(id, "Failed to connect to Pebble") - except: - raise - - def _exit_signal_handler(self, signum, frame): - print "Disconnecting before exiting..." - self.disconnect() - time.sleep(1) - os._exit(0) - - def __del__(self): - try: - self._ser.close() - except: - pass - - def _reader(self): - try: - while self._alive: - endpoint, resp = self._recv_message() - if resp == None: - continue - - if endpoint in self._internal_endpoint_handlers: - resp = self._internal_endpoint_handlers[endpoint](endpoint, resp) - - if endpoint in self._endpoint_handlers and resp: - self._endpoint_handlers[endpoint](endpoint, resp) - except: - traceback.print_exc() - raise PebbleError(self.id, "Lost connection to Pebble") - self._alive = False - - def _pack_message_data(self, lead, parts): - pascal = map(lambda x: x[:255], parts) - d = pack("b" + reduce(lambda x,y: str(x) + "p" + str(y), map(lambda x: len(x) + 1, pascal)) + "p", lead, *pascal) - return d - - def _build_message(self, endpoint, data): - return pack("!HH", len(data), endpoint)+data - - def _send_message(self, endpoint, data, callback = None): - if endpoint not in self.endpoints: - raise PebbleError(self.id, "Invalid endpoint specified") - - msg = self._build_message(self.endpoints[endpoint], data) - - if DEBUG_PROTOCOL: - log.debug('>>> ' + msg.encode('hex')) - self._ser.write(msg) - - def _recv_message(self): - if self.using_lightblue: - try: - endpoint, resp, data = self._ser.read() - if resp is None: - return None, None - except TypeError: - # the lightblue process has likely shutdown and cannot be read from - self.alive = False - return None, None - else: - data = self._ser.read(4) - if len(data) == 0: - return (None, None) - elif len(data) < 4: - raise PebbleError(self.id, "Malformed response with length "+str(len(data))) - size, endpoint = unpack("!HH", data) - resp = self._ser.read(size) - - if DEBUG_PROTOCOL: - log.debug("Got message for endpoint %s of length %d" % (endpoint, len(resp))) - log.debug('<<< ' + (data + resp).encode('hex')) - - return (endpoint, resp) - - def register_endpoint(self, endpoint_name, func): - if endpoint_name not in self.endpoints: - raise PebbleError(self.id, "Invalid endpoint specified") - - endpoint = self.endpoints[endpoint_name] - self._endpoint_handlers[endpoint] = func - - def set_nowplaying_metadata(self, track, album, artist): - - """Update the song metadata displayed in Pebble's music app.""" - - parts = [artist[:30], album[:30], track[:30]] - self._send_message("MUSIC_CONTROL", self._pack_message_data(16, parts)) - - def system_message(self, command): - - """ - Send a 'system message' to the watch. - - These messages are used to signal important events/state-changes to the watch firmware. - """ - - commands = { - "FIRMWARE_AVAILABLE": 0, - "FIRMWARE_START": 1, - "FIRMWARE_COMPLETE": 2, - "FIRMWARE_FAIL": 3, - "FIRMWARE_UP_TO_DATE": 4, - "FIRMWARE_OUT_OF_DATE": 5, - "BLUETOOTH_START_DISCOVERABLE": 6, - "BLUETOOTH_END_DISCOVERABLE": 7 - } - if command not in commands: - raise PebbleError(self.id, "Invalid command \"%s\"" % command) - data = pack("!bb", 0, commands[command]) - log.debug("Sending command %s (code %d)" % (command, commands[command])) - self._send_message("SYSTEM_MESSAGE", data) - - def disconnect(self): - - """Disconnect from the target Pebble.""" - - self._alive = False - self._ser.close() - - def _ping_response(self, endpoint, data): - restype, retcookie = unpack("!bL", data) - return retcookie - - def _get_time_response(self, endpoint, data): - restype, timestamp = unpack("!bL", data) - return timestamp - - def _system_message_response(self, endpoint, data): - if len(data) == 2: - log.info("Got system message %s" % repr(unpack('!bb', data))) - else: - log.info("Got 'unknown' system message...") - - def _log_response(self, endpoint, data): - if (len(data) < 8): - log.warn("Unable to decode log message (length %d is less than 8)" % len(data)) - return - - timestamp, level, msgsize, linenumber = unpack("!IBBH", data[:8]) - filename = data[8:24].decode('utf-8') - message = data[24:24+msgsize].decode('utf-8') - - str_level = self.log_levels[level] if level in self.log_levels else "?" - - print timestamp, str_level, filename, linenumber, message - - def _app_log_response(self, endpoint, data): - if (len(data) < 8): - log.warn("Unable to decode log message (length %d is less than 8)" % len(data)) - return - - app_uuid = uuid.UUID(bytes=data[0:16]) - timestamp, level, msgsize, linenumber = unpack("!IBBH", data[16:24]) - filename = data[24:40].decode('utf-8') - message = data[40:40+msgsize].decode('utf-8') - - str_level = self.log_levels[level] if level in self.log_levels else "?" - - print timestamp, str_level, app_uuid, filename, linenumber, message - - def _appbank_status_response(self, endpoint, data): - apps = {} - restype, = unpack("!b", data[0]) - - app_install_message = { - 0: "app available", - 1: "app removed", - 2: "app updated" - } - - if restype == 1: - apps["banks"], apps_installed = unpack("!II", data[1:9]) - apps["apps"] = [] - - appinfo_size = 78 - offset = 9 - for i in xrange(apps_installed): - app = {} - try: - app["id"], app["index"], app["name"], app["company"], app["flags"], app["version"] = \ - unpack("!II32s32sIH", data[offset:offset+appinfo_size]) - app["name"] = app["name"].replace("\x00", "") - app["company"] = app["company"].replace("\x00", "") - apps["apps"] += [app] - except: - if offset+appinfo_size > len(data): - log.warn("Couldn't load bank %d; remaining data = %s" % (i,repr(data[offset:]))) - else: - raise - offset += appinfo_size - - return apps - - elif restype == 2: - message_id = unpack("!I", data[1:]) - message_id = int(''.join(map(str, message_id))) - return app_install_message[message_id] - - def _version_response(self, endpoint, data): - fw_names = { - 0: "normal_fw", - 1: "recovery_fw" - } - - resp = {} - for i in xrange(2): - fwver_size = 47 - offset = i*fwver_size+1 - fw = {} - fw["timestamp"],fw["version"],fw["commit"],fw["is_recovery"], \ - fw["hardware_platform"],fw["metadata_ver"] = \ - unpack("!i32s8s?bb", data[offset:offset+fwver_size]) - - fw["version"] = fw["version"].replace("\x00", "") - fw["commit"] = fw["commit"].replace("\x00", "") - - fw_name = fw_names[i] - resp[fw_name] = fw - - resp["bootloader_timestamp"],resp["hw_version"],resp["serial"] = \ - unpack("!L9s12s", data[95:120]) - - resp["hw_version"] = resp["hw_version"].replace("\x00","") - - btmac_hex = binascii.hexlify(data[120:126]) - resp["btmac"] = ":".join([btmac_hex[i:i+2].upper() for i in reversed(xrange(0, 12, 2))]) - - return resp - - def _application_message_response(self, endpoint, data): - app_messages = { - b'\x01': "PUSH", - b'\x02': "REQUEST", - b'\xFF': "ACK", - b'\x7F': "NACK" - } - - if len(data) > 1: - rest = data[1:] - else: - rest = '' - if data[0] in app_messages: - return app_messages[data[0]] + rest - - - def _phone_version_response(self, endpoint, data): - session_cap = { - "GAMMA_RAY" : 0x80000000, - } - remote_cap = { - "TELEPHONY" : 16, - "SMS" : 32, - "GPS" : 64, - "BTLE" : 128, - "CAMERA_REAR" : 256, - "ACCEL" : 512, - "GYRO" : 1024, - "COMPASS" : 2048, - } - os = { - "UNKNOWN" : 0, - "IOS" : 1, - "ANDROID" : 2, - "OSX" : 3, - "LINUX" : 4, - "WINDOWS" : 5, - } - - # Then session capabilities, android adds GAMMA_RAY and it's - # the only session flag so far - session = session_cap["GAMMA_RAY"] - - # Then phone capabilities, android app adds TELEPHONY and SMS, - # and the phone type (we know android works for now) - remote = remote_cap["TELEPHONY"] | remote_cap["SMS"] | os["ANDROID"] - - msg = pack("!biII", 1, -1, session, remote) - self._send_message("PHONE_VERSION", msg); - - def _music_control_response(self, endpoint, data): - event, = unpack("!b", data) - - event_names = { - 1: "PLAYPAUSE", - 4: "NEXT", - 5: "PREVIOUS", - } - - return event_names[event] if event in event_names else None - -class PutBytesClient(object): - states = { - "NOT_STARTED": 0, - "WAIT_FOR_TOKEN": 1, - "IN_PROGRESS": 2, - "COMMIT": 3, - "COMPLETE": 4, - "FAILED": 5 - } - - transfer_types = { - "FIRMWARE": 1, - "RECOVERY": 2, - "SYS_RESOURCES": 3, - "RESOURCES": 4, - "BINARY": 5 - } - - def __init__(self, pebble, index, transfer_type, buffer): - self._pebble = pebble - self._state = self.states["NOT_STARTED"] - self._transfer_type = self.transfer_types[transfer_type] - self._buffer = buffer - self._index = index - self._done = False - self._error = False - - def init(self): - data = pack("!bIbb", 1, len(self._buffer), self._transfer_type, self._index) - self._pebble._send_message("PUTBYTES", data) - self._state = self.states["WAIT_FOR_TOKEN"] - - def wait_for_token(self, resp): - res, = unpack("!b", resp[0]) - if res != 1: - log.error("init failed with code %d" % res) - self._error = True - return - self._token, = unpack("!I", resp[1:]) - self._left = len(self._buffer) - self._state = self.states["IN_PROGRESS"] - self.send() - - def in_progress(self, resp): - res, = unpack("!b", resp[0]) - if res != 1: - self.abort() - return - if self._left > 0: - self.send() - log.debug("Sent %d of %d bytes" % (len(self._buffer)-self._left, len(self._buffer))) - else: - self._state = self.states["COMMIT"] - self.commit() - - def commit(self): - data = pack("!bII", 3, self._token & 0xFFFFFFFF, stm32_crc.crc32(self._buffer)) - self._pebble._send_message("PUTBYTES", data) - - def handle_commit(self, resp): - res, = unpack("!b", resp[0]) - if res != 1: - self.abort() - return - self._state = self.states["COMPLETE"] - self.complete() - - def complete(self): - data = pack("!bI", 5, self._token & 0xFFFFFFFF) - self._pebble._send_message("PUTBYTES", data) - - def handle_complete(self, resp): - res, = unpack("!b", resp[0]) - if res != 1: - self.abort() - return - self._done = True - - def abort(self): - msgdata = pack("!bI", 4, self._token & 0xFFFFFFFF) - self._pebble.send_message("PUTBYTES", msgdata) - self._error = True - - def send(self): - datalen = min(self._left, 2000) - rg = len(self._buffer)-self._left - msgdata = pack("!bII", 2, self._token & 0xFFFFFFFF, datalen) - msgdata += self._buffer[rg:rg+datalen] - self._pebble._send_message("PUTBYTES", msgdata) - self._left -= datalen - - def handle_message(self, endpoint, resp): - if self._state == self.states["WAIT_FOR_TOKEN"]: - self.wait_for_token(resp) - elif self._state == self.states["IN_PROGRESS"]: - self.in_progress(resp) - elif self._state == self.states["COMMIT"]: - self.handle_commit(resp) - elif self._state == self.states["COMPLETE"]: - self.handle_complete(resp) diff --git a/pebble/libpebble/pebble/stm32_crc.py b/pebble/libpebble/pebble/stm32_crc.py deleted file mode 100644 index cfc5ff7..0000000 --- a/pebble/libpebble/pebble/stm32_crc.py +++ /dev/null @@ -1,37 +0,0 @@ -import array -import sys - -CRC_POLY = 0x04C11DB7 - -def process_word(data, crc=0xffffffff): - if (len(data) < 4): - d_array = array.array('B', data) - for x in range(0, 4 - len(data)): - d_array.insert(0,0) - d_array.reverse() - data = d_array.tostring() - - d = array.array('I', data)[0] - crc = crc ^ d - - for i in xrange(0, 32): - if (crc & 0x80000000) != 0: - crc = (crc << 1) ^ CRC_POLY - else: - crc = (crc << 1) - - result = crc & 0xffffffff - return result - -def process_buffer(buf, c = 0xffffffff): - word_count = len(buf) / 4 - if (len(buf) % 4 != 0): - word_count += 1 - - crc = c - for i in xrange(0, word_count): - crc = process_word(buf[i * 4 : (i + 1) * 4], crc) - return crc - -def crc32(data): - return process_buffer(data) diff --git a/pebble/libpebble/setup.py b/pebble/libpebble/setup.py deleted file mode 100644 index 51b3767..0000000 --- a/pebble/libpebble/setup.py +++ /dev/null @@ -1,34 +0,0 @@ -from setuptools import setup - -setup(name='pebble-remote', - version='2.0', - description='Remote control for LibreOffice Impress with Pebble', - url='https://github.com/LibreOffice/impress_remote/tree/master/pebble', - author='Gulsah KOSE', - author_email='gulsah.1004@gmail.com', - license='MPLv2', - packages=['pebble'], - scripts=[ - 'pebble/p.py', - 'pebble/data/scripts/pebble-remote', - 'pebble/data/scripts/exit_click.sh' - ], - package_data={ - 'data/i18n/ca/LC_MESSAGES': ['pebble-remote.mo'], - 'data/i18n/tr/LC_MESSAGES': ['pebble-remote.mo'], - 'data/i18n/es/LC_MESSAGES': ['pebble-remote.mo'], - 'data/i18n/it/LC_MESSAGES': ['pebble-remote.mo'], - 'data/mimetype': ['pebble-remote','pebble-remote.png','pebble-remote.desktop'] - }, - data_files=[ - ('/opt/pebble/i18n/ca/LC_MESSAGES', ['pebble/data/i18n/ca/LC_MESSAGES/pebble-remote.mo']), - ('/opt/pebble/i18n/tr/LC_MESSAGES', ['pebble/data/i18n/tr/LC_MESSAGES/pebble-remote.mo']), - ('/opt/pebble/i18n/es/LC_MESSAGES', ['pebble/data/i18n/es/LC_MESSAGES/pebble-remote.mo']), - ('/opt/pebble/i18n/it/LC_MESSAGES', ['pebble/data/i18n/it/LC_MESSAGES/pebble-remote.mo']), - ('/usr/share/man/man1', ['pebble/data/man/pebble-remote.1.gz']), - ('/usr/share/applications', ['pebble/data/mimetype/pebble-remote.desktop']), - ('/usr/share/menu', ['pebble/data/mimetype/pebble-remote']), - ('/usr/share/pixmaps', ['pebble/data/mimetype/pebble-remote.png']) - ], - install_requires = ['setuptools'], - zip_safe=False) diff --git a/pebble/libpebble/stm32_crc.py b/pebble/libpebble/stm32_crc.py new file mode 100644 index 0000000..cfc5ff7 --- /dev/null +++ b/pebble/libpebble/stm32_crc.py @@ -0,0 +1,37 @@ +import array +import sys + +CRC_POLY = 0x04C11DB7 + +def process_word(data, crc=0xffffffff): + if (len(data) < 4): + d_array = array.array('B', data) + for x in range(0, 4 - len(data)): + d_array.insert(0,0) + d_array.reverse() + data = d_array.tostring() + + d = array.array('I', data)[0] + crc = crc ^ d + + for i in xrange(0, 32): + if (crc & 0x80000000) != 0: + crc = (crc << 1) ^ CRC_POLY + else: + crc = (crc << 1) + + result = crc & 0xffffffff + return result + +def process_buffer(buf, c = 0xffffffff): + word_count = len(buf) / 4 + if (len(buf) % 4 != 0): + word_count += 1 + + crc = c + for i in xrange(0, word_count): + crc = process_word(buf[i * 4 : (i + 1) * 4], crc) + return crc + +def crc32(data): + return process_buffer(data) diff --git a/pebble/pebble_remote/LICENCE b/pebble/pebble_remote/LICENCE new file mode 100644 index 0000000..735331f --- /dev/null +++ b/pebble/pebble_remote/LICENCE @@ -0,0 +1,159 @@ +Mozilla Public License +Version 2.0 +1. Definitions + +1.1. “Contributor” + + means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. +1.2. “Contributor Version” + + means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor’s Contribution. +1.3. “Contribution” + + means Covered Software of a particular Contributor. +1.4. “Covered Software” + + means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. +1.5. “Incompatible With Secondary Licenses” + + means + + that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or + + that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. + +1.6. “Executable Form” + + means any form of the work other than Source Code Form. +1.7. “Larger Work” + + means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. +1.8. “License” + + means this document. +1.9. “Licensable” + + means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. +1.10. “Modifications” + + means any of the following: + + any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or + + any new file in Source Code Form that contains any Covered Software. + +1.11. “Patent Claims” of a Contributor + + means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. +1.12. “Secondary License” + + means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. +1.13. “Source Code Form” + + means the form of the work preferred for making modifications. +1.14. “You” (or “Your”) + + means an individual or a legal entity exercising rights under this License. For legal entities, “You” includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, “control” means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. + +2. License Grants and Conditions +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: + + under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and + + under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: + + for any code that a Contributor has removed from Covered Software; or + + for infringements caused by: (i) Your and any other third party’s modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or + + under Patent Claims infringed by Covered Software in the absence of its Contributions. + +This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). +2.5. Representation + +Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. +2.6. Fair Use + +This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. +3. Responsibilities +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients’ rights in the Source Code Form. +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + + such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and + + You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients’ rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). +3.4. Notices + +You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. +4. Inability to Comply Due to Statute or Regulation + +If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. +5. Termination + +5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. +6. Disclaimer of Warranty + +Covered Software is provided under this License on an “as is” basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer. +7. Limitation of Liability + +Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such party’s negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You. +8. Litigation + +Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party’s ability to bring cross-claims or counter-claims. +9. Miscellaneous + +This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. +10. Versions of the License +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. +10.3. Modified Versions + +If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). +10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses + +If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. +Exhibit A - Source Code Form License Notice + + This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. + +You may add additional accurate notices of copyright ownership. +Exhibit B - “Incompatible With Secondary Licenses” Notice + + This Source Code Form is “Incompatible With Secondary Licenses”, as defined by the Mozilla Public License, v. 2.0. + diff --git a/pebble/pebble_remote/__init__.py b/pebble/pebble_remote/__init__.py new file mode 100644 index 0000000..314b9fa --- /dev/null +++ b/pebble/pebble_remote/__init__.py @@ -0,0 +1 @@ +#__init__.py diff --git a/pebble/pebble_remote/data/i18n/ca/LC_MESSAGES/pebble-remote.mo b/pebble/pebble_remote/data/i18n/ca/LC_MESSAGES/pebble-remote.mo new file mode 100644 index 0000000..e7ee00a Binary files /dev/null and b/pebble/pebble_remote/data/i18n/ca/LC_MESSAGES/pebble-remote.mo differ diff --git a/pebble/pebble_remote/data/i18n/es/LC_MESSAGES/pebble-remote.mo b/pebble/pebble_remote/data/i18n/es/LC_MESSAGES/pebble-remote.mo new file mode 100644 index 0000000..0f3a4b1 Binary files /dev/null and b/pebble/pebble_remote/data/i18n/es/LC_MESSAGES/pebble-remote.mo differ diff --git a/pebble/pebble_remote/data/i18n/it/LC_MESSAGES/pebble-remote.mo b/pebble/pebble_remote/data/i18n/it/LC_MESSAGES/pebble-remote.mo new file mode 100644 index 0000000..5139aec Binary files /dev/null and b/pebble/pebble_remote/data/i18n/it/LC_MESSAGES/pebble-remote.mo differ diff --git a/pebble/pebble_remote/data/i18n/tr/LC_MESSAGES/pebble-remote.mo b/pebble/pebble_remote/data/i18n/tr/LC_MESSAGES/pebble-remote.mo new file mode 100644 index 0000000..d2c966b Binary files /dev/null and b/pebble/pebble_remote/data/i18n/tr/LC_MESSAGES/pebble-remote.mo differ diff --git a/pebble/pebble_remote/data/man/pebble-remote.1.gz b/pebble/pebble_remote/data/man/pebble-remote.1.gz new file mode 100644 index 0000000..08bb9a8 Binary files /dev/null and b/pebble/pebble_remote/data/man/pebble-remote.1.gz differ diff --git a/pebble/pebble_remote/data/mimetype/pebble-remote b/pebble/pebble_remote/data/mimetype/pebble-remote new file mode 100644 index 0000000..fabdc8b --- /dev/null +++ b/pebble/pebble_remote/data/mimetype/pebble-remote @@ -0,0 +1,5 @@ +?package(pebble-remote):needs="X11" section="Applications/Office"\ + title="Pebble Remote" command="/usr/bin/pebble-remote"\ + hints="Presentation"\ + kderemove="y"\ + icon="/usr/share/icons/hicolor/32x32/apps/libreoffice-impress.xpm" diff --git a/pebble/pebble_remote/data/mimetype/pebble-remote.desktop b/pebble/pebble_remote/data/mimetype/pebble-remote.desktop new file mode 100644 index 0000000..e3c0335 --- /dev/null +++ b/pebble/pebble_remote/data/mimetype/pebble-remote.desktop @@ -0,0 +1,33 @@ +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# This file incorporates work covered by the following license notice: +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to you under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of +# the License at http://www.apache.org/licenses/LICENSE-2.0 . +# +[Desktop Entry] +Version=2.0 +Terminal=false +Icon=/usr/share/pixmaps/pebble-remote.png +Type=Application +Categories=Office;Presentation;X-Red-Hat-Base;X-MandrivaLinux-Office-Presentations; +Exec=pebble-remote %U +MimeType=application/vnd.oasis.opendocument.presentation;application/vnd.oasis.opendocument.presentation-template;application/vnd.sun.xml.impress;application/vnd.sun.xml.impress.template;application/mspowerpoint;application/vnd.ms-powerpoint;application/vnd.openxmlformats-officedocument.presentationml.presentation;application/vnd.ms-powerpoint.presentation.macroenabled.12;application/vnd.openxmlformats-officedocument.presentationml.template;application/vnd.ms-powerpoint.template.macroenabled.12;application/vnd.openxmlformats-officedocument.presentationml.slide;application/vnd.openxmlformats-officedocument.presentationml.slideshow;application/vnd.ms-powerpoint.slideshow.macroEnabled.12;application/vnd.oasis.opendocument.presentation-flat-xml;application/x-iwork-keynote-sffkey; +Name=Pebble Remote +GenericName=Presentation +Comment=Pebble remote control for LibreOffice Impress. +StartupNotify=true +Keywords=Slideshow;Slides;OpenDocument Presentation;Microsoft PowerPoint;Microsoft Works;OpenOffice Impress;odp;ppt;pptx; +InitialPreference=5 +StartupWMClass=libreoffice-impress +X-KDE-Protocols=file,http,smb,ftp,webdav diff --git a/pebble/pebble_remote/data/mimetype/pebble-remote.png b/pebble/pebble_remote/data/mimetype/pebble-remote.png new file mode 100644 index 0000000..0f2090a Binary files /dev/null and b/pebble/pebble_remote/data/mimetype/pebble-remote.png differ diff --git a/pebble/pebble_remote/data/scripts/exit_click.sh b/pebble/pebble_remote/data/scripts/exit_click.sh new file mode 100755 index 0000000..bbfb104 --- /dev/null +++ b/pebble/pebble_remote/data/scripts/exit_click.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +ps aux | grep p.py | sed 's/\s\+/ /g' | cut -d' ' -f2 | xargs kill diff --git a/pebble/pebble_remote/data/scripts/pebble-remote b/pebble/pebble_remote/data/scripts/pebble-remote new file mode 100755 index 0000000..83a0599 --- /dev/null +++ b/pebble/pebble_remote/data/scripts/pebble-remote @@ -0,0 +1,25 @@ +#!/bin/bash + +export PEBBLE_ID=`bt-device -l | grep Pebble | cut -d ' ' -f3 | cut -c2-18` +export PARAMETERS=--lightblue +export SUBCOMMAND=remote +export APP_NAME=libreoffice + +if [ "$1" == "-h" ] || [ "$1" == "--help" ]; +then + + echo "Usage: `basename $0` [path_to_odp_file]" + exit 0 + +elif [ "$1" == "-v" ] || [ "$1" == "--version" ]; +then + + echo "2.0" + exit 0 + +else + + p.py --pebble_id $PEBBLE_ID $PARAMETERS $SUBCOMMAND $APP_NAME $1 + +fi + diff --git a/pebble/pebble_remote/i18n.py b/pebble/pebble_remote/i18n.py new file mode 100644 index 0000000..272ccbf --- /dev/null +++ b/pebble/pebble_remote/i18n.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- + +import os, sys +import locale +import gettext + +# Change this variable to your app name! +# The translation files will be under +# @LOCALE_DIR@/@LANGUAGE@/LC_MESSAGES/@APP_NAME@.mo +APP_NAME = "pebble-remote" + +# This is ok for maemo. Not sure in a regular desktop: +APP_DIR = os.path.dirname(os.path.abspath("/opt/pebble/i18n")) #APP_DIR returns pebble-rmeote project path on your system +LOCALE_DIR = os.path.join(APP_DIR, 'i18n') # .mo files will then be located in APP_Dir/i18n/LANGUAGECODE/LC_MESSAGES/ + +# Now we need to choose the language. We will provide a list, and gettext +# will use the first translation available in the list +# +# In maemo it is in the LANG environment variable +# (on desktop is usually LANGUAGES) +DEFAULT_LANGUAGES = os.environ.get('LANG', '').split('.') +DEFAULT_LANGUAGES += ['en_US'] + +lc, encoding = locale.getdefaultlocale() +if lc: + languages = [lc] + +# Concat all languages (env + default locale), +# and here we have the languages and location of the translations +languages += DEFAULT_LANGUAGES +mo_location = LOCALE_DIR + +# Lets tell those details to gettext +# (nothing to change here for you) +gettext.install(True, localedir=None, unicode=1) + +gettext.find(APP_NAME, mo_location) + +gettext.textdomain (APP_NAME) + +gettext.bind_textdomain_codeset(APP_NAME, "UTF-8") + +language = gettext.translation(APP_NAME, mo_location, languages=languages, fallback=True) diff --git a/pebble/setup.py b/pebble/setup.py new file mode 100644 index 0000000..c0eca35 --- /dev/null +++ b/pebble/setup.py @@ -0,0 +1,34 @@ +from setuptools import setup + +setup(name='pebble-remote', + version='2.0', + description='Remote control for LibreOffice Impress with Pebble', + url='https://github.com/LibreOffice/impress_remote/tree/master/pebble', + author='Gulsah KOSE', + author_email='gulsah.1004@gmail.com', + license='MPLv2', + packages=['pebble_remote','libpebble'], + scripts=[ + 'libpebble/p.py', + 'pebble_remote/data/scripts/pebble-remote', + 'pebble_remote/data/scripts/exit_click.sh' + ], + package_data={ + 'pebble_remote/data/i18n/ca/LC_MESSAGES': ['pebble-remote.mo'], + 'pebble_remote/data/i18n/tr/LC_MESSAGES': ['pebble-remote.mo'], + 'pebble_remote/data/i18n/es/LC_MESSAGES': ['pebble-remote.mo'], + 'pebble_remote/data/i18n/it/LC_MESSAGES': ['pebble-remote.mo'], + 'pebble_remote/data/mimetype': ['pebble-remote','pebble-remote.png','pebble-remote.desktop'] + }, + data_files=[ + ('/opt/pebble/i18n/ca/LC_MESSAGES', ['pebble_remote/data/i18n/ca/LC_MESSAGES/pebble-remote.mo']), + ('/opt/pebble/i18n/tr/LC_MESSAGES', ['pebble_remote/data/i18n/tr/LC_MESSAGES/pebble-remote.mo']), + ('/opt/pebble/i18n/es/LC_MESSAGES', ['pebble_remote/data/i18n/es/LC_MESSAGES/pebble-remote.mo']), + ('/opt/pebble/i18n/it/LC_MESSAGES', ['pebble_remote/data/i18n/it/LC_MESSAGES/pebble-remote.mo']), + ('/usr/share/man/man1', ['pebble_remote/data/man/pebble-remote.1.gz']), + ('/usr/share/applications', ['pebble_remote/data/mimetype/pebble-remote.desktop']), + ('/usr/share/menu', ['pebble_remote/data/mimetype/pebble-remote']), + ('/usr/share/pixmaps', ['pebble_remote/data/mimetype/pebble-remote.png']) + ], + install_requires = ['setuptools'], + zip_safe=False) -- cgit v1.2.3