2018-01-22 04:28:35 +01:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
#
|
|
|
|
# This program is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation; either version 2 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
|
|
|
|
from gi.repository import GObject, Gio, GLib
|
|
|
|
import sys
|
|
|
|
import argparse
|
2018-02-13 20:01:56 +01:00
|
|
|
import binascii
|
2018-01-26 11:20:36 +01:00
|
|
|
import cmd
|
2018-01-30 14:01:48 +01:00
|
|
|
import errno
|
2018-01-24 12:06:16 +01:00
|
|
|
import os
|
2018-01-23 04:36:29 +01:00
|
|
|
import json
|
2018-01-22 04:28:35 +01:00
|
|
|
import logging
|
2018-01-26 17:05:50 +01:00
|
|
|
import re
|
2018-01-26 12:33:37 +01:00
|
|
|
import readline
|
2018-02-13 20:01:56 +01:00
|
|
|
import struct
|
2018-01-26 11:20:36 +01:00
|
|
|
import threading
|
2018-01-23 04:36:29 +01:00
|
|
|
import time
|
2018-01-25 05:52:56 +01:00
|
|
|
import svgwrite
|
2018-02-06 15:13:08 +01:00
|
|
|
import xdg.BaseDirectory
|
|
|
|
|
|
|
|
|
|
|
|
CONFIG_PATH = os.path.join(xdg.BaseDirectory.xdg_data_home, 'tuhi-kete')
|
2018-01-22 04:28:35 +01:00
|
|
|
|
2018-01-23 18:18:05 +01:00
|
|
|
|
2018-01-29 01:59:08 +01:00
|
|
|
class ColorFormatter(logging.Formatter):
|
|
|
|
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, LIGHT_GRAY = range(30, 38)
|
|
|
|
DARK_GRAY, LIGHT_RED, LIGHT_GREEN, LIGHT_YELLOW, LIGHT_BLUE, LIGHT_MAGENTA, LIGHT_CYAN, WHITE = range(90, 98)
|
|
|
|
COLORS = {
|
|
|
|
'WARNING': LIGHT_RED,
|
|
|
|
'INFO': LIGHT_GREEN,
|
|
|
|
'DEBUG': LIGHT_GRAY,
|
|
|
|
'CRITICAL': YELLOW,
|
|
|
|
'ERROR': RED,
|
|
|
|
}
|
2018-01-29 12:04:51 +01:00
|
|
|
RESET_SEQ = '\033[0m'
|
|
|
|
COLOR_SEQ = '\033[%dm'
|
|
|
|
BOLD_SEQ = '\033[1m'
|
2018-01-29 01:59:08 +01:00
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
logging.Formatter.__init__(self, *args, **kwargs)
|
|
|
|
|
|
|
|
def format(self, record):
|
|
|
|
levelname = record.levelname
|
|
|
|
color = self.COLOR_SEQ % (self.COLORS[levelname])
|
|
|
|
message = logging.Formatter.format(self, record)
|
2018-01-29 12:04:51 +01:00
|
|
|
message = message.replace('$RESET', self.RESET_SEQ)\
|
|
|
|
.replace('$BOLD', self.BOLD_SEQ)\
|
|
|
|
.replace('$COLOR', color)
|
2018-01-29 01:59:08 +01:00
|
|
|
for k, v in self.COLORS.items():
|
2018-01-29 12:04:51 +01:00
|
|
|
message = message.replace('$' + k, self.COLOR_SEQ % (v + 30))
|
2018-01-29 01:59:08 +01:00
|
|
|
return message + self.RESET_SEQ
|
|
|
|
|
|
|
|
|
|
|
|
log_format = '$COLOR%(levelname)s: %(message)s'
|
2018-01-23 18:18:05 +01:00
|
|
|
logger_handler = logging.StreamHandler()
|
2018-01-29 01:59:08 +01:00
|
|
|
logger_handler.setFormatter(ColorFormatter(log_format))
|
2018-01-22 04:28:35 +01:00
|
|
|
logger = logging.getLogger('tuhi-kete')
|
2018-01-23 18:18:05 +01:00
|
|
|
logger.addHandler(logger_handler)
|
|
|
|
logger.setLevel(logging.INFO)
|
2018-01-22 04:28:35 +01:00
|
|
|
|
|
|
|
TUHI_DBUS_NAME = 'org.freedesktop.tuhi1'
|
|
|
|
ORG_FREEDESKTOP_TUHI1_MANAGER = 'org.freedesktop.tuhi1.Manager'
|
|
|
|
ORG_FREEDESKTOP_TUHI1_DEVICE = 'org.freedesktop.tuhi1.Device'
|
|
|
|
ROOT_PATH = '/org/freedesktop/tuhi1'
|
|
|
|
|
2018-02-01 00:40:33 +01:00
|
|
|
ORG_BLUEZ_DEVICE1 = 'org.bluez.Device1'
|
|
|
|
|
2018-01-29 11:09:02 +01:00
|
|
|
# remove ':' from the completer delimiters of readline so we can match on
|
|
|
|
# device addresses
|
|
|
|
completer_delims = readline.get_completer_delims()
|
|
|
|
completer_delims = completer_delims.replace(':', '')
|
|
|
|
readline.set_completer_delims(completer_delims)
|
|
|
|
|
2018-01-22 04:28:35 +01:00
|
|
|
|
2018-02-13 20:01:56 +01:00
|
|
|
def b2hex(bs):
|
|
|
|
'''Convert bytes() to a two-letter hex string in the form "1a 2b c3"'''
|
|
|
|
hx = binascii.hexlify(bs).decode('ascii')
|
|
|
|
return ' '.join([''.join(s) for s in zip(hx[::2], hx[1::2])])
|
|
|
|
|
|
|
|
|
2018-01-22 04:28:35 +01:00
|
|
|
class DBusError(Exception):
|
|
|
|
def __init__(self, message):
|
|
|
|
self.message = message
|
|
|
|
|
|
|
|
|
|
|
|
class _DBusObject(GObject.Object):
|
|
|
|
_connection = None
|
|
|
|
|
|
|
|
def __init__(self, name, interface, objpath):
|
|
|
|
GObject.GObject.__init__(self)
|
|
|
|
|
|
|
|
if _DBusObject._connection is None:
|
|
|
|
self._connect_to_session()
|
|
|
|
|
|
|
|
self.interface = interface
|
|
|
|
self.objpath = objpath
|
|
|
|
|
|
|
|
try:
|
2018-02-01 00:40:33 +01:00
|
|
|
self.proxy = Gio.DBusProxy.new_sync(self._connection,
|
2018-01-22 04:28:35 +01:00
|
|
|
Gio.DBusProxyFlags.NONE, None,
|
|
|
|
name, objpath, interface, None)
|
|
|
|
except GLib.Error as e:
|
|
|
|
if (e.domain == 'g-io-error-quark' and
|
|
|
|
e.code == Gio.IOErrorEnum.DBUS_ERROR):
|
|
|
|
raise DBusError(e.message)
|
|
|
|
else:
|
|
|
|
raise e
|
|
|
|
|
|
|
|
if self.proxy.get_name_owner() is None:
|
2018-01-29 11:38:14 +01:00
|
|
|
raise DBusError(f'No-one is handling {name}, is the daemon running?')
|
2018-01-22 04:28:35 +01:00
|
|
|
|
|
|
|
self.proxy.connect('g-properties-changed', self._on_properties_changed)
|
|
|
|
self.proxy.connect('g-signal', self._on_signal_received)
|
|
|
|
|
|
|
|
def _connect_to_session(self):
|
|
|
|
try:
|
|
|
|
_DBusObject._connection = Gio.bus_get_sync(Gio.BusType.SESSION, None)
|
|
|
|
except GLib.Error as e:
|
|
|
|
if (e.domain == 'g-io-error-quark' and
|
|
|
|
e.code == Gio.IOErrorEnum.DBUS_ERROR):
|
|
|
|
raise DBusError(e.message)
|
|
|
|
else:
|
|
|
|
raise e
|
|
|
|
|
|
|
|
def _on_properties_changed(self, proxy, changed_props, invalidated_props):
|
|
|
|
# Implement this in derived classes to respond to property changes
|
|
|
|
pass
|
|
|
|
|
|
|
|
def _on_signal_received(self, proxy, sender, signal, parameters):
|
|
|
|
# Implement this in derived classes to respond to signals
|
|
|
|
pass
|
|
|
|
|
|
|
|
def property(self, name):
|
|
|
|
p = self.proxy.get_cached_property(name)
|
|
|
|
if p is not None:
|
|
|
|
return p.unpack()
|
|
|
|
return p
|
|
|
|
|
2018-01-31 19:22:44 +01:00
|
|
|
def terminate(self):
|
|
|
|
del(self.proxy)
|
|
|
|
|
2018-01-22 04:28:35 +01:00
|
|
|
|
2018-02-01 00:40:33 +01:00
|
|
|
class _DBusSystemObject(_DBusObject):
|
|
|
|
'''
|
|
|
|
Same as the _DBusObject, but connects to the system bus instead
|
|
|
|
'''
|
|
|
|
def __init__(self, name, interface, objpath):
|
|
|
|
self._connect_to_system()
|
|
|
|
super().__init__(name, interface, objpath)
|
|
|
|
|
|
|
|
def _connect_to_system(self):
|
|
|
|
try:
|
|
|
|
self._connection = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
|
|
|
|
except GLib.Error as e:
|
|
|
|
if (e.domain == 'g-io-error-quark' and
|
|
|
|
e.code == Gio.IOErrorEnum.DBUS_ERROR):
|
|
|
|
raise DBusError(e.message)
|
|
|
|
else:
|
|
|
|
raise e
|
|
|
|
|
|
|
|
|
|
|
|
class BlueZDevice(_DBusSystemObject):
|
|
|
|
def __init__(self, objpath):
|
|
|
|
super().__init__('org.bluez', ORG_BLUEZ_DEVICE1, objpath)
|
2018-02-13 20:01:56 +01:00
|
|
|
self.proxy.connect('g-properties-changed', self._on_properties_changed)
|
|
|
|
|
|
|
|
@GObject.Property
|
|
|
|
def connected(self):
|
|
|
|
return self.proxy.get_cached_property('Connected').unpack()
|
|
|
|
|
|
|
|
def _on_properties_changed(self, obj, properties, invalidated_properties):
|
|
|
|
properties = properties.unpack()
|
|
|
|
|
|
|
|
if 'Connected' in properties:
|
|
|
|
self.notify('connected')
|
2018-02-01 00:40:33 +01:00
|
|
|
|
|
|
|
|
2018-01-22 04:28:35 +01:00
|
|
|
class TuhiKeteDevice(_DBusObject):
|
|
|
|
def __init__(self, manager, objpath):
|
|
|
|
_DBusObject.__init__(self, TUHI_DBUS_NAME,
|
|
|
|
ORG_FREEDESKTOP_TUHI1_DEVICE,
|
|
|
|
objpath)
|
|
|
|
self.manager = manager
|
2018-02-02 00:28:26 +01:00
|
|
|
self.is_registering = False
|
2018-02-13 20:01:56 +01:00
|
|
|
self.live = False
|
2018-02-01 00:40:33 +01:00
|
|
|
self._bluez_device = BlueZDevice(self.property('BlueZDevice'))
|
2018-02-13 20:01:56 +01:00
|
|
|
self._bluez_device.connect('notify::connected', self._on_connected)
|
2018-01-22 04:28:35 +01:00
|
|
|
|
2018-01-26 17:05:50 +01:00
|
|
|
@classmethod
|
|
|
|
def is_device_address(cls, string):
|
2018-01-29 12:04:51 +01:00
|
|
|
if re.match(r'[0-9a-f]{2}(:[0-9a-f]{2}){5}$', string.lower()):
|
2018-01-26 17:05:50 +01:00
|
|
|
return string
|
|
|
|
raise argparse.ArgumentTypeError(f'"{string}" is not a valid device address')
|
|
|
|
|
2018-01-22 04:28:35 +01:00
|
|
|
@GObject.Property
|
|
|
|
def address(self):
|
2018-02-01 00:40:33 +01:00
|
|
|
return self._bluez_device.property('Address')
|
2018-01-22 04:28:35 +01:00
|
|
|
|
|
|
|
@GObject.Property
|
|
|
|
def name(self):
|
2018-02-01 00:40:33 +01:00
|
|
|
return self._bluez_device.property('Name')
|
2018-01-22 04:28:35 +01:00
|
|
|
|
2018-01-23 02:29:22 +01:00
|
|
|
@GObject.Property
|
|
|
|
def listening(self):
|
|
|
|
return self.property('Listening')
|
|
|
|
|
2018-01-23 02:34:22 +01:00
|
|
|
@GObject.Property
|
|
|
|
def drawings_available(self):
|
|
|
|
return self.property('DrawingsAvailable')
|
|
|
|
|
2018-01-29 04:44:02 +01:00
|
|
|
@GObject.Property
|
|
|
|
def battery_percent(self):
|
|
|
|
return self.property('BatteryPercent')
|
|
|
|
|
|
|
|
@GObject.Property
|
|
|
|
def battery_state(self):
|
|
|
|
return self.property('BatteryState')
|
|
|
|
|
2018-02-13 20:01:56 +01:00
|
|
|
@GObject.Property
|
|
|
|
def connected(self):
|
|
|
|
return self._bluez_device.connected
|
|
|
|
|
|
|
|
def _on_connected(self, bluez_device, pspec):
|
|
|
|
self.notify('connected')
|
|
|
|
|
2018-02-02 00:28:26 +01:00
|
|
|
def register(self):
|
|
|
|
logger.debug(f'{self}: Register')
|
|
|
|
# FIXME: Register() doesn't return anything useful yet, so we wait until
|
2018-01-22 04:28:35 +01:00
|
|
|
# the device is in the Manager's Devices property
|
2018-01-31 19:22:44 +01:00
|
|
|
self.s1 = self.manager.connect('notify::devices', self._on_mgr_devices_updated)
|
2018-02-02 00:28:26 +01:00
|
|
|
self.is_registering = True
|
|
|
|
self.proxy.Register()
|
2018-01-22 04:28:35 +01:00
|
|
|
|
2018-01-23 02:29:22 +01:00
|
|
|
def start_listening(self):
|
|
|
|
self.proxy.StartListening()
|
|
|
|
|
|
|
|
def stop_listening(self):
|
2018-02-13 13:55:57 +01:00
|
|
|
try:
|
|
|
|
self.proxy.StopListening()
|
|
|
|
except GLib.Error as e:
|
|
|
|
if (e.domain != 'g-dbus-error-quark' or
|
|
|
|
e.code != Gio.IOErrorEnum.EXISTS or
|
|
|
|
Gio.dbus_error_get_remote_error(e) != 'org.freedesktop.DBus.Error.ServiceUnknown'):
|
|
|
|
raise e
|
2018-01-23 02:29:22 +01:00
|
|
|
|
2018-02-13 20:01:56 +01:00
|
|
|
def start_live(self, fd):
|
2018-02-13 20:01:56 +01:00
|
|
|
fd_list = Gio.UnixFDList.new()
|
|
|
|
fd_list.append(fd)
|
|
|
|
|
|
|
|
res, fds = self.proxy.call_with_unix_fd_list_sync('org.freedesktop.tuhi1.Device.StartLive',
|
|
|
|
GLib.Variant('(h)', (fd,)),
|
|
|
|
Gio.DBusCallFlags.NO_AUTO_START,
|
|
|
|
-1,
|
|
|
|
fd_list,
|
|
|
|
None)
|
|
|
|
if res[0] == 0:
|
|
|
|
self.live = True
|
2018-02-13 20:01:56 +01:00
|
|
|
|
|
|
|
def stop_live(self):
|
|
|
|
self.proxy.StopLive()
|
|
|
|
self.live = False
|
|
|
|
|
2018-01-23 04:36:29 +01:00
|
|
|
def json(self, index):
|
|
|
|
return self.proxy.GetJSONData('(u)', index)
|
|
|
|
|
2018-01-22 04:28:35 +01:00
|
|
|
def _on_signal_received(self, proxy, sender, signal, parameters):
|
|
|
|
if signal == 'ButtonPressRequired':
|
2018-01-26 13:22:06 +01:00
|
|
|
logger.info(f'{self}: Press button on device now')
|
2018-01-23 02:29:22 +01:00
|
|
|
elif signal == 'ListeningStopped':
|
2018-01-24 12:06:16 +01:00
|
|
|
err = parameters[0]
|
2018-01-30 14:01:48 +01:00
|
|
|
if err == -errno.EACCES:
|
2018-02-02 00:28:26 +01:00
|
|
|
logger.error(f'{self}: wrong device, please re-register.')
|
2018-01-30 14:01:48 +01:00
|
|
|
elif err < 0:
|
|
|
|
logger.error(f'{self}: an error occured: {os.strerror(-err)}')
|
2018-01-23 02:29:22 +01:00
|
|
|
self.notify('listening')
|
2018-01-22 04:28:35 +01:00
|
|
|
|
2018-01-23 02:34:22 +01:00
|
|
|
def _on_properties_changed(self, proxy, changed_props, invalidated_props):
|
|
|
|
if changed_props is None:
|
|
|
|
return
|
|
|
|
|
|
|
|
changed_props = changed_props.unpack()
|
|
|
|
|
|
|
|
if 'DrawingsAvailable' in changed_props:
|
|
|
|
self.notify('drawings-available')
|
2018-01-25 06:44:02 +01:00
|
|
|
elif 'Listening' in changed_props:
|
|
|
|
self.notify('listening')
|
2018-01-29 04:44:02 +01:00
|
|
|
elif 'BatteryPercent' in changed_props:
|
|
|
|
self.notify('battery-percent')
|
|
|
|
elif 'BatteryState' in changed_props:
|
|
|
|
self.notify('battery-state')
|
2018-01-23 02:34:22 +01:00
|
|
|
|
2018-01-22 04:28:35 +01:00
|
|
|
def __repr__(self):
|
2018-01-29 11:38:14 +01:00
|
|
|
return f'{self.address} - {self.name}'
|
2018-01-22 04:28:35 +01:00
|
|
|
|
|
|
|
def _on_mgr_devices_updated(self, manager, pspec):
|
2018-02-02 00:28:26 +01:00
|
|
|
if not self.is_registering:
|
2018-01-22 04:28:35 +01:00
|
|
|
return
|
|
|
|
|
|
|
|
for d in manager.devices:
|
|
|
|
if d.address == self.address:
|
2018-02-02 00:28:26 +01:00
|
|
|
self.is_registering = False
|
2018-01-31 19:22:44 +01:00
|
|
|
self.manager.disconnect(self.s1)
|
|
|
|
del(self.s1)
|
2018-02-02 00:28:26 +01:00
|
|
|
logger.info(f'{self}: Registration successful')
|
2018-01-22 04:28:35 +01:00
|
|
|
|
2018-01-31 19:22:44 +01:00
|
|
|
def terminate(self):
|
|
|
|
try:
|
|
|
|
self.manager.disconnect(self.s1)
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
self._bluez_device.terminate()
|
|
|
|
super(TuhiKeteDevice, self).terminate()
|
|
|
|
|
2018-01-22 04:28:35 +01:00
|
|
|
|
|
|
|
class TuhiKeteManager(_DBusObject):
|
|
|
|
__gsignals__ = {
|
2018-02-02 00:28:26 +01:00
|
|
|
'unregistered-device':
|
2018-02-01 12:02:05 +01:00
|
|
|
(GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_PYOBJECT,)),
|
2018-01-22 04:28:35 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
_DBusObject.__init__(self, TUHI_DBUS_NAME,
|
|
|
|
ORG_FREEDESKTOP_TUHI1_MANAGER,
|
|
|
|
ROOT_PATH)
|
|
|
|
|
|
|
|
self._devices = {}
|
2018-02-02 00:28:26 +01:00
|
|
|
self._unregistered_devices = {}
|
2018-01-31 03:14:32 +01:00
|
|
|
|
2018-01-22 04:28:35 +01:00
|
|
|
for objpath in self.property('Devices'):
|
|
|
|
device = TuhiKeteDevice(self, objpath)
|
|
|
|
self._devices[device.address] = device
|
|
|
|
|
|
|
|
@GObject.Property
|
|
|
|
def devices(self):
|
|
|
|
return [v for k, v in self._devices.items()]
|
|
|
|
|
2018-01-29 11:06:43 +01:00
|
|
|
@GObject.Property
|
2018-02-02 00:28:26 +01:00
|
|
|
def unregistered_devices(self):
|
|
|
|
return [v for k, v in self._unregistered_devices.items()]
|
2018-01-29 11:06:43 +01:00
|
|
|
|
2018-01-22 04:28:35 +01:00
|
|
|
@GObject.Property
|
|
|
|
def searching(self):
|
2018-01-24 03:46:43 +01:00
|
|
|
return self.proxy.get_cached_property('Searching')
|
2018-01-23 04:44:46 +01:00
|
|
|
|
2018-01-22 04:28:35 +01:00
|
|
|
def start_search(self):
|
2018-02-02 00:28:26 +01:00
|
|
|
self._unregistered_devices = {}
|
2018-01-22 04:28:35 +01:00
|
|
|
self.proxy.StartSearch()
|
|
|
|
|
|
|
|
def stop_search(self):
|
2018-02-02 00:56:24 +01:00
|
|
|
try:
|
|
|
|
self.proxy.StopSearch()
|
|
|
|
except GLib.Error as e:
|
|
|
|
if (e.domain != 'g-dbus-error-quark' or
|
|
|
|
e.code != Gio.IOErrorEnum.EXISTS or
|
|
|
|
Gio.dbus_error_get_remote_error(e) != 'org.freedesktop.DBus.Error.ServiceUnknown'):
|
|
|
|
raise e
|
2018-02-02 00:28:26 +01:00
|
|
|
self._unregistered_devices = {}
|
2018-01-22 08:13:12 +01:00
|
|
|
|
2018-01-31 19:22:44 +01:00
|
|
|
def terminate(self):
|
|
|
|
for dev in self._devices.values():
|
|
|
|
dev.terminate()
|
|
|
|
self._devices = {}
|
2018-02-02 00:28:26 +01:00
|
|
|
self._unregistered_devices = {}
|
2018-01-31 19:22:44 +01:00
|
|
|
super(TuhiKeteManager, self).terminate()
|
2018-01-23 03:32:39 +01:00
|
|
|
|
2018-01-22 08:13:12 +01:00
|
|
|
def _on_properties_changed(self, proxy, changed_props, invalidated_props):
|
|
|
|
if changed_props is None:
|
|
|
|
return
|
|
|
|
|
|
|
|
changed_props = changed_props.unpack()
|
|
|
|
|
|
|
|
if 'Devices' in changed_props:
|
|
|
|
objpaths = changed_props['Devices']
|
|
|
|
for objpath in objpaths:
|
2018-01-23 05:21:32 +01:00
|
|
|
try:
|
2018-02-02 00:28:26 +01:00
|
|
|
d = self._unregistered_devices[objpath]
|
2018-01-23 05:21:32 +01:00
|
|
|
self._devices[d.address] = d
|
2018-02-02 00:28:26 +01:00
|
|
|
del self._unregistered_devices[objpath]
|
2018-01-23 05:21:32 +01:00
|
|
|
except KeyError:
|
2018-02-02 00:28:26 +01:00
|
|
|
# if we called Register() on an existing device it's not
|
|
|
|
# in unregistered devices
|
2018-01-23 05:21:32 +01:00
|
|
|
pass
|
2018-01-22 08:13:12 +01:00
|
|
|
self.notify('devices')
|
2018-02-13 14:01:49 +01:00
|
|
|
if 'Searching' in changed_props:
|
|
|
|
self.notify('searching')
|
2018-01-22 04:28:35 +01:00
|
|
|
|
2018-02-12 03:19:39 +01:00
|
|
|
def _handle_unregistered_device(self, objpath):
|
|
|
|
for addr, dev in self._devices.items():
|
|
|
|
if dev.objpath == objpath:
|
|
|
|
self.emit('unregistered-device', dev)
|
|
|
|
return
|
|
|
|
|
|
|
|
device = TuhiKeteDevice(self, objpath)
|
|
|
|
self._unregistered_devices[objpath] = device
|
|
|
|
|
|
|
|
logger.debug(f'New unregistered device: {device}')
|
|
|
|
self.emit('unregistered-device', device)
|
|
|
|
|
2018-01-22 04:28:35 +01:00
|
|
|
def _on_signal_received(self, proxy, sender, signal, parameters):
|
|
|
|
if signal == 'SearchStopped':
|
|
|
|
self.notify('searching')
|
2018-02-02 00:28:26 +01:00
|
|
|
elif signal == 'UnregisteredDevice':
|
2018-01-22 04:28:35 +01:00
|
|
|
objpath = parameters[0]
|
2018-02-12 03:19:39 +01:00
|
|
|
self._handle_unregistered_device(objpath)
|
2018-01-22 04:28:35 +01:00
|
|
|
|
|
|
|
def __getitem__(self, btaddr):
|
|
|
|
return self._devices[btaddr]
|
|
|
|
|
|
|
|
|
2018-01-25 15:55:56 +01:00
|
|
|
class Worker(GObject.Object):
|
2018-01-29 12:04:51 +01:00
|
|
|
'''Implements a command to be executed.
|
2018-01-25 15:55:56 +01:00
|
|
|
Subclasses need to overwrite run() that will be executed
|
2018-01-31 15:56:49 +01:00
|
|
|
while calling the command.
|
2018-01-25 15:55:56 +01:00
|
|
|
Subclass can also implement the stop() method which
|
|
|
|
will be executed to terminate the command, once the
|
2018-01-31 15:56:49 +01:00
|
|
|
mainloop has finished.'''
|
2018-01-25 15:55:56 +01:00
|
|
|
|
|
|
|
def __init__(self, manager, args=None):
|
2018-01-22 04:28:35 +01:00
|
|
|
GObject.GObject.__init__(self)
|
|
|
|
self.manager = manager
|
2018-02-13 13:58:33 +01:00
|
|
|
self._connected_signals = {}
|
|
|
|
|
|
|
|
def oject_connect(self, obj, signal, callback):
|
|
|
|
if signal in self._connected_signals:
|
|
|
|
# FIXME: this should be an exception
|
|
|
|
logger.error(f'signal {signal} is already set, ignoring')
|
|
|
|
return
|
|
|
|
|
|
|
|
s = obj.connect(signal, callback)
|
|
|
|
self._connected_signals[signal] = (obj, s)
|
|
|
|
|
|
|
|
def manager_connect(self, signal, callback):
|
|
|
|
self.oject_connect(self.manager, signal, callback)
|
|
|
|
|
|
|
|
def cleanup(self):
|
|
|
|
for obj, signal in self._connected_signals.values():
|
|
|
|
obj.disconnect(signal)
|
|
|
|
self._connected_signals = {}
|
2018-01-25 15:55:56 +01:00
|
|
|
|
|
|
|
def run(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def stop(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class Searcher(Worker):
|
|
|
|
def __init__(self, manager, args):
|
|
|
|
super(Searcher, self).__init__(manager)
|
2018-02-13 13:58:33 +01:00
|
|
|
self.manager_connect('notify::searching', self._on_notify_search)
|
|
|
|
self.manager_connect('unregistered-device', self._on_unregistered_device)
|
2018-01-22 04:28:35 +01:00
|
|
|
|
|
|
|
def run(self):
|
2018-01-24 03:46:43 +01:00
|
|
|
if self.manager.searching:
|
|
|
|
logger.error('Another client is already searching')
|
|
|
|
return
|
|
|
|
|
2018-02-13 14:01:49 +01:00
|
|
|
logger.debug(f'Starting searching')
|
2018-01-22 04:28:35 +01:00
|
|
|
self.manager.start_search()
|
2018-01-23 05:21:32 +01:00
|
|
|
|
2018-01-25 15:55:56 +01:00
|
|
|
def stop(self):
|
2018-01-22 04:28:35 +01:00
|
|
|
if self.manager.searching:
|
|
|
|
logger.debug('Stopping search')
|
|
|
|
self.manager.stop_search()
|
2018-01-29 00:26:08 +01:00
|
|
|
|
2018-02-13 13:58:33 +01:00
|
|
|
self.cleanup()
|
2018-01-22 04:28:35 +01:00
|
|
|
|
|
|
|
def _on_notify_search(self, manager, pspec):
|
2018-01-23 04:44:46 +01:00
|
|
|
if not manager.searching:
|
2018-01-24 03:46:43 +01:00
|
|
|
logger.info('Search cancelled')
|
2018-02-12 04:31:05 +01:00
|
|
|
self.stop()
|
2018-02-13 14:01:49 +01:00
|
|
|
else:
|
|
|
|
logger.info('Search started')
|
2018-01-22 04:28:35 +01:00
|
|
|
|
2018-02-02 00:28:26 +01:00
|
|
|
def _on_unregistered_device(self, manager, device):
|
|
|
|
logger.info(f'Unregistered device: {device}')
|
2018-01-26 13:50:14 +01:00
|
|
|
|
2018-01-22 04:28:35 +01:00
|
|
|
|
2018-01-25 15:55:56 +01:00
|
|
|
class Listener(Worker):
|
|
|
|
def __init__(self, manager, args):
|
|
|
|
super(Listener, self).__init__(manager)
|
2018-01-23 02:29:22 +01:00
|
|
|
|
|
|
|
self.device = None
|
|
|
|
for d in manager.devices:
|
2018-01-25 15:55:56 +01:00
|
|
|
if d.address == args.address:
|
2018-01-23 02:29:22 +01:00
|
|
|
self.device = d
|
|
|
|
break
|
|
|
|
else:
|
2018-01-29 11:38:14 +01:00
|
|
|
logger.error(f'{args.address}: device not found')
|
2018-01-25 15:55:56 +01:00
|
|
|
# FIXME: this should be an exception
|
2018-01-23 02:29:22 +01:00
|
|
|
return
|
|
|
|
|
2018-02-13 13:58:33 +01:00
|
|
|
def device_connect(self, signal, callback):
|
|
|
|
self.oject_connect(self.device, signal, callback)
|
|
|
|
|
2018-01-23 02:29:22 +01:00
|
|
|
def run(self):
|
|
|
|
if self.device is None:
|
|
|
|
return
|
|
|
|
|
2018-01-24 07:12:31 +01:00
|
|
|
if self.device.drawings_available:
|
|
|
|
self._log_drawings_available(self.device)
|
2018-01-23 02:34:22 +01:00
|
|
|
|
2018-01-23 02:29:22 +01:00
|
|
|
if self.device.listening:
|
2018-01-29 11:38:14 +01:00
|
|
|
logger.info(f'{self.device}: device already listening')
|
2018-01-23 02:29:22 +01:00
|
|
|
return
|
|
|
|
|
2018-01-29 11:38:14 +01:00
|
|
|
logger.debug(f'{self.device}: starting listening')
|
2018-02-13 13:58:33 +01:00
|
|
|
self.device_connect('notify::listening', self._on_device_listening)
|
|
|
|
self.device_connect('notify::drawings-available', self._on_drawings_available)
|
2018-01-23 02:29:22 +01:00
|
|
|
self.device.start_listening()
|
|
|
|
|
2018-01-25 15:55:56 +01:00
|
|
|
def stop(self):
|
2018-02-13 14:01:49 +01:00
|
|
|
if self.device.listening:
|
|
|
|
logger.debug(f'{self.device}: stopping listening')
|
|
|
|
self.device.stop_listening()
|
2018-02-13 13:58:33 +01:00
|
|
|
|
|
|
|
self.cleanup()
|
2018-01-23 02:29:22 +01:00
|
|
|
|
|
|
|
def _on_device_listening(self, device, pspec):
|
2018-01-25 06:44:02 +01:00
|
|
|
if self.device.listening:
|
|
|
|
return
|
|
|
|
|
2018-01-29 11:38:14 +01:00
|
|
|
logger.info(f'{device}: Listening stopped')
|
2018-02-12 04:31:05 +01:00
|
|
|
self.stop()
|
2018-01-23 02:29:22 +01:00
|
|
|
|
2018-01-23 02:34:22 +01:00
|
|
|
def _on_drawings_available(self, device, pspec):
|
2018-01-24 07:12:31 +01:00
|
|
|
self._log_drawings_available(device)
|
|
|
|
|
|
|
|
def _log_drawings_available(self, device):
|
2018-01-29 11:38:14 +01:00
|
|
|
s = ', '.join([f'{t}' for t in device.drawings_available])
|
|
|
|
logger.info(f'{device}: drawings available: {s}')
|
2018-01-23 02:34:22 +01:00
|
|
|
|
2018-01-23 02:29:22 +01:00
|
|
|
|
2018-01-25 15:55:56 +01:00
|
|
|
class Fetcher(Worker):
|
|
|
|
def __init__(self, manager, args):
|
|
|
|
super(Fetcher, self).__init__(manager)
|
2018-01-23 04:36:29 +01:00
|
|
|
self.device = None
|
|
|
|
self.indices = None
|
2018-01-25 15:55:56 +01:00
|
|
|
address = args.address
|
|
|
|
index = args.index
|
2018-01-23 04:36:29 +01:00
|
|
|
|
|
|
|
for d in manager.devices:
|
|
|
|
if d.address == address:
|
|
|
|
self.device = d
|
|
|
|
break
|
|
|
|
else:
|
2018-01-29 11:38:14 +01:00
|
|
|
logger.error(f'{address}: device not found')
|
2018-01-23 04:36:29 +01:00
|
|
|
return
|
|
|
|
|
|
|
|
if index != 'all':
|
|
|
|
try:
|
2018-01-24 07:12:31 +01:00
|
|
|
index = int(index)
|
|
|
|
if index not in self.device.drawings_available:
|
2018-01-23 04:36:29 +01:00
|
|
|
raise ValueError()
|
2018-01-24 07:12:31 +01:00
|
|
|
self.indices = [index]
|
2018-01-23 04:36:29 +01:00
|
|
|
except ValueError:
|
2018-01-29 11:38:14 +01:00
|
|
|
logger.error(f'Invalid index {index}')
|
2018-01-23 04:36:29 +01:00
|
|
|
return
|
|
|
|
else:
|
2018-01-24 07:12:31 +01:00
|
|
|
self.indices = self.device.drawings_available
|
2018-01-23 04:36:29 +01:00
|
|
|
|
|
|
|
def run(self):
|
|
|
|
if self.device is None or self.indices is None:
|
|
|
|
return
|
|
|
|
|
|
|
|
for idx in self.indices:
|
|
|
|
jsondata = self.device.json(idx)
|
|
|
|
data = json.loads(jsondata)
|
2018-01-28 23:42:05 +01:00
|
|
|
t = time.localtime(data['timestamp'])
|
2018-01-25 05:52:56 +01:00
|
|
|
t = time.strftime('%Y-%m-%d-%H-%M', t)
|
|
|
|
path = f'{data["devicename"]}-{t}.svg'
|
|
|
|
self.json_to_svg(data, path)
|
|
|
|
logger.info(f'{data["devicename"]}: saved file "{path}"')
|
|
|
|
|
|
|
|
def json_to_svg(self, js, filename):
|
|
|
|
dimensions = js['dimensions']
|
|
|
|
if dimensions == [0, 0]:
|
|
|
|
dimensions = 100, 100
|
|
|
|
svg = svgwrite.Drawing(filename=filename, size=dimensions)
|
|
|
|
g = svgwrite.container.Group(id='layer0')
|
|
|
|
for s in js['strokes']:
|
|
|
|
svgpoints = []
|
|
|
|
mode = 'M'
|
|
|
|
for p in s['points']:
|
|
|
|
x, y = p['position']
|
|
|
|
svgpoints.append((mode, x, y))
|
|
|
|
mode = 'L'
|
|
|
|
path = svgwrite.path.Path(d=svgpoints,
|
2018-01-29 12:04:51 +01:00
|
|
|
style='fill:none;stroke:black;stroke-width:5')
|
2018-01-25 05:52:56 +01:00
|
|
|
g.add(path)
|
|
|
|
|
|
|
|
svg.add(g)
|
|
|
|
svg.save()
|
2018-01-23 04:36:29 +01:00
|
|
|
|
|
|
|
|
2018-02-13 20:01:56 +01:00
|
|
|
class LiveChanger(Worker):
|
|
|
|
def __init__(self, manager, args):
|
|
|
|
super(LiveChanger, self).__init__(manager)
|
|
|
|
|
|
|
|
self.device = None
|
|
|
|
for d in manager.devices:
|
|
|
|
if d.address == args.address:
|
|
|
|
self.device = d
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
logger.error(f'{args.address}: device not found')
|
|
|
|
# FIXME: this should be an exception
|
|
|
|
return
|
|
|
|
|
|
|
|
def run(self):
|
|
|
|
if self.device is None:
|
|
|
|
return
|
|
|
|
|
2018-02-13 20:01:56 +01:00
|
|
|
read_fd, write_fd = os.pipe()
|
|
|
|
|
|
|
|
logger.info(f'{self.device}: starting live mode, please press button on device')
|
|
|
|
self._cb = GLib.io_add_watch(read_fd, GLib.IO_IN, self._on_uhid_data)
|
|
|
|
self.device.start_live(write_fd)
|
|
|
|
|
|
|
|
def _on_uhid_data(self, source, cb_condition):
|
|
|
|
buf = os.read(source, 4380)
|
|
|
|
|
|
|
|
header = '< L'
|
|
|
|
uhid_type = struct.unpack_from(header, buf)[0]
|
|
|
|
|
|
|
|
if uhid_type == 11: # UHID_CREATE2
|
|
|
|
fmt = '< L 128s 64s 64s H H L L L L 4096s'
|
|
|
|
uhid_type, name, phys, uniq, rdesc_size, bus, vid, pid, version, country, rdesc = struct.unpack_from(fmt, buf)
|
|
|
|
name = name.rstrip(b'\x00')
|
|
|
|
rdesc = rdesc[:rdesc_size]
|
|
|
|
logger.info(f'Live mode started for device {name} with rdesc {b2hex(rdesc)}')
|
|
|
|
elif uhid_type == 12: # UHID_INPUT2
|
|
|
|
fmt = '< L H 4096s'
|
|
|
|
uhid_type, data_len, data = struct.unpack_from(fmt, buf)
|
|
|
|
data = data[:data_len]
|
|
|
|
logger.info(f'Live data: {b2hex(data)}')
|
|
|
|
|
|
|
|
return True
|
2018-02-13 20:01:56 +01:00
|
|
|
|
|
|
|
def stop(self):
|
|
|
|
logger.debug(f'{self.device}: stopping live mode')
|
|
|
|
try:
|
|
|
|
self.device.stop_live()
|
|
|
|
except GLib.Error as e:
|
|
|
|
if (e.domain != 'g-dbus-error-quark' or
|
|
|
|
e.code != Gio.IOErrorEnum.EXISTS or
|
|
|
|
Gio.dbus_error_get_remote_error(e) != 'org.freedesktop.DBus.Error.ServiceUnknown'):
|
|
|
|
raise e
|
2018-02-13 20:01:56 +01:00
|
|
|
GLib.source_remove(self._cb)
|
2018-02-13 20:01:56 +01:00
|
|
|
|
|
|
|
|
2018-01-23 18:18:05 +01:00
|
|
|
class TuhiKeteShellLogHandler(logging.StreamHandler):
|
|
|
|
def __init__(self):
|
|
|
|
super(TuhiKeteShellLogHandler, self).__init__(sys.stdout)
|
2018-01-29 01:59:08 +01:00
|
|
|
self.setFormatter(ColorFormatter(log_format))
|
2018-01-26 12:33:37 +01:00
|
|
|
self._prompt = ''
|
|
|
|
|
|
|
|
def emit(self, record):
|
|
|
|
self.terminator = f'\n{self._prompt}{readline.get_line_buffer()}'
|
|
|
|
super(TuhiKeteShellLogHandler, self).emit(record)
|
2018-01-23 18:18:05 +01:00
|
|
|
|
|
|
|
def set_normal_mode(self):
|
|
|
|
self.acquire()
|
2018-01-29 01:59:08 +01:00
|
|
|
self.setFormatter(ColorFormatter(log_format))
|
2018-01-23 18:18:05 +01:00
|
|
|
self.terminator = '\n'
|
2018-01-26 12:33:37 +01:00
|
|
|
self._prompt = ''
|
2018-01-23 18:18:05 +01:00
|
|
|
self.release()
|
|
|
|
|
|
|
|
def set_prompt_mode(self, prompt):
|
|
|
|
self.acquire()
|
2018-01-26 12:33:37 +01:00
|
|
|
# '\x1b[2K\r' clears the current line and start again from the beginning
|
2018-01-29 01:59:08 +01:00
|
|
|
self.setFormatter(ColorFormatter(f'\x1b[2K\r{log_format}'))
|
2018-01-26 12:33:37 +01:00
|
|
|
self._prompt = prompt
|
2018-01-23 18:18:05 +01:00
|
|
|
self.release()
|
|
|
|
|
|
|
|
|
2018-01-26 11:20:36 +01:00
|
|
|
class TuhiKeteShell(cmd.Cmd):
|
|
|
|
intro = 'Tuhi shell control'
|
|
|
|
prompt = 'tuhi> '
|
|
|
|
|
2018-01-31 19:22:44 +01:00
|
|
|
def __init__(self, completekey='tab', stdin=None, stdout=None):
|
2018-01-26 11:20:36 +01:00
|
|
|
super(TuhiKeteShell, self).__init__(completekey, stdin, stdout)
|
2018-01-31 19:22:44 +01:00
|
|
|
self._manager = None
|
2018-01-26 11:20:36 +01:00
|
|
|
self._workers = []
|
2018-01-23 18:18:05 +01:00
|
|
|
self._log_handler = TuhiKeteShellLogHandler()
|
|
|
|
logger.removeHandler(logger_handler)
|
|
|
|
logger.addHandler(self._log_handler)
|
2018-01-31 19:22:44 +01:00
|
|
|
self._log_handler.set_prompt_mode(self.prompt)
|
|
|
|
|
2018-01-26 12:55:52 +01:00
|
|
|
# patching get_names to hide some functions we do not want in the help
|
|
|
|
self.get_names = self._filtered_get_names
|
2018-01-31 19:22:44 +01:00
|
|
|
|
2018-02-06 15:13:08 +01:00
|
|
|
try:
|
|
|
|
os.mkdir(CONFIG_PATH)
|
|
|
|
except FileExistsError:
|
|
|
|
pass
|
|
|
|
|
2018-02-07 09:15:59 +01:00
|
|
|
self._history_file = os.path.join(CONFIG_PATH, 'histfile')
|
2018-02-06 15:13:08 +01:00
|
|
|
|
|
|
|
try:
|
|
|
|
readline.read_history_file(self._history_file)
|
|
|
|
except FileNotFoundError:
|
|
|
|
readline.write_history_file(self._history_file)
|
|
|
|
|
|
|
|
readline.set_history_length(100)
|
|
|
|
|
2018-01-31 19:22:44 +01:00
|
|
|
Gio.bus_watch_name(Gio.BusType.SESSION,
|
|
|
|
TUHI_DBUS_NAME,
|
|
|
|
Gio.BusNameWatcherFlags.NONE,
|
|
|
|
self._on_name_appeared,
|
|
|
|
self._on_name_vanished)
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
# we can not call GLib.MainLoop() here or it will install a unix signal
|
|
|
|
# handler for SIGINT, and we will not be able to catch
|
|
|
|
# KeyboardInterrupt in cmdloop()
|
|
|
|
self._mainloop = GLib.MainLoop.new(None, False)
|
|
|
|
|
|
|
|
self._glib_thread = threading.Thread(target=self._mainloop.run)
|
|
|
|
self._glib_thread.daemon = True
|
|
|
|
self._glib_thread.start()
|
|
|
|
|
|
|
|
return self
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
|
|
self._mainloop.quit()
|
|
|
|
self._glib_thread.join()
|
2018-01-26 12:55:52 +01:00
|
|
|
|
|
|
|
def _filtered_get_names(self):
|
|
|
|
names = super(TuhiKeteShell, self).get_names()
|
|
|
|
names.remove('do_EOF')
|
|
|
|
return names
|
2018-01-26 11:20:36 +01:00
|
|
|
|
2018-01-31 19:22:44 +01:00
|
|
|
def _on_name_appeared(self, connection, name, client):
|
2018-02-01 23:27:23 +01:00
|
|
|
logger.info('Connected to the Tuhi daemon')
|
2018-01-31 19:22:44 +01:00
|
|
|
self._manager = TuhiKeteManager()
|
|
|
|
|
|
|
|
def _on_name_vanished(self, connection, name):
|
|
|
|
if self._manager is not None:
|
2018-02-01 23:27:23 +01:00
|
|
|
logger.error('Tuhi daemon has quit')
|
2018-01-31 19:22:44 +01:00
|
|
|
else:
|
2018-02-01 23:27:23 +01:00
|
|
|
logger.warning('Tuhi daemon not running')
|
2018-01-31 18:37:17 +01:00
|
|
|
self.terminate_workers()
|
2018-01-31 19:22:44 +01:00
|
|
|
if self._manager is not None:
|
|
|
|
self._manager.terminate()
|
|
|
|
self._manager = None
|
2018-01-31 16:23:32 +01:00
|
|
|
|
2018-01-26 11:20:36 +01:00
|
|
|
def emptyline(self):
|
|
|
|
# make sure we do not re-enter the last typed command
|
|
|
|
pass
|
|
|
|
|
|
|
|
def do_EOF(self, arg):
|
|
|
|
print('\n\r', end='') # to remove the appended weird char
|
|
|
|
return self.do_exit(arg)
|
|
|
|
|
|
|
|
def do_exit(self, args):
|
2018-01-29 00:56:32 +01:00
|
|
|
'''Leave the shell'''
|
2018-01-31 18:37:17 +01:00
|
|
|
self.terminate_workers()
|
2018-01-26 11:20:36 +01:00
|
|
|
return True
|
|
|
|
|
2018-01-23 18:18:05 +01:00
|
|
|
def precmd(self, line):
|
|
|
|
# Restore the logger facility to something sane:
|
|
|
|
self._log_handler.set_normal_mode()
|
2018-02-01 23:55:48 +01:00
|
|
|
if self._manager is None and line not in ['EOF', 'exit', 'help']:
|
2018-02-01 23:55:13 +01:00
|
|
|
print('Not connected to the Tuhi daemon')
|
2018-01-31 19:22:44 +01:00
|
|
|
return ''
|
2018-02-06 15:13:08 +01:00
|
|
|
|
|
|
|
readline.write_history_file(self._history_file)
|
2018-01-23 18:18:05 +01:00
|
|
|
return line
|
|
|
|
|
|
|
|
def postcmd(self, stop, line):
|
|
|
|
# overwrite the logger facility to remove the current prompt and append
|
|
|
|
# a new one
|
|
|
|
self._log_handler.set_prompt_mode(self.prompt)
|
2018-01-29 14:29:21 +01:00
|
|
|
|
|
|
|
# restore any completion display hook we might have set
|
|
|
|
readline.set_completion_display_matches_hook()
|
2018-01-23 18:18:05 +01:00
|
|
|
return stop
|
|
|
|
|
2018-01-26 11:20:36 +01:00
|
|
|
def run(self, init=None):
|
|
|
|
try:
|
|
|
|
self.cmdloop(init)
|
|
|
|
except KeyboardInterrupt as e:
|
2018-01-29 12:04:51 +01:00
|
|
|
print('^C')
|
2018-01-26 11:20:36 +01:00
|
|
|
self.run('')
|
|
|
|
|
|
|
|
def start_worker(self, worker_class, args=None):
|
|
|
|
worker = worker_class(self._manager, args)
|
|
|
|
worker.run()
|
|
|
|
self._workers.append(worker)
|
|
|
|
|
2018-01-31 18:37:17 +01:00
|
|
|
def terminate_worker(self, worker):
|
|
|
|
worker.stop()
|
|
|
|
self._workers.remove(worker)
|
|
|
|
|
|
|
|
def terminate_workers(self):
|
|
|
|
for worker in self._workers:
|
|
|
|
worker.stop()
|
|
|
|
self._workers = []
|
|
|
|
|
2018-01-31 16:29:43 +01:00
|
|
|
def do_devices(self, arg):
|
2018-02-02 00:28:26 +01:00
|
|
|
'''List known devices. These are devices previously registered with
|
|
|
|
the daemon.'''
|
2018-01-31 16:17:55 +01:00
|
|
|
logger.debug('Listing available devices:')
|
|
|
|
for d in self._manager.devices:
|
|
|
|
print(d)
|
2018-01-26 11:20:36 +01:00
|
|
|
|
2018-01-26 16:00:30 +01:00
|
|
|
def help_listen(self):
|
|
|
|
self.do_listen('-h')
|
2018-01-26 11:20:36 +01:00
|
|
|
|
2018-01-29 11:09:02 +01:00
|
|
|
def complete_listen(self, text, line, begidx, endidx):
|
|
|
|
# mark the end of the line so we can match on the number of fields
|
|
|
|
if line.endswith(' '):
|
|
|
|
line += 'm'
|
|
|
|
fields = line.split()
|
|
|
|
|
|
|
|
completion = []
|
|
|
|
if len(fields) == 2:
|
|
|
|
for device in self._manager.devices:
|
2018-01-29 11:27:17 +01:00
|
|
|
if device.address.startswith(text.upper()):
|
2018-01-29 11:09:02 +01:00
|
|
|
completion.append(device.address)
|
|
|
|
elif len(fields) == 3:
|
|
|
|
for v in ('on', 'off'):
|
2018-01-29 11:27:17 +01:00
|
|
|
if v.startswith(text.lower()):
|
2018-01-29 11:09:02 +01:00
|
|
|
completion.append(v)
|
|
|
|
return completion
|
|
|
|
|
2018-01-26 16:00:30 +01:00
|
|
|
def do_listen(self, args):
|
2018-01-29 00:56:32 +01:00
|
|
|
desc = '''Enable or disable listening on the given device. When
|
|
|
|
listening, all drawings are downloaded from the device as they
|
|
|
|
device allows connections (this usually requires a button press).
|
|
|
|
Drawings are deleted from the device as they are downloaded, they
|
|
|
|
are available with the 'fetch' command.
|
|
|
|
'''
|
2018-01-26 16:00:30 +01:00
|
|
|
parser = argparse.ArgumentParser(prog='listen',
|
2018-01-29 00:56:32 +01:00
|
|
|
description=desc,
|
2018-01-26 16:00:30 +01:00
|
|
|
add_help=False)
|
|
|
|
parser.add_argument('-h', action='help', help=argparse.SUPPRESS)
|
|
|
|
parser.add_argument('address', metavar='12:34:56:AB:CD:EF',
|
|
|
|
type=TuhiKeteDevice.is_device_address,
|
|
|
|
default=None,
|
|
|
|
help='the address of the device to listen to')
|
|
|
|
parser.add_argument('mode', choices=['on', 'off'], nargs='?',
|
|
|
|
const='on', default='on')
|
2018-01-26 11:20:36 +01:00
|
|
|
try:
|
2018-01-26 16:00:30 +01:00
|
|
|
parsed_args = parser.parse_args(args.split())
|
|
|
|
except SystemExit:
|
2018-01-26 11:20:36 +01:00
|
|
|
return
|
|
|
|
|
2018-01-26 16:00:30 +01:00
|
|
|
address = parsed_args.address
|
|
|
|
mode = parsed_args.mode
|
|
|
|
|
2018-01-26 11:20:36 +01:00
|
|
|
for d in self._manager.devices:
|
|
|
|
if d.address == address:
|
|
|
|
if mode == 'on' and d.listening:
|
|
|
|
print(f'Already listening on {address}')
|
|
|
|
return
|
|
|
|
elif mode == 'off' and not d.listening:
|
|
|
|
print(f'Not listening on {address}')
|
|
|
|
return
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
print(f'Device {address} not found')
|
|
|
|
return
|
|
|
|
|
|
|
|
if mode == 'off':
|
|
|
|
for worker in [w for w in self._workers if isinstance(w, Listener)]:
|
|
|
|
if worker.device.address == address:
|
2018-01-31 18:37:17 +01:00
|
|
|
self.terminate_worker(worker)
|
2018-01-26 11:20:36 +01:00
|
|
|
break
|
|
|
|
return
|
|
|
|
|
2018-01-29 10:03:28 +01:00
|
|
|
self.start_worker(Listener, parsed_args)
|
2018-01-26 11:20:36 +01:00
|
|
|
|
2018-01-26 13:05:15 +01:00
|
|
|
def help_fetch(self):
|
|
|
|
self.do_fetch('-h')
|
|
|
|
|
2018-01-29 11:09:02 +01:00
|
|
|
def complete_fetch(self, text, line, begidx, endidx):
|
2018-01-29 14:29:21 +01:00
|
|
|
|
|
|
|
def draw_timestamp(substitution, matches, longest_match_length):
|
|
|
|
print()
|
|
|
|
|
|
|
|
for drawing in matches:
|
|
|
|
# we underline the current matching, because it makes easier to
|
|
|
|
# visually go through the list
|
|
|
|
display_drawing = f'\033[4m{drawing[:len(substitution)]}\033[0m{drawing[len(substitution):]}'
|
|
|
|
|
|
|
|
try:
|
|
|
|
t = time.localtime(int(drawing))
|
|
|
|
t = time.strftime('%Y-%m-%d at %H:%M', t)
|
|
|
|
print(f'{display_drawing}: drawn on the {t}')
|
|
|
|
except ValueError:
|
|
|
|
# 'all' case
|
|
|
|
print(f'{display_drawing}{":":<8} fetch all drawings')
|
|
|
|
|
|
|
|
print(self.prompt, readline.get_line_buffer(), sep='', end='')
|
|
|
|
sys.stdout.flush()
|
|
|
|
|
2018-01-29 11:09:02 +01:00
|
|
|
# mark the end of the line so we can match on the number of fields
|
|
|
|
if line.endswith(' '):
|
|
|
|
line += 'm'
|
|
|
|
fields = line.split()
|
|
|
|
|
|
|
|
completion = []
|
|
|
|
if len(fields) == 2:
|
|
|
|
for device in self._manager.devices:
|
2018-01-29 11:27:17 +01:00
|
|
|
if device.address.startswith(text.upper()):
|
2018-01-29 11:09:02 +01:00
|
|
|
completion.append(device.address)
|
|
|
|
|
|
|
|
elif len(fields) == 3:
|
2018-01-29 14:29:21 +01:00
|
|
|
readline.set_completion_display_matches_hook(draw_timestamp)
|
2018-01-29 11:09:02 +01:00
|
|
|
device = None
|
|
|
|
for d in self._manager.devices:
|
|
|
|
if d.address == fields[1]:
|
|
|
|
device = d
|
|
|
|
break
|
|
|
|
|
|
|
|
if device is None:
|
|
|
|
return
|
|
|
|
|
|
|
|
timestamps = [str(t) for t in d.drawings_available]
|
|
|
|
timestamps.append('all')
|
|
|
|
|
|
|
|
for t in timestamps:
|
2018-01-29 11:27:17 +01:00
|
|
|
if t.startswith(text.lower()):
|
2018-01-29 11:09:02 +01:00
|
|
|
completion.append(t)
|
|
|
|
|
|
|
|
return completion
|
|
|
|
|
2018-01-26 13:05:15 +01:00
|
|
|
def do_fetch(self, args):
|
|
|
|
def is_index_or_all(string):
|
|
|
|
try:
|
|
|
|
n = int(string)
|
|
|
|
except ValueError:
|
|
|
|
if string == 'all':
|
|
|
|
return string
|
|
|
|
raise argparse.ArgumentTypeError(f'"{string}" is neither a timestamp nor "all"')
|
|
|
|
else:
|
|
|
|
return n
|
|
|
|
|
2018-01-29 00:56:32 +01:00
|
|
|
desc = '''
|
|
|
|
Fetches one or all drawings from the given device. These drawings
|
|
|
|
must have been previously downloaded from the device (see the
|
|
|
|
'listen' command) and are saved in $PWD as SVG files.
|
|
|
|
'''
|
2018-01-26 13:05:15 +01:00
|
|
|
parser = argparse.ArgumentParser(prog='fetch',
|
2018-01-29 00:56:32 +01:00
|
|
|
description=desc,
|
2018-01-26 13:05:15 +01:00
|
|
|
add_help=False)
|
|
|
|
parser.add_argument('-h', action='help', help=argparse.SUPPRESS)
|
|
|
|
parser.add_argument('address', metavar='12:34:56:AB:CD:EF',
|
|
|
|
type=TuhiKeteDevice.is_device_address,
|
|
|
|
default=None,
|
|
|
|
help='the address of the device to fetch drawing from')
|
|
|
|
parser.add_argument('index', metavar='{<index>|all}',
|
|
|
|
type=is_index_or_all,
|
|
|
|
const='all', nargs='?', default='all',
|
|
|
|
help='the index of the drawing to fetch or a literal "all"')
|
|
|
|
|
|
|
|
try:
|
|
|
|
parsed_args = parser.parse_args(args.split())
|
|
|
|
except SystemExit:
|
|
|
|
return
|
|
|
|
|
2018-01-31 17:04:54 +01:00
|
|
|
# we do not call start_worker() as we don't need to retain the
|
|
|
|
# worker
|
|
|
|
worker = Fetcher(self._manager, parsed_args)
|
|
|
|
worker.run()
|
2018-01-26 13:05:15 +01:00
|
|
|
|
2018-01-26 13:50:14 +01:00
|
|
|
def help_search(self):
|
|
|
|
self.do_search('-h')
|
|
|
|
|
2018-01-29 11:09:02 +01:00
|
|
|
def complete_search(self, text, line, begidx, endidx):
|
|
|
|
# mark the end of the line so we can match on the number of fields
|
|
|
|
if line.endswith(' '):
|
|
|
|
line += 'm'
|
|
|
|
fields = line.split()
|
|
|
|
|
|
|
|
completion = []
|
|
|
|
if len(fields) == 2:
|
|
|
|
for v in ('on', 'off'):
|
2018-01-29 11:27:17 +01:00
|
|
|
if v.startswith(text.lower()):
|
2018-01-29 11:09:02 +01:00
|
|
|
completion.append(v)
|
|
|
|
|
|
|
|
return completion
|
|
|
|
|
2018-01-26 13:50:14 +01:00
|
|
|
def do_search(self, args):
|
2018-01-29 00:56:32 +01:00
|
|
|
desc = '''
|
2018-02-02 00:28:26 +01:00
|
|
|
Start/Stop listening for devices that can be registered with the
|
|
|
|
daemon. The devices must be in registration mode (blue LED blinking).
|
2018-01-29 00:56:32 +01:00
|
|
|
'''
|
2018-01-26 13:50:14 +01:00
|
|
|
parser = argparse.ArgumentParser(prog='search',
|
2018-01-29 00:56:32 +01:00
|
|
|
description=desc,
|
2018-01-26 13:50:14 +01:00
|
|
|
add_help=False)
|
|
|
|
parser.add_argument('-h', action='help', help=argparse.SUPPRESS)
|
|
|
|
parser.add_argument('mode', choices=['on', 'off'], nargs='?',
|
|
|
|
const='on', default='on')
|
|
|
|
|
|
|
|
try:
|
|
|
|
parsed_args = parser.parse_args(args.split())
|
|
|
|
except SystemExit:
|
|
|
|
return
|
|
|
|
|
2018-01-31 16:14:44 +01:00
|
|
|
current_searcher = None
|
|
|
|
workers = [w for w in self._workers if isinstance(w, Searcher)]
|
|
|
|
if len(workers) == 1:
|
|
|
|
current_searcher = workers[0]
|
2018-01-26 13:50:14 +01:00
|
|
|
|
2018-01-31 16:14:44 +01:00
|
|
|
if current_searcher is None:
|
|
|
|
if parsed_args.mode == 'on':
|
|
|
|
self.start_worker(Searcher, parsed_args)
|
|
|
|
else:
|
|
|
|
if parsed_args.mode == 'off':
|
2018-01-31 18:37:17 +01:00
|
|
|
self.terminate_worker(current_searcher)
|
2018-01-31 16:14:44 +01:00
|
|
|
else:
|
|
|
|
logger.info('Already searching')
|
2018-01-26 13:50:14 +01:00
|
|
|
|
2018-02-02 00:28:26 +01:00
|
|
|
def help_register(self):
|
|
|
|
self.do_register('-h')
|
2018-01-26 13:50:14 +01:00
|
|
|
|
2018-02-02 00:28:26 +01:00
|
|
|
def complete_register(self, text, line, begidx, endidx):
|
2018-01-29 11:09:02 +01:00
|
|
|
# mark the end of the line so we can match on the number of fields
|
|
|
|
if line.endswith(' '):
|
|
|
|
line += 'm'
|
|
|
|
fields = line.split()
|
|
|
|
|
|
|
|
completion = []
|
|
|
|
if len(fields) == 2:
|
2018-02-02 00:28:26 +01:00
|
|
|
for device in self._manager.unregistered_devices + self._manager.devices:
|
2018-01-29 11:27:17 +01:00
|
|
|
if device.address.startswith(text.upper()):
|
2018-01-29 11:09:02 +01:00
|
|
|
completion.append(device.address)
|
|
|
|
|
|
|
|
return completion
|
|
|
|
|
2018-02-02 00:28:26 +01:00
|
|
|
def do_register(self, args):
|
2018-01-26 13:50:14 +01:00
|
|
|
if not self._manager.searching and '-h' not in args.split():
|
2018-01-29 12:04:51 +01:00
|
|
|
print('please call search first')
|
2018-01-26 13:50:14 +01:00
|
|
|
return
|
|
|
|
|
2018-01-29 00:56:32 +01:00
|
|
|
desc = '''
|
2018-02-02 00:28:26 +01:00
|
|
|
Register the given device. The device must be in registration mode
|
|
|
|
(blue LED blinking).
|
2018-01-29 00:56:32 +01:00
|
|
|
'''
|
2018-02-02 00:28:26 +01:00
|
|
|
parser = argparse.ArgumentParser(prog='register',
|
2018-01-29 00:56:32 +01:00
|
|
|
description=desc,
|
2018-01-26 13:50:14 +01:00
|
|
|
add_help=False)
|
|
|
|
parser.add_argument('-h', action='help', help=argparse.SUPPRESS)
|
|
|
|
parser.add_argument('address', metavar='12:34:56:AB:CD:EF',
|
|
|
|
type=TuhiKeteDevice.is_device_address,
|
|
|
|
default=None,
|
2018-02-02 00:28:26 +01:00
|
|
|
help='the address of the device to register')
|
2018-01-26 13:50:14 +01:00
|
|
|
|
|
|
|
try:
|
|
|
|
parsed_args = parser.parse_args(args.split())
|
|
|
|
except SystemExit:
|
|
|
|
return
|
|
|
|
|
|
|
|
address = parsed_args.address
|
|
|
|
|
|
|
|
device = None
|
|
|
|
|
2018-01-31 18:37:17 +01:00
|
|
|
# make sure we do not keep a listener on the device
|
|
|
|
for worker in [w for w in self._workers if isinstance(w, Listener)]:
|
|
|
|
if worker.device.address == address:
|
|
|
|
self.terminate_worker(worker)
|
|
|
|
|
2018-02-02 00:28:26 +01:00
|
|
|
for d in self._manager.devices + self._manager.unregistered_devices:
|
2018-01-26 13:50:14 +01:00
|
|
|
if d.address == address:
|
|
|
|
device = d
|
|
|
|
break
|
|
|
|
else:
|
2018-01-29 11:38:14 +01:00
|
|
|
logger.error(f'{address}: device not found')
|
2018-01-26 13:50:14 +01:00
|
|
|
return
|
|
|
|
|
2018-02-02 00:28:26 +01:00
|
|
|
device.register()
|
2018-01-26 13:50:14 +01:00
|
|
|
|
2018-01-26 17:23:30 +01:00
|
|
|
def help_info(self):
|
|
|
|
self.do_info('-h')
|
|
|
|
|
2018-01-29 11:09:02 +01:00
|
|
|
def complete_info(self, text, line, begidx, endidx):
|
|
|
|
# mark the end of the line so we can match on the number of fields
|
|
|
|
if line.endswith(' '):
|
|
|
|
line += 'm'
|
|
|
|
fields = line.split()
|
|
|
|
|
|
|
|
completion = []
|
|
|
|
if len(fields) == 2:
|
|
|
|
for device in self._manager.devices:
|
|
|
|
if device.address.startswith(text):
|
|
|
|
completion.append(device.address)
|
|
|
|
|
|
|
|
return completion
|
|
|
|
|
2018-01-26 17:23:30 +01:00
|
|
|
def do_info(self, args):
|
2018-01-29 00:56:32 +01:00
|
|
|
desc = '''
|
|
|
|
Show information about the given device. If no device is given, show
|
|
|
|
information about all known devices'''
|
2018-01-26 17:23:30 +01:00
|
|
|
parser = argparse.ArgumentParser(prog='info',
|
2018-01-29 00:56:32 +01:00
|
|
|
description=desc,
|
2018-01-26 17:23:30 +01:00
|
|
|
add_help=False)
|
|
|
|
parser.add_argument('-h', action='help', help=argparse.SUPPRESS)
|
|
|
|
parser.add_argument('address', metavar='12:34:56:AB:CD:EF',
|
|
|
|
type=TuhiKeteDevice.is_device_address,
|
|
|
|
default=None, nargs='?',
|
|
|
|
help='the address of the device to listen to')
|
|
|
|
|
|
|
|
try:
|
|
|
|
parsed_args = parser.parse_args(args.split())
|
|
|
|
except SystemExit:
|
|
|
|
return
|
|
|
|
|
|
|
|
for device in self._manager.devices:
|
|
|
|
if parsed_args.address is None or parsed_args.address == device.address:
|
|
|
|
print(device)
|
2018-01-29 04:44:02 +01:00
|
|
|
charge_strs = {
|
|
|
|
0: 'unknown',
|
|
|
|
1: 'charging',
|
|
|
|
2: 'discharging'
|
|
|
|
}
|
|
|
|
try:
|
|
|
|
charge_str = charge_strs[device.battery_state]
|
|
|
|
except KeyError:
|
|
|
|
charge_str = 'invalid'
|
|
|
|
print(f'\tBattery level: {device.battery_percent}%, {charge_str}')
|
2018-01-26 17:23:30 +01:00
|
|
|
print('\tAvailable drawings:')
|
|
|
|
for d in device.drawings_available:
|
|
|
|
t = time.localtime(d)
|
|
|
|
t = time.strftime('%Y-%m-%d at %H:%M', t)
|
|
|
|
print(f'\t\t* {d}: drawn on the {t}')
|
|
|
|
|
2018-02-13 20:01:56 +01:00
|
|
|
def complete_enable_live(self, text, line, begidx, endidx):
|
|
|
|
# mark the end of the line so we can match on the number of fields
|
|
|
|
if line.endswith(' '):
|
|
|
|
line += 'm'
|
|
|
|
fields = line.split()
|
|
|
|
|
|
|
|
completion = []
|
|
|
|
if len(fields) == 2:
|
|
|
|
for device in self._manager.devices:
|
|
|
|
if device.address.startswith(text.upper()):
|
|
|
|
completion.append(device.address)
|
|
|
|
elif len(fields) == 3:
|
|
|
|
for v in ('on', 'off'):
|
|
|
|
if v.startswith(text.lower()):
|
|
|
|
completion.append(v)
|
|
|
|
return completion
|
|
|
|
|
|
|
|
def do_enable_live(self, args):
|
|
|
|
desc = '''Enable or disable live mode on a particular device'''
|
|
|
|
parser = argparse.ArgumentParser(prog='enable_live',
|
|
|
|
description=desc,
|
|
|
|
add_help=False)
|
|
|
|
parser.add_argument('-h', action='help', help=argparse.SUPPRESS)
|
|
|
|
parser.add_argument('address', metavar='12:34:56:AB:CD:EF',
|
|
|
|
type=TuhiKeteDevice.is_device_address,
|
|
|
|
default=None, nargs='?',
|
|
|
|
help='the address of the device to listen to')
|
|
|
|
parser.add_argument('mode', choices=['on', 'off'], nargs='?',
|
|
|
|
const='on', default='on')
|
|
|
|
|
|
|
|
try:
|
|
|
|
parsed_args = parser.parse_args(args.split())
|
|
|
|
except SystemExit:
|
|
|
|
return
|
|
|
|
|
|
|
|
address = parsed_args.address
|
|
|
|
mode = parsed_args.mode
|
|
|
|
|
|
|
|
for d in self._manager.devices:
|
|
|
|
if d.address == address:
|
|
|
|
if mode == 'on' and d.live:
|
|
|
|
print(f'Live mode already enabled on {address}')
|
|
|
|
return
|
|
|
|
elif mode == 'off' and not d.live:
|
|
|
|
print(f'Live mode not started on {address}')
|
|
|
|
return
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
print(f'Device {address} not found')
|
|
|
|
return
|
|
|
|
|
|
|
|
if mode == 'off':
|
|
|
|
for worker in [w for w in self._workers if isinstance(w, LiveChanger)]:
|
|
|
|
if worker.device.address == address:
|
|
|
|
self.terminate_worker(worker)
|
|
|
|
break
|
|
|
|
return
|
|
|
|
|
|
|
|
self.start_worker(LiveChanger, parsed_args)
|
|
|
|
|
2018-01-26 11:20:36 +01:00
|
|
|
|
2018-01-22 04:28:35 +01:00
|
|
|
def parse(args):
|
2018-01-31 03:14:32 +01:00
|
|
|
desc = 'Interactive commandline client to the Tuhi DBus daemon'
|
2018-01-22 04:28:35 +01:00
|
|
|
parser = argparse.ArgumentParser(description=desc)
|
|
|
|
parser.add_argument('-v', '--verbose',
|
|
|
|
help='Show some debugging informations',
|
|
|
|
action='store_true',
|
|
|
|
default=False)
|
|
|
|
|
|
|
|
return parser.parse_args(args[1:])
|
|
|
|
|
|
|
|
|
|
|
|
def main(args):
|
|
|
|
args = parse(args)
|
|
|
|
if args.verbose:
|
|
|
|
logger.setLevel(logging.DEBUG)
|
|
|
|
|
|
|
|
try:
|
2018-01-31 19:22:44 +01:00
|
|
|
with TuhiKeteShell() as shell:
|
2018-01-31 15:51:31 +01:00
|
|
|
shell.run()
|
2018-01-22 04:28:35 +01:00
|
|
|
|
|
|
|
except DBusError as e:
|
|
|
|
logger.error(e.message)
|
|
|
|
|
|
|
|
|
2018-01-29 12:04:51 +01:00
|
|
|
if __name__ == '__main__':
|
2018-01-22 04:28:35 +01:00
|
|
|
main(sys.argv)
|