├── tbtool ├── __init__.py ├── tingbot.key.pub ├── tingbot.key ├── __main__.py └── appdirs.py ├── tests ├── __init__.py ├── blank.png ├── GifSample.gif ├── button_test.py ├── typesetter_tests.py ├── tingapp_test.py ├── hardware_test.py ├── cache_test.py └── peripherals.json ├── requirements.txt ├── docs ├── readme.rst ├── images │ ├── align │ │ ├── top.png │ │ ├── left.png │ │ ├── right.png │ │ ├── bottom.png │ │ ├── center.png │ │ ├── topleft.png │ │ ├── topright.png │ │ ├── bottomleft.png │ │ └── bottomright.png │ ├── alignxy │ │ ├── top.png │ │ ├── bottom.png │ │ ├── center.png │ │ ├── left.png │ │ ├── right.png │ │ ├── topleft.png │ │ ├── topright.png │ │ ├── bottomleft.png │ │ └── bottomright.png │ ├── simulator-live.gif │ ├── simulator-time.png │ ├── simulator-time-2.png │ └── simulator-hello-world.png ├── reference.rst ├── index.rst ├── hardware.rst ├── sound.rst ├── runloop.rst ├── webhooks.rst ├── touch.rst ├── settings.rst ├── buttons.rst ├── Makefile ├── conf.py └── graphics.rst ├── requirements_dev.txt ├── tingbot ├── resources │ ├── 04B_03__.TTF │ ├── Geneva.ttf │ ├── MiniSet2.ttf │ ├── broken_image.png │ └── default-icon-texture-96.png ├── platform_specific │ ├── bot.png │ ├── bot@2x.png │ ├── simulator-icon.png │ ├── __init__.py │ ├── sdl_wrapper.py │ ├── tingbot.py │ └── osx.py ├── hardware.py ├── audio.py ├── quit.py ├── web.py ├── __init__.py ├── error.py ├── input.py ├── utils.py ├── run_loop.py ├── button.py ├── cache.py ├── tingapp.py └── typesetter.py ├── .gitignore ├── README.rst ├── setup.cfg ├── .travis.yml ├── MANIFEST.in ├── LICENSE ├── Makefile └── setup.py /tbtool/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | -e . 2 | 3 | -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | -------------------------------------------------------------------------------- /tests/blank.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/tests/blank.png -------------------------------------------------------------------------------- /tests/GifSample.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/tests/GifSample.gif -------------------------------------------------------------------------------- /docs/images/align/top.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/align/top.png -------------------------------------------------------------------------------- /docs/images/align/left.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/align/left.png -------------------------------------------------------------------------------- /docs/images/align/right.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/align/right.png -------------------------------------------------------------------------------- /docs/images/alignxy/top.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/alignxy/top.png -------------------------------------------------------------------------------- /docs/images/align/bottom.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/align/bottom.png -------------------------------------------------------------------------------- /docs/images/align/center.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/align/center.png -------------------------------------------------------------------------------- /docs/images/align/topleft.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/align/topleft.png -------------------------------------------------------------------------------- /docs/images/align/topright.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/align/topright.png -------------------------------------------------------------------------------- /docs/images/alignxy/bottom.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/alignxy/bottom.png -------------------------------------------------------------------------------- /docs/images/alignxy/center.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/alignxy/center.png -------------------------------------------------------------------------------- /docs/images/alignxy/left.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/alignxy/left.png -------------------------------------------------------------------------------- /docs/images/alignxy/right.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/alignxy/right.png -------------------------------------------------------------------------------- /docs/images/simulator-live.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/simulator-live.gif -------------------------------------------------------------------------------- /docs/images/simulator-time.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/simulator-time.png -------------------------------------------------------------------------------- /requirements_dev.txt: -------------------------------------------------------------------------------- 1 | bumpversion==0.5.3 2 | wheel==0.23.0 3 | Sphinx==1.3.1 4 | httpretty==0.8.14 5 | mock==2.0.0 6 | -------------------------------------------------------------------------------- /tingbot/resources/04B_03__.TTF: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/tingbot/resources/04B_03__.TTF -------------------------------------------------------------------------------- /tingbot/resources/Geneva.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/tingbot/resources/Geneva.ttf -------------------------------------------------------------------------------- /tingbot/resources/MiniSet2.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/tingbot/resources/MiniSet2.ttf -------------------------------------------------------------------------------- /docs/images/align/bottomleft.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/align/bottomleft.png -------------------------------------------------------------------------------- /docs/images/alignxy/topleft.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/alignxy/topleft.png -------------------------------------------------------------------------------- /docs/images/alignxy/topright.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/alignxy/topright.png -------------------------------------------------------------------------------- /docs/images/simulator-time-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/simulator-time-2.png -------------------------------------------------------------------------------- /docs/images/align/bottomright.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/align/bottomright.png -------------------------------------------------------------------------------- /docs/images/alignxy/bottomleft.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/alignxy/bottomleft.png -------------------------------------------------------------------------------- /docs/images/alignxy/bottomright.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/alignxy/bottomright.png -------------------------------------------------------------------------------- /docs/reference.rst: -------------------------------------------------------------------------------- 1 | 2 | Full reference 3 | -------------- 4 | 5 | .. automodule:: tingbot.graphics 6 | :members: 7 | 8 | -------------------------------------------------------------------------------- /tingbot/platform_specific/bot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/tingbot/platform_specific/bot.png -------------------------------------------------------------------------------- /tingbot/resources/broken_image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/tingbot/resources/broken_image.png -------------------------------------------------------------------------------- /docs/images/simulator-hello-world.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/docs/images/simulator-hello-world.png -------------------------------------------------------------------------------- /tingbot/platform_specific/bot@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/tingbot/platform_specific/bot@2x.png -------------------------------------------------------------------------------- /tingbot/platform_specific/simulator-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/tingbot/platform_specific/simulator-icon.png -------------------------------------------------------------------------------- /tingbot/resources/default-icon-texture-96.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tingbot/tingbot-python/HEAD/tingbot/resources/default-icon-texture-96.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # virtualenv 7 | /env 8 | 9 | # Sphinx 10 | docs/_build 11 | 12 | *~ 13 | 14 | #Build Folders 15 | build/ 16 | dist/ 17 | *.egg-info 18 | *.egg 19 | .eggs/ 20 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | =============================== 2 | Tingbot 3 | =============================== 4 | 5 | Python APIs to write apps for `Tingbot `_. 6 | 7 | * Documentation: http://tingbot-python.readthedocs.org/. 8 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 1.2.2 3 | commit = True 4 | tag = True 5 | message = Bump version 6 | 7 | [bumpversion:file:setup.py] 8 | 9 | [bumpversion:file:tingbot/__init__.py] 10 | 11 | [pep8] 12 | ignore = E501,E128,E401,E126,E302 13 | 14 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "2.7" 4 | virtualenv: 5 | # let the tests pick up the system-installed pygame 6 | system_site_packages: true 7 | before_install: 8 | - sudo apt-get -qq update 9 | - sudo apt-get install python-pygame 10 | install: "pip install -r requirements_dev.txt -r requirements.txt" 11 | script: python setup.py test 12 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include README.rst 3 | 4 | recursive-exclude * __pycache__ 5 | recursive-exclude * *.py[co] 6 | 7 | recursive-include docs *.rst conf.py Makefile make.bat 8 | recursive-include tingbot *.png *.ttf *.TTF 9 | recursive-include tingbot/platform_specific *.py 10 | recursive-include tests *.png *.gif *.py 11 | recursive-include tbtool *.key *.key.pub 12 | -------------------------------------------------------------------------------- /tbtool/tingbot.key.pub: -------------------------------------------------------------------------------- 1 | ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDJoXrHrntI5XS0Le0nDPpQ9xkN58IBxYIV9phYmh6mV51X+W/81QzSryWPZHvyEjpAY/Efb4rJ5QysfrT8o1HEpOf8VCgmCMIPxihipSny5vcdnqbSkz74S/Gh+ld+eHH97AXjHKpCWHquCzitt/bfKrYDiRmBj+OPRAf+tj99FhgBt5lZPyuL3lt7rqXSIPrVnWfLAjYBFavZl7pqVFmM2jJ0i6VX3uaigIN1Dgw/xIjhdXDTyLZrPPAXA7Cay/f0fkkxBULGfndkh97tjZJhkYcHARFEX+Wptb7qmuQWv/eHWV+U3321qjat6cm+fvz5BiSv23WgrvIln6v7HeDx joerick@joerick 2 | -------------------------------------------------------------------------------- /tingbot/hardware.py: -------------------------------------------------------------------------------- 1 | import socket 2 | from . import platform_specific 3 | 4 | mouse_attached = platform_specific.mouse_attached 5 | keyboard_attached = platform_specific.keyboard_attached 6 | joystick_attached = platform_specific.joystick_attached 7 | get_wifi_cell = platform_specific.get_wifi_cell 8 | 9 | def get_ip_address(): 10 | try: 11 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 12 | s.connect(("8.8.8.8", 80)) 13 | ip_addr = s.getsockname()[0] 14 | except IOError: 15 | ip_addr = None 16 | finally: 17 | s.close() 18 | return ip_addr 19 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. tingbot documentation master file, created by 2 | sphinx-quickstart on Tue Jul 9 22:26:36 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to Tingbot's documentation! 7 | ====================================== 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | readme 15 | graphics 16 | touch 17 | buttons 18 | webhooks 19 | settings 20 | runloop 21 | hardware 22 | sound 23 | reference 24 | 25 | Indices and tables 26 | ================== 27 | 28 | * :ref:`search` 29 | 30 | -------------------------------------------------------------------------------- /tingbot/audio.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | 3 | is_setup = False 4 | 5 | def ensure_setup(): 6 | global is_setup 7 | if not is_setup: 8 | setup() 9 | is_setup = True 10 | 11 | 12 | def setup(): 13 | from . import platform_specific 14 | platform_specific.setup_audio() 15 | pygame.mixer.init(frequency=44100, size=-16, channels=2, buffer=4096) 16 | 17 | 18 | class Sound(object): 19 | def __init__(self, path): 20 | ensure_setup() 21 | self._pygame_sound = pygame.mixer.Sound(path) 22 | 23 | def play(self, loop=False): 24 | loops = -1 if loop else 0 # -1 means keep looping 25 | self._pygame_sound.play(loops=loops) 26 | 27 | def stop(self): 28 | self._pygame_sound.stop() 29 | -------------------------------------------------------------------------------- /tingbot/quit.py: -------------------------------------------------------------------------------- 1 | import sys, signal 2 | import pygame 3 | 4 | def fixup_sigterm_behaviour(): 5 | ''' 6 | SDL registers its own signal handler for SIGTERM, which pushes a SDL_QUIT event to the event 7 | loop, instead of killing the process right away. This is a problem for us, because when using 8 | the fbcon drivers, the process activates and locks a virtual terminal which survives after the 9 | process dies. We need to ensure that the process cleans up this virtual terminal, otherwise the 10 | Tingbot needs a reboot. 11 | 12 | We do this by calling the cleanup and exiting straight away on SIGTERM. 13 | ''' 14 | 15 | def quit_handler(sig, frame): 16 | pygame.quit() 17 | sys.exit(128 + sig) 18 | 19 | signal.signal(signal.SIGTERM, quit_handler) 20 | -------------------------------------------------------------------------------- /docs/hardware.rst: -------------------------------------------------------------------------------- 1 | 📟 Hardware 2 | ----------- 3 | 4 | There are several useful functions that can be used to see if hardware is connected to the tingbot. 5 | 6 | .. py:function:: get_ip_address() 7 | 8 | Returns the IP address of the tingbot or None if it is not connected. 9 | 10 | .. py:function:: get_wifi_cell() 11 | 12 | Returns a WifiCell object (or None if there is no wifi adapter). 13 | 14 | A WifiCell object has the following attributes: 15 | 16 | * ssid 17 | * link_quality 18 | * signal_level 19 | 20 | .. py:function:: mouse_attached() 21 | 22 | Returns True if a mouse is attached 23 | 24 | .. py:function:: keyboard_attached() 25 | 26 | Returns True if a keyboard is attached 27 | 28 | .. py:function:: joystick_attached() 29 | 30 | Returns True if a joystick is attached 31 | -------------------------------------------------------------------------------- /docs/sound.rst: -------------------------------------------------------------------------------- 1 | 🔊 Sounds 2 | --------- 3 | 4 | If you plug in a USB audio device into your Tingbot, you can play sounds. 5 | 6 | .. code-block:: python 7 | :caption: Example: Simple sounds app 8 | 9 | import tingbot 10 | from tingbot import * 11 | 12 | sound = Sound('car_chirp.wav') 13 | 14 | @left_button.press 15 | def on_press(): 16 | sound.play() 17 | 18 | @every(seconds=1.0/30) 19 | def draw(): 20 | screen.fill(color='black') 21 | screen.text('Press the left button to play a sound.') 22 | 23 | tingbot.run() 24 | 25 | 26 | .. py:class:: Sound(filename) 27 | 28 | Loads a sound ready for playing. Currently WAV and OGG files are supported. 29 | 30 | .. py:method:: play(loop=False) 31 | 32 | Starts the playback of the sound. 33 | 34 | :param bool loop: Pass ``True`` to loop the sound until ``stop()`` is called. 35 | 36 | .. py:method:: stop() 37 | 38 | Stops the sound. -------------------------------------------------------------------------------- /docs/runloop.rst: -------------------------------------------------------------------------------- 1 | ⏱ Run loop 2 | ----------- 3 | 4 | Tingbot has an internal run loop that it uses to schedule events. 5 | 6 | .. py:function:: tingbot.run(loop=None) 7 | 8 | This function starts the run loop. 9 | 10 | The optional ``loop`` function is called every 1/30th seconds. 11 | 12 | .. py:decorator:: every(hours=0, minutes=0, seconds=0) 13 | 14 | This decorator will call the function marked periodically, according to the time specified. 15 | 16 | .. code-block:: python 17 | :caption: Example: Refreshing data every 10 minutes 18 | 19 | @every(minutes=10) 20 | def refresh_data(): 21 | r = requests.get('http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=bd82977b86bf27fb59a04b61b657fb6f') 22 | state['data'] = r.json() 23 | 24 | .. py:decorator:: once(hours=0, minutes=0, seconds=0) 25 | 26 | This decorator will call the function marked once, after the duration specified. 27 | 28 | .. py:function:: tingbot.RunLoop.call_after(callable) 29 | 30 | Call function ``callable`` at the next possible moment from the run loop. This allows threads 31 | to communicate with the main run loop in a thread-safe fashion 32 | -------------------------------------------------------------------------------- /tingbot/platform_specific/__init__.py: -------------------------------------------------------------------------------- 1 | import sys, os 2 | 3 | def is_running_on_tingbot(): 4 | """ 5 | Return True if running as a tingbot. 6 | """ 7 | # TB_RUN_ON_LCD is an environment variable set by tbprocessd when running tingbot apps. 8 | return 'TB_RUN_ON_LCD' in os.environ 9 | 10 | def no_op(*args, **kwargs): 11 | pass 12 | 13 | def no_op_returning(return_value): 14 | def inner(*args, **kwargs): 15 | return return_value 16 | return inner 17 | 18 | # set fallback functions (some of these will be replaced by the real versions below) 19 | set_backlight = no_op 20 | mouse_attached = no_op_returning(True) 21 | keyboard_attached = no_op_returning(True) 22 | joystick_attached = no_op_returning(False) 23 | get_wifi_cell = no_op_returning(None) 24 | setup_audio = no_op 25 | 26 | if sys.platform == 'darwin': 27 | from osx import fixup_env, create_main_surface, register_button_callback 28 | elif is_running_on_tingbot(): 29 | from tingbot import (fixup_env, create_main_surface, register_button_callback, 30 | set_backlight, mouse_attached, keyboard_attached, joystick_attached, 31 | get_wifi_cell, setup_audio) 32 | else: 33 | from sdl_wrapper import fixup_env, create_main_surface, register_button_callback 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | This project is licensed under the 'BSD 2-clause license'. 2 | 3 | Copyright (c) 2015, Tingbot. All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | 8 | 1. Redistributions of source code must retain the above copyright notice, this 9 | list of conditions and the following disclaimer. 10 | 11 | 2. Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | 15 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 16 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 18 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 19 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 20 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 21 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 22 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 23 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 24 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 | 26 | -------------------------------------------------------------------------------- /tingbot/web.py: -------------------------------------------------------------------------------- 1 | import zmq 2 | 3 | class webhook(object): 4 | def __init__(self, hook_name): 5 | ensure_setup() 6 | 7 | self.hook_name = hook_name 8 | 9 | def __call__(self, f): 10 | register_webhook(self.hook_name, f) 11 | return f 12 | 13 | is_setup = False 14 | zmq_subscriber = None 15 | registered_webhooks = {} 16 | 17 | def ensure_setup(): 18 | global is_setup 19 | if not is_setup: 20 | setup() 21 | is_setup = True 22 | 23 | def setup(): 24 | global zmq_subscriber 25 | 26 | ctx = zmq.Context.instance() 27 | zmq_subscriber = ctx.socket(zmq.SUB) 28 | zmq_subscriber.connect("tcp://webhook.tingbot.com:20452") 29 | 30 | from tingbot.run_loop import main_run_loop 31 | main_run_loop.add_wait_callback(run_loop_wait) 32 | 33 | def register_webhook(hook_name, callback): 34 | registered_webhooks[hook_name] = callback 35 | zmq_subscriber.setsockopt(zmq.SUBSCRIBE, hook_name) 36 | 37 | def run_loop_wait(): 38 | try: 39 | topic, data = zmq_subscriber.recv_multipart(flags=zmq.NOBLOCK) 40 | except zmq.ZMQError, e: 41 | if e.errno == zmq.EAGAIN: 42 | pass # no message was ready 43 | else: 44 | raise 45 | else: 46 | from tingbot.utils import call_with_optional_arguments 47 | 48 | if topic in registered_webhooks: 49 | callback = registered_webhooks[topic] 50 | call_with_optional_arguments(callback, data=data) 51 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean-pyc clean-build docs clean 2 | define BROWSER_PYSCRIPT 3 | import os, webbrowser, sys 4 | try: 5 | from urllib import pathname2url 6 | except: 7 | from urllib.request import pathname2url 8 | 9 | webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) 10 | endef 11 | export BROWSER_PYSCRIPT 12 | BROWSER := python -c "$$BROWSER_PYSCRIPT" 13 | 14 | help: 15 | @echo "clean - remove all build, test, coverage and Python artifacts" 16 | @echo "clean-build - remove build artifacts" 17 | @echo "clean-pyc - remove Python file artifacts" 18 | @echo "docs - generate Sphinx HTML documentation, including API docs" 19 | @echo "release - package and upload a release" 20 | @echo "install - install the package to the active Python's site-packages" 21 | 22 | clean: clean-build clean-pyc 23 | 24 | clean-build: 25 | rm -fr build/ 26 | rm -fr dist/ 27 | rm -fr .eggs/ 28 | find . -name '*.egg-info' -exec rm -fr {} + 29 | find . -name '*.egg' -exec rm -f {} + 30 | 31 | clean-pyc: 32 | find . -name '*.pyc' -exec rm -f {} + 33 | find . -name '*.pyo' -exec rm -f {} + 34 | find . -name '*~' -exec rm -f {} + 35 | find . -name '__pycache__' -exec rm -fr {} + 36 | 37 | docs: 38 | $(MAKE) -C docs clean 39 | $(MAKE) -C docs html 40 | $(BROWSER) docs/_build/html/index.html 41 | 42 | servedocs: docs 43 | watchmedo shell-command -p '*.rst;*.py' -c '$(MAKE) -C docs html' -R -D . 44 | 45 | release: clean 46 | python setup.py sdist upload 47 | python setup.py bdist_wheel upload 48 | 49 | install: clean 50 | python setup.py install 51 | -------------------------------------------------------------------------------- /docs/webhooks.rst: -------------------------------------------------------------------------------- 1 | ⚡️ Webhooks 2 | ---------- 3 | 4 | You can push data to Tingbot using webhooks. 5 | 6 | Here is an example that displays SMS messages using `If This Then That `_. See 7 | our `tutorial video `_ to see how to set up IFTTT with 8 | webhooks. 9 | 10 | .. code-block:: python 11 | 12 | import tingbot 13 | from tingbot import * 14 | 15 | screen.fill(color='black') 16 | screen.text('Waiting...') 17 | 18 | @webhook('demo_sms') 19 | def on_webhook(data): 20 | screen.fill(color='black') 21 | screen.text(data, color='green') 22 | 23 | tingbot.run() 24 | 25 | .. py:decorator:: webhook(webhook_name…) 26 | 27 | This decorator calls the marked function when a HTTP POST request is made to the URL 28 | :samp:`http://webhook.tingbot.com/{webhook_name}`. To avoid choosing the same name as somebody else, you can add a `random string of characters `_ to the end. 29 | 30 | The POST data of the URL is available to the marked function as the ``data`` parameter. The data is limited to 1kb, and the last value that was POSTed is remembered by the server, 31 | so you can feed in relatively slow data sources. 32 | 33 | You can use webhooks to push data to Tingbot, or to notify Tingbot of an update that happened 34 | elsewhere on the internet. 35 | 36 | 37 | .. hint:: 38 | 39 | `IFTTT `_ is a great place to start for ideas for webhooks. 40 | `Slack `_ also has native support for webhooks! 41 | -------------------------------------------------------------------------------- /docs/touch.rst: -------------------------------------------------------------------------------- 1 | 👈 Touch 2 | -------- 3 | 4 | Your Tingbot comes equipped with a resistive touch screen! It's easy to react to touch events. 5 | 6 | .. code-block:: python 7 | :caption: Example: Simple drawing app 8 | 9 | import tingbot 10 | from tingbot import * 11 | 12 | screen.fill(color='black') 13 | 14 | @touch() 15 | def on_touch(xy): 16 | screen.rectangle(xy=xy, size=(5,5), color='blue') 17 | 18 | tingbot.run() 19 | 20 | This is a simple drawing app. It uses the ``@touch()`` decorator to receive touch events and draws a 21 | rectangle to the screen at the same place. 22 | 23 | .. py:decorator:: touch(xy=…, size=…, align=…) 24 | 25 | This 'decorator' marks the function after it to receive touch events. 26 | 27 | You can optionally pass an area that you're interested in, using the ``xy``, ``size`` and 28 | ``align`` arguments. If you specify no area, you will receive all touch events. 29 | 30 | The handler function can optionally take the arguments ``xy`` and ``action``. ``xy`` is the 31 | location of the touch. ``action`` is one of 'down', 'move', 'up'. 32 | 33 | .. code-block:: python 34 | :caption: Example: Simple Drawing app code 35 | 36 | @touch() 37 | def on_touch(xy): 38 | screen.rectangle(xy=xy, size=(5,5), color='blue') 39 | 40 | .. code-block:: python 41 | :caption: Example: Making a button do something 42 | 43 | @touch(xy=(0,0), size=(100,50), align='topleft') 44 | def on_touch(xy, action): 45 | if action == 'down': 46 | state['screen_number'] = 2 47 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import platform 5 | 6 | try: 7 | from setuptools import setup 8 | except ImportError: 9 | from distutils.core import setup 10 | 11 | with open('README.rst') as readme_file: 12 | readme = readme_file.read() 13 | 14 | requirements = [ 15 | 'pyzmq', 16 | 'docopt', 17 | 'virtualenv', 18 | 'requests', 19 | 'Pillow', 20 | 'pyudev', 21 | 'paramiko>=2.0.0', 22 | ] 23 | 24 | if 'arm' in platform.machine(): 25 | requirements.append('wiringpi') 26 | 27 | setup( 28 | name='tingbot-python', 29 | version='1.2.2', 30 | description="Python APIs to write apps for Tingbot", 31 | long_description=readme, 32 | author="Joe Rickerby", 33 | author_email='joerick@mac.com', 34 | url='https://github.com/tingbot/tingbot-python', 35 | packages=[ 36 | 'tingbot', 37 | 'tbtool' 38 | ], 39 | package_dir={'tingbot': 'tingbot', 40 | 'tbtool': 'tbtool'}, 41 | include_package_data=True, 42 | install_requires=requirements, 43 | obsoletes=['tingbot'], 44 | license="BSD", 45 | zip_safe=False, 46 | keywords='tingbot', 47 | classifiers=[ 48 | 'Intended Audience :: Developers', 49 | 'Natural Language :: English', 50 | "Programming Language :: Python :: 2", 51 | 'Programming Language :: Python :: 2.7', 52 | ], 53 | entry_points={ 54 | 'console_scripts': [ 55 | 'tbtool = tbtool.__main__:main', 56 | ], 57 | }, 58 | test_suite='tests', 59 | tests_require=['httpretty','mock'], 60 | ) 61 | -------------------------------------------------------------------------------- /tbtool/tingbot.key: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIIEogIBAAKCAQEAyaF6x657SOV0tC3tJwz6UPcZDefCAcWCFfaYWJoepledV/lv 3 | /NUM0q8lj2R78hI6QGPxH2+KyeUMrH60/KNRxKTn/FQoJgjCD8YoYqUp8ub3HZ6m 4 | 0pM++EvxofpXfnhx/ewF4xyqQlh6rgs4rbf23yq2A4kZgY/jj0QH/rY/fRYYAbeZ 5 | WT8ri95be66l0iD61Z1nywI2ARWr2Ze6alRZjNoydIulV97mooCDdQ4MP8SI4XVw 6 | 08i2azzwFwOwmsv39H5JMQVCxn53ZIfe7Y2SYZGHBwERRF/lqbW+6prkFr/3h1lf 7 | lN99tao2renJvn78+QYkr9t1oK7yJZ+r+x3g8QIDAQABAoIBAHbBrVc+5U4iF4Ko 8 | Ki397tEROKiAADya3+ufuks1OyguInZWbCc2NL9CeZTjUj1ZjwWt1670O4J+beCL 9 | IH5MkzSHDDwKNTtxnRs9UzwGm5Z9gr7nWspb/5Ku6DrHABF1T26HPVBu6bj59Afe 10 | hBuNZtI6jcm3TlaJMTaIk0zqeqpo87ChhVUrcHxhSYfhJ3thDHIiMkvTshNY9A1K 11 | Jsyp2X6c87BDeZomkyg36LvALwCNC44zf48YCtdzkOXtjUQyLq/osAFKfbFZubdU 12 | KAtTz+O4XHn/De0bKTe/hv9jZoSYVhOnu+hZFuMDBxcHOMRo8pYOYJK3XoKIbchU 13 | 7K7dIiECgYEA/WeEDEWuJTCacJPJTHR/KGaw5chO1oy44oQYkZlQtrgG2FFWtX0/ 14 | xlpnT8gR7Nqwm3SwT4lfnoRRXRSjXTVEMU7ohPnkVZJ2lWmFv4rLFvWMNRWvxA9N 15 | gEecyfFKFyQfxxl4xkGxzCcDfDY0cjJguEZJlrJDEOfC855o/ZCGfx8CgYEAy7Iz 16 | nh3NJ2mGn8T3ch0BU2TMicUdZQgovdUOwfJh+84Lawcyv8zTWh8r0YyPmlKxer9H 17 | qkRCMJOvMW10oBr9LAZdeTuRoFnq1xjJkWifmjK3skdMr6dL3iy3mwyqX+po1UA1 18 | tIrogyiA/a1cNSRu+YXloT44Fj0KcmZM4QHzbe8CgYAVDbWt41gtpNUgB1dRL9ik 19 | vaty2+qY7sYpo7n61tca5z1CWbevioFy9G3i9gdvO1gzAkXnxc0Y+XtdFWrhQpyw 20 | 0BKHgc+TwIBzt3mySVDIToxgmLWqv267+rcvHAoA1DKDsz0Sk8C26oLingpLdp4M 21 | kWJpz9O8otTSstWcQ5a5FwKBgDfn0djsrvjJMqS5B3zvTwTXXnfVfMrU4XGwfxtl 22 | 7dSRaXrXf+s6SSur8HfTzzn4xjM9OmsVzuDMN8ImG2Mx5RhnKtJyMfbDlvuwFups 23 | v5kvoFEy1m5DSURSG5ZXdI9co6cbt2G02jndLQHyyaLgPAEJ6ctGa1hXKn3Za/I5 24 | edlLAoGAQgnAIjm8ItxfePjbE933cmR2FSk8NBEukwQdAVPLubfWidTNKORbI3Yl 25 | p2Gg7WOpbhZfmK32ezZtv7oazonEBYaARFxjRmahc6uud9AJzNhtC3g7+CTkQau7 26 | SikodIa3OjZQY9wLR6kUH0IsJkBuvraYyKsi3fdP4zDHNCmRIRk= 27 | -----END RSA PRIVATE KEY----- 28 | -------------------------------------------------------------------------------- /tingbot/__init__.py: -------------------------------------------------------------------------------- 1 | import warnings 2 | try: 3 | import pygame 4 | except ImportError: 5 | print 'Failed to import pygame' 6 | print '-----------------------' 7 | print '' 8 | print 'tingbot-python requires pygame. Please download and install pygame 1.9.1' 9 | print 'or later from http://www.pygame.org/download.shtml' 10 | print '' 11 | print "If you're using a virtualenv, you should make the virtualenv with the " 12 | print "--system-site-packages flag so the system-wide installation is still " 13 | print "accessible." 14 | print '' 15 | print '-----------------------' 16 | print '' 17 | raise 18 | 19 | from . import platform_specific, input, quit 20 | 21 | from .graphics import screen, Surface, Image 22 | from .run_loop import main_run_loop, create_timer, every, after, once, RunLoop 23 | from .input import touch 24 | from .button import press, left_button, midleft_button, midright_button, right_button 25 | from .web import webhook 26 | from .tingapp import app 27 | from .hardware import get_ip_address, get_wifi_cell, mouse_attached, keyboard_attached, joystick_attached 28 | from .audio import Sound 29 | 30 | # enable deprecation warnings 31 | warnings.filterwarnings("once", ".*", DeprecationWarning) 32 | 33 | platform_specific.fixup_env() 34 | quit.fixup_sigterm_behaviour() 35 | 36 | def run(loop=None): 37 | if loop is not None: 38 | every(seconds=1.0/30)(loop) 39 | 40 | main_run_loop.run() 41 | 42 | __all__ = [ 43 | 'run', 'screen', 'Surface', 'Image', 'create_timer', 44 | 'every', 'once', 'after', 'RunLoop', 'touch', 'press', 'button', 'webhook', 45 | 'left_button', 'midleft_button', 'midright_button', 'right_button', 46 | 'get_ip_address', 'get_wifi_cell', 'mouse_attached', 'keyboard_attached', 'joystick_attached', 47 | 'Sound', 48 | ] 49 | __author__ = 'Joe Rickerby' 50 | __email__ = 'joerick@mac.com' 51 | __version__ = '1.2.2' 52 | -------------------------------------------------------------------------------- /tests/button_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from tingbot.button import Button 3 | 4 | 5 | class ButtonTestCase(unittest.TestCase): 6 | def setUp(self): 7 | self.button = Button() 8 | 9 | def assertActions(self, action_types): 10 | self.assertEqual(action_types, [a.type for a in self.button.actions]) 11 | 12 | def testPress(self): 13 | self.button.add_event('down', timestamp=1) 14 | self.button.add_event('up', timestamp=1.5) 15 | self.button.process_events(time=2) 16 | self.assertActions(['down', 'up', 'press']) 17 | 18 | def testHold(self): 19 | self.button.add_event('down', timestamp=1) 20 | self.button.add_event('up', timestamp=3) 21 | self.button.process_events(3.1) 22 | self.assertActions(['down', 'hold', 'up']) 23 | 24 | def testIncrementalHold(self): 25 | self.button.add_event('down', timestamp=1) 26 | self.button.process_events(time=1.1) 27 | self.assertActions(['down']) 28 | 29 | self.button.process_events(time=2.1) 30 | self.assertActions(['down', 'hold']) 31 | 32 | self.button.add_event('up', timestamp=3) 33 | self.button.process_events(time=3.1) 34 | self.assertActions(['down', 'hold', 'up']) 35 | 36 | def testRepeatedPress(self): 37 | self.button.add_event('down', timestamp=1) 38 | self.button.add_event('up', timestamp=1.5) 39 | self.button.add_event('down', timestamp=3.5) 40 | self.button.add_event('up', timestamp=4.0) 41 | self.button.process_events(time=4.1) 42 | self.assertActions(['down', 'up', 'press','down', 'up', 'press']) 43 | 44 | def testRepeatedQuickPress(self): 45 | self.button.add_event('down', timestamp=1) 46 | self.button.add_event('up', timestamp=1.5) 47 | self.button.add_event('down', timestamp=1.6) 48 | self.button.add_event('up', timestamp=2.2) 49 | self.button.process_events(time=4.1) 50 | self.assertActions(['down', 'up', 'press','down', 'up', 'press']) 51 | -------------------------------------------------------------------------------- /tests/typesetter_tests.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | import unittest, sys 3 | from tingbot.typesetter import Typesetter 4 | 5 | character_metrics = (0, 1, 0, 1, 1) 6 | def metrics_for_string(string): 7 | ''' All characters are 1x1 for easy testability ''' 8 | return (character_metrics, ) * len(string) 9 | 10 | class TypesetterTestCase(unittest.TestCase): 11 | def assertRenders(self, input, expected_output, max_lines=sys.maxsize, max_width=sys.maxsize, 12 | ellipsis='...', ellipsis_metrics=metrics_for_string('...')): 13 | t = Typesetter(input, metrics_for_string(input)) 14 | 15 | lines = t.lines( 16 | max_lines=max_lines, 17 | max_width=max_width, 18 | ellipsis=ellipsis, 19 | ellipsis_metrics=ellipsis_metrics) 20 | 21 | self.assertEqual(expected_output, [l.string for l in lines]) 22 | 23 | def test_trucate(self): 24 | self.assertRenders('12345678901234567890', ['1234567...', ], max_lines=1, max_width=10) 25 | 26 | def test_no_trucate(self): 27 | self.assertRenders('1234567890', ['1234567890', ], max_width=10) 28 | 29 | def test_midword_break(self): 30 | self.assertRenders('123456789012345', ['1234567890', '12345'], max_width=10) 31 | 32 | def test_word_break(self): 33 | self.assertRenders('asd asd asd asd', ['asd asd', 'asd asd'], max_width=10) 34 | 35 | def test_multiple_word_breaks(self): 36 | self.assertRenders('asd asd asd asd asd', ['asd asd', 'asd asd', 'asd'], max_width=10) 37 | 38 | def test_newline_break(self): 39 | self.assertRenders('asd asd\nasd asd', ['asd asd', 'asd asd']) 40 | 41 | def test_break_and_truncate(self): 42 | self.assertRenders('asd asd asd asd asd', ['asd asd', 'asd asd...'], max_lines=2, max_width=10) 43 | 44 | def test_zero_width(self): 45 | self.assertRenders('1234', ['1', '2', '3', '4'], max_width=0) 46 | 47 | def test_zero_width_and_truncate(self): 48 | self.assertRenders('1234', ['1', '2', '...'], max_width=0, max_lines=3) 49 | 50 | def test_single_line_zero_width_and_truncate(self): 51 | self.assertRenders('1234', ['...'], max_width=0, max_lines=1) 52 | 53 | def test_whitespace_after_newline(self): 54 | self.assertRenders('abc\n def', ['abc', ' def']) 55 | 56 | def test_truncate_whitespace_single_line(self): 57 | self.assertRenders('abc ', ['abc ...'], max_width=8, max_lines=1) 58 | -------------------------------------------------------------------------------- /docs/settings.rst: -------------------------------------------------------------------------------- 1 | ☑️ Settings 2 | ---------- 3 | 4 | You can store local data on the tingbot. Simply use ``tingbot.app.settings`` as a `dict `_. This will store 5 | any variables you like on a file in the application directory (called local_settings.json). This is 6 | stored in `JSON `_ format. 7 | 8 | .. code-block:: python 9 | 10 | import tingbot 11 | 12 | #store an item 13 | tingbot.app.settings['favourite_colour'] = 'red' 14 | 15 | #local_settings.json on disk now contains: {"favourite_colour":"red"} 16 | 17 | #retrieve an item 18 | tingbot.screen.fill(tingbot.app.settings['favourite_colour']) 19 | 20 | Any item that can be stored in JSON can be used in tingbot.app.settings - so strings, ints, floats, even dicts and lists can be used. 21 | 22 | .. note:: 23 | Take care when changing the insides of dicts or lists that are stored in tingbot.app.settings, as your changes will not be saved automatically. 24 | 25 | You can force a save by calling `tingbot.app.settings.save()` 26 | 27 | .. code-block:: python 28 | 29 | import tingbot 30 | 31 | # create a sub-dictionary 32 | tingbot.app.settings['ages'] = {'Phil': 39, 'Mabel': 73} 33 | 34 | # local_settings.json on disk now contains: {"ages":{"Phil":39,"Mabel":73}} 35 | 36 | tingbot.app.settings['ages']['Barry'] = 74 37 | 38 | # warning: local_settings.json has not been updated because you haven't directly changed tingbot.app.settings 39 | 40 | tingbot.app.settings.save() 41 | 42 | # now local_settings.json on disk now contains: {"ages":{"Phil":39,"Mabel":73,"Barry":74}} 43 | 44 | Storage 45 | ''''''' 46 | 47 | There are three settings files, that have different uses: 48 | 49 | * ``default_settings.json`` When writing your app, you can put default values for your settings in this file. 50 | 51 | * ``settings.json`` Somebody who's downloaded your app can create this file in Tide to fill in some settings before uploading to Tingbot. This file should be 'gitignored' so it's not shared when the app is copied, and can contain secrets like API keys or passwords. 52 | 53 | * ``local_settings.json`` When code within the app sets a setting, it's stored in this file. This prevents the app from overwriting data from the previous two files. This shouldn't be copied with an app and should be 'gitignored' too. 54 | 55 | When the first setting is accessed the app loads each file in turn, so values in 'local_settings' override those in 'settings', which override those is 'default_settings'. 56 | -------------------------------------------------------------------------------- /tingbot/error.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pygame.image, pygame.transform, pygame.font 3 | from . import graphics, utils 4 | 5 | sad_tingbot_string = ''' 6 | ######################### 7 | # # 8 | # # 9 | # ################# # 10 | # # # # 11 | # # # # 12 | # # # # # # # # 13 | # # # # # # 14 | # # # # # # # # 15 | # # # # 16 | # # # # # # 17 | # # ## # # 18 | # # # # 19 | # # ##### # # 20 | # # # ## # # 21 | # # # # # 22 | # # # # 23 | # ################# # 24 | # # 25 | # # 26 | ######################### 27 | # # 28 | # ## # 29 | # # # 30 | # # 31 | ######################### 32 | '''.replace('\n', '') 33 | 34 | 35 | def sad_tingbot_image(): 36 | result = pygame.image.fromstring(sad_tingbot_string, (25, 26), 'P') 37 | result.set_palette_at(ord('#'), (0,0,0)) 38 | result.set_palette_at(ord(' '), (255,255,255)) 39 | 40 | result = pygame.transform.scale(result, (50, 52)) 41 | 42 | return result 43 | 44 | 45 | def error_screen(exc_info): 46 | screen = graphics.screen 47 | if screen.has_surface: 48 | 49 | screen.fill(color='black') 50 | 51 | image = graphics.Image(surface=sad_tingbot_image()) 52 | 53 | screen.image(image, xy=(320/2, 85), align='center') 54 | 55 | line1 = type(exc_info[1]).__name__ 56 | frame = get_app_frame(exc_info[2]) 57 | filename = os.path.basename(frame.f_code.co_filename) 58 | line2 = '%s:%i' % (filename, frame.f_lineno) 59 | 60 | font = utils.get_resource('04B_03__.TTF') 61 | 62 | screen.text(line1, xy=(320/2, 135), color='white', align='center', font=font, font_size=16) 63 | screen.text(line2, xy=(320/2, 155), color='white', align='center', font=font, font_size=16) 64 | 65 | pygame.display.update() 66 | 67 | 68 | def get_app_frame(traceback): 69 | stack = [] 70 | 71 | while traceback: 72 | stack.append(traceback) 73 | traceback = traceback.tb_next 74 | 75 | # stack now contains all the tracebacks up to the frame where the exception was raised 76 | 77 | # loop starting from the most recent call 78 | for traceback in reversed(stack): 79 | frame = traceback.tb_frame 80 | 81 | filename = frame.f_code.co_filename 82 | 83 | is_library_code = (os.sep+'lib'+os.sep) in filename or ('-packages'+os.sep) in filename 84 | 85 | if not is_library_code: 86 | return frame 87 | 88 | # if the whole stack is library code, return the most recent frame 89 | return stack[-1].tb_frame 90 | -------------------------------------------------------------------------------- /tests/tingapp_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import tingbot.tingapp as tingapp 3 | import json 4 | import os 5 | import tempfile 6 | import shutil 7 | 8 | def fake_load_json(filename): 9 | if os.path.basename(filename) == 'default_settings.json': 10 | return {'a':1, 'b':2, 'c':3} 11 | elif os.path.basename(filename) == 'settings.json': 12 | return {'b':4, 'c':5} 13 | elif os.path.basename(filename) == 'local_settings.json': 14 | return {'c':6} 15 | 16 | class TestSettings(unittest.TestCase): 17 | def setUp(self): 18 | self.fake_tingapp_dir = tempfile.mkdtemp() 19 | 20 | with open(os.path.join(self.fake_tingapp_dir, 'default_settings.json'), 'w') as f: 21 | json.dump({'a':1, 'b':2, 'c':3}, f) 22 | with open(os.path.join(self.fake_tingapp_dir, 'settings.json'), 'w') as f: 23 | json.dump({'b':4, 'c':5}, f) 24 | with open(os.path.join(self.fake_tingapp_dir, 'local_settings.json'), 'w') as f: 25 | json.dump({'c':6}, f) 26 | 27 | self.settings = tingapp.SettingsDict(self.fake_tingapp_dir) 28 | 29 | def tearDown(self): 30 | shutil.rmtree(self.fake_tingapp_dir) 31 | 32 | def local_settings_contents(self): 33 | with open(os.path.join(self.fake_tingapp_dir, 'local_settings.json')) as f: 34 | return json.load(f) 35 | 36 | def test_simple_assign_and_retrieve(self): 37 | self.settings['fred'] = 12 38 | self.assertEqual(self.settings['fred'],12) 39 | 40 | def test_load_from_defaults(self): 41 | self.assertEqual(self.settings['a'],1) 42 | 43 | def test_load_from_gui(self): 44 | self.assertEqual(self.settings['b'],4) 45 | 46 | def test_load_from_locals(self): 47 | self.assertEqual(self.settings['c'],6) 48 | 49 | def test_save_updates_only_local_vars(self): 50 | self.settings.load() 51 | self.settings.save() 52 | self.assertEqual(self.local_settings_contents(),{'c':6}) 53 | 54 | def test_assign_to_existing(self): 55 | self.settings['a'] = 25 56 | self.assertEqual(self.local_settings_contents(),{'a':25,'c':6}) 57 | 58 | def test_update_existing(self): 59 | self.settings['c'] = 8 60 | self.assertEqual(self.local_settings_contents(),{'c':8}) 61 | 62 | def test_assign_to_new_key(self): 63 | self.settings['fred'] = 15 64 | self.assertEqual(self.local_settings_contents(),{'fred':15,'c':6}) 65 | 66 | def test_contains(self): 67 | self.assertEqual('a' in self.settings, True) 68 | 69 | @unittest.expectedFailure 70 | def test_assign_to_subkey(self): 71 | self.settings['map'] = {} 72 | self.settings['map']['subkey'] = 12 73 | self.assertEqual(self.local_settings_contents(),{'map':{'subkey':12},'c':6}) 74 | -------------------------------------------------------------------------------- /tingbot/input.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import sys 3 | from collections import namedtuple 4 | from .utils import call_with_optional_arguments 5 | from .graphics import screen, _topleft_from_aligned_xy, _xy_add, _xy_subtract 6 | 7 | mouse_down = False 8 | hit_areas = [] 9 | active_hit_areas = [] 10 | 11 | HitArea = namedtuple('HitArea', ('rect', 'callback')) 12 | 13 | class EventHandler(object): 14 | """call poll to handle touch events. Inherit from this class if you want 15 | to create a new touch handler, eg for within a modal dialog box""" 16 | 17 | def poll(self): 18 | if not pygame.display.get_init(): 19 | return 20 | for event in pygame.event.get(): 21 | # filter events if a touch handler is installed 22 | self.touch_handler(event) 23 | if event.type == pygame.KEYDOWN: 24 | command_down = (event.mod & 1024) or (event.mod & 2048) 25 | 26 | if event.key == 113 and command_down: 27 | sys.exit() 28 | 29 | elif event.type == pygame.QUIT: 30 | sys.exit() 31 | 32 | def touch_handler(self, event): 33 | handle_events(event) 34 | 35 | def handle_events(event): 36 | if event.type == pygame.MOUSEBUTTONDOWN: 37 | mouse_down(pygame.mouse.get_pos()) 38 | 39 | elif event.type == pygame.MOUSEMOTION: 40 | mouse_move(pygame.mouse.get_pos()) 41 | 42 | elif event.type == pygame.MOUSEBUTTONUP: 43 | mouse_up(pygame.mouse.get_pos()) 44 | 45 | 46 | def mouse_down(pos): 47 | for hit_area in hit_areas: 48 | if hit_area.rect.collidepoint(pos): 49 | active_hit_areas.append(hit_area) 50 | call_with_optional_arguments(hit_area.callback, xy=pos, action='down') 51 | 52 | def mouse_move(pos): 53 | for hit_area in active_hit_areas: 54 | call_with_optional_arguments(hit_area.callback, xy=pos, action='move') 55 | 56 | def mouse_up(pos): 57 | for hit_area in active_hit_areas: 58 | call_with_optional_arguments(hit_area.callback, xy=pos, action='up') 59 | 60 | # clear the list 61 | active_hit_areas[:] = [] 62 | 63 | class touch(object): 64 | def __init__(self, xy=None, size=None, align='center'): 65 | if xy is None and size is None: 66 | xy = (160, 120) 67 | size = screen.size 68 | align = 'center' 69 | elif size is None: 70 | size = (50, 50) 71 | 72 | topleft = _topleft_from_aligned_xy(xy=xy, align=align, size=size, surface_size=screen.size) 73 | self.offset = screen.surface.get_abs_offset() 74 | topleft = _xy_add(topleft, self.offset) 75 | self.rect = pygame.Rect(topleft, size) 76 | 77 | def __call__(self, f): 78 | def offset_callback(xy, action): 79 | temp_xy = _xy_subtract(xy, self.offset) 80 | call_with_optional_arguments(f, xy=temp_xy, action=action) 81 | 82 | hit_areas.append(HitArea(self.rect, offset_callback)) 83 | return f 84 | -------------------------------------------------------------------------------- /tingbot/platform_specific/sdl_wrapper.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import os 3 | 4 | button_callback = None 5 | 6 | left_margin = 25 7 | bottom_margin = 12 8 | top_margin = 12 9 | 10 | bot_width = 470 11 | bot_height = 353 12 | 13 | background_color = (50, 50, 50) 14 | button_color = (170, 170, 170) 15 | 16 | simulator = None 17 | 18 | class Simulator(object): 19 | def __init__(self): 20 | pygame.init() 21 | height = top_margin + bot_height + bottom_margin 22 | width = bot_width + left_margin 23 | self.surface = pygame.display.set_mode((width, height)) 24 | 25 | self.screen = self.surface.subsurface((86, 54, 320, 240)) 26 | bot_image = pygame.image.load(os.path.join(os.path.dirname(__file__), 'bot.png')) 27 | self.surface.fill(background_color) 28 | self.surface.blit(bot_image, (left_margin, top_margin)) 29 | 30 | button_positions = (85, 125, 345, 385) 31 | self.buttons = [] 32 | for button_index, x_position in enumerate(button_positions): 33 | button_surface = self.surface.subsurface(x_position, top_margin, 22, 12) 34 | button = Button(button_surface, button_index) 35 | self.buttons.append(button) 36 | 37 | pygame.display.update() 38 | 39 | 40 | class Button(object): 41 | def __init__(self, surface, number): 42 | from ..input import hit_areas, HitArea 43 | self.number = number 44 | surface.fill(button_color) 45 | 46 | # register our button as something clickable 47 | self.surface = surface 48 | hit_areas.append(HitArea(pygame.Rect(surface.get_abs_offset(), surface.get_size()), self.click)) 49 | 50 | def click(self, xy, action): 51 | if action == 'down': 52 | w, h = self.surface.get_size() 53 | self.surface.fill(background_color, (0, 0, w, h*0.2)) 54 | self.surface.fill(button_color, (0, h*0.2, w, h)) 55 | if button_callback: 56 | button_callback(self.number, 'down') 57 | elif action == 'up': 58 | self.surface.fill(button_color) 59 | if button_callback: 60 | button_callback(self.number, 'up') 61 | pygame.display.update((self.surface.get_abs_offset(), self.surface.get_size())) 62 | 63 | def ensure_setup(): 64 | if simulator is None: 65 | setup() 66 | 67 | def setup(): 68 | global simulator 69 | simulator = Simulator() 70 | 71 | def create_main_surface(): 72 | ensure_setup() 73 | return simulator.screen 74 | 75 | def fixup_env(): 76 | pass 77 | 78 | def register_button_callback(callback): 79 | ''' 80 | callback(button_index, action) 81 | button_index is a zero-based index that identifies which button has been pressed 82 | action is either 'down', or 'up'. 83 | 84 | The callback might not be called on the main thread. 85 | 86 | Currently only 'down' is implemented. 87 | ''' 88 | ensure_setup() 89 | global button_callback 90 | button_callback = callback 91 | -------------------------------------------------------------------------------- /tests/hardware_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import subprocess 3 | import json 4 | 5 | # hardware function implementations are in the platform_specific module 6 | import tingbot.platform_specific.tingbot as hardware 7 | 8 | class FakeDevice(object): 9 | def __init__(self, items): 10 | self.properties = items 11 | 12 | class FakeContext(object): 13 | def __init__(self): 14 | with open("tests/peripherals.json", "r") as fp: 15 | devices = json.load(fp) 16 | self.devices = [FakeDevice(x) for x in devices] 17 | 18 | def list_devices(self, **kwargs): 19 | devs = [] 20 | for k, v in kwargs.items(): 21 | devs.extend([x for x in self.devices if k in x.properties]) 22 | return devs 23 | 24 | class TestPeripherals(unittest.TestCase): 25 | def setUp(self): 26 | hardware.udev_context = FakeContext() 27 | 28 | def test_count_peripherals(self): 29 | self.assertEqual(hardware.count_peripherals('SOMETHING RANDOM'), 0) 30 | self.assertEqual(hardware.count_peripherals('ID_INPUT_KEYBOARD'), 2) 31 | self.assertEqual(hardware.count_peripherals('ID_INPUT_MOUSE'), 1) 32 | self.assertEqual(hardware.count_peripherals('ID_INPUT_JOYSTICK'), 0) 33 | 34 | def test_mouse_attached(self): 35 | self.assertTrue(hardware.mouse_attached()) 36 | 37 | def test_keyboard_attached(self): 38 | self.assertTrue(hardware.keyboard_attached()) 39 | 40 | def test_joystick_attached(self): 41 | self.assertFalse(hardware.joystick_attached()) 42 | 43 | class TestNetwork(unittest.TestCase): 44 | def setUp(self): 45 | self.old_check_output = subprocess.check_output 46 | subprocess.check_output = self.generate_iw_config 47 | self.connected = True 48 | self.adapter = True 49 | 50 | def tearDown(self): 51 | subprocess.check_output = self.old_check_output 52 | 53 | def generate_iw_config(self, dummy): 54 | if self.adapter: 55 | if self.connected: 56 | return """ 57 | wlan0 IEEE 802.11bgn ESSID:"wifi_test_cell" 58 | Mode:Managed Frequency:2.437 GHz Access Point: 00:11:22:33:44:55 59 | Bit Rate=150 Mb/s Tx-Power=16 dBm 60 | Retry short limit:7 RTS thr:off Fragment thr:off 61 | Power Management:off 62 | Link Quality=64/70 Signal level=-36 dBm 63 | Rx invalid nwid:0 Rx invalid crypt:0 Rx invalid frag:0 64 | Tx excessive retries:1 Invalid misc:331 Missed beacon:0 65 | """ 66 | else: 67 | return """ 68 | wlan0 IEEE 802.11bgn ESSID:off/any 69 | Mode:Managed Access Point: Not-Associated Tx-Power=15 dBm 70 | Retry short limit:7 RTS thr:off Fragment thr:off 71 | Power Management:off 72 | """ 73 | else: 74 | raise subprocess.CalledProcessError(-1, "command failed") 75 | 76 | def test_get_wifi_cell_connected(self): 77 | self.connected = True 78 | cell = hardware.get_wifi_cell() 79 | self.assertEqual(cell.ssid, "wifi_test_cell") 80 | self.assertEqual(cell.link_quality, 64) 81 | self.assertEqual(cell.signal_level, -36) 82 | 83 | def test_get_wifi_cell_disconnected(self): 84 | self.connected = False 85 | cell = hardware.get_wifi_cell() 86 | self.assertIsNone(cell.ssid) 87 | self.assertIsNone(cell.link_quality) 88 | self.assertIsNone(cell.signal_level) 89 | 90 | def test_get_wifi_cell_no_adapter(self): 91 | self.adapter = False 92 | cell = hardware.get_wifi_cell() 93 | self.assertIsNone(cell) 94 | -------------------------------------------------------------------------------- /docs/buttons.rst: -------------------------------------------------------------------------------- 1 | ◽️ ️Buttons 2 | --------- 3 | 4 | There are four buttons on the top of the Tingbot. These can be used in programs to trigger functions in your code. 5 | 6 | .. code-block:: python 7 | :caption: Example: Score-keeping app. 8 | 9 | import tingbot 10 | from tingbot import * 11 | 12 | state = {'score': 0} 13 | 14 | @left_button.press 15 | def on_left(): 16 | state['score'] -= 1 17 | 18 | @right_button.press 19 | def on_right(): 20 | state['score'] += 1 21 | 22 | def loop(): 23 | screen.fill( 24 | color='black') 25 | screen.text( 26 | state['score'], 27 | color='white') 28 | 29 | tingbot.run(loop) 30 | 31 | This is a simple counter program. Whenever the right button is pressed, the score goes up by one. On 32 | the left button, the score goes down. 33 | 34 | .. py:decorator:: left_button.press 35 | .. py:decorator:: midleft_button.press 36 | .. py:decorator:: midright_button.press 37 | .. py:decorator:: right_button.press 38 | 39 | This 'decorator' marks the function to be called when a button is pressed. 40 | 41 | ``button`` can be one of: left_button, midleft_button, midright_button, right_button. 42 | 43 | .. code-block:: python 44 | :caption: Example: Button handler 45 | 46 | @left_button.press 47 | def on_left(): 48 | state['score'] -= 1 49 | 50 | .. code-block:: python 51 | :caption: Example: Button handler for all buttons 52 | 53 | @left_button.press 54 | @midleft_button.press 55 | @midright_button.press 56 | @right_button.press 57 | def on_button(): 58 | state['score'] -= 1 59 | 60 | Only presses shorter than a second count - anything longer counts as a 'hold' event. 61 | 62 | .. py:decorator:: Button.hold 63 | 64 | This marks the function to be called when a button is held down for longer than a 65 | second. 66 | 67 | .. code-block:: python 68 | :caption: Example: Reset button handler 69 | 70 | @left_button.hold 71 | def reset_score(): 72 | state['score'] = 0 73 | 74 | .. py:decorator:: Button.down 75 | 76 | This marks the function to be called as soon as a button is pushed down. This could 77 | be the start of a 'press' or a 'hold' event. 78 | 79 | This one is useful for games or when you want the button to be as responsive as possible. 80 | 81 | .. code-block:: python 82 | :caption: Example: Reset button handler 83 | 84 | @right_button.down 85 | def jump(): 86 | dude.jump() 87 | 88 | .. py:decorator:: Button.up 89 | 90 | This marks the function to be called when a button is released. 91 | 92 | .. code-block:: python 93 | :caption: Example: Down/up handler pair 94 | 95 | @right_button.down 96 | def down(): 97 | state['button_is_down'] = True 98 | 99 | @right_button.up 100 | def up(): 101 | state['button_is_down'] = False 102 | 103 | .. py:decorator:: button.combo(buttons...) 104 | 105 | This marks the function to be called when some buttons are pressed at the same time. 106 | 107 | You can give it as many buttons as you like and ``combo`` will call the function when all 108 | the buttons are pressed together. 109 | 110 | .. code-block:: python 111 | :caption: Example: Combo to dim/wake the screen 112 | 113 | @button.combo(left_button, right_button) 114 | def screen_dim(): 115 | if screen.brightness == 100: 116 | screen.brightness = 0 117 | else: 118 | screen.brightness = 100 119 | 120 | -------------------------------------------------------------------------------- /tingbot/utils.py: -------------------------------------------------------------------------------- 1 | 2 | class Struct(object): 3 | def __init__(self, **kwds): 4 | self.__dict__.update(kwds) 5 | 6 | 7 | class CallbackList(object): 8 | def __init__(self): 9 | self._list = [] 10 | 11 | def __call__(self): 12 | for callback in self._list: 13 | callback() 14 | 15 | def add(self, callback): 16 | self._list.append(callback) 17 | 18 | def copy(self): 19 | obj = CallbackList() 20 | obj._list = self._list[:] 21 | return obj 22 | 23 | 24 | # cached_property from werkzeug 25 | _missing = object() 26 | 27 | class cached_property(object): 28 | """A decorator that converts a function into a lazy property. The 29 | function wrapped is called the first time to retrieve the result 30 | and then that calculated result is used the next time you access 31 | the value:: 32 | 33 | class Foo(object): 34 | 35 | @cached_property 36 | def foo(self): 37 | # calculate something important here 38 | return 42 39 | 40 | The class has to have a `__dict__` in order for this property to 41 | work. 42 | """ 43 | 44 | # implementation detail: this property is implemented as non-data 45 | # descriptor. non-data descriptors are only invoked if there is 46 | # no entry with the same name in the instance's __dict__. 47 | # this allows us to completely get rid of the access function call 48 | # overhead. If one choses to invoke __get__ by hand the property 49 | # will still work as expected because the lookup logic is replicated 50 | # in __get__ for manual invocation. 51 | 52 | def __init__(self, func, name=None, doc=None): 53 | self.__name__ = name or func.__name__ 54 | self.__module__ = func.__module__ 55 | self.__doc__ = doc or func.__doc__ 56 | self.func = func 57 | 58 | def __get__(self, obj, type=None): 59 | if obj is None: 60 | return self 61 | value = obj.__dict__.get(self.__name__, _missing) 62 | if value is _missing: 63 | value = self.func(obj) 64 | obj.__dict__[self.__name__] = value 65 | return value 66 | 67 | 68 | class only_call_once(object): 69 | ''' 70 | A function decorator that only calls the wrapped function once. Subsequent calls do nothing. 71 | ''' 72 | def __init__(self, func): 73 | self.__name__ = func.__name__ 74 | self.__module__ = func.__module__ 75 | self.__doc__ = func.__doc__ 76 | self.func = func 77 | self.has_run = False 78 | 79 | def __call__(self): 80 | if not self.has_run: 81 | self.func() 82 | self.has_run = True 83 | 84 | 85 | def call_with_optional_arguments(func, **kwargs): 86 | ''' 87 | calls a function with the arguments **kwargs, but only those that the function defines. 88 | e.g. 89 | 90 | def fn(a, b): 91 | print a, b 92 | 93 | call_with_optional_arguments(fn, a=2, b=3, c=4) # because fn doesn't accept `c`, it is discarded 94 | ''' 95 | 96 | import inspect 97 | function_arg_names = inspect.getargspec(func).args 98 | 99 | for arg in kwargs.keys(): 100 | if arg not in function_arg_names: 101 | del kwargs[arg] 102 | 103 | func(**kwargs) 104 | 105 | 106 | def get_resource(name): 107 | ''' 108 | Returns the path to a resource bundled in this library (at tingbot/resources/) 109 | ''' 110 | import os 111 | return os.path.join(os.path.dirname(__file__), 'resources', name) 112 | 113 | 114 | import warnings 115 | 116 | 117 | class deprecated(object): 118 | ''' 119 | Decorates ("marks") a callable as deprecated. 120 | 121 | Example: 122 | 123 | @deprecated('Use after instead', version='1.1.0') 124 | def once(): 125 | pass 126 | ''' 127 | def __init__(self, message, version=''): 128 | self.message = message 129 | self.version = version 130 | 131 | def __call__(self, func): 132 | return deprecated_callable(func, message=self.message, version=self.version) 133 | 134 | 135 | def deprecated_callable(func, version, message='', name=None): 136 | ''' 137 | Returns a function that will warn the caller when called, but otherwise 138 | work as normal. 139 | ''' 140 | 141 | def deprecated_callable_inner(*args, **kwargs): 142 | warnings.warn( 143 | '{func_name} is deprecated (since {version}). {message}'.format( 144 | func_name=name or func.__name__, 145 | version=version, 146 | message=message), 147 | DeprecationWarning, 148 | stacklevel=2) 149 | 150 | return func(*args, **kwargs) 151 | 152 | return deprecated_callable_inner 153 | -------------------------------------------------------------------------------- /tingbot/platform_specific/tingbot.py: -------------------------------------------------------------------------------- 1 | import os, subprocess, re 2 | from ..utils import only_call_once 3 | 4 | def fixup_env(): 5 | import evdev 6 | os.environ["SDL_FBDEV"] = "/dev/fb1" 7 | 8 | mouse_path = None 9 | 10 | for device_path in evdev.list_devices(): 11 | device = evdev.InputDevice(device_path) 12 | if device.name == "ADS7846 Touchscreen": 13 | mouse_path = device_path 14 | 15 | if mouse_path: 16 | os.environ["SDL_MOUSEDRV"] = "TSLIB" 17 | os.environ["SDL_MOUSEDEV"] = mouse_path 18 | else: 19 | print 'Mouse input device not found in /dev/input. Touch support not available.' 20 | 21 | def create_main_surface(): 22 | import pygame 23 | pygame.init() 24 | surface = pygame.display.set_mode((320, 240)) 25 | import pygame.mouse 26 | pygame.mouse.set_visible(0) 27 | return surface 28 | 29 | ########### 30 | # Buttons # 31 | ########### 32 | 33 | button_callback = None 34 | 35 | def register_button_callback(callback): 36 | global button_callback 37 | ensure_button_setup() 38 | button_callback = callback 39 | 40 | button_pins = (17, 23, 24, 14) 41 | 42 | @only_call_once 43 | def ensure_wiringpi_setup(): 44 | import wiringpi 45 | wiringpi.wiringPiSetupGpio() 46 | 47 | @only_call_once 48 | def ensure_button_setup(): 49 | import wiringpi 50 | 51 | ensure_wiringpi_setup() 52 | 53 | for button_pin in button_pins: 54 | wiringpi.pinMode(button_pin, wiringpi.INPUT) 55 | wiringpi.wiringPiISR(button_pin, wiringpi.INT_EDGE_BOTH, GPIO_callback) 56 | 57 | button_previous_states = [0, 0, 0, 0] 58 | 59 | def GPIO_callback(): 60 | import wiringpi 61 | global button_previous_states 62 | 63 | button_states = [wiringpi.digitalRead(pin) for pin in button_pins] 64 | 65 | for button_index, (old, new) in enumerate(zip(button_previous_states, button_states)): 66 | if old != new and button_callback is not None: 67 | button_callback(button_index, 'down' if (new == 1) else 'up') 68 | 69 | button_previous_states = button_states 70 | 71 | ############# 72 | # Backlight # 73 | ############# 74 | 75 | @only_call_once 76 | def ensure_backlight_setup(): 77 | subprocess.check_call(['gpio', '-g', 'mode', '18', 'pwm']) 78 | subprocess.check_call(['gpio', '-g', 'pwmr', '65536']) 79 | 80 | def set_backlight(brightness): 81 | ''' 82 | Sets the backlight of the screen to `brightness`. `brightness` is a number from 0 to 100. 83 | ''' 84 | ensure_backlight_setup() 85 | 86 | if brightness <= 4: 87 | # linear scaling from 0 to 4 88 | value = brightness 89 | else: 90 | # cubic scaling from 4 to 100 91 | value = 65536 * (brightness/100.0)**3 92 | 93 | subprocess.check_call(['gpio', '-g', 'pwm', '18', str(value)]) 94 | 95 | ############### 96 | # Peripherals # 97 | ############### 98 | 99 | udev_context = None 100 | 101 | def ensure_udev_setup(): 102 | global udev_context 103 | if udev_context is None: 104 | import pyudev 105 | udev_context = pyudev.Context() 106 | 107 | def count_peripherals(name): 108 | ensure_udev_setup() 109 | 110 | args = {name: 1} 111 | devices = udev_context.list_devices(**args) 112 | unique_devices = set(x.properties['ID_PATH'] for x in devices) 113 | return len(unique_devices) 114 | 115 | def mouse_attached(): 116 | return count_peripherals('ID_INPUT_MOUSE') > 0 117 | 118 | def keyboard_attached(): 119 | return count_peripherals('ID_INPUT_KEYBOARD') > 0 120 | 121 | def joystick_attached(): 122 | return count_peripherals('ID_INPUT_JOYSTICK') > 0 123 | 124 | ########### 125 | # Network # 126 | ########### 127 | 128 | class WifiCell(): 129 | attribute_patterns = { 130 | 'ssid': r'ESSID:"(.+)"', 131 | 'link_quality': r'Link Quality\s*=\s*(-?\d+)', 132 | 'signal_level': r'Signal Level\s*=\s*(-?\d+)' 133 | } 134 | 135 | def __init__(self, data): 136 | for attr, pattern in self.attribute_patterns.items(): 137 | match = re.search(pattern, data, flags=re.I) 138 | if match: 139 | if attr in ('ssid',): 140 | setattr(self, attr, match.group(1)) 141 | else: 142 | setattr(self, attr, int(match.group(1))) 143 | else: 144 | setattr(self, attr, None) 145 | 146 | def get_wifi_cell(): 147 | """ 148 | Returns the current wifi cell (if attached) 149 | Returns "" if not currently attached 150 | Returns None if no wifi adapter present 151 | """ 152 | try: 153 | iw_data = subprocess.check_output(['iwconfig', 'wlan0']) 154 | except subprocess.CalledProcessError: 155 | # wlan0 not found 156 | return None 157 | return WifiCell(iw_data) 158 | 159 | ######### 160 | # Audio # 161 | ######### 162 | 163 | def setup_audio(): 164 | subprocess.check_call(['tbsetupaudio']) 165 | -------------------------------------------------------------------------------- /tingbot/run_loop.py: -------------------------------------------------------------------------------- 1 | import sys, operator, time, traceback, Queue 2 | from .utils import Struct, CallbackList, deprecated_callable 3 | from . import error 4 | from .graphics import screen 5 | from .input import EventHandler 6 | 7 | class Timer(Struct): 8 | def __init__(self, **kwargs): 9 | self.active = True 10 | super(Timer, self).__init__(**kwargs) 11 | 12 | def stop(self): 13 | self.active = False 14 | 15 | def run(self): 16 | if self.active: 17 | self.action() 18 | 19 | def create_timer(action, hours=0, minutes=0, seconds=0, period=0, repeating=True): 20 | if period == 0: 21 | period = (hours * 60 + minutes) * 60 + seconds 22 | timer = Timer(action=action, period=period, repeating=repeating, next_fire_time=None) 23 | main_run_loop.schedule(timer) 24 | return timer 25 | 26 | class every(object): 27 | def __init__(self, hours=0, minutes=0, seconds=0): 28 | self.period = (hours * 60 + minutes) * 60 + seconds 29 | 30 | def __call__(self, f): 31 | create_timer(action=f, period=self.period, repeating=True) 32 | return f 33 | 34 | class after(object): 35 | def __init__(self, hours=0, minutes=0, seconds=0): 36 | self.period = (hours * 60 + minutes) * 60 + seconds 37 | 38 | def __call__(self, f): 39 | create_timer(action=f, period=self.period, repeating=False) 40 | return f 41 | 42 | once = deprecated_callable( 43 | after, 44 | name='once', 45 | version='1.1.1', 46 | message='once has been renamed to \'after\'. Use \'after\' instead.') 47 | 48 | class RunLoop(object): 49 | 50 | _call_after_queue = Queue.Queue() 51 | 52 | def __init__(self, event_handler=None): 53 | self._wait_callbacks = CallbackList() 54 | self._before_action_callbacks = CallbackList() 55 | self._after_action_callbacks = CallbackList() 56 | self.timers = [] 57 | 58 | # add screen update callbacks 59 | self.add_after_action_callback(screen.update_if_needed) 60 | 61 | if event_handler: 62 | self.add_wait_callback(event_handler.poll) 63 | # in case screen updates happen in input.poll... 64 | self.add_wait_callback(screen.update_if_needed) 65 | 66 | def schedule(self, timer): 67 | if timer.next_fire_time is None: 68 | if timer.repeating: 69 | # if it's repeating, and it's never been called, call it now 70 | timer.next_fire_time = 0 71 | else: 72 | # call it after 'period' 73 | timer.next_fire_time = time.time() + timer.period 74 | 75 | self.timers.append(timer) 76 | self.timers.sort(key=operator.attrgetter('next_fire_time'), reverse=True) 77 | 78 | def run(self): 79 | self.running = True 80 | while self.running: 81 | if len(self.timers) > 0: 82 | try: 83 | self._wait(lambda: self.timers[-1].next_fire_time) 84 | except Exception as e: 85 | self._error(e) 86 | continue 87 | 88 | next_timer = self.timers.pop() 89 | 90 | if next_timer.active: 91 | before_action_time = time.time() 92 | 93 | try: 94 | self._before_action_callbacks() 95 | next_timer.run() 96 | self._after_action_callbacks() 97 | except Exception as e: 98 | self._error(e) 99 | finally: 100 | if next_timer.repeating and next_timer.active: 101 | next_timer.next_fire_time = before_action_time + next_timer.period 102 | self.schedule(next_timer) 103 | else: 104 | try: 105 | wait_delay = time.time() + 0.1 106 | self._wait(lambda: wait_delay) 107 | except Exception as e: 108 | self._error(e) 109 | 110 | def stop(self): 111 | self.running = False 112 | 113 | def add_wait_callback(self, callback): 114 | self._wait_callbacks.add(callback) 115 | 116 | def add_before_action_callback(self, callback): 117 | self._before_action_callbacks.add(callback) 118 | 119 | def add_after_action_callback(self, callback): 120 | self._after_action_callbacks.add(callback) 121 | 122 | @classmethod 123 | def call_after(cls, func): 124 | cls._call_after_queue.put(func) 125 | 126 | @classmethod 127 | def empty_call_after_queue(cls): 128 | while True: 129 | try: 130 | func = cls._call_after_queue.get_nowait() 131 | func() 132 | cls._call_after_queue.task_done() 133 | except Queue.Empty: 134 | break 135 | 136 | 137 | def _wait(self, until): 138 | self._wait_callbacks() 139 | 140 | while time.time() < until(): 141 | if not self._call_after_queue.empty(): 142 | self.empty_call_after_queue() 143 | time.sleep(0.001) 144 | self._wait_callbacks() 145 | 146 | def _error(self, exception): 147 | sys.stderr.write('\n' + str(exception) + '\n') 148 | 149 | traceback.print_exc() 150 | 151 | error.error_screen(sys.exc_info()) 152 | time.sleep(0.5) 153 | 154 | 155 | main_run_loop = RunLoop(event_handler=EventHandler()) 156 | -------------------------------------------------------------------------------- /tingbot/button.py: -------------------------------------------------------------------------------- 1 | import time 2 | import threading 3 | import warnings 4 | from collections import namedtuple, deque 5 | import Queue 6 | 7 | from .utils import CallbackList 8 | 9 | ButtonEvent = namedtuple('ButtonEvent', ('state', 'timestamp',)) 10 | ButtonAction = namedtuple('ButtonAction', ('type', 'timestamp',)) 11 | 12 | action_types = ['press', 'hold', 'down', 'up'] 13 | 14 | 15 | class Button(object): 16 | def __init__(self): 17 | self.event_queue = Queue.Queue() 18 | self.last_event = None 19 | self.hold_time = 1.0 20 | self.last_hold_check_time = 0 21 | self.callbacks = {x: CallbackList() for x in action_types} 22 | self.actions = deque() 23 | 24 | def process_events(self, time): 25 | while True: 26 | try: 27 | event = self.event_queue.get(block=False) 28 | except Queue.Empty: 29 | break 30 | 31 | self.fire_hold_if_due(event.timestamp) 32 | 33 | if event.state == 'down': 34 | self.fire(ButtonAction('down', timestamp=event.timestamp)) 35 | elif event.state == 'up': 36 | self.fire(ButtonAction('up', timestamp=event.timestamp)) 37 | 38 | # check to see if press should be fired 39 | if self.last_event.state == 'down': 40 | press_duration = event.timestamp - self.last_event.timestamp 41 | 42 | if press_duration < self.hold_time: 43 | self.fire(ButtonAction('press', timestamp=event.timestamp)) 44 | 45 | self.last_event = event 46 | 47 | self.fire_hold_if_due(time) 48 | 49 | def fire_hold_if_due(self, time): 50 | ''' check to see if the hold event needs to be fired ''' 51 | 52 | if self.last_event and self.last_event.state == 'down': 53 | hold_trigger_time = self.last_event.timestamp + self.hold_time 54 | 55 | if self.last_hold_check_time < hold_trigger_time <= time: 56 | self.fire(ButtonAction('hold', timestamp=hold_trigger_time)) 57 | 58 | self.last_hold_check_time = time 59 | 60 | def fire(self, action): 61 | self.actions.append(action) 62 | 63 | def run_callbacks(self): 64 | while self.actions: 65 | action = self.actions.popleft() 66 | self.callbacks[action.type]() 67 | 68 | def add_event(self, action, timestamp=None): 69 | if timestamp is None: 70 | timestamp = time.time() 71 | self.event_queue.put(ButtonEvent(action, timestamp)) 72 | 73 | def add_callback(self, event, func): 74 | ensure_setup() 75 | self.callbacks[event].add(func) 76 | 77 | def __call__(self, f): 78 | print "calling" 79 | self.down(f) 80 | 81 | def down(self, f): 82 | self.add_callback('down', f) 83 | return f 84 | 85 | def up(self, f): 86 | self.add_callback('up', f) 87 | return f 88 | 89 | def press(self, f): 90 | self.add_callback('press', f) 91 | return f 92 | 93 | def hold(self, f): 94 | self.add_callback('hold', f) 95 | return f 96 | 97 | 98 | class combo(object): 99 | ''' 100 | A decorator to define an action when multiple buttons are pressed together. 101 | 102 | Pass the buttons to use in a combo into the contructor. 103 | 104 | Example: 105 | @combo(left_button, right_button) 106 | def do_a_thing(): 107 | screen.text('C-c-c-COMBO!') 108 | ''' 109 | def __init__(self, *args): 110 | self.buttons = args 111 | self.button_states = [False,] * len(self.buttons) 112 | 113 | for button_i, button in enumerate(self.buttons): 114 | down_handler, up_handler = self.make_handlers(button_i) 115 | button.down(down_handler) 116 | button.up(up_handler) 117 | 118 | def make_handlers(self, button_i): 119 | # this code is in a separate method to avoid loop 'late-binding' 120 | # problems 121 | def down_handler(): 122 | self.button_states[button_i] = True 123 | self.check_button_states() 124 | def up_handler(): 125 | self.button_states[button_i] = False 126 | return down_handler, up_handler 127 | 128 | def __call__(self, func): 129 | self.func = func 130 | 131 | def check_button_states(self): 132 | if all(self.button_states): 133 | self.func() 134 | 135 | 136 | # create buttons 137 | button_names = ('left', 'midleft', 'midright', 'right') 138 | buttons = {x: Button() for x in button_names} 139 | left_button, midleft_button, midright_button, right_button = [buttons[x] for x in button_names] 140 | 141 | 142 | is_setup = False 143 | 144 | def ensure_setup(): 145 | global is_setup 146 | if not is_setup: 147 | setup() 148 | is_setup = True 149 | 150 | class press(object): 151 | def __init__(self, button): 152 | warnings.warn( 153 | 'press is deprecated. Use .down (or up, press, or hold) instead.', 154 | DeprecationWarning, 155 | stacklevel=2) 156 | self.button = buttons[button] 157 | 158 | def __call__(self, f): 159 | self.button.down(f) 160 | 161 | 162 | def setup(): 163 | from platform_specific import register_button_callback 164 | register_button_callback(button_callback) 165 | 166 | from .run_loop import main_run_loop 167 | main_run_loop.add_wait_callback(wait) 168 | 169 | def button_callback(button_index, action): 170 | button_name = button_names[button_index] 171 | button = buttons[button_name] 172 | 173 | button.add_event(action) 174 | 175 | def wait(): 176 | for button in buttons.values(): 177 | button.process_events(time.time()) 178 | button.run_callbacks() 179 | -------------------------------------------------------------------------------- /tingbot/cache.py: -------------------------------------------------------------------------------- 1 | # image cache 2 | import time 3 | import re 4 | import rfc822 5 | import calendar 6 | import requests 7 | import io 8 | import os 9 | import threading 10 | from urlparse import urlparse 11 | 12 | 13 | def get_http_timestamp(dt): 14 | return calendar.timegm(rfc822.parsedate(dt)) 15 | 16 | 17 | def get_server_date(response): 18 | try: 19 | return get_http_timestamp(response.headers['date']) 20 | except (KeyError, TypeError): 21 | # no date supplied, have to assume no time offset 22 | return time.time() 23 | 24 | 25 | def get_last_modified(response): 26 | """try and determine the last_modified time of a request""" 27 | try: 28 | return get_http_timestamp(response.headers['last-modified']) 29 | except (KeyError, TypeError): 30 | return None 31 | 32 | 33 | def get_max_age(response, last_modified): 34 | """return how many seconds from original access this response is valid for""" 35 | try: 36 | cache_control = response.headers['cache-control'] 37 | return int(re.match(r"max-age\W*=\W*(\d+)", cache_control).group(1)) 38 | except (KeyError, ValueError, AttributeError, TypeError): 39 | pass 40 | try: 41 | return int(response.headers['max-age']) 42 | except (KeyError, ValueError): 43 | pass 44 | try: 45 | expires = get_http_timestamp(response.headers['expires']) 46 | return expires - get_server_date(response) 47 | except (KeyError, TypeError): 48 | # really no info from server so guess based on last-modified 49 | if last_modified: 50 | return min(24*60*60, (get_server_date(response) - last_modified)/10) 51 | else: 52 | # not even a last_modified - so conservative guess of 60s 53 | return 60 54 | 55 | 56 | def get_etag(response): 57 | try: 58 | return response.headers['etag'] 59 | except KeyError: 60 | return None 61 | 62 | 63 | def is_url(loc): 64 | """returns true if loc is a url, and false if not""" 65 | return (urlparse(loc).scheme != '') 66 | 67 | 68 | class ImageEntry(object): 69 | # abstract base class 70 | def get_image(self): 71 | self.last_accessed = time.time() # local time 72 | return self.image 73 | 74 | def get_size(self): 75 | return self.image.get_memory_usage() 76 | 77 | 78 | class WebImage(ImageEntry): 79 | def __init__(self, url): 80 | import graphics 81 | self.url = url 82 | response = requests.get(url) 83 | response.raise_for_status() # raise exception if url not appropriate 84 | self.set_attributes(response) 85 | image_file = io.BytesIO(response.content) 86 | self.image = graphics.Image.load_file(image_file, url) 87 | self.last_accessed = time.time() # local time 88 | self.retrieved = time.time() # local time 89 | 90 | def set_attributes(self, response): 91 | self.last_modified = get_last_modified(response) # server time 92 | self.max_age = get_max_age(response, self.last_modified) # seconds unit, no timeframe 93 | self.etag = get_etag(response) 94 | 95 | def is_fresh(self): 96 | now = time.time() 97 | if (now-self.retrieved) < self.max_age: # local time - local time 98 | return True 99 | try: 100 | response = requests.head(self.url) 101 | response.raise_for_status() 102 | old_lm = self.last_modified 103 | old_etag = self.etag 104 | self.retrieved = time.time() 105 | self.set_attributes(response) 106 | if old_etag and self.etag == old_etag: 107 | return True 108 | if old_lm and self.last_modified == old_lm: 109 | return True 110 | except IOError: 111 | return False 112 | return False 113 | 114 | 115 | class FileImage(ImageEntry): 116 | def __init__(self, filename): 117 | import graphics 118 | self.filename = filename 119 | self.image = graphics.Image.load_filename(filename) 120 | self.last_modified = os.path.getmtime(filename) 121 | self.last_accessed = time.time() 122 | 123 | def is_fresh(self): 124 | try: 125 | return self.last_modified == os.path.getmtime(self.filename) 126 | except IOError: 127 | return False 128 | 129 | 130 | class ImageCache(object): 131 | def __init__(self, cache_size=2*10**6): 132 | self.images = {} 133 | self.size = 0 134 | self.cache_size = cache_size 135 | self.lock = threading.RLock() 136 | 137 | def get_image(self, location): 138 | image = self.images.get(location) 139 | if image and image.is_fresh(): 140 | return image.image 141 | if is_url(location): 142 | image = WebImage(location) 143 | else: 144 | image = FileImage(location) 145 | self.add_image(location, image) 146 | return image.image 147 | 148 | def add_image(self, location, image): 149 | with self.lock: 150 | # delete image if already in cache and being over-written 151 | if location in self.images: 152 | self.del_image(location) 153 | self.images[location] = image 154 | self.size += image.get_size() 155 | 156 | # clean out cache if too big 157 | if self.size > self.cache_size: 158 | for key in sorted(self.images, key = lambda a: self.images[a].last_accessed): 159 | if self.size <= self.cache_size: 160 | break 161 | elif key != location: 162 | self.del_image(key) 163 | 164 | def del_image(self, location): 165 | with self.lock: 166 | self.size -= self.images[location].get_size() 167 | del self.images[location] 168 | -------------------------------------------------------------------------------- /tingbot/tingapp.py: -------------------------------------------------------------------------------- 1 | import collections 2 | import json 3 | import os 4 | import sys 5 | import hashlib 6 | import logging 7 | from .utils import cached_property, get_resource 8 | from .graphics import Image 9 | 10 | def load_json(filename): 11 | try: 12 | with open(filename, 'r') as fp: 13 | result = json.load(fp) 14 | if not isinstance(result, dict): 15 | raise ValueError('Failed to load %s because it should contain a dictionary object, not an array.' % filename) 16 | return result 17 | except ValueError: 18 | raise ValueError('Failed to load %s because it\'s not a valid JSON file' % filename) 19 | except IOError: 20 | #either non-existent file or empty filename 21 | return {} 22 | 23 | 24 | def save_json(filename, obj): 25 | data = json.dumps(obj) 26 | 27 | with open(filename, 'w') as fp: 28 | fp.write(data) 29 | 30 | 31 | class SettingsDict(collections.MutableMapping): 32 | ''' 33 | Represents the tingapp.settings dict-like object. 34 | 35 | The settings are loaded from three files in the app bundle 36 | 37 | - default_settings.json 38 | This file contains default settings as defined by the app creator 39 | - settings.json 40 | This file contains settings as set by a user when installing the app 41 | (via Tide, for example) 42 | - local_settings.json 43 | This file contains settings written by the app itself. 44 | 45 | Settings can be overridden by later files. 46 | 47 | Changes are always saved to the local_settings.json file. 48 | ''' 49 | def __init__(self, path): 50 | #note we do NOT initialise self.dct or self.local_settings here - this ensures we 51 | #raise an error in the event that they are accessed before self.load 52 | self.loaded = False 53 | self.path = path 54 | 55 | def __contains__(self, item): 56 | if not self.loaded: 57 | self.load() 58 | return item in self.dct 59 | 60 | def __len__(self): 61 | if not self.loaded: 62 | self.load() 63 | return len(self.dct) 64 | 65 | def __getitem__(self, key): 66 | if not self.loaded: 67 | self.load() 68 | return self.dct[key] 69 | 70 | def __setitem__(self, key, value): 71 | if not self.loaded: 72 | self.load() 73 | self.dct[key] = value 74 | self.local_settings[key] = value 75 | self.save() 76 | 77 | def __delitem__(self, key): 78 | if not self.loaded: 79 | self.load() 80 | del self.local_settings[key] 81 | 82 | def __iter__(self): 83 | if not self.loaded: 84 | self.load() 85 | return iter(self.dct) 86 | 87 | def load(self): 88 | self.dct = load_json(os.path.join(self.path, 'default_settings.json')) 89 | self.dct.update(load_json(os.path.join(self.path, 'settings.json'))) 90 | self.local_settings = load_json(os.path.join(self.path, 'local_settings.json')) 91 | self.dct.update(self.local_settings) 92 | self.loaded = True 93 | 94 | def save(self): 95 | save_json(os.path.join(self.path, 'local_settings.json'), self.local_settings) 96 | 97 | 98 | def generic_icon(name): 99 | name_hash = int(hashlib.md5(name).hexdigest(), 16) 100 | color_options = [ 101 | 'blue', 'teal', 'green', 'olive', 'yellow', 'orange', 'red', 102 | 'fuchsia', 'purple', 'maroon' 103 | ] 104 | color = color_options[name_hash % len(color_options)] 105 | 106 | letter = name[0].lower() 107 | icon = Image(size=(96, 96)) 108 | 109 | icon.fill(color=color) 110 | image = get_resource('default-icon-texture-96.png') 111 | icon.image(image) 112 | font = get_resource('MiniSet2.ttf') 113 | 114 | descenders = ['g', 'p', 'q', 'y'] 115 | ascenders = ['b', 'd', 'f', 'h', 'k', 'l', 't'] 116 | y_offset = 0 117 | 118 | if letter in descenders: 119 | y_offset -= 8 120 | if letter in ascenders: 121 | y_offset += 6 122 | 123 | icon.text(letter, 124 | xy=(52, 41 + y_offset), 125 | color='white', 126 | font=font, 127 | font_size=70) 128 | 129 | # they're a little large compared to the real icons, let's size them down a bit 130 | resized_icon = Image(size=(96,96)) 131 | resized_icon.image(icon, scale=0.9) 132 | 133 | return resized_icon 134 | 135 | 136 | class TingApp(object): 137 | def __init__(self, path=None): 138 | """path is the root path of the app you want to inspect 139 | if path is None, then will let you inspect the current app""" 140 | if path is None: 141 | path = os.path.dirname(os.path.abspath(sys.argv[0])) 142 | self.path = path 143 | self.settings = SettingsDict(path) 144 | 145 | @cached_property 146 | def info(self): 147 | return load_json(os.path.join(self.path, 'app.tbinfo')) 148 | 149 | @property 150 | def name(self): 151 | if 'name' in self.info and self.info['name'] != '': 152 | return self.info['name'] 153 | else: 154 | return os.path.basename(self.path) 155 | 156 | @cached_property 157 | def icon(self): 158 | icon_path = os.path.join(self.path, 'icon.png') 159 | 160 | if not os.path.isfile(icon_path): 161 | return generic_icon(self.name) 162 | 163 | try: 164 | icon = Image.load(icon_path) 165 | except: 166 | logging.exception('Failed to load icon at %s', icon_path) 167 | return generic_icon(self.name) 168 | 169 | if icon.size != (96, 96): 170 | # resize the icon by redrawing in the correct size 171 | resized_icon = Image(size=(96, 96)) 172 | resized_icon.image(icon, scale='shrinkToFit') 173 | return resized_icon 174 | 175 | return icon 176 | 177 | app = TingApp() 178 | -------------------------------------------------------------------------------- /tingbot/typesetter.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | class Line(object): 4 | def __init__(self, string, string_metrics): 5 | self.string = string 6 | self.string_metrics = string_metrics 7 | 8 | def truncate(self, max_width, ellipsis, ellipsis_metrics): 9 | ''' 10 | Returns a copy of the line, truncated so the width is less than 'max_width' if necessary. 11 | If truncated, 'ellipsis' is added at the end. 12 | ''' 13 | # do we need to truncate? 14 | string_width = sum(char_metric[4] for char_metric in self.string_metrics) 15 | 16 | if string_width <= max_width: 17 | return Line(self.string, self.string_metrics) 18 | 19 | ellipsis_width = sum(char_metric[4] for char_metric in ellipsis_metrics) 20 | string_max_width = max_width - ellipsis_width 21 | line_width = 0 22 | 23 | for string_i in xrange(len(self.string)): 24 | # [4] refers to the 'advance' metric 25 | line_width += self.string_metrics[string_i][4] 26 | 27 | if line_width > string_max_width: 28 | return Line( 29 | string=self.string[:string_i] + ellipsis, 30 | string_metrics=self.string_metrics[:string_i] + ellipsis_metrics) 31 | 32 | def __repr__(self): 33 | return 'Line(string=%r)' % self.string 34 | 35 | class Typesetter(object): 36 | def __init__(self, string, string_metrics): 37 | self.string = string 38 | self.string_metrics = string_metrics 39 | self.line_start = 0 40 | 41 | def suggest_line_break(self, start_i, max_width): 42 | line_width = 0 43 | last_split_point = None 44 | 45 | string_i = start_i 46 | char = None 47 | 48 | for string_i in xrange(start_i, len(self.string)): 49 | prev_char = char 50 | char = self.string[string_i] 51 | 52 | # handle newlines 53 | if char == '\n': 54 | # '+ 1' means break after the newline character 55 | return string_i + 1 56 | 57 | # [4] refers to the 'advance' metric 58 | line_width += self.string_metrics[string_i][4] 59 | 60 | # always break at the end of a string of whitespace 61 | if char.isspace(): 62 | continue 63 | 64 | if prev_char in (' ', '-', '\t'): 65 | last_split_point = string_i 66 | 67 | if line_width > max_width: 68 | if last_split_point is None: 69 | # there wasn't a split point before the line was too big. Break here 70 | if string_i == start_i: 71 | # don't return zero character line 72 | return string_i + 1 73 | else: 74 | return string_i 75 | else: 76 | # there was a possible split point back there. Return up to that split point 77 | return last_split_point 78 | 79 | # got to the end of the string without wrapping 80 | return len(self.string) 81 | 82 | def create_line(self, start_i, end_i, remove_trailing_whitespace=False): 83 | if remove_trailing_whitespace: 84 | string = self.string[start_i:end_i].rstrip() 85 | string_metrics = self.string_metrics[start_i:start_i+len(string)] 86 | else: 87 | string = self.string[start_i:end_i] 88 | string_metrics = self.string_metrics[start_i:end_i] 89 | 90 | return Line(string, string_metrics) 91 | 92 | def lines(self, max_lines, max_width, ellipsis, ellipsis_metrics): 93 | lines = [] 94 | line_start_i = 0 95 | 96 | for line_i in xrange(max_lines): 97 | final_line = (line_i == max_lines - 1) 98 | 99 | if final_line: 100 | line_end_i = len(self.string) 101 | remove_trailing_whitespace = False 102 | else: 103 | line_end_i = self.suggest_line_break(line_start_i, max_width) 104 | # remove trailing whitespace if the line's been broken 105 | remove_trailing_whitespace = (line_end_i != len(self.string)) 106 | 107 | line = self.create_line(line_start_i, line_end_i, remove_trailing_whitespace) 108 | 109 | if final_line: 110 | line = line.truncate(max_width, ellipsis, ellipsis_metrics) 111 | 112 | lines.append(line) 113 | 114 | if line_end_i == len(self.string): 115 | break 116 | 117 | line_start_i = line_end_i 118 | 119 | return lines 120 | 121 | def render_text(string, font, antialias, color, max_lines, max_width, ellipsis=u'…', align=0): 122 | ''' Render a multiline string to a pygame surface. 123 | 124 | Arguments: 125 | string - the string to render 126 | font - the pygame Font object to use 127 | antialias - whether to antialias the text 128 | color - an RGB or RGBA triple describing the color 129 | max_lines - the maximum lines to use before truncating the string 130 | max_width - the maximum width of each line 131 | ellipsis - the string used to indicate more text wasn't displayed 132 | align - horizontal alignment - 0=left, 0.5=center, 1=right 133 | ''' 134 | import pygame 135 | 136 | string_metrics = font.metrics(string) 137 | ellipsis_metrics = font.metrics(ellipsis) 138 | 139 | lines = Typesetter(string, string_metrics).lines( 140 | max_lines=max_lines, 141 | max_width=max_width, 142 | ellipsis=ellipsis, 143 | ellipsis_metrics=ellipsis_metrics) 144 | 145 | line_surfaces = [] 146 | 147 | for line in lines: 148 | line_surfaces.append(font.render(line.string, antialias, color)) 149 | 150 | if len(line_surfaces) > 0: 151 | width = max(s.get_width() for s in line_surfaces) 152 | height = sum(s.get_height() for s in line_surfaces) 153 | else: 154 | width = 0 155 | height = 0 156 | 157 | surface = pygame.Surface((width, height), flags=pygame.SRCALPHA) 158 | 159 | y = 0 160 | for line_surface in line_surfaces: 161 | x = (width - line_surface.get_width()) * align 162 | surface.blit(line_surface, (x, y)) 163 | y += line_surface.get_height() 164 | 165 | return surface 166 | -------------------------------------------------------------------------------- /tingbot/platform_specific/osx.py: -------------------------------------------------------------------------------- 1 | import os 2 | from Cocoa import ( 3 | NSImageView, NSView, NSRectFill, NSColor, NSApplication, NSNotificationCenter, NSRect, NSImage, 4 | NSWindow, NSUserDefaults, NSRunLoop, NSDefaultRunLoopMode, NSDate) 5 | from Quartz import CGPointZero, CGRectMake, CGPointMake 6 | import objc 7 | import pygame 8 | from ..utils import cached_property, get_resource 9 | 10 | 11 | class BackgroundImageView(NSImageView): 12 | def mouseDownCanMoveWindow(self): 13 | return True 14 | 15 | 16 | class TingbotButton(NSView): 17 | def initWithFrame_buttonIndex_(self, frame, button_index): 18 | self = super(TingbotButton, self).initWithFrame_(frame) 19 | self.button_index = button_index 20 | self.is_down = False 21 | return self 22 | 23 | def drawRect_(self, rect): 24 | fill_rect = self.frame().copy() 25 | fill_rect.origin = CGPointZero 26 | 27 | NSColor.colorWithWhite_alpha_(0.3, 1.0).set() 28 | 29 | if self.is_down: 30 | fill_rect.size.height *= 0.8 31 | 32 | NSRectFill(fill_rect) 33 | 34 | def mouseDown_(self, event): 35 | self.is_down = True 36 | self.setNeedsDisplay_(True) 37 | 38 | if button_callback is not None: 39 | button_callback(self.button_index, 'down') 40 | 41 | def mouseUp_(self, event): 42 | self.is_down = False 43 | self.setNeedsDisplay_(True) 44 | 45 | if button_callback is not None: 46 | button_callback(self.button_index, 'up') 47 | 48 | 49 | class WindowController(object): 50 | def __init__(self): 51 | app = NSApplication.sharedApplication() 52 | 53 | self.screen_window = app.windows()[0] 54 | 55 | self.screen_window.setStyleMask_(0) 56 | self.screen_window.setHasShadow_(False) 57 | 58 | frame = self.screen_window.frame() 59 | frame.origin = self.image_window.frame().origin 60 | frame.origin.x += 61 61 | frame.origin.y += 72 62 | self.screen_window.setFrame_display_(frame, False) 63 | 64 | self.image_window.makeKeyAndOrderFront_(None) 65 | self.image_window.addChildWindow_ordered_(self.screen_window, 1) 66 | 67 | image_window_frame = self.image_window.frame().copy() 68 | if 'TIDE_WINDOW_FRAME' in os.environ: 69 | left, top, width, height = (float(x) for x in os.environ['TIDE_WINDOW_FRAME'].split(',')) 70 | # image_window_frame. 71 | print left, top, width, height 72 | 73 | image_window_left = left + width + 20 74 | image_window_top = top + height/2 + 180 75 | 76 | self.image_window.cascadeTopLeftFromPoint_(CGPointMake(image_window_left, image_window_top)) 77 | else: 78 | pass 79 | 80 | def window_did_close(notification): 81 | app.terminate_(None) 82 | 83 | NSNotificationCenter.defaultCenter().addObserverForName_object_queue_usingBlock_( 84 | "NSWindowDidCloseNotification", 85 | self.image_window, 86 | None, 87 | window_did_close) 88 | 89 | @cached_property 90 | def image_window(self): 91 | rect = NSRect() 92 | rect.origin = self.screen_window.frame().origin 93 | rect.size.width = 470 94 | rect.size.height = 353 95 | 96 | view_rect = rect.copy() 97 | view_rect.origin = CGPointZero 98 | 99 | image_view = BackgroundImageView.alloc().initWithFrame_(view_rect) 100 | image = NSImage.alloc().initWithContentsOfFile_(os.path.join(os.path.dirname(__file__), 'bot.png')) 101 | image_view.setImage_(image) 102 | 103 | content_view = NSView.alloc().initWithFrame_(view_rect) 104 | 105 | for button in self.buttons: 106 | content_view.addSubview_(button) 107 | 108 | content_view.addSubview_(image_view) 109 | 110 | image_window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_( 111 | rect, 112 | 0, 113 | 2, 114 | False) 115 | 116 | image_window.setContentView_(content_view) 117 | image_window.setOpaque_(False) 118 | image_window.setBackgroundColor_(NSColor.clearColor()) 119 | image_window.setHasShadow_(True) 120 | image_window.setMovableByWindowBackground_(True) 121 | 122 | image_window.setReleasedWhenClosed_(False) 123 | 124 | return image_window 125 | 126 | @cached_property 127 | def buttons(self): 128 | buttons = [] 129 | xPositions = (60, 100, 320, 360) 130 | 131 | for i in xrange(0, 4): 132 | frame = CGRectMake(xPositions[i], 340, 22, 12) 133 | b = TingbotButton.alloc().initWithFrame_buttonIndex_(frame, i) 134 | buttons.append(b) 135 | 136 | return buttons 137 | 138 | 139 | window_controller = None 140 | 141 | def create_main_surface(): 142 | pygame.init() 143 | surface = pygame.display.set_mode((320, 240)) 144 | 145 | try: 146 | SDL_QuartzWindow = objc.lookUpClass('SDL_QuartzWindow') 147 | except objc.nosuchclass_error: 148 | # SDL2 doesn't have this class or need the runtime patch 149 | pass 150 | else: 151 | class SDL_QuartzWindow(objc.Category(SDL_QuartzWindow)): 152 | def canBecomeKeyWindow(self): 153 | return True 154 | 155 | def canBecomeMainWindow(self): 156 | return True 157 | 158 | def acceptsFirstResponder(self): 159 | return True 160 | 161 | def becomeFirstResponder(self): 162 | return True 163 | 164 | def resignFirstResponder(self): 165 | return True 166 | 167 | global window_controller 168 | window_controller = WindowController() 169 | 170 | # run the run loop just once to finish setting up the window 171 | NSRunLoop.mainRunLoop().runMode_beforeDate_(NSDefaultRunLoopMode, NSDate.date()) 172 | 173 | return surface 174 | 175 | 176 | def fixup_env(): 177 | from pygame import sdlmain_osx 178 | 179 | icon_file = os.path.join(os.path.dirname(__file__), 'simulator-icon.png') 180 | with open(icon_file) as f: 181 | icon_data = f.read() 182 | 183 | sdlmain_osx.InstallNSApplication(icon_data) 184 | 185 | NSUserDefaults.standardUserDefaults().setBool_forKey_(False, 'ApplePersistenceIgnoreState') 186 | 187 | button_callback = None 188 | 189 | 190 | def register_button_callback(callback): 191 | ''' 192 | callback(button_index, action) 193 | button_index is a zero-based index that identifies which button has been pressed 194 | action is either 'down', or 'up'. 195 | 196 | The callback might not be called on the main thread. 197 | 198 | Currently only 'down' is implemented. 199 | ''' 200 | global button_callback 201 | button_callback = callback 202 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/tingbot.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/tingbot.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/tingbot" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/tingbot" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # tingbot documentation build configuration file, created by 5 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | import sys 17 | import os 18 | import subprocess 19 | 20 | # If extensions (or modules to document with autodoc) are in another 21 | # directory, add these directories to sys.path here. If the directory is 22 | # relative to the documentation root, use os.path.abspath to make it 23 | # absolute, like shown here. 24 | #sys.path.insert(0, os.path.abspath('.')) 25 | 26 | # Get the project root dir, which is the parent dir of this 27 | cwd = os.getcwd() 28 | project_root = os.path.dirname(cwd) 29 | 30 | # Insert the project root dir as the first element in the PYTHONPATH. 31 | # This lets us ensure that the source package is imported, and that its 32 | # version is used. 33 | sys.path.insert(0, project_root) 34 | 35 | 36 | # -- General configuration --------------------------------------------- 37 | 38 | # If your documentation needs a minimal Sphinx version, state it here. 39 | #needs_sphinx = '1.0' 40 | 41 | # Add any Sphinx extension module names here, as strings. They can be 42 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 43 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinx.ext.autosummary'] 44 | 45 | napoleon_google_docstring = True 46 | autodoc_docstring_signature= True 47 | autodoc_member_order = 'bysource' 48 | # Add any paths that contain templates here, relative to this directory. 49 | templates_path = ['_templates'] 50 | 51 | # The suffix of source filenames. 52 | source_suffix = '.rst' 53 | 54 | # The encoding of source files. 55 | #source_encoding = 'utf-8-sig' 56 | 57 | # The master toctree document. 58 | master_doc = 'index' 59 | 60 | # General information about the project. 61 | project = u'Tingbot' 62 | copyright = u'2016 Tingbot Ltd' 63 | 64 | # The version info for the project you're documenting, acts as replacement 65 | # for |version| and |release|, also used in various other places throughout 66 | # the built documents. 67 | # 68 | # The short X.Y version. 69 | version = subprocess.check_output(['python', 'setup.py', '--version'], cwd=project_root).strip() 70 | 71 | # The full version, including alpha/beta/rc tags. 72 | release = version 73 | 74 | # The language for content autogenerated by Sphinx. Refer to documentation 75 | # for a list of supported languages. 76 | #language = None 77 | 78 | # There are two options for replacing |today|: either, you set today to 79 | # some non-false value, then it is used: 80 | #today = '' 81 | # Else, today_fmt is used as the format for a strftime call. 82 | #today_fmt = '%B %d, %Y' 83 | 84 | # List of patterns, relative to source directory, that match files and 85 | # directories to ignore when looking for source files. 86 | exclude_patterns = ['_build'] 87 | 88 | # The reST default role (used for this markup: `text`) to use for all 89 | # documents. 90 | #default_role = None 91 | 92 | # If true, '()' will be appended to :func: etc. cross-reference text. 93 | #add_function_parentheses = True 94 | 95 | # If true, the current module name will be prepended to all description 96 | # unit titles (such as .. function::). 97 | #add_module_names = True 98 | 99 | # If true, sectionauthor and moduleauthor directives will be shown in the 100 | # output. They are ignored by default. 101 | #show_authors = False 102 | 103 | # The name of the Pygments (syntax highlighting) style to use. 104 | pygments_style = 'sphinx' 105 | 106 | # A list of ignored prefixes for module index sorting. 107 | #modindex_common_prefix = [] 108 | 109 | # If true, keep warnings as "system message" paragraphs in the built 110 | # documents. 111 | #keep_warnings = False 112 | 113 | 114 | # -- Options for HTML output ------------------------------------------- 115 | 116 | # The theme to use for HTML and HTML Help pages. See the documentation for 117 | # a list of builtin themes. 118 | html_theme = 'sphinx_rtd_theme' 119 | 120 | # Theme options are theme-specific and customize the look and feel of a 121 | # theme further. For a list of options available for each theme, see the 122 | # documentation. 123 | #html_theme_options = {} 124 | 125 | # Add any paths that contain custom themes here, relative to this directory. 126 | #html_theme_path = [] 127 | 128 | # The name for this set of Sphinx documents. If None, it defaults to 129 | # " v documentation". 130 | #html_title = None 131 | 132 | # A shorter title for the navigation bar. Default is the same as 133 | # html_title. 134 | #html_short_title = None 135 | 136 | # The name of an image file (relative to this directory) to place at the 137 | # top of the sidebar. 138 | #html_logo = None 139 | 140 | # The name of an image file (within the static path) to use as favicon 141 | # of the docs. This file should be a Windows icon file (.ico) being 142 | # 16x16 or 32x32 pixels large. 143 | #html_favicon = None 144 | 145 | # Add any paths that contain custom static files (such as style sheets) 146 | # here, relative to this directory. They are copied after the builtin 147 | # static files, so a file named "default.css" will overwrite the builtin 148 | # "default.css". 149 | #html_static_path = ['_static'] 150 | 151 | # If not '', a 'Last updated on:' timestamp is inserted at every page 152 | # bottom, using the given strftime format. 153 | #html_last_updated_fmt = '%b %d, %Y' 154 | 155 | # If true, SmartyPants will be used to convert quotes and dashes to 156 | # typographically correct entities. 157 | #html_use_smartypants = True 158 | 159 | # Custom sidebar templates, maps document names to template names. 160 | #html_sidebars = {} 161 | 162 | # Additional templates that should be rendered to pages, maps page names 163 | # to template names. 164 | #html_additional_pages = {} 165 | 166 | # If false, no module index is generated. 167 | #html_domain_indices = True 168 | 169 | # If false, no index is generated. 170 | #html_use_index = True 171 | 172 | # If true, the index is split into individual pages for each letter. 173 | #html_split_index = False 174 | 175 | # If true, links to the reST sources are added to the pages. 176 | #html_show_sourcelink = True 177 | 178 | # If true, "Created using Sphinx" is shown in the HTML footer. 179 | # Default is True. 180 | #html_show_sphinx = True 181 | 182 | # If true, "(C) Copyright ..." is shown in the HTML footer. 183 | # Default is True. 184 | #html_show_copyright = True 185 | 186 | # If true, an OpenSearch description file will be output, and all pages 187 | # will contain a tag referring to it. The value of this option 188 | # must be the base URL from which the finished HTML is served. 189 | #html_use_opensearch = '' 190 | 191 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 192 | #html_file_suffix = None 193 | 194 | # Output file base name for HTML help builder. 195 | htmlhelp_basename = 'tingbotdoc' 196 | 197 | 198 | # -- Options for LaTeX output ------------------------------------------ 199 | 200 | latex_elements = { 201 | # The paper size ('letterpaper' or 'a4paper'). 202 | #'papersize': 'letterpaper', 203 | 204 | # The font size ('10pt', '11pt' or '12pt'). 205 | #'pointsize': '10pt', 206 | 207 | # Additional stuff for the LaTeX preamble. 208 | #'preamble': '', 209 | } 210 | 211 | # Grouping the document tree into LaTeX files. List of tuples 212 | # (source start file, target name, title, author, documentclass 213 | # [howto/manual]). 214 | latex_documents = [ 215 | ('index', 'tingbot.tex', 216 | u'Tingbot Documentation', 217 | u'Joe Rickerby', 'manual'), 218 | ] 219 | 220 | # The name of an image file (relative to this directory) to place at 221 | # the top of the title page. 222 | #latex_logo = None 223 | 224 | # For "manual" documents, if this is true, then toplevel headings 225 | # are parts, not chapters. 226 | #latex_use_parts = False 227 | 228 | # If true, show page references after internal links. 229 | #latex_show_pagerefs = False 230 | 231 | # If true, show URL addresses after external links. 232 | #latex_show_urls = False 233 | 234 | # Documents to append as an appendix to all manuals. 235 | #latex_appendices = [] 236 | 237 | # If false, no module index is generated. 238 | #latex_domain_indices = True 239 | 240 | 241 | # -- Options for manual page output ------------------------------------ 242 | 243 | # One entry per manual page. List of tuples 244 | # (source start file, name, description, authors, manual section). 245 | man_pages = [ 246 | ('index', 'tingbot', 247 | u'Tingbot Documentation', 248 | [u'Joe Rickerby'], 1) 249 | ] 250 | 251 | # If true, show URL addresses after external links. 252 | #man_show_urls = False 253 | 254 | 255 | # -- Options for Texinfo output ---------------------------------------- 256 | 257 | # Grouping the document tree into Texinfo files. List of tuples 258 | # (source start file, target name, title, author, 259 | # dir menu entry, description, category) 260 | texinfo_documents = [ 261 | ('index', 'tingbot', 262 | u'Tingbot Documentation', 263 | u'Joe Rickerby', 264 | 'tingbot', 265 | 'One line description of project.', 266 | 'Miscellaneous'), 267 | ] 268 | 269 | # Documents to append as an appendix to all manuals. 270 | #texinfo_appendices = [] 271 | 272 | # If false, no module index is generated. 273 | #texinfo_domain_indices = True 274 | 275 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 276 | #texinfo_show_urls = 'footnote' 277 | 278 | # If true, do not generate a @detailmenu in the "Top" node's menu. 279 | #texinfo_no_detailmenu = False 280 | -------------------------------------------------------------------------------- /tests/cache_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import time 3 | import httpretty 4 | import mock 5 | import re 6 | 7 | import tingbot.cache as cache 8 | import tingbot.graphics as graphics 9 | from requests.structures import CaseInsensitiveDict as idict 10 | from email.Utils import formatdate 11 | 12 | class TimeHelper(object): 13 | def __init__(self): 14 | self.tm = 1000.0 15 | def __call__(self): 16 | return self.tm 17 | 18 | class DummyResponse(object): 19 | def __init__(self,**kwargs): 20 | self.__dict__.update(kwargs) 21 | 22 | 23 | class TimeControlCase(unittest.TestCase): 24 | def setUp(self): 25 | mytime = TimeHelper() 26 | self.old_time = time.time 27 | time.time = mytime 28 | 29 | def tearDown(self): 30 | time.time = self.old_time 31 | 32 | class TestGetLastModified(TimeControlCase): 33 | def test_simple_case(self): 34 | resp = DummyResponse(headers=idict({'last-modified':formatdate(100.0)})) 35 | self.assertEqual(cache.get_last_modified(resp),100.0) 36 | 37 | def test_bad_last_modified(self): 38 | resp = DummyResponse(headers=idict({'last-modified':'ted'})) 39 | self.assertEqual(cache.get_last_modified(resp),None) 40 | 41 | def test_date(self): 42 | resp = DummyResponse(headers=idict({'last-modified':formatdate(200.0)})) 43 | self.assertEqual(cache.get_last_modified(resp),200.0) 44 | 45 | def test_bad_date(self): 46 | resp = DummyResponse(headers=idict({'last-modified':'phil'})) 47 | self.assertEqual(cache.get_last_modified(resp),None) 48 | 49 | def test_no_useful_headers(self): 50 | resp = DummyResponse(headers=idict({})) 51 | self.assertEqual(cache.get_last_modified(resp),None) 52 | 53 | 54 | class TestGetMaxAge(TimeControlCase): 55 | def test_simple_case(self): 56 | resp = DummyResponse(headers=idict({'cache-control':'max-age = 300'})) 57 | self.assertEqual(cache.get_max_age(resp,400),300) 58 | 59 | def test_bad_cache_control(self): 60 | resp = DummyResponse(headers=idict({'cache-control':'max-age = fred'})) 61 | self.assertEqual(cache.get_max_age(resp,400),60) 62 | 63 | def test_plain_max_age(self): 64 | resp = DummyResponse(headers=idict({'max-age':'500'})) 65 | self.assertEqual(cache.get_max_age(resp,400),500) 66 | 67 | def test_bad_max_age(self): 68 | resp = DummyResponse(headers=idict({'max-age':'ten'})) 69 | self.assertEqual(cache.get_max_age(resp,400),60) 70 | 71 | def test_empty_headers(self): 72 | resp = DummyResponse(headers=idict({})) 73 | self.assertEqual(cache.get_max_age(resp,400),60) 74 | 75 | class TestWebImage(TimeControlCase): 76 | def setUp(self): 77 | super(TestWebImage,self).setUp() 78 | httpretty.enable() 79 | self.image_content = open("tingbot/resources/broken_image.png",'r').read() 80 | 81 | def tearDown(self): 82 | httpretty.disable() 83 | super(TestWebImage,self).tearDown() 84 | 85 | def test_basic_load(self): 86 | httpretty.register_uri(httpretty.GET,"http://example.com/cats.png",body=self.image_content) 87 | f = cache.WebImage('http://example.com/cats.png') 88 | 89 | def test_raises_error_on_bad_URL(self): 90 | httpretty.register_uri(httpretty.GET,"http://example.com/cats.png",body="not found",status=404) 91 | with self.assertRaises(IOError): 92 | f = cache.WebImage('http://example.com/cats.png') 93 | 94 | def test_is_fresh_while_within_maxage(self): 95 | httpretty.register_uri(httpretty.GET,"http://example.com/cats.png", 96 | body=self.image_content, max_age=300, last_modified = formatdate(200.0)) 97 | httpretty.register_uri(httpretty.HEAD,"http://example.com/cats.png", 98 | max_age=300, last_modified = formatdate(300.0) ) 99 | f = cache.WebImage('http://example.com/cats.png') 100 | time.time.tm=1200 101 | self.assertTrue(f.is_fresh()) 102 | 103 | def test_is_fresh_on_recheck_with_last_modified_unchanged(self): 104 | httpretty.register_uri(httpretty.GET,"http://example.com/cats.png", 105 | body=self.image_content, max_age=300, last_modified = formatdate(200.0) ) 106 | httpretty.register_uri(httpretty.HEAD,"http://example.com/cats.png", 107 | max_age=300, last_modified = formatdate(200.0) ) 108 | f = cache.WebImage('http://example.com/cats.png') 109 | time.time.tm=1400 110 | self.assertTrue(f.is_fresh()) 111 | 112 | def test_is_fresh_on_recheck_with_last_modified_changed(self): 113 | httpretty.register_uri(httpretty.GET,"http://example.com/cats.png", 114 | body=self.image_content, max_age=300, last_modified = formatdate(200.0) ) 115 | httpretty.register_uri(httpretty.HEAD,"http://example.com/cats.png", 116 | max_age=300, last_modified = formatdate(300.0) ) 117 | f = cache.WebImage('http://example.com/cats.png') 118 | time.time.tm=1400 119 | self.assertFalse(f.is_fresh()) 120 | 121 | def test_is_fresh_on_recheck_with_etag_unchanged(self): 122 | httpretty.register_uri(httpretty.GET,"http://example.com/cats.png", 123 | body=self.image_content, max_age=300, etag="a", last_modified = formatdate(200.0) ) 124 | httpretty.register_uri(httpretty.HEAD,"http://example.com/cats.png", 125 | max_age=300, etag="a", last_modified = formatdate(300.0) ) 126 | f = cache.WebImage('http://example.com/cats.png') 127 | time.time.tm=1400 128 | self.assertTrue(f.is_fresh()) 129 | 130 | def test_is_fresh_on_recheck_with_etag_changed(self): 131 | httpretty.register_uri(httpretty.GET,"http://example.com/cats.png", 132 | body=self.image_content, max_age=300, etag="a", last_modified = formatdate(200.0) ) 133 | httpretty.register_uri(httpretty.HEAD,"http://example.com/cats.png", 134 | max_age=300, etag="b", last_modified = formatdate(300.0) ) 135 | f = cache.WebImage('http://example.com/cats.png') 136 | time.time.tm=1400 137 | self.assertFalse(f.is_fresh()) 138 | 139 | def test_is_fresh_if_no_last_modified_or_etag(self): 140 | httpretty.register_uri(httpretty.GET,"http://example.com/cats.png", 141 | body=self.image_content, max_age=300) 142 | httpretty.register_uri(httpretty.HEAD,"http://example.com/cats.png", 143 | max_age=300) 144 | f = cache.WebImage('http://example.com/cats.png') 145 | time.time.tm=1400 146 | self.assertFalse(f.is_fresh()) 147 | 148 | class TestFileImage(unittest.TestCase): 149 | def test_basic_load(self): 150 | f = cache.FileImage('tingbot/resources/broken_image.png') 151 | 152 | def test_bad_location(self): 153 | with self.assertRaises(IOError): 154 | f = cache.FileImage('tingbot_bork/broken_image.png') 155 | 156 | @mock.patch('tingbot.cache.os.path.getmtime') 157 | def test_is_fresh_if_unchanged_mod_time(self,mtime): 158 | mtime.return_value = 200 159 | f = cache.FileImage('tingbot/resources/broken_image.png') 160 | self.assertTrue(f.is_fresh()) 161 | 162 | @mock.patch('tingbot.cache.os.path.getmtime') 163 | def test_is_fresh_if_changed_mod_time(self,mtime): 164 | mtime.return_value = 200 165 | f = cache.FileImage('tingbot/resources/broken_image.png') 166 | mtime.return_value = 300 167 | self.assertFalse(f.is_fresh()) 168 | 169 | class TestImageCache(TimeControlCase): 170 | def setUp(self): 171 | super(TestImageCache,self).setUp() 172 | httpretty.enable() 173 | self.image_content = open("tingbot/resources/broken_image.png",'r').read() 174 | self.tiny_content = open("tests/blank.png",'r').read() 175 | httpretty.register_uri(httpretty.GET,re.compile("http://example.com/..png"), body=self.image_content) 176 | httpretty.register_uri(httpretty.GET,re.compile("http://example.com/tiny/..png"), body=self.tiny_content) 177 | 178 | def tearDown(self): 179 | httpretty.disable() 180 | super(TestImageCache,self).tearDown() 181 | 182 | def test_can_init(self): 183 | c = cache.ImageCache() 184 | 185 | def test_loads_one_file(self): 186 | c = cache.ImageCache(1000000) 187 | image = c.get_image("http://example.com/a.png") 188 | self.assertIsInstance(image,graphics.Image) 189 | 190 | def test_loads_gif(self): 191 | c = cache.ImageCache(1000000) 192 | image = c.get_image('tests/GifSample.gif') 193 | self.assertIsInstance(image,graphics.GIFImage) 194 | 195 | def test_loads_one_massive_file(self): 196 | c = cache.ImageCache(100) 197 | image = c.get_image("http://example.com/a.png") 198 | self.assertIsInstance(image,graphics.Image) 199 | 200 | def test_removes_a_file_when_full(self): 201 | image_size = cache.WebImage('http://example.com/a.png').get_size() 202 | c = cache.ImageCache(image_size+1) 203 | a = c.get_image('http://example.com/a.png') 204 | b = c.get_image('http://example.com/b.png') 205 | self.assertEqual(len(c.images),1) 206 | 207 | def test_removes_oldest_file_when_full(self): 208 | image_size = cache.WebImage('http://example.com/a.png').get_size() 209 | print image_size 210 | c = cache.ImageCache(image_size+1) 211 | a_url = 'http://example.com/a.png' 212 | b_url = 'http://example.com/b.png' 213 | a = c.get_image(a_url) 214 | b = c.get_image(b_url) 215 | self.assertFalse(a_url in c.images) 216 | self.assertTrue(b_url in c.images) 217 | 218 | def test_removes_more_than_one_file_if_needed(self): 219 | image_size = cache.WebImage('http://example.com/a.png').get_size() 220 | c = cache.ImageCache(image_size+1) 221 | tiny_url_a = 'http://example.com/tiny/a.png' 222 | tiny_url_b = 'http://example.com/tiny/b.png' 223 | url_d = 'http://example.com/a.png' 224 | a = c.get_image(tiny_url_a) 225 | b = c.get_image(tiny_url_b) 226 | d = c.get_image(url_d) 227 | self.assertEqual(len(c.images),1) 228 | self.assertFalse(tiny_url_a in c.images) 229 | self.assertFalse(tiny_url_b in c.images) 230 | self.assertTrue(url_d in c.images) 231 | 232 | def test_successfully_reloads_an_expired_file(self): 233 | httpretty.register_uri(httpretty.GET,re.compile("http://example.com/x/1.png"), body=self.image_content, etag="a", max_age="300") 234 | c = cache.ImageCache() 235 | a = c.get_image("http://example.com/x/1.png") 236 | httpretty.register_uri(httpretty.GET,re.compile("http://example.com/x/1.png"), body=self.image_content, etag="b", max_age="300") 237 | httpretty.register_uri(httpretty.HEAD,re.compile("http://example.com/x/1.png"), etag="b", max_age="300") 238 | time.time.tm=1400 239 | b = c.get_image("http://example.com/x/1.png") 240 | 241 | -------------------------------------------------------------------------------- /tbtool/__main__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from docopt import docopt 4 | import os, textwrap, shutil, filecmp, subprocess, sys, logging, fnmatch, sys 5 | import paramiko 6 | from .appdirs import AppDirs 7 | 8 | 9 | class SSHSession(object): 10 | def __init__(self, hostname): 11 | self.client = paramiko.SSHClient() 12 | self.client.set_missing_host_key_policy(SSHSession.IgnoreHostKeyPolicy()) 13 | key_path = os.path.join(os.path.dirname(__file__), 'tingbot.key') 14 | self.client.connect(hostname, username='pi', key_filename=key_path) 15 | 16 | def exec_command(self, command): 17 | channel = self.client.get_transport().open_session() 18 | channel.set_combine_stderr(True) 19 | 20 | channel.exec_command(command) 21 | 22 | # pass through the output to stdout 23 | while True: 24 | data = channel.recv(1024) 25 | if data == '': 26 | break 27 | sys.stdout.write(data) 28 | sys.stdout.flush() 29 | 30 | code = channel.recv_exit_status() 31 | 32 | channel.shutdown_read() 33 | channel.shutdown_write() 34 | 35 | if code != 0: 36 | raise SSHSession.RemoteCommandError(command, code) 37 | 38 | put_dir_default_ignore_patterns = ['venv', 'local_settings.json', '.git', '*.pyc'] 39 | 40 | def put_dir(self, source, target, ignore_patterns=put_dir_default_ignore_patterns): 41 | sftp = self.client.open_sftp() 42 | 43 | try: 44 | sftp.mkdir(target, 0755) 45 | 46 | for filename in os.listdir(source): 47 | # if filename matches any of the patterns in ignore_patterns, continue to 48 | # the next file 49 | if any(fnmatch.fnmatch(filename, i) for i in ignore_patterns): 50 | continue 51 | 52 | local_path = os.path.join(source, filename) 53 | remote_path = '%s/%s' % (target, filename) 54 | 55 | if os.path.islink(local_path): 56 | link_destination = os.readlink(local_path) 57 | sftp.symlink(remote_path, link_destination) 58 | 59 | elif os.path.isfile(local_path): 60 | sftp.put(local_path, remote_path) 61 | 62 | elif os.path.isdir(local_path): 63 | self.put_dir(local_path, remote_path) 64 | finally: 65 | sftp.close() 66 | 67 | def close(self): 68 | self.client.close() 69 | 70 | class IgnoreHostKeyPolicy(object): 71 | def missing_host_key(self, client, hostname, key): 72 | return 73 | 74 | class RemoteCommandError(Exception): 75 | def __init__(self, command, code, output, error_output): 76 | self.command = command 77 | self.code = code 78 | self.output = output 79 | self.error_output = error_output 80 | message = 'Remote command %s failed with code %i. \n%s\n%s' % ( 81 | command, code, output, error_output) 82 | super(SSHSession.RemoteCommandError, self).__init__(message) 83 | 84 | 85 | def _app_exec_info(app_path, python_exe='python'): 86 | """ Returns a pair ([args], working_directory) """ 87 | 88 | app_path = os.path.abspath(app_path) 89 | 90 | if os.path.isfile(app_path): 91 | return ([app_path], os.path.dirname(app_path)) 92 | 93 | if os.path.isdir(app_path): 94 | main_file = os.path.join(app_path, 'main') 95 | if os.path.isfile(main_file): 96 | return ([main_file], app_path) 97 | 98 | main_py_file = os.path.join(app_path, 'main.py') 99 | if os.path.isfile(main_py_file): 100 | return ([python_exe, main_py_file], app_path) 101 | 102 | return (None, None) 103 | 104 | def _exec(args, env): 105 | if sys.platform != 'win32': 106 | os.execvpe(args[0], args, env) 107 | else: 108 | # 'exec' on Windows doesn't have the same semantics - on Windows the calling process 109 | # returns as if it had exited. Here we simulate *nix 'exec' behaviour. 110 | 111 | # Ignore CTRL-C events as they're handled by the subprocess 112 | import signal 113 | signal.signal(signal.SIGINT, signal.SIG_IGN) 114 | 115 | process = subprocess.Popen(args, env=env) 116 | process.wait() 117 | sys.exit(process.returncode) 118 | 119 | def _run(app_path, extra_env=None): 120 | python_exe = build(app_path) 121 | 122 | args, working_directory = _app_exec_info(app_path, python_exe=python_exe) 123 | 124 | if args is None: 125 | raise ValueError('Tingbot app not found at %s' % app_path) 126 | 127 | env = os.environ.copy() 128 | 129 | if extra_env: 130 | env.update(extra_env) 131 | 132 | os.chdir(working_directory) 133 | _exec(args, env) 134 | 135 | def simulate(app_path): 136 | _run(app_path) 137 | 138 | 139 | def run(app_path, hostname): 140 | print 'tbtool: Connecting to Pi...' 141 | 142 | session = SSHSession(hostname) 143 | 144 | try: 145 | app_name = os.path.basename(app_path) 146 | 147 | app_install_location = '/tmp/tide/%s' % app_name 148 | app_install_folder = os.path.dirname(app_install_location) 149 | 150 | print 'tbtool: Setting up Pi...' 151 | session.exec_command('mkdir -p "%s"' % app_install_folder) 152 | 153 | print 'tbtool: Copying app to %s...' % app_install_location 154 | session.exec_command('sudo rm -rf "%s"' % app_install_location) 155 | session.put_dir(app_path, app_install_location) 156 | 157 | print 'tbtool: Starting app...' 158 | session.exec_command('tbopen --follow "%s"' % app_install_location) 159 | finally: 160 | session.close() 161 | 162 | def build(app_path): 163 | ''' 164 | Installs the dependencies in requirements.txt into a virtualenv in the app directory 165 | Returns the path to the python executable that should be used to run the app. 166 | ''' 167 | import virtualenv 168 | wheelhouse = os.path.join(AppDirs('Tingbot', 'Tingbot').user_cache_dir, 'Wheelhouse') 169 | 170 | if not os.path.exists(wheelhouse): 171 | os.makedirs(wheelhouse) 172 | 173 | requirements_txt_path = os.path.join(app_path, 'requirements.txt') 174 | venv_path = os.path.join(app_path, 'venv') 175 | _, venv_lib_dir, _, venv_bin_dir = virtualenv.path_locations(venv_path) 176 | venv_python_path = os.path.join(venv_bin_dir, 'python') 177 | venv_previous_requirements_path = os.path.join(venv_path, 'requirements.txt') 178 | 179 | if not os.path.isfile(requirements_txt_path): 180 | # delete the venv if it's there and use the system python 181 | clean(app_path) 182 | return sys.executable 183 | 184 | # check that there's a virtualenv there and that it's got a working 185 | # version of python 186 | try: 187 | subprocess.check_call([ 188 | venv_python_path, 189 | '-c', 'import sys; sys.exit(0)' 190 | ]) 191 | except (OSError, subprocess.CalledProcessError): 192 | # we've got to build the virtualenv 193 | clean(app_path) 194 | print 'tbtool: Creating virtualenv...' 195 | virtualenv.create_environment(venv_path, site_packages=True,) 196 | 197 | # ignore the virtualenv when the app is tracked with git 198 | gitignore_path = os.path.join(venv_path, '.gitignore') 199 | with open(gitignore_path, 'w') as f: 200 | f.write(textwrap.dedent(''' 201 | # Generated by tbtool. 202 | 203 | # Don't commit virtualenvs to git, because they contain platform-specific 204 | # code and don't relocate well. 205 | 206 | # '*' matches everything in this folder 207 | 208 | * 209 | ''')) 210 | 211 | # if PYTHONPATH is defined (this is how Tide bundles packages on Mac and Linux), 212 | # the packages there have precidence over the packages in this virtualenv. That 213 | # prevents the user upgrading anything that's bundled, so we'll add the virtualenv's 214 | # packages in front of the existing PYTHONPATH. 215 | if 'PYTHONPATH' in os.environ: 216 | venv_site_packages = os.path.join(venv_lib_dir, 'site-packages') 217 | os.environ['PYTHONPATH'] = venv_site_packages + ':' + os.environ['PYTHONPATH'] 218 | 219 | requirements_unchanged_since_last_run = ( 220 | os.path.isfile(venv_previous_requirements_path) 221 | and filecmp.cmp(requirements_txt_path, venv_previous_requirements_path) 222 | ) 223 | 224 | if not requirements_unchanged_since_last_run: 225 | print 'tbtool: Installing dependencies into virtualenv...' 226 | venv_pip_path = os.path.join(venv_bin_dir, 'pip') 227 | 228 | env = os.environ.copy() 229 | # str() calls are needed because Windows doesn't allow unicode in the environment 230 | # (and wheelhouse is a unicode path) 231 | env['PIP_FIND_LINKS'] = 'file://%s' % str(wheelhouse) 232 | env['PIP_WHEEL_DIR'] = str(wheelhouse) 233 | 234 | subprocess.check_call([ 235 | venv_python_path, 236 | '-m', 'pip', 237 | 'install', '-r', requirements_txt_path, 238 | ], 239 | env=env 240 | ) 241 | 242 | # copy requirements into the venv so we don't need to run pip every run 243 | shutil.copyfile(requirements_txt_path, venv_previous_requirements_path) 244 | 245 | return venv_python_path 246 | 247 | 248 | def clean(app_path): 249 | venv_path = os.path.join(app_path, 'venv') 250 | shutil.rmtree(venv_path, ignore_errors=True) 251 | 252 | 253 | def install(app_path, hostname): 254 | session = SSHSession(hostname) 255 | 256 | try: 257 | app_name = os.path.basename(app_path) 258 | 259 | app_install_location = '/apps/%s' % app_name 260 | 261 | print 'tbtool: Copying app to %s...' % app_install_location 262 | session.exec_command('sudo rm -rf "%s"' % app_install_location) 263 | session.put_dir(app_path, app_install_location) 264 | 265 | print 'tbtool: Preparing app...' 266 | session.exec_command('tbtool build "%s"' % app_install_location) 267 | 268 | print 'tbtool: Restarting springboard...' 269 | session.exec_command('tbopen /apps/home') 270 | 271 | print 'tbtool: App installed.' 272 | finally: 273 | session.close() 274 | 275 | 276 | def tingbot_run(app_path): 277 | _run(app_path, extra_env={'TB_RUN_ON_LCD': '1'}) 278 | 279 | 280 | def main(): 281 | args = docopt(textwrap.dedent(''' 282 | Usage: 283 | tbtool [-v] simulate 284 | tbtool [-v] run 285 | tbtool [-v] install 286 | tbtool [-v] build 287 | tbtool [-v] clean 288 | tbtool [-v] tingbot_run 289 | tbtool -h|--help 290 | 291 | Options: 292 | -v, --verbose Output more information when errors occur 293 | 294 | Commands: 295 | simulate Runs the app in the simulator 296 | run Runs the app on the Tingbot specified by hostname 297 | install Installs the app on the Tingbot specified by 298 | hostname 299 | build If the app contains a requirements.txt file, creates 300 | a virtualenv with those packages installed. Not 301 | usually required to be called directly, building is 302 | automatic when using 'simulate', 'run' and 'install'. 303 | clean Removes temporary files in the app 304 | tingbot_run Used by tbprocessd to run Tingbot apps on the 305 | Tingbot itself. Users should probably use `tbopen' 306 | instead. 307 | ''')) 308 | 309 | if args['--verbose']: 310 | logging.basicConfig(level=logging.INFO) 311 | else: 312 | logging.basicConfig(level=logging.CRITICAL+1) 313 | 314 | try: 315 | if not os.path.exists(args['']): 316 | raise Exception("%s: no such file or directory" % args['']) 317 | 318 | app_path = os.path.realpath(args['']) 319 | 320 | if args['simulate']: 321 | simulate(app_path) 322 | 323 | elif args['run']: 324 | run(app_path, args['']) 325 | 326 | elif args['install']: 327 | install(app_path, args['']) 328 | 329 | elif args['build']: 330 | build(app_path) 331 | 332 | elif args['clean']: 333 | clean(app_path) 334 | 335 | elif args['tingbot_run']: 336 | tingbot_run(app_path) 337 | 338 | except Exception as e: 339 | for arg in e.args: 340 | if isinstance(arg, int) and arg == e.args[0]: 341 | sys.stderr.write('tbtool: %s error %i\n' % (e.__class__.__name__, arg)) 342 | else: 343 | for line in str(arg).splitlines(): 344 | sys.stderr.write('tbtool: %s\n' % line) 345 | if args['--verbose']: 346 | import traceback 347 | traceback.print_exc(file=sys.stderr) 348 | except KeyboardInterrupt: 349 | pass 350 | 351 | if __name__ == '__main__': 352 | main() 353 | -------------------------------------------------------------------------------- /docs/graphics.rst: -------------------------------------------------------------------------------- 1 | 🌈 Graphics 2 | ----------- 3 | 4 | Drawing 5 | ~~~~~~~ 6 | 7 | .. py:function:: screen.fill(color) 8 | 9 | Fills the screen with the specified ``color``. 10 | 11 | :ref:`color-option` can be specified using a name (e.g. 'white', 'black'), or an RGB triple. 12 | 13 | .. code-block:: python 14 | :caption: Example: fill the screen with white 15 | 16 | screen.fill(color='white') 17 | 18 | .. code-block:: python 19 | :caption: Example: fill the screen with red 20 | 21 | screen.fill(color=(255, 0, 0)) 22 | 23 | .. py:function:: screen.text(string…, xy=…, color=…, align=…, font=…, font_size=…, max_width=…, max_lines=…, max_height=…) 24 | 25 | Draws text ``string``. 26 | 27 | ``xy`` is the position that the text will be drawn. 28 | 29 | :ref:`align-option` is one of: 30 | 31 | topleft, left, bottomleft, top, center, bottom, topright, right, bottomright 32 | 33 | If a custom font is used, it must be included in the tingapp bundle. 34 | 35 | .. code-block:: python 36 | :caption: Example: Write 'Hello world' in black on the screen 37 | 38 | screen.text('Hello world!', color='black') 39 | 40 | .. code-block:: python 41 | :caption: Example: changing the alignment 42 | 43 | screen.text('Hello world!', xy=(20,20), color='black', align='topleft') 44 | 45 | .. code-block:: python 46 | :caption: Example: Using a custom font 47 | 48 | screen.text('Hello world!', color='black', font='Helvetica.ttf') 49 | 50 | .. code-block:: python 51 | :caption: Example: Changing the text size 52 | 53 | screen.text('Hello world!', color='black', font_size=50) 54 | 55 | .. code-block:: python 56 | :caption: Example: Confining text to a single line 57 | 58 | screen.text('Lorem ipsum dolor sit amet, consectetur adipiscing elit!', color='black', max_lines=1) 59 | 60 | .. code-block:: python 61 | :caption: Example: Confining text to two lines 62 | 63 | screen.text('Lorem ipsum dolor sit amet, consectetur adipiscing elit!', color='black', max_width=300, max_lines=2) 64 | 65 | 66 | .. py:function:: screen.rectangle(xy=…, size=…, color=…, align=…) 67 | 68 | Draws a rectangle at position xy, with the specified size and color. 69 | 70 | Align is one of 71 | 72 | topleft, left, bottomleft, top, center, bottom, topright, right, bottomright, 73 | 74 | .. code-block:: python 75 | :caption: Example: Drawing a red square 76 | 77 | screen.rectangle(xy=(25,25), size=(100,100), color=(255,0,0)) 78 | 79 | .. code-block:: python 80 | :caption: Example: Drawing centered 81 | 82 | screen.rectangle(xy=(160,120), size=(100,100), color=(255,0,0), align='center') 83 | 84 | .. function:: screen.image(filename…, xy=…, scale=…, align=…, max_width=…, max_height=…, raise_error=True) 85 | 86 | Draws an image with name filename at position xy. If filename is a URL (e.g. http://example.com/cats.png) then 87 | it will attempt to download this and display it. 88 | 89 | Images can be animated GIFs. Make sure to draw them in a loop() function to see them animate. 90 | 91 | Scale is a number that changes the size of the image e.g. scale=2 makes the image bigger, scale=0.5 makes the image smaller. There are also special values 'fit' and 'fill', which will fit or fill the image according to ``max_width`` and ``max_height``. 92 | 93 | Align is one of 94 | 95 | topleft, left, bottomleft, top, center, bottom, topright, right, bottomright 96 | 97 | If raise_error is True then any errors encountered while opening or retrieving the image will cause 98 | an `exception `_. If it is False, then if there is an error a "file not found" icon will be displayed instead 99 | 100 | .. code-block:: python 101 | :caption: Example: Drawing an Image 102 | 103 | screen.image('tingbot.png', xy=(25,25)) 104 | 105 | .. code-block:: python 106 | :caption: Example: Drawing an Image from a URL 107 | 108 | screen.image('http://i.imgur.com/xbT92Gm.png') 109 | 110 | .. py:function:: screen.line(start_xy=…, end_xy=…, color=…, width=…) 111 | 112 | Draws a line between ``start_xy`` and ``end_xy``. 113 | 114 | Screen 115 | ~~~~~~ 116 | 117 | The screen supports all the methods above, and some extras below. 118 | 119 | .. py:function:: screen.update() 120 | 121 | After drawing, this method should to be called to refresh the screen. When drawing in a 122 | ``draw()`` or ``loop()`` function, this is called automatically, but when drawing in a tight 123 | loop, e.g. during a calculation, it can called manually. 124 | 125 | .. code-block:: python 126 | :caption: Example: An app without a run loop - calling ``screen.update()`` manually 127 | 128 | import tingbot 129 | from tingbot import * 130 | 131 | screen.fill(color='black') 132 | 133 | # pump the main run loop just once to make sure the app starts 134 | tingbot.input.EventHandler().poll() 135 | 136 | frame_count = 0 137 | 138 | while True: 139 | screen.fill(color='black') 140 | screen.text(frame_count) 141 | screen.update() 142 | frame_count += 1 143 | 144 | .. py:attribute:: screen.brightness 145 | 146 | The brightness of the screen, between 0 and 100. 147 | 148 | .. code-block:: python 149 | :caption: Example: Dimming the screen 150 | 151 | screen.brightness = 25 152 | 153 | .. code-block:: python 154 | :caption: Example: Brightness test app 155 | 156 | import tingbot 157 | from tingbot import * 158 | 159 | state = {'brightness': 0} 160 | 161 | def loop(): 162 | screen.brightness = state['brightness'] 163 | 164 | screen.fill(color='black') 165 | screen.text('Brightness\n %i' % state['brightness']) 166 | 167 | state['brightness'] += 1 168 | 169 | if state['brightness'] > 100: 170 | state['brightness'] = 0 171 | 172 | tingbot.run(loop) 173 | 174 | .. _align-option: 175 | 176 | The ``align`` option 177 | ~~~~~~~~~~~~~~~~~~~~ 178 | 179 | When used without the ``xy`` parameter, the item is positioned relative to the screen/drawing surface. 180 | 181 | =============== ======================================= ======================================================== 182 | Setting Screenshot Code 183 | =============== ======================================= ======================================================== 184 | **topleft** .. image:: images/align/topleft.png ``screen.rectangle(color='green', align='topleft')`` 185 | :scale: 15% 186 | 187 | **top** .. image:: images/align/top.png ``screen.rectangle(color='green', align='top')`` 188 | :scale: 15% 189 | 190 | **topright** .. image:: images/align/topright.png ``screen.rectangle(color='green', align='topright')`` 191 | :scale: 15% 192 | 193 | **left** .. image:: images/align/left.png ``screen.rectangle(color='green', align='left')`` 194 | :scale: 15% 195 | 196 | **center** .. image:: images/align/center.png ``screen.rectangle(color='green', align='center')`` 197 | :scale: 15% 198 | 199 | **right** .. image:: images/align/right.png ``screen.rectangle(color='green', align='right')`` 200 | :scale: 15% 201 | 202 | **bottomleft** .. image:: images/align/bottomleft.png ``screen.rectangle(color='green', align='bottomleft')`` 203 | :scale: 15% 204 | 205 | **bottom** .. image:: images/align/bottom.png ``screen.rectangle(color='green', align='bottom')`` 206 | :scale: 15% 207 | 208 | **bottomright** .. image:: images/align/bottomright.png ``screen.rectangle(color='green', align='bottomright')`` 209 | :scale: 15% 210 | =============== ======================================= ======================================================== 211 | 212 | When used with the ``xy`` parameter, it positions the item relative to the ``xy`` point. 213 | 214 | =============== ========================================= ======================================================== 215 | Setting Screenshot Code 216 | =============== ========================================= ======================================================== 217 | **topleft** .. image:: images/alignxy/topleft.png ``screen.rectangle(xy=(160, 120), align='topleft')`` 218 | :scale: 15% 219 | 220 | **top** .. image:: images/alignxy/top.png ``screen.rectangle(xy=(160, 120), align='top')`` 221 | :scale: 15% 222 | 223 | **topright** .. image:: images/alignxy/topright.png ``screen.rectangle(xy=(160, 120), align='topright')`` 224 | :scale: 15% 225 | 226 | **left** .. image:: images/alignxy/left.png ``screen.rectangle(xy=(160, 120), align='left')`` 227 | :scale: 15% 228 | 229 | **center** .. image:: images/alignxy/center.png ``screen.rectangle(xy=(160, 120), align='center')`` 230 | :scale: 15% 231 | 232 | **right** .. image:: images/alignxy/right.png ``screen.rectangle(xy=(160, 120), align='right')`` 233 | :scale: 15% 234 | 235 | **bottomleft** .. image:: images/alignxy/bottomleft.png ``screen.rectangle(xy=(160, 120), align='bottomleft')`` 236 | :scale: 15% 237 | 238 | **bottom** .. image:: images/alignxy/bottom.png ``screen.rectangle(xy=(160, 120), align='bottom')`` 239 | :scale: 15% 240 | 241 | **bottomright** .. image:: images/alignxy/bottomright.png ``screen.rectangle(xy=(160, 120), align='bottomright')`` 242 | :scale: 15% 243 | =============== ========================================= ======================================================== 244 | 245 | .. _color-option: 246 | 247 | The ``color`` option 248 | ~~~~~~~~~~~~~~~~~~~~ 249 | 250 | The color option can be either an RGB value, or predefined color name. 251 | 252 | RGB values 253 | '''''''''' 254 | 255 | RGB values (as a tuple), like ``(255, 128, 0)``. 256 | 257 | Predefined colors 258 | ''''''''''''''''' 259 | 260 | We also have a set of default colors, referred to by their name, as a string. 261 | 262 | 263 | .. raw:: html 264 | 265 | 308 |
309 |
310 | 'navy' 311 | (0, 116, 217) 312 |
313 |
314 | 'blue' 315 | (0, 116, 217) 316 |
317 |
318 | 'aqua' 319 | (127, 219, 255) 320 |
321 |
322 | 'teal' 323 | (57, 204, 204) 324 |
325 |
326 | 'olive' 327 | (61, 153, 112) 328 |
329 |
330 | 'green' 331 | (46, 204, 64) 332 |
333 |
334 | 'lime' 335 | (1, 255, 112) 336 |
337 |
338 | 'yellow' 339 | (255, 220, 0) 340 |
341 |
342 | 'orange' 343 | (255, 133, 27) 344 |
345 |
346 | 'red' 347 | (255, 65, 54) 348 |
349 |
350 | 'maroon' 351 | (133, 20, 75) 352 |
353 |
354 | 'fuchsia' 355 | (240, 18, 190) 356 |
357 |
358 | 'purple' 359 | (177, 13, 201) 360 |
361 |
362 | 'black' 363 | (0, 0, 0) 364 |
365 |
366 | 'gray' 367 | (170, 170, 170) 368 |
369 |
370 | 'silver' 371 | (221, 221, 221) 372 |
373 |
374 | 'white' 375 | (255, 255, 255) 376 |
377 |
378 |
379 | 380 | Thanks to http://clrs.cc for the color scheme! 381 | -------------------------------------------------------------------------------- /tbtool/appdirs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Copyright (c) 2005-2010 ActiveState Software Inc. 4 | # Copyright (c) 2013 Eddy Petrișor 5 | 6 | """Utilities for determining application-specific dirs. 7 | 8 | See for details and usage. 9 | """ 10 | # Dev Notes: 11 | # - MSDN on where to store app data files: 12 | # http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120 13 | # - Mac OS X: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/index.html 14 | # - XDG spec for Un*x: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html 15 | 16 | __version_info__ = (1, 4, 0) 17 | __version__ = '.'.join(map(str, __version_info__)) 18 | 19 | 20 | import sys 21 | import os 22 | 23 | PY3 = sys.version_info[0] == 3 24 | 25 | if PY3: 26 | unicode = str 27 | 28 | if sys.platform.startswith('java'): 29 | import platform 30 | os_name = platform.java_ver()[3][0] 31 | if os_name.startswith('Windows'): # "Windows XP", "Windows 7", etc. 32 | system = 'win32' 33 | elif os_name.startswith('Mac'): # "Mac OS X", etc. 34 | system = 'darwin' 35 | else: # "Linux", "SunOS", "FreeBSD", etc. 36 | # Setting this to "linux2" is not ideal, but only Windows or Mac 37 | # are actually checked for and the rest of the module expects 38 | # *sys.platform* style strings. 39 | system = 'linux2' 40 | else: 41 | system = sys.platform 42 | 43 | 44 | 45 | def user_data_dir(appname=None, appauthor=None, version=None, roaming=False): 46 | r"""Return full path to the user-specific data dir for this application. 47 | 48 | "appname" is the name of application. 49 | If None, just the system directory is returned. 50 | "appauthor" (only used on Windows) is the name of the 51 | appauthor or distributing body for this application. Typically 52 | it is the owning company name. This falls back to appname. You may 53 | pass False to disable it. 54 | "version" is an optional version path element to append to the 55 | path. You might want to use this if you want multiple versions 56 | of your app to be able to run independently. If used, this 57 | would typically be ".". 58 | Only applied when appname is present. 59 | "roaming" (boolean, default False) can be set True to use the Windows 60 | roaming appdata directory. That means that for users on a Windows 61 | network setup for roaming profiles, this user data will be 62 | sync'd on login. See 63 | 64 | for a discussion of issues. 65 | 66 | Typical user data directories are: 67 | Mac OS X: ~/Library/Application Support/ 68 | Unix: ~/.local/share/ # or in $XDG_DATA_HOME, if defined 69 | Win XP (not roaming): C:\Documents and Settings\\Application Data\\ 70 | Win XP (roaming): C:\Documents and Settings\\Local Settings\Application Data\\ 71 | Win 7 (not roaming): C:\Users\\AppData\Local\\ 72 | Win 7 (roaming): C:\Users\\AppData\Roaming\\ 73 | 74 | For Unix, we follow the XDG spec and support $XDG_DATA_HOME. 75 | That means, by default "~/.local/share/". 76 | """ 77 | if system == "win32": 78 | if appauthor is None: 79 | appauthor = appname 80 | const = roaming and "CSIDL_APPDATA" or "CSIDL_LOCAL_APPDATA" 81 | path = os.path.normpath(_get_win_folder(const)) 82 | if appname: 83 | if appauthor is not False: 84 | path = os.path.join(path, appauthor, appname) 85 | else: 86 | path = os.path.join(path, appname) 87 | elif system == 'darwin': 88 | path = os.path.expanduser('~/Library/Application Support/') 89 | if appname: 90 | path = os.path.join(path, appname) 91 | else: 92 | path = os.getenv('XDG_DATA_HOME', os.path.expanduser("~/.local/share")) 93 | if appname: 94 | path = os.path.join(path, appname) 95 | if appname and version: 96 | path = os.path.join(path, version) 97 | return path 98 | 99 | 100 | def site_data_dir(appname=None, appauthor=None, version=None, multipath=False): 101 | """Return full path to the user-shared data dir for this application. 102 | 103 | "appname" is the name of application. 104 | If None, just the system directory is returned. 105 | "appauthor" (only used on Windows) is the name of the 106 | appauthor or distributing body for this application. Typically 107 | it is the owning company name. This falls back to appname. You may 108 | pass False to disable it. 109 | "version" is an optional version path element to append to the 110 | path. You might want to use this if you want multiple versions 111 | of your app to be able to run independently. If used, this 112 | would typically be ".". 113 | Only applied when appname is present. 114 | "multipath" is an optional parameter only applicable to *nix 115 | which indicates that the entire list of data dirs should be 116 | returned. By default, the first item from XDG_DATA_DIRS is 117 | returned, or '/usr/local/share/', 118 | if XDG_DATA_DIRS is not set 119 | 120 | Typical user data directories are: 121 | Mac OS X: /Library/Application Support/ 122 | Unix: /usr/local/share/ or /usr/share/ 123 | Win XP: C:\Documents and Settings\All Users\Application Data\\ 124 | Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) 125 | Win 7: C:\ProgramData\\ # Hidden, but writeable on Win 7. 126 | 127 | For Unix, this is using the $XDG_DATA_DIRS[0] default. 128 | 129 | WARNING: Do not use this on Windows. See the Vista-Fail note above for why. 130 | """ 131 | if system == "win32": 132 | if appauthor is None: 133 | appauthor = appname 134 | path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) 135 | if appname: 136 | if appauthor is not False: 137 | path = os.path.join(path, appauthor, appname) 138 | else: 139 | path = os.path.join(path, appname) 140 | elif system == 'darwin': 141 | path = os.path.expanduser('/Library/Application Support') 142 | if appname: 143 | path = os.path.join(path, appname) 144 | else: 145 | # XDG default for $XDG_DATA_DIRS 146 | # only first, if multipath is False 147 | path = os.getenv('XDG_DATA_DIRS', 148 | os.pathsep.join(['/usr/local/share', '/usr/share'])) 149 | pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)] 150 | if appname: 151 | if version: 152 | appname = os.path.join(appname, version) 153 | pathlist = [os.sep.join([x, appname]) for x in pathlist] 154 | 155 | if multipath: 156 | path = os.pathsep.join(pathlist) 157 | else: 158 | path = pathlist[0] 159 | return path 160 | 161 | if appname and version: 162 | path = os.path.join(path, version) 163 | return path 164 | 165 | 166 | def user_config_dir(appname=None, appauthor=None, version=None, roaming=False): 167 | r"""Return full path to the user-specific config dir for this application. 168 | 169 | "appname" is the name of application. 170 | If None, just the system directory is returned. 171 | "appauthor" (only used on Windows) is the name of the 172 | appauthor or distributing body for this application. Typically 173 | it is the owning company name. This falls back to appname. You may 174 | pass False to disable it. 175 | "version" is an optional version path element to append to the 176 | path. You might want to use this if you want multiple versions 177 | of your app to be able to run independently. If used, this 178 | would typically be ".". 179 | Only applied when appname is present. 180 | "roaming" (boolean, default False) can be set True to use the Windows 181 | roaming appdata directory. That means that for users on a Windows 182 | network setup for roaming profiles, this user data will be 183 | sync'd on login. See 184 | 185 | for a discussion of issues. 186 | 187 | Typical user data directories are: 188 | Mac OS X: same as user_data_dir 189 | Unix: ~/.config/ # or in $XDG_CONFIG_HOME, if defined 190 | Win *: same as user_data_dir 191 | 192 | For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME. 193 | That means, by deafult "~/.config/". 194 | """ 195 | if system in ["win32", "darwin"]: 196 | path = user_data_dir(appname, appauthor, None, roaming) 197 | else: 198 | path = os.getenv('XDG_CONFIG_HOME', os.path.expanduser("~/.config")) 199 | if appname: 200 | path = os.path.join(path, appname) 201 | if appname and version: 202 | path = os.path.join(path, version) 203 | return path 204 | 205 | 206 | def site_config_dir(appname=None, appauthor=None, version=None, multipath=False): 207 | """Return full path to the user-shared data dir for this application. 208 | 209 | "appname" is the name of application. 210 | If None, just the system directory is returned. 211 | "appauthor" (only used on Windows) is the name of the 212 | appauthor or distributing body for this application. Typically 213 | it is the owning company name. This falls back to appname. You may 214 | pass False to disable it. 215 | "version" is an optional version path element to append to the 216 | path. You might want to use this if you want multiple versions 217 | of your app to be able to run independently. If used, this 218 | would typically be ".". 219 | Only applied when appname is present. 220 | "multipath" is an optional parameter only applicable to *nix 221 | which indicates that the entire list of config dirs should be 222 | returned. By default, the first item from XDG_CONFIG_DIRS is 223 | returned, or '/etc/xdg/', if XDG_CONFIG_DIRS is not set 224 | 225 | Typical user data directories are: 226 | Mac OS X: same as site_data_dir 227 | Unix: /etc/xdg/ or $XDG_CONFIG_DIRS[i]/ for each value in 228 | $XDG_CONFIG_DIRS 229 | Win *: same as site_data_dir 230 | Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) 231 | 232 | For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False 233 | 234 | WARNING: Do not use this on Windows. See the Vista-Fail note above for why. 235 | """ 236 | if system in ["win32", "darwin"]: 237 | path = site_data_dir(appname, appauthor) 238 | if appname and version: 239 | path = os.path.join(path, version) 240 | else: 241 | # XDG default for $XDG_CONFIG_DIRS 242 | # only first, if multipath is False 243 | path = os.getenv('XDG_CONFIG_DIRS', '/etc/xdg') 244 | pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)] 245 | if appname: 246 | if version: 247 | appname = os.path.join(appname, version) 248 | pathlist = [os.sep.join([x, appname]) for x in pathlist] 249 | 250 | if multipath: 251 | path = os.pathsep.join(pathlist) 252 | else: 253 | path = pathlist[0] 254 | return path 255 | 256 | 257 | def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True): 258 | r"""Return full path to the user-specific cache dir for this application. 259 | 260 | "appname" is the name of application. 261 | If None, just the system directory is returned. 262 | "appauthor" (only used on Windows) is the name of the 263 | appauthor or distributing body for this application. Typically 264 | it is the owning company name. This falls back to appname. You may 265 | pass False to disable it. 266 | "version" is an optional version path element to append to the 267 | path. You might want to use this if you want multiple versions 268 | of your app to be able to run independently. If used, this 269 | would typically be ".". 270 | Only applied when appname is present. 271 | "opinion" (boolean) can be False to disable the appending of 272 | "Cache" to the base app data dir for Windows. See 273 | discussion below. 274 | 275 | Typical user cache directories are: 276 | Mac OS X: ~/Library/Caches/ 277 | Unix: ~/.cache/ (XDG default) 278 | Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Cache 279 | Vista: C:\Users\\AppData\Local\\\Cache 280 | 281 | On Windows the only suggestion in the MSDN docs is that local settings go in 282 | the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming 283 | app data dir (the default returned by `user_data_dir` above). Apps typically 284 | put cache data somewhere *under* the given dir here. Some examples: 285 | ...\Mozilla\Firefox\Profiles\\Cache 286 | ...\Acme\SuperApp\Cache\1.0 287 | OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. 288 | This can be disabled with the `opinion=False` option. 289 | """ 290 | if system == "win32": 291 | if appauthor is None: 292 | appauthor = appname 293 | path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA")) 294 | if appname: 295 | if appauthor is not False: 296 | path = os.path.join(path, appauthor, appname) 297 | else: 298 | path = os.path.join(path, appname) 299 | if opinion: 300 | path = os.path.join(path, "Cache") 301 | elif system == 'darwin': 302 | path = os.path.expanduser('~/Library/Caches') 303 | if appname: 304 | path = os.path.join(path, appname) 305 | else: 306 | path = os.getenv('XDG_CACHE_HOME', os.path.expanduser('~/.cache')) 307 | if appname: 308 | path = os.path.join(path, appname) 309 | if appname and version: 310 | path = os.path.join(path, version) 311 | return path 312 | 313 | 314 | def user_log_dir(appname=None, appauthor=None, version=None, opinion=True): 315 | r"""Return full path to the user-specific log dir for this application. 316 | 317 | "appname" is the name of application. 318 | If None, just the system directory is returned. 319 | "appauthor" (only used on Windows) is the name of the 320 | appauthor or distributing body for this application. Typically 321 | it is the owning company name. This falls back to appname. You may 322 | pass False to disable it. 323 | "version" is an optional version path element to append to the 324 | path. You might want to use this if you want multiple versions 325 | of your app to be able to run independently. If used, this 326 | would typically be ".". 327 | Only applied when appname is present. 328 | "opinion" (boolean) can be False to disable the appending of 329 | "Logs" to the base app data dir for Windows, and "log" to the 330 | base cache dir for Unix. See discussion below. 331 | 332 | Typical user cache directories are: 333 | Mac OS X: ~/Library/Logs/ 334 | Unix: ~/.cache//log # or under $XDG_CACHE_HOME if defined 335 | Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Logs 336 | Vista: C:\Users\\AppData\Local\\\Logs 337 | 338 | On Windows the only suggestion in the MSDN docs is that local settings 339 | go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in 340 | examples of what some windows apps use for a logs dir.) 341 | 342 | OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA` 343 | value for Windows and appends "log" to the user cache dir for Unix. 344 | This can be disabled with the `opinion=False` option. 345 | """ 346 | if system == "darwin": 347 | path = os.path.join( 348 | os.path.expanduser('~/Library/Logs'), 349 | appname) 350 | elif system == "win32": 351 | path = user_data_dir(appname, appauthor, version) 352 | version = False 353 | if opinion: 354 | path = os.path.join(path, "Logs") 355 | else: 356 | path = user_cache_dir(appname, appauthor, version) 357 | version = False 358 | if opinion: 359 | path = os.path.join(path, "log") 360 | if appname and version: 361 | path = os.path.join(path, version) 362 | return path 363 | 364 | 365 | class AppDirs(object): 366 | """Convenience wrapper for getting application dirs.""" 367 | def __init__(self, appname, appauthor=None, version=None, roaming=False, 368 | multipath=False): 369 | self.appname = appname 370 | self.appauthor = appauthor 371 | self.version = version 372 | self.roaming = roaming 373 | self.multipath = multipath 374 | 375 | @property 376 | def user_data_dir(self): 377 | return user_data_dir(self.appname, self.appauthor, 378 | version=self.version, roaming=self.roaming) 379 | 380 | @property 381 | def site_data_dir(self): 382 | return site_data_dir(self.appname, self.appauthor, 383 | version=self.version, multipath=self.multipath) 384 | 385 | @property 386 | def user_config_dir(self): 387 | return user_config_dir(self.appname, self.appauthor, 388 | version=self.version, roaming=self.roaming) 389 | 390 | @property 391 | def site_config_dir(self): 392 | return site_config_dir(self.appname, self.appauthor, 393 | version=self.version, multipath=self.multipath) 394 | 395 | @property 396 | def user_cache_dir(self): 397 | return user_cache_dir(self.appname, self.appauthor, 398 | version=self.version) 399 | 400 | @property 401 | def user_log_dir(self): 402 | return user_log_dir(self.appname, self.appauthor, 403 | version=self.version) 404 | 405 | 406 | #---- internal support stuff 407 | 408 | def _get_win_folder_from_registry(csidl_name): 409 | """This is a fallback technique at best. I'm not sure if using the 410 | registry for this guarantees us the correct answer for all CSIDL_* 411 | names. 412 | """ 413 | import _winreg 414 | 415 | shell_folder_name = { 416 | "CSIDL_APPDATA": "AppData", 417 | "CSIDL_COMMON_APPDATA": "Common AppData", 418 | "CSIDL_LOCAL_APPDATA": "Local AppData", 419 | }[csidl_name] 420 | 421 | key = _winreg.OpenKey( 422 | _winreg.HKEY_CURRENT_USER, 423 | r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" 424 | ) 425 | dir, type = _winreg.QueryValueEx(key, shell_folder_name) 426 | return dir 427 | 428 | 429 | def _get_win_folder_with_pywin32(csidl_name): 430 | from win32com.shell import shellcon, shell 431 | dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0) 432 | # Try to make this a unicode path because SHGetFolderPath does 433 | # not return unicode strings when there is unicode data in the 434 | # path. 435 | try: 436 | dir = unicode(dir) 437 | 438 | # Downgrade to short path name if have highbit chars. See 439 | # . 440 | has_high_char = False 441 | for c in dir: 442 | if ord(c) > 255: 443 | has_high_char = True 444 | break 445 | if has_high_char: 446 | try: 447 | import win32api 448 | dir = win32api.GetShortPathName(dir) 449 | except ImportError: 450 | pass 451 | except UnicodeError: 452 | pass 453 | return dir 454 | 455 | 456 | def _get_win_folder_with_ctypes(csidl_name): 457 | import ctypes 458 | 459 | csidl_const = { 460 | "CSIDL_APPDATA": 26, 461 | "CSIDL_COMMON_APPDATA": 35, 462 | "CSIDL_LOCAL_APPDATA": 28, 463 | }[csidl_name] 464 | 465 | buf = ctypes.create_unicode_buffer(1024) 466 | ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf) 467 | 468 | # Downgrade to short path name if have highbit chars. See 469 | # . 470 | has_high_char = False 471 | for c in buf: 472 | if ord(c) > 255: 473 | has_high_char = True 474 | break 475 | if has_high_char: 476 | buf2 = ctypes.create_unicode_buffer(1024) 477 | if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024): 478 | buf = buf2 479 | 480 | return buf.value 481 | 482 | def _get_win_folder_with_jna(csidl_name): 483 | import array 484 | from com.sun import jna 485 | from com.sun.jna.platform import win32 486 | 487 | buf_size = win32.WinDef.MAX_PATH * 2 488 | buf = array.zeros('c', buf_size) 489 | shell = win32.Shell32.INSTANCE 490 | shell.SHGetFolderPath(None, getattr(win32.ShlObj, csidl_name), None, win32.ShlObj.SHGFP_TYPE_CURRENT, buf) 491 | dir = jna.Native.toString(buf.tostring()).rstrip("\0") 492 | 493 | # Downgrade to short path name if have highbit chars. See 494 | # . 495 | has_high_char = False 496 | for c in dir: 497 | if ord(c) > 255: 498 | has_high_char = True 499 | break 500 | if has_high_char: 501 | buf = array.zeros('c', buf_size) 502 | kernel = win32.Kernel32.INSTANCE 503 | if kernal.GetShortPathName(dir, buf, buf_size): 504 | dir = jna.Native.toString(buf.tostring()).rstrip("\0") 505 | 506 | return dir 507 | 508 | if system == "win32": 509 | try: 510 | import win32com.shell 511 | _get_win_folder = _get_win_folder_with_pywin32 512 | except ImportError: 513 | try: 514 | from ctypes import windll 515 | _get_win_folder = _get_win_folder_with_ctypes 516 | except ImportError: 517 | try: 518 | import com.sun.jna 519 | _get_win_folder = _get_win_folder_with_jna 520 | except ImportError: 521 | _get_win_folder = _get_win_folder_from_registry 522 | 523 | 524 | #---- self test code 525 | 526 | if __name__ == "__main__": 527 | appname = "MyApp" 528 | appauthor = "MyCompany" 529 | 530 | props = ("user_data_dir", "site_data_dir", 531 | "user_config_dir", "site_config_dir", 532 | "user_cache_dir", "user_log_dir") 533 | 534 | print("-- app dirs (with optional 'version')") 535 | dirs = AppDirs(appname, appauthor, version="1.0") 536 | for prop in props: 537 | print("%s: %s" % (prop, getattr(dirs, prop))) 538 | 539 | print("\n-- app dirs (without optional 'version')") 540 | dirs = AppDirs(appname, appauthor) 541 | for prop in props: 542 | print("%s: %s" % (prop, getattr(dirs, prop))) 543 | 544 | print("\n-- app dirs (without optional 'appauthor')") 545 | dirs = AppDirs(appname) 546 | for prop in props: 547 | print("%s: %s" % (prop, getattr(dirs, prop))) 548 | 549 | print("\n-- app dirs (with disabled 'appauthor')") 550 | dirs = AppDirs(appname, appauthor=False) 551 | for prop in props: 552 | print("%s: %s" % (prop, getattr(dirs, prop))) 553 | -------------------------------------------------------------------------------- /tests/peripherals.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "DEVPATH": "/devices/LNXSYSTM:00/LNXPWRBN:00/input/input2", 4 | "EV": "3", 5 | "ID_FOR_SEAT": "input-acpi-LNXPWRBN_00", 6 | "ID_INPUT": "1", 7 | "ID_INPUT_KEY": "1", 8 | "ID_PATH": "acpi-LNXPWRBN:00", 9 | "ID_PATH_TAG": "acpi-LNXPWRBN_00", 10 | "KEY": "10000000000000 0", 11 | "MODALIAS": "input:b0019v0000p0001e0000-e0,1,k74,ramlsfw", 12 | "NAME": "\"Power Button\"", 13 | "PHYS": "\"LNXPWRBN/button/input0\"", 14 | "PRODUCT": "19/0/1/0", 15 | "PROP": "0", 16 | "SUBSYSTEM": "input", 17 | "TAGS": ":seat:", 18 | "USEC_INITIALIZED": "1600578", 19 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 20 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 21 | }, 22 | { 23 | "BACKSPACE": "guess", 24 | "DEVNAME": "/dev/input/event2", 25 | "DEVPATH": "/devices/LNXSYSTM:00/LNXPWRBN:00/input/input2/event2", 26 | "ID_INPUT": "1", 27 | "ID_INPUT_KEY": "1", 28 | "ID_PATH": "acpi-LNXPWRBN:00", 29 | "ID_PATH_TAG": "acpi-LNXPWRBN_00", 30 | "MAJOR": "13", 31 | "MINOR": "66", 32 | "SUBSYSTEM": "input", 33 | "TAGS": ":power-switch:", 34 | "USEC_INITIALIZED": "1624315", 35 | "XKBLAYOUT": "gb", 36 | "XKBMODEL": "pc105", 37 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 38 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 39 | }, 40 | { 41 | "DEVPATH": "/devices/LNXSYSTM:00/LNXSYBUS:00/PNP0A08:00/LNXVIDEO:00/input/input12", 42 | "EV": "3", 43 | "ID_FOR_SEAT": "input-acpi-LNXVIDEO_00", 44 | "ID_INPUT": "1", 45 | "ID_INPUT_KEY": "1", 46 | "ID_PATH": "acpi-LNXVIDEO:00", 47 | "ID_PATH_TAG": "acpi-LNXVIDEO_00", 48 | "KEY": "3e000b00000000 0 0 0", 49 | "MODALIAS": "input:b0019v0000p0006e0000-e0,1,kE0,E1,E3,F1,F2,F3,F4,F5,ramlsfw", 50 | "NAME": "\"Video Bus\"", 51 | "PHYS": "\"LNXVIDEO/video/input0\"", 52 | "PRODUCT": "19/0/6/0", 53 | "PROP": "0", 54 | "SUBSYSTEM": "input", 55 | "TAGS": ":seat:", 56 | "USEC_INITIALIZED": "2902684", 57 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 58 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 59 | }, 60 | { 61 | "BACKSPACE": "guess", 62 | "DEVNAME": "/dev/input/event4", 63 | "DEVPATH": "/devices/LNXSYSTM:00/LNXSYBUS:00/PNP0A08:00/LNXVIDEO:00/input/input12/event4", 64 | "ID_INPUT": "1", 65 | "ID_INPUT_KEY": "1", 66 | "ID_PATH": "acpi-LNXVIDEO:00", 67 | "ID_PATH_TAG": "acpi-LNXVIDEO_00", 68 | "MAJOR": "13", 69 | "MINOR": "68", 70 | "SUBSYSTEM": "input", 71 | "TAGS": ":power-switch:", 72 | "USEC_INITIALIZED": "2932245", 73 | "XKBLAYOUT": "gb", 74 | "XKBMODEL": "pc105", 75 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 76 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 77 | }, 78 | { 79 | "DEVPATH": "/devices/LNXSYSTM:00/LNXSYBUS:00/PNP0A08:00/PNP0C0C:00/input/input0", 80 | "EV": "3", 81 | "ID_FOR_SEAT": "input-acpi-PNP0C0C_00", 82 | "ID_INPUT": "1", 83 | "ID_INPUT_KEY": "1", 84 | "ID_PATH": "acpi-PNP0C0C:00", 85 | "ID_PATH_TAG": "acpi-PNP0C0C_00", 86 | "KEY": "10000000000000 0", 87 | "MODALIAS": "input:b0019v0000p0001e0000-e0,1,k74,ramlsfw", 88 | "NAME": "\"Power Button\"", 89 | "PHYS": "\"PNP0C0C/button/input0\"", 90 | "PRODUCT": "19/0/1/0", 91 | "PROP": "0", 92 | "SUBSYSTEM": "input", 93 | "TAGS": ":seat:", 94 | "USEC_INITIALIZED": "1609847", 95 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 96 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 97 | }, 98 | { 99 | "BACKSPACE": "guess", 100 | "DEVNAME": "/dev/input/event0", 101 | "DEVPATH": "/devices/LNXSYSTM:00/LNXSYBUS:00/PNP0A08:00/PNP0C0C:00/input/input0/event0", 102 | "ID_INPUT": "1", 103 | "ID_INPUT_KEY": "1", 104 | "ID_PATH": "acpi-PNP0C0C:00", 105 | "ID_PATH_TAG": "acpi-PNP0C0C_00", 106 | "MAJOR": "13", 107 | "MINOR": "64", 108 | "SUBSYSTEM": "input", 109 | "TAGS": ":power-switch:", 110 | "USEC_INITIALIZED": "1656292", 111 | "XKBLAYOUT": "gb", 112 | "XKBMODEL": "pc105", 113 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 114 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 115 | }, 116 | { 117 | "DEVPATH": "/devices/LNXSYSTM:00/LNXSYBUS:00/PNP0C0D:00/input/input1", 118 | "EV": "21", 119 | "ID_FOR_SEAT": "input-acpi-PNP0C0D_00", 120 | "ID_INPUT": "1", 121 | "ID_PATH": "acpi-PNP0C0D:00", 122 | "ID_PATH_TAG": "acpi-PNP0C0D_00", 123 | "MODALIAS": "input:b0019v0000p0005e0000-e0,5,kramlsfw0,", 124 | "NAME": "\"Lid Switch\"", 125 | "PHYS": "\"PNP0C0D/button/input0\"", 126 | "PRODUCT": "19/0/5/0", 127 | "PROP": "0", 128 | "SUBSYSTEM": "input", 129 | "SW": "1", 130 | "TAGS": ":seat:", 131 | "USEC_INITIALIZED": "1601030", 132 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 133 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 134 | }, 135 | { 136 | "DEVNAME": "/dev/input/event1", 137 | "DEVPATH": "/devices/LNXSYSTM:00/LNXSYBUS:00/PNP0C0D:00/input/input1/event1", 138 | "ID_INPUT": "1", 139 | "ID_PATH": "acpi-PNP0C0D:00", 140 | "ID_PATH_TAG": "acpi-PNP0C0D_00", 141 | "MAJOR": "13", 142 | "MINOR": "65", 143 | "SUBSYSTEM": "input", 144 | "TAGS": ":power-switch:", 145 | "USEC_INITIALIZED": "1631192", 146 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 147 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 148 | }, 149 | { 150 | "DEVPATH": "/devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.2/1-1.2:1.0/0003:1A2C:0C21.0001/input/input18", 151 | "EV": "120013", 152 | "ID_BUS": "usb", 153 | "ID_FOR_SEAT": "input-pci-0000_00_1a_0-usb-0_1_2_1_0", 154 | "ID_INPUT": "1", 155 | "ID_INPUT_KEY": "1", 156 | "ID_INPUT_KEYBOARD": "1", 157 | "ID_MODEL": "USB_Keyboard", 158 | "ID_MODEL_ENC": "USB\\x20Keyboard", 159 | "ID_MODEL_ID": "0c21", 160 | "ID_PATH": "pci-0000:00:1a.0-usb-0:1.2:1.0", 161 | "ID_PATH_TAG": "pci-0000_00_1a_0-usb-0_1_2_1_0", 162 | "ID_REVISION": "0110", 163 | "ID_SERIAL": "USB_USB_Keyboard", 164 | "ID_TYPE": "hid", 165 | "ID_USB_DRIVER": "usbhid", 166 | "ID_USB_INTERFACES": ":030101:030102:", 167 | "ID_USB_INTERFACE_NUM": "00", 168 | "ID_VENDOR": "USB", 169 | "ID_VENDOR_ENC": "USB", 170 | "ID_VENDOR_ID": "1a2c", 171 | "KEY": "1000000000007 ff800000000007ff febeffdff3cfffff fffffffffffffffe", 172 | "LED": "7", 173 | "MODALIAS": "input:b0003v1A2Cp0C21e0110-e0,1,4,11,14,k71,72,73,74,75,77,79,7A,7B,7C,7D,7E,7F,80,81,82,83,84,85,86,87,88,89,8A,B7,B8,B9,BA,BB,BC,BD,BE,BF,C0,C1,C2,F0,ram4,l0,1,2,sfw", 174 | "MSC": "10", 175 | "NAME": "\"USB USB Keyboard\"", 176 | "PHYS": "\"usb-0000:00:1a.0-1.2/input0\"", 177 | "PRODUCT": "3/1a2c/c21/110", 178 | "PROP": "0", 179 | "SUBSYSTEM": "input", 180 | "TAGS": ":seat:", 181 | "UNIQ": "\"\"", 182 | "USEC_INITIALIZED": "5360884685", 183 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 184 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 185 | }, 186 | { 187 | "BACKSPACE": "guess", 188 | "DEVLINKS": "/dev/input/by-path/pci-0000:00:1a.0-usb-0:1.2:1.0-event-kbd /dev/input/by-id/usb-USB_USB_Keyboard-event-kbd", 189 | "DEVNAME": "/dev/input/event11", 190 | "DEVPATH": "/devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.2/1-1.2:1.0/0003:1A2C:0C21.0001/input/input18/event11", 191 | "ID_BUS": "usb", 192 | "ID_INPUT": "1", 193 | "ID_INPUT_KEY": "1", 194 | "ID_INPUT_KEYBOARD": "1", 195 | "ID_MODEL": "USB_Keyboard", 196 | "ID_MODEL_ENC": "USB\\x20Keyboard", 197 | "ID_MODEL_ID": "0c21", 198 | "ID_PATH": "pci-0000:00:1a.0-usb-0:1.2:1.0", 199 | "ID_PATH_TAG": "pci-0000_00_1a_0-usb-0_1_2_1_0", 200 | "ID_REVISION": "0110", 201 | "ID_SERIAL": "USB_USB_Keyboard", 202 | "ID_TYPE": "hid", 203 | "ID_USB_DRIVER": "usbhid", 204 | "ID_USB_INTERFACES": ":030101:030102:", 205 | "ID_USB_INTERFACE_NUM": "00", 206 | "ID_VENDOR": "USB", 207 | "ID_VENDOR_ENC": "USB", 208 | "ID_VENDOR_ID": "1a2c", 209 | "MAJOR": "13", 210 | "MINOR": "75", 211 | "SUBSYSTEM": "input", 212 | "USEC_INITIALIZED": "5360901646", 213 | "XKBLAYOUT": "gb", 214 | "XKBMODEL": "pc105", 215 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 216 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 217 | }, 218 | { 219 | "ABS": "100000000", 220 | "DEVPATH": "/devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.2/1-1.2:1.1/0003:1A2C:0C21.0002/input/input19", 221 | "EV": "1f", 222 | "ID_BUS": "usb", 223 | "ID_FOR_SEAT": "input-pci-0000_00_1a_0-usb-0_1_2_1_1", 224 | "ID_INPUT": "1", 225 | "ID_INPUT_KEY": "1", 226 | "ID_INPUT_MOUSE": "1", 227 | "ID_MODEL": "USB_Keyboard", 228 | "ID_MODEL_ENC": "USB\\x20Keyboard", 229 | "ID_MODEL_ID": "0c21", 230 | "ID_PATH": "pci-0000:00:1a.0-usb-0:1.2:1.1", 231 | "ID_PATH_TAG": "pci-0000_00_1a_0-usb-0_1_2_1_1", 232 | "ID_REVISION": "0110", 233 | "ID_SERIAL": "USB_USB_Keyboard", 234 | "ID_TYPE": "hid", 235 | "ID_USB_DRIVER": "usbhid", 236 | "ID_USB_INTERFACES": ":030101:030102:", 237 | "ID_USB_INTERFACE_NUM": "01", 238 | "ID_VENDOR": "USB", 239 | "ID_VENDOR_ENC": "USB", 240 | "ID_VENDOR_ID": "1a2c", 241 | "KEY": "3007f 0 0 483ffff17aff32d bf54444600000000 70001 130c130b17c000 267bfad941dfed 9e168000004400 10000002", 242 | "MODALIAS": "input:b0003v1A2Cp0C21e0110-e0,1,2,3,4,k71,72,73,74,77,80,82,83,85,86,87,88,89,8A,8B,8C,8E,8F,90,96,98,9B,9C,9E,9F,A1,A3,A4,A5,A6,A7,A8,A9,AB,AC,AD,AE,B1,B2,B5,CE,CF,D0,D1,D2,D4,D8,D9,DB,E0,E1,E4,EA,EB,F0,F1,F4,100,110,111,112,161,162,166,16A,16E,172,174,176,178,179,17A,17B,17C,17D,17F,180,182,183,185,188,189,18C,18D,18E,18F,190,191,192,193,195,197,198,199,19A,19C,1A0,1A1,1A2,1A3,1A4,1A5,1A6,1A7,1A8,1A9,1AA,1AB,1AC,1AD,1AE,1AF,1B0,1B1,1B7,1BA,240,241,242,243,244,245,246,250,251,r0,1,6,8,a20,m4,lsfw", 243 | "MSC": "10", 244 | "NAME": "\"USB USB Keyboard\"", 245 | "PHYS": "\"usb-0000:00:1a.0-1.2/input1\"", 246 | "PRODUCT": "3/1a2c/c21/110", 247 | "PROP": "0", 248 | "REL": "143", 249 | "SUBSYSTEM": "input", 250 | "TAGS": ":seat:", 251 | "UNIQ": "\"\"", 252 | "USEC_INITIALIZED": "5360883332", 253 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 254 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 255 | }, 256 | { 257 | "BACKSPACE": "guess", 258 | "DEVLINKS": "/dev/input/by-id/usb-USB_USB_Keyboard-if01-event-mouse /dev/input/by-path/pci-0000:00:1a.0-usb-0:1.2:1.1-event-mouse", 259 | "DEVNAME": "/dev/input/event12", 260 | "DEVPATH": "/devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.2/1-1.2:1.1/0003:1A2C:0C21.0002/input/input19/event12", 261 | "ID_BUS": "usb", 262 | "ID_INPUT": "1", 263 | "ID_INPUT_KEY": "1", 264 | "ID_INPUT_MOUSE": "1", 265 | "ID_MODEL": "USB_Keyboard", 266 | "ID_MODEL_ENC": "USB\\x20Keyboard", 267 | "ID_MODEL_ID": "0c21", 268 | "ID_PATH": "pci-0000:00:1a.0-usb-0:1.2:1.1", 269 | "ID_PATH_TAG": "pci-0000_00_1a_0-usb-0_1_2_1_1", 270 | "ID_REVISION": "0110", 271 | "ID_SERIAL": "USB_USB_Keyboard", 272 | "ID_TYPE": "hid", 273 | "ID_USB_DRIVER": "usbhid", 274 | "ID_USB_INTERFACES": ":030101:030102:", 275 | "ID_USB_INTERFACE_NUM": "01", 276 | "ID_VENDOR": "USB", 277 | "ID_VENDOR_ENC": "USB", 278 | "ID_VENDOR_ID": "1a2c", 279 | "MAJOR": "13", 280 | "MINOR": "76", 281 | "SUBSYSTEM": "input", 282 | "USEC_INITIALIZED": "5360917695", 283 | "XKBLAYOUT": "gb", 284 | "XKBMODEL": "pc105", 285 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 286 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 287 | }, 288 | { 289 | "DEVLINKS": "/dev/input/by-path/pci-0000:00:1a.0-usb-0:1.2:1.1-mouse /dev/input/by-id/usb-USB_USB_Keyboard-if01-mouse", 290 | "DEVNAME": "/dev/input/mouse1", 291 | "DEVPATH": "/devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.2/1-1.2:1.1/0003:1A2C:0C21.0002/input/input19/mouse1", 292 | "ID_BUS": "usb", 293 | "ID_INPUT": "1", 294 | "ID_INPUT_KEY": "1", 295 | "ID_INPUT_MOUSE": "1", 296 | "ID_MODEL": "USB_Keyboard", 297 | "ID_MODEL_ENC": "USB\\x20Keyboard", 298 | "ID_MODEL_ID": "0c21", 299 | "ID_PATH": "pci-0000:00:1a.0-usb-0:1.2:1.1", 300 | "ID_PATH_TAG": "pci-0000_00_1a_0-usb-0_1_2_1_1", 301 | "ID_REVISION": "0110", 302 | "ID_SERIAL": "USB_USB_Keyboard", 303 | "ID_TYPE": "hid", 304 | "ID_USB_DRIVER": "usbhid", 305 | "ID_USB_INTERFACES": ":030101:030102:", 306 | "ID_USB_INTERFACE_NUM": "01", 307 | "ID_VENDOR": "USB", 308 | "ID_VENDOR_ENC": "USB", 309 | "ID_VENDOR_ID": "1a2c", 310 | "MAJOR": "13", 311 | "MINOR": "33", 312 | "SUBSYSTEM": "input", 313 | "USEC_INITIALIZED": "5360894766", 314 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 315 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 316 | }, 317 | { 318 | "DEVPATH": "/devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.3/1-1.3:1.0/input/input17", 319 | "EV": "3", 320 | "ID_BUS": "usb", 321 | "ID_FOR_SEAT": "input-pci-0000_00_1a_0-usb-0_1_3_1_0", 322 | "ID_INPUT": "1", 323 | "ID_INPUT_KEY": "1", 324 | "ID_MODEL": "TOSHIBA_Web_Camera_-_HD", 325 | "ID_MODEL_ENC": "TOSHIBA\\x20Web\\x20Camera\\x20-\\x20HD", 326 | "ID_MODEL_ID": "7017", 327 | "ID_PATH": "pci-0000:00:1a.0-usb-0:1.3:1.0", 328 | "ID_PATH_TAG": "pci-0000_00_1a_0-usb-0_1_3_1_0", 329 | "ID_REVISION": "0016", 330 | "ID_SERIAL": "0420-00RV0TBDAJD1M_TOSHIBA_Web_Camera_-_HD_200901010001", 331 | "ID_SERIAL_SHORT": "200901010001", 332 | "ID_TYPE": "video", 333 | "ID_USB_DRIVER": "uvcvideo", 334 | "ID_USB_INTERFACES": ":0e0100:0e0200:", 335 | "ID_USB_INTERFACE_NUM": "00", 336 | "ID_VENDOR": "0420-00RV0TBDAJD1M", 337 | "ID_VENDOR_ENC": "0420-00RV0TBDAJD1M", 338 | "ID_VENDOR_ID": "04ca", 339 | "KEY": "100000 0 0 0", 340 | "MODALIAS": "input:b0003v04CAp7017e0016-e0,1,kD4,ramlsfw", 341 | "NAME": "\"TOSHIBA Web Camera - HD\"", 342 | "PHYS": "\"usb-0000:00:1a.0-1.3/button\"", 343 | "PRODUCT": "3/4ca/7017/16", 344 | "PROP": "0", 345 | "SUBSYSTEM": "input", 346 | "TAGS": ":seat:", 347 | "USEC_INITIALIZED": "15329959", 348 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 349 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 350 | }, 351 | { 352 | "BACKSPACE": "guess", 353 | "DEVLINKS": "/dev/input/by-path/pci-0000:00:1a.0-usb-0:1.3:1.0-event /dev/input/by-id/usb-0420-00RV0TBDAJD1M_TOSHIBA_Web_Camera_-_HD_200901010001-event-if00", 354 | "DEVNAME": "/dev/input/event10", 355 | "DEVPATH": "/devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.3/1-1.3:1.0/input/input17/event10", 356 | "ID_BUS": "usb", 357 | "ID_INPUT": "1", 358 | "ID_INPUT_KEY": "1", 359 | "ID_MODEL": "TOSHIBA_Web_Camera_-_HD", 360 | "ID_MODEL_ENC": "TOSHIBA\\x20Web\\x20Camera\\x20-\\x20HD", 361 | "ID_MODEL_ID": "7017", 362 | "ID_PATH": "pci-0000:00:1a.0-usb-0:1.3:1.0", 363 | "ID_PATH_TAG": "pci-0000_00_1a_0-usb-0_1_3_1_0", 364 | "ID_REVISION": "0016", 365 | "ID_SERIAL": "0420-00RV0TBDAJD1M_TOSHIBA_Web_Camera_-_HD_200901010001", 366 | "ID_SERIAL_SHORT": "200901010001", 367 | "ID_TYPE": "video", 368 | "ID_USB_DRIVER": "uvcvideo", 369 | "ID_USB_INTERFACES": ":0e0100:0e0200:", 370 | "ID_USB_INTERFACE_NUM": "00", 371 | "ID_VENDOR": "0420-00RV0TBDAJD1M", 372 | "ID_VENDOR_ENC": "0420-00RV0TBDAJD1M", 373 | "ID_VENDOR_ID": "04ca", 374 | "MAJOR": "13", 375 | "MINOR": "74", 376 | "SUBSYSTEM": "input", 377 | "USEC_INITIALIZED": "15357097", 378 | "XKBLAYOUT": "gb", 379 | "XKBMODEL": "pc105", 380 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 381 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 382 | }, 383 | { 384 | "DEVPATH": "/devices/pci0000:00/0000:00:1b.0/sound/card0/input13", 385 | "EV": "21", 386 | "ID_FOR_SEAT": "input-pci-0000_00_1b_0", 387 | "ID_INPUT": "1", 388 | "ID_PATH": "pci-0000:00:1b.0", 389 | "ID_PATH_TAG": "pci-0000_00_1b_0", 390 | "MODALIAS": "input:b0000v0000p0000e0000-e0,5,kramlsfw4,", 391 | "NAME": "\"HDA Intel PCH Mic\"", 392 | "PHYS": "\"ALSA\"", 393 | "PRODUCT": "0/0/0/0", 394 | "PROP": "0", 395 | "SUBSYSTEM": "input", 396 | "SW": "10", 397 | "TAGS": ":seat:", 398 | "USEC_INITIALIZED": "14164991", 399 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 400 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 401 | }, 402 | { 403 | "DEVNAME": "/dev/input/event6", 404 | "DEVPATH": "/devices/pci0000:00/0000:00:1b.0/sound/card0/input13/event6", 405 | "ID_INPUT": "1", 406 | "ID_PATH": "pci-0000:00:1b.0", 407 | "ID_PATH_TAG": "pci-0000_00_1b_0", 408 | "MAJOR": "13", 409 | "MINOR": "70", 410 | "SUBSYSTEM": "input", 411 | "USEC_INITIALIZED": "14185004", 412 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 413 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 414 | }, 415 | { 416 | "DEVPATH": "/devices/pci0000:00/0000:00:1b.0/sound/card0/input14", 417 | "EV": "21", 418 | "ID_FOR_SEAT": "input-pci-0000_00_1b_0", 419 | "ID_INPUT": "1", 420 | "ID_PATH": "pci-0000:00:1b.0", 421 | "ID_PATH_TAG": "pci-0000_00_1b_0", 422 | "MODALIAS": "input:b0000v0000p0000e0000-e0,5,kramlsfw2,", 423 | "NAME": "\"HDA Intel PCH Headphone\"", 424 | "PHYS": "\"ALSA\"", 425 | "PRODUCT": "0/0/0/0", 426 | "PROP": "0", 427 | "SUBSYSTEM": "input", 428 | "SW": "4", 429 | "TAGS": ":seat:", 430 | "USEC_INITIALIZED": "14164671", 431 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 432 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 433 | }, 434 | { 435 | "DEVNAME": "/dev/input/event7", 436 | "DEVPATH": "/devices/pci0000:00/0000:00:1b.0/sound/card0/input14/event7", 437 | "ID_INPUT": "1", 438 | "ID_PATH": "pci-0000:00:1b.0", 439 | "ID_PATH_TAG": "pci-0000_00_1b_0", 440 | "MAJOR": "13", 441 | "MINOR": "71", 442 | "SUBSYSTEM": "input", 443 | "USEC_INITIALIZED": "14184519", 444 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 445 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 446 | }, 447 | { 448 | "DEVPATH": "/devices/pci0000:00/0000:00:1b.0/sound/card0/input15", 449 | "EV": "21", 450 | "ID_FOR_SEAT": "input-pci-0000_00_1b_0", 451 | "ID_INPUT": "1", 452 | "ID_PATH": "pci-0000:00:1b.0", 453 | "ID_PATH_TAG": "pci-0000_00_1b_0", 454 | "MODALIAS": "input:b0000v0000p0000e0000-e0,5,kramlsfw6,8,", 455 | "NAME": "\"HDA Intel PCH HDMI/DP,pcm=3\"", 456 | "PHYS": "\"ALSA\"", 457 | "PRODUCT": "0/0/0/0", 458 | "PROP": "0", 459 | "SUBSYSTEM": "input", 460 | "SW": "140", 461 | "TAGS": ":seat:", 462 | "USEC_INITIALIZED": "14165462", 463 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 464 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 465 | }, 466 | { 467 | "DEVNAME": "/dev/input/event8", 468 | "DEVPATH": "/devices/pci0000:00/0000:00:1b.0/sound/card0/input15/event8", 469 | "ID_INPUT": "1", 470 | "ID_PATH": "pci-0000:00:1b.0", 471 | "ID_PATH_TAG": "pci-0000_00_1b_0", 472 | "MAJOR": "13", 473 | "MINOR": "72", 474 | "SUBSYSTEM": "input", 475 | "USEC_INITIALIZED": "14184491", 476 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 477 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 478 | }, 479 | { 480 | "DEVPATH": "/devices/platform/i8042/serio0/input/input3", 481 | "EV": "120013", 482 | "ID_FOR_SEAT": "input-platform-i8042-serio-0", 483 | "ID_INPUT": "1", 484 | "ID_INPUT_KEY": "1", 485 | "ID_INPUT_KEYBOARD": "1", 486 | "ID_PATH": "platform-i8042-serio-0", 487 | "ID_PATH_TAG": "platform-i8042-serio-0", 488 | "ID_SERIAL": "noserial", 489 | "KEY": "402000000 3803078f800d001 feffffdfffefffff fffffffffffffffe", 490 | "LED": "7", 491 | "MODALIAS": "input:b0011v0001p0001eAB83-e0,1,4,11,14,k71,72,73,74,75,76,77,79,7A,7B,7C,7D,7E,7F,80,8C,8E,8F,9B,9C,9D,9E,9F,A3,A4,A5,A6,AC,AD,B7,B8,B9,D9,E2,ram4,l0,1,2,sfw", 492 | "MSC": "10", 493 | "NAME": "\"AT Translated Set 2 keyboard\"", 494 | "PHYS": "\"isa0060/serio0/input0\"", 495 | "PRODUCT": "11/1/1/ab83", 496 | "PROP": "0", 497 | "SUBSYSTEM": "input", 498 | "TAGS": ":seat:", 499 | "USEC_INITIALIZED": "1640313", 500 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 501 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 502 | }, 503 | { 504 | "BACKSPACE": "guess", 505 | "DEVLINKS": "/dev/input/by-path/platform-i8042-serio-0-event-kbd", 506 | "DEVNAME": "/dev/input/event3", 507 | "DEVPATH": "/devices/platform/i8042/serio0/input/input3/event3", 508 | "ID_INPUT": "1", 509 | "ID_INPUT_KEY": "1", 510 | "ID_INPUT_KEYBOARD": "1", 511 | "ID_PATH": "platform-i8042-serio-0", 512 | "ID_PATH_TAG": "platform-i8042-serio-0", 513 | "ID_SERIAL": "noserial", 514 | "MAJOR": "13", 515 | "MINOR": "67", 516 | "SUBSYSTEM": "input", 517 | "USEC_INITIALIZED": "1680250", 518 | "XKBLAYOUT": "gb", 519 | "XKBMODEL": "pc105", 520 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 521 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 522 | }, 523 | { 524 | "ABS": "260800011000003", 525 | "DEVPATH": "/devices/platform/i8042/serio4/input/input11", 526 | "EV": "b", 527 | "ID_FOR_SEAT": "input-platform-i8042-serio-4", 528 | "ID_INPUT": "1", 529 | "ID_INPUT_TOUCHPAD": "1", 530 | "ID_INPUT_TOUCHSCREEN": "1", 531 | "ID_PATH": "platform-i8042-serio-4", 532 | "ID_PATH_TAG": "platform-i8042-serio-4", 533 | "ID_SERIAL": "noserial", 534 | "KEY": "6420 30000 0 0 0 0", 535 | "MODALIAS": "input:b0011v0002p0007e01B1-e0,1,3,k110,111,145,14A,14D,14E,ra0,1,18,1C,2F,35,36,39,mlsfw", 536 | "NAME": "\"SynPS/2 Synaptics TouchPad\"", 537 | "PHYS": "\"isa0060/serio4/input0\"", 538 | "PRODUCT": "11/2/7/1b1", 539 | "PROP": "9", 540 | "SUBSYSTEM": "input", 541 | "TAGS": ":seat:", 542 | "USEC_INITIALIZED": "3526054", 543 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 544 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 545 | }, 546 | { 547 | "DEVLINKS": "/dev/input/by-path/platform-i8042-serio-4-event-mouse", 548 | "DEVNAME": "/dev/input/event5", 549 | "DEVPATH": "/devices/platform/i8042/serio4/input/input11/event5", 550 | "ID_INPUT": "1", 551 | "ID_INPUT_HEIGHT_MM": "32", 552 | "ID_INPUT_TOUCHPAD": "1", 553 | "ID_INPUT_TOUCHSCREEN": "1", 554 | "ID_INPUT_WIDTH_MM": "63", 555 | "ID_PATH": "platform-i8042-serio-4", 556 | "ID_PATH_TAG": "platform-i8042-serio-4", 557 | "ID_SERIAL": "noserial", 558 | "MAJOR": "13", 559 | "MINOR": "69", 560 | "SUBSYSTEM": "input", 561 | "USEC_INITIALIZED": "3552261", 562 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 563 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 564 | }, 565 | { 566 | "DEVLINKS": "/dev/input/by-path/platform-i8042-serio-4-mouse", 567 | "DEVNAME": "/dev/input/mouse0", 568 | "DEVPATH": "/devices/platform/i8042/serio4/input/input11/mouse0", 569 | "ID_INPUT": "1", 570 | "ID_INPUT_TOUCHPAD": "1", 571 | "ID_INPUT_TOUCHSCREEN": "1", 572 | "ID_PATH": "platform-i8042-serio-4", 573 | "ID_PATH_TAG": "platform-i8042-serio-4", 574 | "ID_SERIAL": "noserial", 575 | "MAJOR": "13", 576 | "MINOR": "32", 577 | "SUBSYSTEM": "input", 578 | "USEC_INITIALIZED": "3526660", 579 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 580 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 581 | }, 582 | { 583 | "DEVPATH": "/devices/virtual/input/input16", 584 | "EV": "1", 585 | "ID_INPUT": "1", 586 | "MODALIAS": "input:b0019v0000p0000e0000-e0,kramlsfw", 587 | "NAME": "\"Toshiba WMI hotkeys\"", 588 | "PHYS": "\"wmi/input0\"", 589 | "PRODUCT": "19/0/0/0", 590 | "PROP": "0", 591 | "SUBSYSTEM": "input", 592 | "TAGS": ":seat:", 593 | "USEC_INITIALIZED": "14187630", 594 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 595 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 596 | }, 597 | { 598 | "DEVNAME": "/dev/input/event9", 599 | "DEVPATH": "/devices/virtual/input/input16/event9", 600 | "ID_INPUT": "1", 601 | "MAJOR": "13", 602 | "MINOR": "73", 603 | "SUBSYSTEM": "input", 604 | "TAGS": ":power-switch:", 605 | "USEC_INITIALIZED": "14216404", 606 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 607 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 608 | }, 609 | { 610 | "DEVNAME": "/dev/input/mice", 611 | "DEVPATH": "/devices/virtual/input/mice", 612 | "MAJOR": "13", 613 | "MINOR": "63", 614 | "SUBSYSTEM": "input", 615 | "USEC_INITIALIZED": "1677994", 616 | "hotplugscript": "/etc/.mplab_ide/mchplinusbdevice", 617 | "seghotplugscript": "/etc/.mplab_ide/mchpsegusbdevice" 618 | } 619 | ] --------------------------------------------------------------------------------