22 Commits

Author SHA1 Message Date
96eb02fbbf moved protobuf files to new repo 2017-01-31 19:42:28 +01:00
d79dde527f first implementation of protobuf
restructure in client server model
loads of work still missing
2017-01-31 15:00:44 +01:00
Giovanni Harting
7d6d289178 fixed wrong calculation of read pwm frequency
some more error handling
2015-11-14 14:35:42 +01:00
Giovanni Harting
db379ccdf0 reverted some derps 2015-11-13 23:58:41 +01:00
Giovanni Harting
99a7252194 added default val for pwm_freq 2/2 2015-11-13 23:56:09 +01:00
Giovanni Harting
a99d879298 added default val for pwm_freq 2015-11-13 23:51:53 +01:00
Giovanni Harting
6ae2cc4fb8 added some more error handling
fixed pwm_freq not getting set on init
2015-11-13 23:41:38 +01:00
Giovanni Harting
a65bb770fd added error handling when color can't get read 2015-11-13 23:17:49 +01:00
Giovanni Harting
02f6837d27 removed more unnecessary debug output 2015-11-13 23:13:17 +01:00
Giovanni Harting
df90bc8a68 fixed some bugs in the installation description 2015-11-13 22:25:45 +01:00
Giovanni Harting
f9d696b1b3 removed more unnecessary debug output 2015-10-31 22:47:09 +01:00
Giovanni Harting
aadcfafd00 added error handling of oserror 70 mostly caused by a busy i2c line
need to add a proper rate limiting and requeue of requests for a future release
2015-10-31 22:41:07 +01:00
Giovanni Harting
6f2a8faa6a Update README.md 2015-10-15 13:41:48 +02:00
Giovanni Harting
01ba0a4d2c added set_all_channel method
reintroduced caching of stripes & controllers
added session cleanup handling
renamed --daemon to --detach for better understanding
added coloredlogs to make logs better readable and more appealing
2015-10-15 13:26:36 +02:00
Giovanni Harting
4c052b8edb moved json encoder to a monkey patch
added bugs introduced in latest sqlalchemy and json-rpc switch (d5f403d557)
2015-10-11 21:43:33 +02:00
Giovanni Harting
2bb52aa3a4 added paramcheck too all functions
updated documentation
updated codestyle
2015-10-11 17:04:54 +02:00
Giovanni Harting
d5f403d557 Moved to SQLAlchemy
Finished switch to JSONRPC

commit 9cf6dd9a0e03c71135c01d4ad4f7d3be0f1e3066
Author: Giovanni Harting <giovanni.harting@touchdata.net>
Date:   Sat Oct 10 21:09:20 2015 +0200

    fixed some bugs
    added some missing things from transition

commit 8ed44b8fcde739b541b1834049025b055a50e6fe
Author: Marius Schiffer <marius@mschiffer.de>
Date:   Sat Oct 10 05:53:41 2015 +0200

    Creating fresh database works now. Fixed pwm_freq property.

commit dc88ef0df427f90746a499912eff70dfce967c55
Author: Marius Schiffer <marius@mschiffer.de>
Date:   Sat Oct 10 04:40:41 2015 +0200

    Completed SQLAlchemy integration. Completed JSON-RPC integration.
    All daemon class functionality is now on module-level (required for
    JSON-RPC decorators).
    Migrations will have to be reimplemented with alembic.

commit a4cabdcd00a3e2a3cbbd92a3c9d59a4235e4d277
Author: Marius Schiffer <marius@mschiffer.de>
Date:   Sat Oct 10 03:00:19 2015 +0200

    First steps towards SQLAlchemy integration.
2015-10-10 21:13:29 +02:00
Giovanni Harting
87f2d12c22 fixed missing json + encode 2015-10-09 21:07:05 +02:00
Giovanni Harting
8ee1dd395c Update README.md 2015-10-09 20:59:02 +02:00
Giovanni Harting
4ad3fd50fb first json rpc implementation 2015-10-09 20:44:55 +02:00
Giovanni Harting
7b67984c80 Update README.md 2015-10-09 19:42:27 +02:00
Giovanni Harting
1a568b194c renamed stuff
added first gamma correction, closes #1
added db upgrade logic
2015-10-04 08:10:52 +02:00
29 changed files with 1800 additions and 689 deletions

3
.gitmodules vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "protobuf"]
path = protobuf
url = git@github.com:LED-Freaks/LedD-protobuf.git

View File

@@ -1,6 +1,6 @@
# LedD # LedD
[![][codeclimate img]][codeclimate] [![][license img]][license] [![][cq img]][cq] [![][license img]][license]
LedD is a daemon for interfacing LED stripes written in python3. It provides an abstract interface for effects to control any kind of LED stripe through an controller, although it is intented to be used with the PCA9685 chip. An Android application can connect and natively change any settings for the effects and stripes. LedD is a daemon for interfacing LED stripes written in python3. It provides an abstract interface for effects to control any kind of LED stripe through an controller, although it is intented to be used with the PCA9685 chip. An Android application can connect and natively change any settings for the effects and stripes.
@@ -18,6 +18,15 @@ LedD is a daemon for interfacing LED stripes written in python3. It provides an
- PCA9685 - PCA9685
- __Note__: Plugins can have different permission requirements - __Note__: Plugins can have different permission requirements
## Installation
Make sure your i2c devices are available (modprobe i2c-dev) before you follow these steps.
1. `apt-get install python3-dev python3-pip python3-cffi python3-docopt python3-nose python3-sqlalchemy python-smbus libffi-dev`
2. `pip3 install -U cffi` (fixes a bug where smbus-cffi can't install)
3. `pip3 install coloredlogs spectra json-rpc smbus-cffi`
4. `adduser $USER i2c`
### Plugins & Effects ### Plugins & Effects
Plugin functionality is planned as we provide APIs for effects and plugins to use. Here are some we are going to provide when they are finished. Plugin functionality is planned as we provide APIs for effects and plugins to use. Here are some we are going to provide when they are finished.
@@ -43,5 +52,5 @@ This project is licensed under the conditions of the GNU GPL 3.0.
[license]:LICENSE [license]:LICENSE
[license img]:https://img.shields.io/github/license/led-freaks/ledd.svg?style=flat-square [license img]:https://img.shields.io/github/license/led-freaks/ledd.svg?style=flat-square
[codeclimate]:https://codeclimate.com/github/LED-Freaks/LedD [cq]:https://www.codacy.com/app/chefeificationful/LedD
[codeclimate img]:https://img.shields.io/codeclimate/github/LED-Freaks/LedD.svg?style=flat-square [cq img]:https://img.shields.io/codacy/bb2de4e1587f48358141cd7465d2ea89.svg?style=flat-square

48
ledd.py
View File

@@ -1,3 +1,5 @@
#!/usr/bin/python3
# LEDD Project # LEDD Project
# Copyright (C) 2015 LEDD Team # Copyright (C) 2015 LEDD Team
# #
@@ -17,53 +19,26 @@
"""LedD Daemon """LedD Daemon
Usage: Usage:
ledd.py [--daemon] [-d | --debug] [-v | --verbose] ledd.py [--detach] [-d | --debug] [-v | --verbose]
ledd.py -h | --help ledd.py -h | --help
ledd.py --version ledd.py --version
Options: Options:
-h --help Show this screen. -h --help Show this screen.
--version Show version. --version Show version.
-d --debug Show debug output. (not recommended for daily use) -d --debug Show debug output. (not recommended)
-v --verbose Be verbose. -v --verbose Be verbose.
--daemon Run in daemon mode. --detach Detach after start.
""" """
import logging import logging
import sys
import os import os
from pkgutil import iter_modules import sys
from docopt import docopt from docopt import docopt
import ledd.daemon
import ledd import ledd
import ledd.daemon
if "smbus" not in (name for loader, name, ispkg in iter_modules()):
print("smbus not found, installing replacement")
class SMBus:
def __init__(self, i2c_address):
self.i2c_address = i2c_address
self.channels = {}
def write_word_data(self, addr, cmd, val):
if (cmd - 6) % 4 == 0:
self.channels[(cmd - 6) // 4] = val
def read_word_data(self, addr, cmd):
if (cmd - 8) // 4 not in self.channels:
self.channels[(cmd - 8) // 4] = 0
return self.channels[(cmd - 8) // 4]
class SMBusModule:
SMBus = SMBus
sys.modules['smbus'] = SMBusModule
sys.modules['smbus'].SMBus = SMBus
def pid_exists(processid): def pid_exists(processid):
@@ -89,9 +64,6 @@ if __name__ == "__main__":
if arguments['--debug']: if arguments['--debug']:
lvl = logging.DEBUG lvl = logging.DEBUG
logging.basicConfig(level=lvl,
format="[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s",
datefmt="%H:%M:%S")
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
try: try:
@@ -106,7 +78,7 @@ if __name__ == "__main__":
except FileNotFoundError: except FileNotFoundError:
pass pass
if arguments['--daemon']: if arguments['--detach']:
wdir = os.path.dirname(os.path.realpath(__file__)) wdir = os.path.dirname(os.path.realpath(__file__))
try: try:
pid = os.fork() pid = os.fork()
@@ -118,7 +90,7 @@ if __name__ == "__main__":
os.chdir(wdir) os.chdir(wdir)
with open("ledd.pid", 'w') as pidf: with open("ledd.pid", 'w') as pidf:
pidf.write(str(os.getpid()) + '\n') pidf.write(str(os.getpid()) + '\n')
daemon = ledd.daemon.Daemon() ledd.daemon.run()
else: else:
sys.exit() sys.exit()
else: else:
@@ -126,4 +98,4 @@ if __name__ == "__main__":
except OSError as e: except OSError as e:
log.fatal("Start failed: %s", e) log.fatal("Start failed: %s", e)
else: else:
daemon = ledd.daemon.Daemon() ledd.daemon.run()

View File

@@ -14,4 +14,4 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
VERSION = "0.1" VERSION = "0.2"

62
ledd/client.py Normal file
View File

@@ -0,0 +1,62 @@
import asyncio
import socket
from ledd import VERSION
from ledd.protobuf import client_pb2
from ledd.protobuf.ledd_pb2 import WrapperMsg, LedD
class LedDClientProtocol(asyncio.Protocol):
def connection_made(self, transport):
print("Connected to client!")
def data_received(self, data):
print('Data received: {!r}'.format(data.decode()))
def connection_lost(self, exc):
print('The client closed the connection')
class Client:
def __init__(self):
super().__init__()
self.msg = client_pb2.Client()
self.proto = None
self.transport = None
def init_from_db(self, row):
self.msg.name = row['name']
self.msg.addr = row['addr']
self.msg.id = row['id']
self.msg.options = row['options']
self.msg.resolution = row['reso']
self.msg.port = row['port']
def init_from_msg(self, msg):
client = client_pb2.Client()
self.msg = client.ParseFromString(msg)
def connect(self):
ledd = LedD()
ledd.version = VERSION
ledd.hostname = socket.gethostname()
wrapper = WrapperMsg()
wrapper.type = WrapperMsg.Type.DISCOVER
wrapper.ledd = ledd
loop = asyncio.get_event_loop()
coro = loop.create_connection(LedDClientProtocol, self.msg.addr, self.msg.port)
loop.run_until_complete(coro)
self.transport = coro[0]
self.proto = coro[1]
self.send_to_client(wrapper.SerializeToString())
def is_connected(self):
return not self.transport.is_closing()
def send_to_client(self, data):
if self.is_connected() and data:
self.transport.write(data)

0
ledd/client/__init__.py Normal file
View File

0
ledd/client/socket.py Normal file
View File

View File

@@ -1,167 +0,0 @@
# LEDD Project
# Copyright (C) 2015 LEDD Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from json import JSONEncoder
import logging
import time
import smbus
from ledd.stripe import Stripe
PCA9685_SUBADR1 = 0x2
PCA9685_SUBADR2 = 0x3
PCA9685_SUBADR3 = 0x4
PCA9685_MODE1 = 0x00
PCA9685_MODE2 = 0x01
PCA9685_PRESCALE = 0xFE
LED0_ON_L = 0x06
LED0_ON_H = 0x07
LED0_OFF_L = 0x08
LED0_OFF_H = 0x09
ALLLED_ON_L = 0xFA
ALLLED_ON_H = 0xFB
ALLLED_OFF_L = 0xFC
ALLLED_OFF_H = 0xFD
class Controller:
"""
A controller controls a number of stripes.
"""
@classmethod
def from_row(cls, db, row):
# load from db
return cls(db, pwm_freq=row["pwm_freq"], channels=row["channels"], i2c_device=row["i2c_device"],
address=row["address"], cid=row["id"], from_db=True)
@staticmethod
def from_db(db):
l = []
cur = db.cursor()
for row in cur.execute("select * from controller"):
c = Controller.from_row(db, row)
l.append(c)
cur.close()
return l
def save_to_db(self):
cur = self.db.cursor()
if self.id == -1:
cur.execute("INSERT INTO controller (pwm_freq, channels, i2c_device, address) VALUES (?,?,?,?)",
(self._pwm_freq, self.channels, self.i2c_device, self.address))
self.id = cur.lastrowid
else:
cur.execute("UPDATE controller SET pwm_freq=?, channels=?, i2c_device=?, address=? WHERE id = ?",
(self._pwm_freq, self.channels, self.i2c_device, self.address, self.id))
cur.close()
self.db.commit()
def __init__(self, db, channels, i2c_device, address, pwm_freq=1526, cid=-1, from_db=False):
self._mode = None
self.channels = channels
self.i2c_device = i2c_device
self.bus = smbus.SMBus(i2c_device)
self.address = address
self._address = int(address, 16)
self.id = cid
self.db = db
self.stripes = []
self._pwm_freq = None
self.pwm_freq = pwm_freq
if not from_db:
self.save_to_db()
self.load_stripes()
def load_stripes(self):
cur = self.db.cursor()
for stripe in cur.execute("select * from stripes where controller_id = ?", (self.id,)):
self.stripes.append(Stripe.from_db(self, stripe))
logging.getLogger(__name__).debug("Loaded %s stripes for controller %s", len(self.stripes), self.id)
cur.close()
def __repr__(self):
return "<Controller stripes={} cid={}>".format(len(self.stripes), self.id)
def set_channel(self, channel, val):
self.bus.write_word_data(self._address, LED0_OFF_L + 4 * channel, int(val * 4095))
self.bus.write_word_data(self._address, LED0_ON_L + 4 * channel, 0)
def get_channel(self, channel):
return self.bus.read_word_data(self._address, LED0_OFF_L + 4 * channel) / 4095
def add_stripe(self, stripe):
self.stripes.append(stripe)
def reset(self):
self.mode = int("0b00100001", 2) # MODE1 -> 0b00000001
time.sleep(0.015)
self.mode = int("0b10100001", 2)
@property
def mode(self):
self._mode = self.bus.read_byte_data(self._address, PCA9685_MODE1)
logging.getLogger(__name__).debug("Controller mode: %s", bin(self._mode))
return self._mode
@mode.setter
def mode(self, mode):
self.bus.write_byte_data(self._address, PCA9685_MODE1, mode)
self._mode = mode
logging.getLogger(__name__).debug("Controller mode: %s", bin(self._mode))
@property
def pwm_freq(self):
self._pwm_freq = (self.bus.read_byte_data(self._address, PCA9685_PRESCALE) + 1) / 4096 * 25000000
return self._pwm_freq
@pwm_freq.setter
def pwm_freq(self, value):
if value < 24 or value > 1526:
raise ValueError("PWM frequency must be 24Hz <= pwm_freq <= 1526Hz: {}".format(value))
prescal = round((25000000.0 / (4096.0 * value))) - 1
logging.getLogger(__name__).debug("Presacle value: %s", prescal)
self.mode = int("0b00110001", 2)
self.bus.write_byte_data(self._address, PCA9685_PRESCALE, prescal)
self.reset()
self._pwm_freq = value
class ControllerEncoder(JSONEncoder):
def default(self, o):
if isinstance(o, Controller):
return {
'id': o.id,
'pwm_freq': o.pwm_freq,
'channel': o.channels,
'address': o.address,
'stripes': o.stripes,
'cstripes': len(o.stripes),
'i2c_device': o.i2c_device,
'mode': o.mode
}
elif isinstance(o, Stripe):
return {
'id': o.id,
'name': o.name,
'rgb': o.rgb,
'channel': o.channels
}

View File

@@ -14,379 +14,340 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import configparser
import json
import sqlite3
import os
import sys
import traceback
import asyncio import asyncio
import configparser
import errno
import logging
import os
import signal import signal
import sqlite3
import sys
import spectra import spectra
from sqlalchemy.orm.exc import NoResultFound
from ledd import controller, VERSION from ledd import VERSION
from ledd.decorators import ledd_protocol from ledd.db_helper import check_db
from ledd.effectstack import EffectStack from ledd.effect.effectstack import EffectStack
from ledd.stripe import Stripe from ledd.led.rgb_stripe import RGBStripe
from ledd.protobuf.ledd_pb2 import WrapperMsg
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
class Daemon:
daemonSection = 'daemon' daemonSection = 'daemon'
databaseSection = 'db' databaseSection = 'db'
instance = None
""":type : Daemon """
loop = None
""" :type : asyncio.BaseEventLoop """ """ :type : asyncio.BaseEventLoop """
protocol = {}
effects = [] effects = []
leds = []
clients = []
conn = None
loop = None
server = None
def __init__(self):
Daemon.instance = self
def run():
try: try:
# read config # read config
self.config = configparser.ConfigParser() config = configparser.ConfigParser()
try: try:
with open('ledd.config', 'w+') as f: with open('ledd.config', 'w+') as f:
self.config.read_file(f) config.read_file(f)
except FileNotFoundError: except FileNotFoundError:
log.info("No config file found!") log.info("No config file found!")
pass
# SQL init # SQL init
self.sqldb = sqlite3.connect(self.config.get(self.databaseSection, 'name', fallback='ledd.sqlite')) global conn
self.sqldb.row_factory = sqlite3.Row conn = sqlite3.connect(config.get(databaseSection, 'name', fallback='ledd.sqlite'))
conn.row_factory = sqlite3.Row
check_db(conn)
if not self.check_db():
self.init_db()
self.sqldb.commit()
# init controllers from db
self.controllers = controller.Controller.from_db(self.sqldb)
log.debug(self.controllers)
logging.getLogger("asyncio").setLevel(log.getEffectiveLevel()) logging.getLogger("asyncio").setLevel(log.getEffectiveLevel())
# sigterm handler # sigterm handler
def sigterm_handler(_signo, _stack_frame): def sigterm_handler():
sys.exit(0) raise SystemExit
signal.signal(signal.SIGTERM, sigterm_handler) signal.signal(signal.SIGTERM, sigterm_handler)
# init plugins
# TODO: check all plugins for existing hooks
# init clients
# main loop # main loop
self.loop = asyncio.get_event_loop() global loop, server
coro = self.loop.create_server(LedDProtocol, loop = asyncio.get_event_loop()
self.config.get(self.daemonSection, 'host', fallback='0.0.0.0'), coro = loop.create_server(LedDProtocol,
self.config.get(self.daemonSection, 'port', fallback=1425)) config.get(daemonSection, 'host', fallback='0.0.0.0'),
self.server = self.loop.run_until_complete(coro) config.get(daemonSection, 'port', fallback=1425))
self.loop.run_forever() server = loop.run_until_complete(coro)
log.info("Start phase finished; starting main loop")
loop.run_forever()
except (KeyboardInterrupt, SystemExit): except (KeyboardInterrupt, SystemExit):
log.info("Exiting") log.info("Exiting")
for c in clients:
c.close()
try: try:
os.remove("ledd.pid") os.remove("ledd.pid")
except FileNotFoundError: except FileNotFoundError:
pass pass
self.sqldb.close() conn.commit()
self.server.close() conn.close()
self.loop.run_until_complete(self.server.wait_closed()) if server is not None:
self.loop.close() server.close()
if loop is not None:
loop.run_until_complete(server.wait_closed())
loop.close()
sys.exit(0) sys.exit(0)
def check_db(self):
"""
Checks database version
:return: database validity
:rtype: bool
"""
c = self.sqldb.cursor()
try:
c.execute("SELECT value FROM meta WHERE option = 'db_version'")
db_version = c.fetchone()
c.close()
if db_version is not None: def start_effect(**kwargs):
log.info("DB connection established; db-version=%s", db_version[0])
return True
else:
return False
except sqlite3.OperationalError:
c.close()
return False
def init_db(self):
self.sqldb.close()
if os.path.exists("ledd.sqlite"):
os.remove("ledd.sqlite")
self.sqldb = sqlite3.connect(self.config.get(self.databaseSection, 'name', fallback='ledd.sqlite'))
self.sqldb.row_factory = sqlite3.Row
with open("ledd/sql/ledd.sql", "r") as sqlfile:
c = self.sqldb.cursor()
c.executescript(sqlfile.read())
c.close()
self.check_db()
@ledd_protocol(protocol)
def start_effect(self, req_json):
""" """
Part of the Color API. Used to start a specific effect. Part of the Color API. Used to start a specific effect.
Required JSON parameters: stripe IDs: sids; effect id: eid, effect options: eopt Required parameters: stripe IDs: sids; effect id: eid, effect options: eopt
:param req_json: dict of request json :param kwargs:
""" """
log.debug("recieved action: %s", req_json['action'])
stripes = [] for stripe in RGBStripe.query.filter(RGBStripe.id.in_(kwargs['sids'])):
if "sids" in req_json:
for sid in req_json['sids']:
found_s = self.find_stripe(sid)
if found_s is not None:
stripes.append(found_s)
if len(stripes) > 0:
# TODO: add anything required to start effect with req_json['eid'] # TODO: add anything required to start effect with req_json['eid']
# on stripes[] with options in req_json['eopt'] # on stripes[] with options in req_json['eopt']
effect = EffectStack() effect = EffectStack()
self.effects.append(effect) effects.append(effect)
effect.stripes.append(self.controllers[0].stripes[0]) effect.stripes.append(stripe)
effect.start() effect.start()
# asyncio.ensure_future(asyncio.get_event_loop().run_in_executor(self.executor, effect.execute)) # asyncio.ensure_future(asyncio.get_event_loop().run_in_executor(executor, effect.execute))
rjson = { rjson = {
'success': True,
'eident': None, # unique effect identifier that identifies excatly this effect started on this set of 'eident': None, # unique effect identifier that identifies excatly this effect started on this set of
# stripes, used to stop them later and to give informations about running effects # stripes, used to stop them later and to give informations about running effect
'ref': req_json['ref']
} }
return json.dumps(rjson) return rjson
else:
rjson = {
'success': False,
'message': "No stripe with this id found",
'ref': req_json['ref']
}
return json.dumps(rjson) # return JSONRPCError(-1003, "Stripeid not found")
@ledd_protocol(protocol)
def stop_effect(self, req_json): def stop_effect(**kwargs):
""" """
Part of the Color API. Used to stop a specific effect. Part of the Color API. Used to stop a specific effect.
Required JSON parameters: effect identifier: eident Required parameters: effect identifier: eident
:param req_json: dict of request json
""" """
log.debug("recieved action: %s", req_json['action'])
# TODO: add stop effect by eident logic # TODO: add stop effect by eident logic
@ledd_protocol(protocol)
def get_effects(self, req_json):
"""
Part of the Color API. Used to show all available and running effects.
Required JSON parameters: -
:param req_json: dict of request json
"""
log.debug("recieved action: %s", req_json['action'])
# TODO: list all effects here and on which stripes they run atm def get_effects(**kwargs):
# TODO: all effects get runtime only ids, "eid"'s. They are shown here for the client to start effects. """
Part of the Color API. Used to show all available and running effect.
Required parameters: -
"""
# TODO: list all effect here and on which stripes they run atm
# TODO: all effect get runtime only ids, "eid"'s. They are shown here for the client to start effect.
# TODO: All options that an effect may have need to be transmitted here too with "eopt". # TODO: All options that an effect may have need to be transmitted here too with "eopt".
@ledd_protocol(protocol)
def set_color(self, req_json): def set_color(**kwargs):
""" """
Part of the Color API. Used to set color of a stripe. Part of the Color API. Used to set color of a stripe.
Required JSON parameters: stripe ID: sid; HSV values hsv: h,s,v, controller id: cid Required parameters: stripe ID: sid; HSV values hsv: h,s,v, controller id: cid
:param req_json: dict of request json
""" """
log.debug("recieved action: %s", req_json['action'])
found_s = self.find_stripe(req_json['sid']) # if "sid" not in kwargs or "hsv" not in kwargs:
# return JSONRPCInvalidParams()
if found_s is None: stripe = get_stripe(kwargs['sid'])
log.warning("Stripe not found: id=%s", req_json['sid'])
else:
found_s.set_color(spectra.hsv(req_json['hsv']['h'], req_json['hsv']['s'], req_json['hsv']['v']))
def find_stripe(self, sid): if stripe:
"""
Finds a given stripeid in the currently known controllers
:param sid stripe id
:return: stripe if found or none
:rtype: ledd.Stripe | None
"""
for c in self.controllers:
for s in c.stripes:
if s.id == sid:
return s
return None
@ledd_protocol(protocol)
def add_controller(self, req_json):
"""
Part of the Color API. Used to add a controller.
Required JSON parameters: channels; i2c_dev: number of i2c device (e.g. /dev/i2c-1 would be i2c_dev = 1);
address: hexdecimal address of controller on i2c bus, e.g. 0x40
:param req_json: dict of request json
"""
log.debug("recieved action: %s", req_json['action'])
try: try:
ncontroller = controller.Controller(Daemon.instance.sqldb, req_json['channels'], stripe.set_color(spectra.hsv(kwargs['hsv']['h'], kwargs['hsv']['s'], kwargs['hsv']['v']))
req_json['i2c_dev'], req_json['address'])
except OSError as e: except OSError as e:
log.error("Error opening i2c device: %s (%s)", req_json['i2c_dev'], os.strerror(int(str(e)))) if int(e) == errno.ECOMM:
rjson = { log.warning("Communication error on I2C Bus")
'success': False, return e
'message': "Error while opening i2c device", else:
'message_detail': os.strerror(int(str(e))), raise
'ref': req_json['ref'] else:
} log.warning("Stripe not found: id=%s", kwargs['sid'])
return json.dumps(rjson) # return JSONRPCError(-1003, "Stripeid not found")
self.controllers.append(ncontroller)
rjson = { def set_color_all(**kwargs):
'success': True, """
'cid': ncontroller.id, Part of the Color API. Used to set brightness of all stripes a controller owns.
'ref': req_json['ref'] Required parameters: controller id: cid, value: v
} """
return json.dumps(rjson) # if "cid" not in kwargs or "v" not in kwargs:
# return JSONRPCInvalidParams()
@ledd_protocol(protocol) try:
def get_color(self, req_json): c = get_controller(kwargs['cid'])
""" :type c: ledd.controller.Controller """
c.set_all_channel(kwargs['v'])
except NoResultFound:
log.warning("Controller not found: id=%s", kwargs['cid'])
# return JSONRPCError(-1002, "Controller not found")
return ""
def add_client(**kwargs):
"""
Part of the ledd protocol. Used to add a client.
"""
# if "i2c_dev" not in kwargs or "channels" not in kwargs or "address" not in kwargs:
# return JSONRPCInvalidParams()
try:
pass
# ncontroller = Controller(channels=int(kwargs['channels']), i2c_device=int(kwargs['i2c_dev']),
# address=kwargs['address'], _pwm_freq=1526)
except OSError as e:
log.error("Error opening i2c device: %s (%s)", kwargs['i2c_dev'], e)
# return JSONRPCError(-1004, "Error while opening i2c device", e)
# session = Session()
# session.add(ncontroller)
# session.commit()
# clients.append(ncontroller)
# return {'cid': ncontroller.id}
def get_color(**kwargs):
""" """
Part of the Color API. Used to get the current color of an stripe. Part of the Color API. Used to get the current color of an stripe.
Required JSON parameters: stripes Required parameters: sid
:param req_json: dict of request json
""" """
log.debug("recieved action: %s", req_json['action'])
found_s = self.find_stripe(req_json['sid']) # if "sid" not in kwargs:
# return JSONRPCInvalidParams()
if found_s is None: stripe = get_stripe(kwargs['sid'])
log.warning("Stripe not found: id=%s", req_json['sid'])
return {
'success': False,
'message': "Stripe not found",
'ref': req_json['ref']
}
rjson = { if not stripe:
'success': True, log.warning("Stripe not found: id=%s", kwargs['sid'])
'color': found_s.color.values, # return JSONRPCError(-1003, "Stripeid not found")
'ref': req_json['ref']
}
return json.dumps(rjson) if stripe.color:
return {'color': stripe.color.values}
else:
log.warning("Stripe has no color: id=%s", kwargs['sid'])
# return JSONRPCError(-1009, "Internal Error")
@ledd_protocol(protocol)
def add_stripe(self, req_json): def add_led(**kwargs):
""" """
Part of the Color API. Used to add stripes. Part of the Color API. Used to add stripes.
Required JSON parameters: name; rgb: bool; map: r: r-channel, g: g-channel, b: b-channel, cid Required parameters: name; rgb: bool; map: r: r-channel, g: g-channel, b: b-channel, cid
:param req_json: dict of request json
""" """
log.debug("recieved action: %s", req_json['action'])
if "stripe" in req_json: # if "name" not in kwargs or "rgb" not in kwargs or "map" not in kwargs or "cid" not in kwargs:
stripe = req_json['stripe'] # return JSONRPCInvalidParams()
c = next((x for x in self.controllers if x.id == stripe['cid']), None)
c = get_controller(kwargs['cid'])
""" :type c: ledd.controller.Controller """ """ :type c: ledd.controller.Controller """
if c is None: if c is None:
return { log.warning("Controller not found: id=%s", kwargs['cid'])
'success': False, # return JSONRPCError(-1002, "Controller not found")
'message': "Controller not found",
'ref': stripe['ref']
}
s = Stripe(c, stripe['name'], stripe['rgb'], s = RGBStripe(name=kwargs['name'], rgb=bool(kwargs['rgb']),
(stripe['map']['r'], stripe['map']['g'], stripe['map']['b'])) channel_r=kwargs['map']['r'], channel_g=kwargs['map']['g'], channel_b=kwargs['map']['b'])
s.controller = c
log.debug("Added stripe %s to controller %s; new len %s", s.id, c.id, len(c.stripes))
c.stripes.append(s) # session = Session()
log.debug("Added stripe %s to controller %s; new len %s", c.id, s.id, len(c.stripes)) # session.add(s)
# session.commit()
leds.append(s)
rjson = { return {'sid': s.id}
'success': True,
'sid': s.id,
'ref': req_json['ref']
}
return json.dumps(rjson)
@ledd_protocol(protocol) def get_leds(**kwargs):
def get_stripes(self, req_json):
""" """
Part of the Color API. Used to get all registered stripes known to the daemon. Part of the Color API. Used to get all registered stripes known to the daemon.
Required JSON parameters: none Required parameters: -
:param req_json: dict of request json
""" """
log.debug("recieved action: %s", req_json['action'])
rjson = { rjson = {
'success': True, # 'ccount': len(controller),
'ccount': len(Daemon.instance.controllers), # 'controller': controller
'controller': Daemon.instance.controllers,
'ref': req_json['ref']
} }
return json.dumps(rjson, cls=controller.ControllerEncoder) return rjson
@ledd_protocol(protocol)
def test_channel(self, req_json): def test_channel(**kwargs):
""" """
Part of the Color API. Used to test a channel on a specified controller. Part of the Color API. Used to test a channel on a specified controller.
Required JSON parameters: controller id: cid, channel, value Required parameters: controller id: cid, channel, value
:param req_json: dict of request json
""" """
log.debug("recieved action: %s", req_json['action'])
result = next(filter(lambda x: x.id == req_json['cid'], self.controllers), None) # if "cid" not in kwargs or "channel" not in kwargs or "value" not in kwargs:
# return JSONRPCInvalidParams()
contr = get_controller(kwargs['cid'])
""" :type : ledd.controller.Controller """ """ :type : ledd.controller.Controller """
if result is not None: if contr is not None:
result.set_channel(req_json['channel'], req_json['value']) try:
contr.set_channel(kwargs['channel'], kwargs['value'], 2.8)
except OSError as e:
pass
# return JSONRPCError(-1009, "Internal Error", e)
else:
pass
# return JSONRPCError(-1002, "Controller not found")
rjson = {
'success': True,
'ref': req_json['ref']
}
return json.dumps(rjson) def discover(**kwargs):
@ledd_protocol(protocol)
def discover(self, req_json):
""" """
Part of the Color API. Used by mobile applications to find the controller. Part of the Color API. Used by mobile applications to find the controller.
Required JSON parameters: none Required parameters: -
:param req_json: dict of request json
""" """
log.debug("recieved action: %s", req_json['action'])
rjson = { return {'version': VERSION}
'success': True,
'ref': req_json['ref'],
'version': VERSION def get_stripe(sid):
pass
# for s in stripes:
# if s.id == sid:
# return s
def get_controller(cid):
pass
# for c in controller:
# if c.id == cid:
# return c
function_mapping = {WrapperMsg.Type.LED_GET_ALL: get_leds,
WrapperMsg.Type.LED_ADD: add_led,
WrapperMsg.Type.CLIENT_ADD: add_client,
# WrapperMsg.Type.LED_PERC_SET: ,
# WrapperMsg.Type.LED_PERC_GET: ,
# WrapperMsg.Type.CLIENT_LED_SET: ,
# WrapperMsg.Type.CLIENT_GET: ,
# WrapperMsg.Type.CLIENT_GET_LED_OPTIONS: ,
# WrapperMsg.Type.CLIENT_SET_LOCAL_DIRECT: ,
# WrapperMsg.Type.LEDGROUP_GET: ,
# WrapperMsg.Type.LEDGROUP_GET_ALL: ,
# WrapperMsg.Type.LEDGROUP_SET_COLOR: ,
# WrapperMsg.Type.LEDGROUP_ADD: ,
} }
return json.dumps(rjson)
def no_action_found(self, req_json):
rjson = {
'success': False,
'message': "No action found",
'ref': req_json['ref']
}
return json.dumps(rjson)
class LedDProtocol(asyncio.Protocol): class LedDProtocol(asyncio.Protocol):
transport = None transport = None
@@ -397,36 +358,23 @@ class LedDProtocol(asyncio.Protocol):
def data_received(self, data): def data_received(self, data):
try: try:
d_decoded = data.decode() wrapper_msg = WrapperMsg()
wrapper_msg = wrapper_msg.ParseFromString(data)
except UnicodeDecodeError: except UnicodeDecodeError:
log.warning("Recieved undecodable data, ignoring") log.warning("Recieved undecodable data, ignoring")
else: else:
log.debug("Received: %s from: %s", d_decoded, self.transport.get_extra_info("peername")) self.select_task(wrapper_msg)
self.select_task(d_decoded)
def select_task(self, data): def select_task(self, data):
if data: if data:
response = function_mapping[data.type](data)
if response:
try: try:
data_split = data.splitlines() # noinspection PyUnresolvedReferences
log.debug(data_split) self.transport.write(response.SerializeToString())
for line in data_split: except TypeError as te:
if line: log.warning("Can't send response: %s", te)
json_decoded = json.loads(line)
if "action" in json_decoded and "ref" in json_decoded:
return_data = Daemon.instance.protocol.get(json_decoded['action'], Daemon.no_action_found)(
Daemon.instance, json_decoded)
if return_data is not None:
self.transport.write("{}\n".format(return_data).encode())
else:
log.debug("no action or ref value found in JSON, ignoring")
except TypeError:
log.debug("No valid JSON found: %s", traceback.format_exc())
except ValueError:
log.debug("No valid JSON detected: %s", traceback.format_exc())
def connection_lost(self, exc): def connection_lost(self, exc):
# The socket has been closed, stop the event loop
# Daemon.loop.stop()
log.info("Lost connection to %s", self.transport.get_extra_info("peername")) log.info("Lost connection to %s", self.transport.get_extra_info("peername"))

22
ledd/db_helper.py Normal file
View File

@@ -0,0 +1,22 @@
DB_VERSION = 1
def check_db(conn):
cur = conn.cursor()
cur.execute("SELECT value FROM meta WHERE name='version'")
ver = cur.fetchone()
if ver:
ver = int(ver)
if ver < DB_VERSION:
upgrade_db(conn, ver, DB_VERSION)
else:
with open('sql/ledd.sql', 'r') as f:
cur.executescript(f.read())
conn.commit()
def upgrade_db(conn, old, new):
pass

View File

@@ -17,7 +17,7 @@
class BaseEffect(object): class BaseEffect(object):
""" """
This class only defines default meta-data for effects. This class only defines default meta-data for effect.
""" """
name = "BaseEffect" name = "BaseEffect"
version = "0.1" version = "0.1"

View File

@@ -0,0 +1,39 @@
# LEDD Project
# Copyright (C) 2015 LEDD Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import asyncio
from ledd.effect.fadeeffect import FadeEffect
class EffectStack(object):
def __init__(self):
self.stripes = []
self.effect = FadeEffect()
# TODO
self.modifiers = []
def start(self):
asyncio.get_event_loop().call_soon(self.execute)
def execute(self):
color = self.effect.execute_internal()
for stripe in self.stripes:
stripe.set_color(color)
# schedule next execution
asyncio.get_event_loop().call_later(0.1, self.execute)

View File

@@ -16,7 +16,7 @@
import spectra import spectra
from ledd.effects.generatoreffect import GeneratorEffect from ledd.effect.generatoreffect import GeneratorEffect
class FadeEffect(GeneratorEffect): class FadeEffect(GeneratorEffect):

View File

@@ -16,12 +16,12 @@
from spectra import Color from spectra import Color
from ledd.effects.baseeffect import BaseEffect from ledd.effect.baseeffect import BaseEffect
class GeneratorEffect(BaseEffect): class GeneratorEffect(BaseEffect):
""" """
This is a base class for simple effects. This is a base class for simple effect.
It should yield a new color on each execution. It should yield a new color on each execution.
""" """

View File

@@ -1,23 +0,0 @@
import asyncio
from ledd.effects.fadeeffect import FadeEffect
class EffectStack(object):
def __init__(self):
self.stripes = []
self.effect = FadeEffect()
# TODO
self.modifiers = []
def start(self):
asyncio.get_event_loop().call_soon(self.execute)
def execute(self):
color = self.effect.execute_internal()
for stripe in self.stripes:
stripe.set_color(color)
# schedule next execution
asyncio.get_event_loop().call_later(0.1, self.execute)

0
ledd/led/__init__.py Normal file
View File

83
ledd/led/rgb_stripe.py Normal file
View File

@@ -0,0 +1,83 @@
# LEDD Project
# Copyright (C) 2015 LEDD Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from spectra import Color
class RGBStripe:
"""
A group of leds representing an common RGB stripe.
"""
__tablename__ = "stripe"
id = Column(Integer, primary_key=True)
controller_id = Column(Integer, ForeignKey('controller.id'))
name = Column(String)
channel_r = Column(Integer)
channel_g = Column(Integer)
channel_b = Column(Integer)
channel_r_gamma = Column(Float, default=2.8)
channel_g_gamma = Column(Float, default=2.8)
channel_b_gamma = Column(Float, default=2.8)
rgb = Column(Boolean)
@property
def channels(self):
return self.channel_r, self.channel_g, self.channel_b
# TODO save channels to db
@channels.setter
def channels(self, t):
self.channel_r, self.channel_g, self.channel_b = t
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._color = None
self.gamma_correct = (self.channel_r_gamma, self.channel_g_gamma, self.channel_b_gamma)
self.read_color()
@reconstructor
def init_on_load(self):
self._color = None
self.gamma_correct = (self.channel_r_gamma, self.channel_g_gamma, self.channel_b_gamma)
self.read_color()
def read_color(self):
if self.controller:
rc = tuple([float(self.controller.get_channel(channel)) for channel in self.channels])
c = Color("rgb", rc[0], rc[1], rc[2])
self._color = c.to("hsv")
def __repr__(self):
return "<Stripe id={}>".format(self.id)
def set_color(self, c):
self._color = c
for channel, gamma_correct, value in zip(self.channels, self.gamma_correct, c.clamped_rgb):
self.controller.set_channel(channel, value, gamma_correct)
def get_color(self):
return self._color
def to_json(self):
return {
'id': self.id,
'name': self.name,
'rgb': self.rgb,
'channel': self.channels
}
color = property(get_color, set_color)

View File

@@ -13,21 +13,3 @@
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
def ledd_protocol(proto):
"""
Decorator used to add functions to action dict
:param proto: dict to add to
:type proto: dict
"""
def wrap(f):
proto[f.__name__] = f
def wrapped_f(*args):
f(*args)
return wrapped_f
return wrap

View File

379
ledd/protobuf/client_pb2.py Normal file
View File

@@ -0,0 +1,379 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: client.proto
import sys
_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='client.proto',
package='ledd',
syntax='proto3',
serialized_pb=_b(
'\n\x0c\x63lient.proto\x12\x04ledd\"\xd3\x01\n\x06\x43lient\x12\n\n\x02id\x18\x01 \x01(\x05\x12\x0f\n\x07\x61\x64\x64ress\x18\x02 \x01(\t\x12\x0f\n\x07max_led\x18\x03 \x01(\x05\x12\x0c\n\x04name\x18\x04 \x01(\t\x12\x0f\n\x07version\x18\x05 \x01(\t\x12\x12\n\nresolution\x18\x06 \x01(\x05\x12\x0c\n\x04port\x18\x07 \x01(\x05\x12*\n\x07options\x18\n \x03(\x0b\x32\x19.ledd.Client.OptionsEntry\x1a.\n\x0cOptionsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"(\n\x07\x43lients\x12\x1d\n\x07\x63lients\x18\x01 \x03(\x0b\x32\x0c.ledd.Client\"?\n\x16\x43lientSetPercentageAll\x12\x12\n\npercentage\x18\x01 \x01(\x02\x12\x11\n\tclient_id\x18\x02 \x03(\x05\"<\n\x14\x43lientSetLocalDirect\x12\x10\n\x08local_id\x18\x01 \x01(\x05\x12\x12\n\npercentage\x18\x02 \x01(\x02\"x\n\x10\x43lientLEDOptions\x12\x34\n\x07options\x18\x01 \x03(\x0b\x32#.ledd.ClientLEDOptions.OptionsEntry\x1a.\n\x0cOptionsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x62\x06proto3')
)
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
_CLIENT_OPTIONSENTRY = _descriptor.Descriptor(
name='OptionsEntry',
full_name='ledd.Client.OptionsEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='ledd.Client.OptionsEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='value', full_name='ledd.Client.OptionsEntry.value', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('8\001')),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=188,
serialized_end=234,
)
_CLIENT = _descriptor.Descriptor(
name='Client',
full_name='ledd.Client',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='id', full_name='ledd.Client.id', index=0,
number=1, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='address', full_name='ledd.Client.address', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='max_led', full_name='ledd.Client.max_led', index=2,
number=3, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='name', full_name='ledd.Client.name', index=3,
number=4, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='version', full_name='ledd.Client.version', index=4,
number=5, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='resolution', full_name='ledd.Client.resolution', index=5,
number=6, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='port', full_name='ledd.Client.port', index=6,
number=7, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='options', full_name='ledd.Client.options', index=7,
number=10, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[_CLIENT_OPTIONSENTRY, ],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=23,
serialized_end=234,
)
_CLIENTS = _descriptor.Descriptor(
name='Clients',
full_name='ledd.Clients',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='clients', full_name='ledd.Clients.clients', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=236,
serialized_end=276,
)
_CLIENTSETPERCENTAGEALL = _descriptor.Descriptor(
name='ClientSetPercentageAll',
full_name='ledd.ClientSetPercentageAll',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='percentage', full_name='ledd.ClientSetPercentageAll.percentage', index=0,
number=1, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='client_id', full_name='ledd.ClientSetPercentageAll.client_id', index=1,
number=2, type=5, cpp_type=1, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=278,
serialized_end=341,
)
_CLIENTSETLOCALDIRECT = _descriptor.Descriptor(
name='ClientSetLocalDirect',
full_name='ledd.ClientSetLocalDirect',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='local_id', full_name='ledd.ClientSetLocalDirect.local_id', index=0,
number=1, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='percentage', full_name='ledd.ClientSetLocalDirect.percentage', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=343,
serialized_end=403,
)
_CLIENTLEDOPTIONS_OPTIONSENTRY = _descriptor.Descriptor(
name='OptionsEntry',
full_name='ledd.ClientLEDOptions.OptionsEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='ledd.ClientLEDOptions.OptionsEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='value', full_name='ledd.ClientLEDOptions.OptionsEntry.value', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('8\001')),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=188,
serialized_end=234,
)
_CLIENTLEDOPTIONS = _descriptor.Descriptor(
name='ClientLEDOptions',
full_name='ledd.ClientLEDOptions',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='options', full_name='ledd.ClientLEDOptions.options', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[_CLIENTLEDOPTIONS_OPTIONSENTRY, ],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=405,
serialized_end=525,
)
_CLIENT_OPTIONSENTRY.containing_type = _CLIENT
_CLIENT.fields_by_name['options'].message_type = _CLIENT_OPTIONSENTRY
_CLIENTS.fields_by_name['clients'].message_type = _CLIENT
_CLIENTLEDOPTIONS_OPTIONSENTRY.containing_type = _CLIENTLEDOPTIONS
_CLIENTLEDOPTIONS.fields_by_name['options'].message_type = _CLIENTLEDOPTIONS_OPTIONSENTRY
DESCRIPTOR.message_types_by_name['Client'] = _CLIENT
DESCRIPTOR.message_types_by_name['Clients'] = _CLIENTS
DESCRIPTOR.message_types_by_name['ClientSetPercentageAll'] = _CLIENTSETPERCENTAGEALL
DESCRIPTOR.message_types_by_name['ClientSetLocalDirect'] = _CLIENTSETLOCALDIRECT
DESCRIPTOR.message_types_by_name['ClientLEDOptions'] = _CLIENTLEDOPTIONS
Client = _reflection.GeneratedProtocolMessageType('Client', (_message.Message,), dict(
OptionsEntry=_reflection.GeneratedProtocolMessageType('OptionsEntry', (_message.Message,), dict(
DESCRIPTOR=_CLIENT_OPTIONSENTRY,
__module__='client_pb2'
# @@protoc_insertion_point(class_scope:ledd.Client.OptionsEntry)
))
,
DESCRIPTOR=_CLIENT,
__module__='client_pb2'
# @@protoc_insertion_point(class_scope:ledd.Client)
))
_sym_db.RegisterMessage(Client)
_sym_db.RegisterMessage(Client.OptionsEntry)
Clients = _reflection.GeneratedProtocolMessageType('Clients', (_message.Message,), dict(
DESCRIPTOR=_CLIENTS,
__module__='client_pb2'
# @@protoc_insertion_point(class_scope:ledd.Clients)
))
_sym_db.RegisterMessage(Clients)
ClientSetPercentageAll = _reflection.GeneratedProtocolMessageType('ClientSetPercentageAll', (_message.Message,), dict(
DESCRIPTOR=_CLIENTSETPERCENTAGEALL,
__module__='client_pb2'
# @@protoc_insertion_point(class_scope:ledd.ClientSetPercentageAll)
))
_sym_db.RegisterMessage(ClientSetPercentageAll)
ClientSetLocalDirect = _reflection.GeneratedProtocolMessageType('ClientSetLocalDirect', (_message.Message,), dict(
DESCRIPTOR=_CLIENTSETLOCALDIRECT,
__module__='client_pb2'
# @@protoc_insertion_point(class_scope:ledd.ClientSetLocalDirect)
))
_sym_db.RegisterMessage(ClientSetLocalDirect)
ClientLEDOptions = _reflection.GeneratedProtocolMessageType('ClientLEDOptions', (_message.Message,), dict(
OptionsEntry=_reflection.GeneratedProtocolMessageType('OptionsEntry', (_message.Message,), dict(
DESCRIPTOR=_CLIENTLEDOPTIONS_OPTIONSENTRY,
__module__='client_pb2'
# @@protoc_insertion_point(class_scope:ledd.ClientLEDOptions.OptionsEntry)
))
,
DESCRIPTOR=_CLIENTLEDOPTIONS,
__module__='client_pb2'
# @@protoc_insertion_point(class_scope:ledd.ClientLEDOptions)
))
_sym_db.RegisterMessage(ClientLEDOptions)
_sym_db.RegisterMessage(ClientLEDOptions.OptionsEntry)
_CLIENT_OPTIONSENTRY.has_options = True
_CLIENT_OPTIONSENTRY._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('8\001'))
_CLIENTLEDOPTIONS_OPTIONSENTRY.has_options = True
_CLIENTLEDOPTIONS_OPTIONSENTRY._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('8\001'))
# @@protoc_insertion_point(module_scope)

79
ledd/protobuf/hsv_pb2.py Normal file
View File

@@ -0,0 +1,79 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: hsv.proto
import sys
_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='hsv.proto',
package='ledd',
syntax='proto3',
serialized_pb=_b(
'\n\thsv.proto\x12\x04ledd\",\n\x03HSV\x12\x0b\n\x03hue\x18\x01 \x01(\x02\x12\x0b\n\x03sat\x18\x02 \x01(\x02\x12\x0b\n\x03val\x18\x03 \x01(\x02\x62\x06proto3')
)
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
_HSV = _descriptor.Descriptor(
name='HSV',
full_name='ledd.HSV',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='hue', full_name='ledd.HSV.hue', index=0,
number=1, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='sat', full_name='ledd.HSV.sat', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='val', full_name='ledd.HSV.val', index=2,
number=3, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=19,
serialized_end=63,
)
DESCRIPTOR.message_types_by_name['HSV'] = _HSV
HSV = _reflection.GeneratedProtocolMessageType('HSV', (_message.Message,), dict(
DESCRIPTOR=_HSV,
__module__='hsv_pb2'
# @@protoc_insertion_point(class_scope:ledd.HSV)
))
_sym_db.RegisterMessage(HSV)
# @@protoc_insertion_point(module_scope)

450
ledd/protobuf/led_pb2.py Normal file
View File

@@ -0,0 +1,450 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: led.proto
import sys
_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from . import hsv_pb2 as hsv__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='led.proto',
package='ledd',
syntax='proto3',
serialized_pb=_b(
'\n\tled.proto\x12\x04ledd\x1a\thsv.proto\"\x9d\x01\n\x03LED\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\n\n\x02id\x18\x02 \x01(\x05\x12\x10\n\x08local_id\x18\x03 \x01(\x05\x12\x11\n\tclient_id\x18\x04 \x01(\x05\x12\'\n\x07options\x18\n \x03(\x0b\x32\x16.ledd.LED.OptionsEntry\x1a.\n\x0cOptionsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x8b\x01\n\x08LEDGroup\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\n\n\x02id\x18\x02 \x01(\x05\x12&\n\x04type\x18\x03 \x01(\x0e\x32\x18.ledd.LEDGroup.GroupType\x12\x0c\n\x04size\x18\x04 \x01(\x05\x12\x0f\n\x07led_ids\x18\n \x03(\x05\"\x1e\n\tGroupType\x12\x07\n\x03RGB\x10\x00\x12\x08\n\x04USER\x10\x01\"\x1f\n\x04LEDs\x12\x17\n\x04leds\x18\x01 \x03(\x0b\x32\t.ledd.LED\"/\n\tLEDGroups\x12\"\n\nled_groups\x18\x01 \x03(\x0b\x32\x0e.ledd.LEDGroup\"0\n\rLEDPercentage\x12\x0b\n\x03led\x18\x01 \x01(\x05\x12\x12\n\npercentage\x18\x02 \x01(\x02\"8\n\rLEDGroupColor\x12\r\n\x05group\x18\x01 \x01(\x05\x12\x18\n\x05\x63olor\x18\x02 \x01(\x0b\x32\t.ledd.HSV\"1\n\x12LEDGroupPercentage\x12\r\n\x05group\x18\x01 \x01(\x05\x12\x0c\n\x04perc\x18\x02 \x01(\x02\x62\x06proto3')
,
dependencies=[hsv__pb2.DESCRIPTOR, ])
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
_LEDGROUP_GROUPTYPE = _descriptor.EnumDescriptor(
name='GroupType',
full_name='ledd.LEDGroup.GroupType',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='RGB', index=0, number=0,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='USER', index=1, number=1,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=300,
serialized_end=330,
)
_sym_db.RegisterEnumDescriptor(_LEDGROUP_GROUPTYPE)
_LED_OPTIONSENTRY = _descriptor.Descriptor(
name='OptionsEntry',
full_name='ledd.LED.OptionsEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='ledd.LED.OptionsEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='value', full_name='ledd.LED.OptionsEntry.value', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('8\001')),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=142,
serialized_end=188,
)
_LED = _descriptor.Descriptor(
name='LED',
full_name='ledd.LED',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='name', full_name='ledd.LED.name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='id', full_name='ledd.LED.id', index=1,
number=2, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='local_id', full_name='ledd.LED.local_id', index=2,
number=3, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='client_id', full_name='ledd.LED.client_id', index=3,
number=4, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='options', full_name='ledd.LED.options', index=4,
number=10, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[_LED_OPTIONSENTRY, ],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=31,
serialized_end=188,
)
_LEDGROUP = _descriptor.Descriptor(
name='LEDGroup',
full_name='ledd.LEDGroup',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='name', full_name='ledd.LEDGroup.name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='id', full_name='ledd.LEDGroup.id', index=1,
number=2, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='type', full_name='ledd.LEDGroup.type', index=2,
number=3, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='size', full_name='ledd.LEDGroup.size', index=3,
number=4, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='led_ids', full_name='ledd.LEDGroup.led_ids', index=4,
number=10, type=5, cpp_type=1, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
_LEDGROUP_GROUPTYPE,
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=191,
serialized_end=330,
)
_LEDS = _descriptor.Descriptor(
name='LEDs',
full_name='ledd.LEDs',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='leds', full_name='ledd.LEDs.leds', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=332,
serialized_end=363,
)
_LEDGROUPS = _descriptor.Descriptor(
name='LEDGroups',
full_name='ledd.LEDGroups',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='led_groups', full_name='ledd.LEDGroups.led_groups', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=365,
serialized_end=412,
)
_LEDPERCENTAGE = _descriptor.Descriptor(
name='LEDPercentage',
full_name='ledd.LEDPercentage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='led', full_name='ledd.LEDPercentage.led', index=0,
number=1, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='percentage', full_name='ledd.LEDPercentage.percentage', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=414,
serialized_end=462,
)
_LEDGROUPCOLOR = _descriptor.Descriptor(
name='LEDGroupColor',
full_name='ledd.LEDGroupColor',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='group', full_name='ledd.LEDGroupColor.group', index=0,
number=1, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='color', full_name='ledd.LEDGroupColor.color', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=464,
serialized_end=520,
)
_LEDGROUPPERCENTAGE = _descriptor.Descriptor(
name='LEDGroupPercentage',
full_name='ledd.LEDGroupPercentage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='group', full_name='ledd.LEDGroupPercentage.group', index=0,
number=1, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='perc', full_name='ledd.LEDGroupPercentage.perc', index=1,
number=2, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=522,
serialized_end=571,
)
_LED_OPTIONSENTRY.containing_type = _LED
_LED.fields_by_name['options'].message_type = _LED_OPTIONSENTRY
_LEDGROUP.fields_by_name['type'].enum_type = _LEDGROUP_GROUPTYPE
_LEDGROUP_GROUPTYPE.containing_type = _LEDGROUP
_LEDS.fields_by_name['leds'].message_type = _LED
_LEDGROUPS.fields_by_name['led_groups'].message_type = _LEDGROUP
_LEDGROUPCOLOR.fields_by_name['color'].message_type = hsv__pb2._HSV
DESCRIPTOR.message_types_by_name['LED'] = _LED
DESCRIPTOR.message_types_by_name['LEDGroup'] = _LEDGROUP
DESCRIPTOR.message_types_by_name['LEDs'] = _LEDS
DESCRIPTOR.message_types_by_name['LEDGroups'] = _LEDGROUPS
DESCRIPTOR.message_types_by_name['LEDPercentage'] = _LEDPERCENTAGE
DESCRIPTOR.message_types_by_name['LEDGroupColor'] = _LEDGROUPCOLOR
DESCRIPTOR.message_types_by_name['LEDGroupPercentage'] = _LEDGROUPPERCENTAGE
LED = _reflection.GeneratedProtocolMessageType('LED', (_message.Message,), dict(
OptionsEntry=_reflection.GeneratedProtocolMessageType('OptionsEntry', (_message.Message,), dict(
DESCRIPTOR=_LED_OPTIONSENTRY,
__module__='led_pb2'
# @@protoc_insertion_point(class_scope:ledd.LED.OptionsEntry)
))
,
DESCRIPTOR=_LED,
__module__='led_pb2'
# @@protoc_insertion_point(class_scope:ledd.LED)
))
_sym_db.RegisterMessage(LED)
_sym_db.RegisterMessage(LED.OptionsEntry)
LEDGroup = _reflection.GeneratedProtocolMessageType('LEDGroup', (_message.Message,), dict(
DESCRIPTOR=_LEDGROUP,
__module__='led_pb2'
# @@protoc_insertion_point(class_scope:ledd.LEDGroup)
))
_sym_db.RegisterMessage(LEDGroup)
LEDs = _reflection.GeneratedProtocolMessageType('LEDs', (_message.Message,), dict(
DESCRIPTOR=_LEDS,
__module__='led_pb2'
# @@protoc_insertion_point(class_scope:ledd.LEDs)
))
_sym_db.RegisterMessage(LEDs)
LEDGroups = _reflection.GeneratedProtocolMessageType('LEDGroups', (_message.Message,), dict(
DESCRIPTOR=_LEDGROUPS,
__module__='led_pb2'
# @@protoc_insertion_point(class_scope:ledd.LEDGroups)
))
_sym_db.RegisterMessage(LEDGroups)
LEDPercentage = _reflection.GeneratedProtocolMessageType('LEDPercentage', (_message.Message,), dict(
DESCRIPTOR=_LEDPERCENTAGE,
__module__='led_pb2'
# @@protoc_insertion_point(class_scope:ledd.LEDPercentage)
))
_sym_db.RegisterMessage(LEDPercentage)
LEDGroupColor = _reflection.GeneratedProtocolMessageType('LEDGroupColor', (_message.Message,), dict(
DESCRIPTOR=_LEDGROUPCOLOR,
__module__='led_pb2'
# @@protoc_insertion_point(class_scope:ledd.LEDGroupColor)
))
_sym_db.RegisterMessage(LEDGroupColor)
LEDGroupPercentage = _reflection.GeneratedProtocolMessageType('LEDGroupPercentage', (_message.Message,), dict(
DESCRIPTOR=_LEDGROUPPERCENTAGE,
__module__='led_pb2'
# @@protoc_insertion_point(class_scope:ledd.LEDGroupPercentage)
))
_sym_db.RegisterMessage(LEDGroupPercentage)
_LED_OPTIONSENTRY.has_options = True
_LED_OPTIONSENTRY._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('8\001'))
# @@protoc_insertion_point(module_scope)

295
ledd/protobuf/ledd_pb2.py Normal file
View File

@@ -0,0 +1,295 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: ledd.proto
import sys
_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from . import led_pb2 as led__pb2
from . import client_pb2 as client__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='ledd.proto',
package='ledd',
syntax='proto3',
serialized_pb=_b(
'\n\nledd.proto\x12\x04ledd\x1a\tled.proto\x1a\x0c\x63lient.proto\")\n\x04LedD\x12\x10\n\x08hostname\x18\x01 \x01(\t\x12\x0f\n\x07version\x18\x02 \x01(\t\"\xe1\x06\n\nWrapperMsg\x12#\n\x04type\x18\x01 \x01(\x0e\x32\x15.ledd.WrapperMsg.Type\x12\x16\n\x03led\x18\x02 \x01(\x0b\x32\t.ledd.LED\x12\x18\n\x04leds\x18\x03 \x01(\x0b\x32\n.ledd.LEDs\x12!\n\tled_group\x18\x04 \x01(\x0b\x32\x0e.ledd.LEDGroup\x12#\n\nled_groups\x18\x05 \x01(\x0b\x32\x0f.ledd.LEDGroups\x12%\n\x08led_perc\x18\x06 \x01(\x0b\x32\x13.ledd.LEDPercentage\x12,\n\x0fled_group_color\x18\x07 \x01(\x0b\x32\x13.ledd.LEDGroupColor\x12\x18\n\x04ledd\x18\x08 \x01(\x0b\x32\n.ledd.LedD\x12\x1c\n\x06\x63lient\x18\t \x01(\x0b\x32\x0c.ledd.Client\x12\x1e\n\x07\x63lients\x18\n \x01(\x0b\x32\r.ledd.Clients\x12\x35\n\x11\x63lient_set_direct\x18\x0b \x01(\x0b\x32\x1a.ledd.ClientSetLocalDirect\x12\x32\n\x12\x63lient_led_options\x18\x0c \x01(\x0b\x32\x16.ledd.ClientLEDOptions\x12\x39\n\x13\x63lient_set_perc_all\x18\r \x01(\x0b\x32\x1c.ledd.ClientSetPercentageAll\x12\x30\n\x0eled_group_perc\x18\x0e \x01(\x0b\x32\x18.ledd.LEDGroupPercentage\"\xae\x02\n\x04Type\x12\x0f\n\x0bLED_GET_ALL\x10\x00\x12\x0b\n\x07LED_ADD\x10\x01\x12\x0e\n\nCLIENT_ADD\x10\x02\x12\x17\n\x13\x43LIENT_SET_PERC_ALL\x10\x03\x12\x10\n\x0cLED_PERC_SET\x10\x04\x12\x10\n\x0cLED_PERC_GET\x10\x05\x12\x12\n\x0e\x43LIENT_LED_SET\x10\x06\x12\x0c\n\x08\x44ISCOVER\x10\x07\x12\x0e\n\nCLIENT_GET\x10\x08\x12\x1a\n\x16\x43LIENT_GET_LED_OPTIONS\x10\t\x12\x1b\n\x17\x43LIENT_SET_LOCAL_DIRECT\x10\n\x12\x10\n\x0cLEDGROUP_GET\x10\x0b\x12\x14\n\x10LEDGROUP_GET_ALL\x10\x0c\x12\x16\n\x12LEDGROUP_SET_COLOR\x10\r\x12\x10\n\x0cLEDGROUP_ADD\x10\x0e\x62\x06proto3')
,
dependencies=[led__pb2.DESCRIPTOR, client__pb2.DESCRIPTOR, ])
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
_WRAPPERMSG_TYPE = _descriptor.EnumDescriptor(
name='Type',
full_name='ledd.WrapperMsg.Type',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='LED_GET_ALL', index=0, number=0,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LED_ADD', index=1, number=1,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CLIENT_ADD', index=2, number=2,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CLIENT_SET_PERC_ALL', index=3, number=3,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LED_PERC_SET', index=4, number=4,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LED_PERC_GET', index=5, number=5,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CLIENT_LED_SET', index=6, number=6,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='DISCOVER', index=7, number=7,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CLIENT_GET', index=8, number=8,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CLIENT_GET_LED_OPTIONS', index=9, number=9,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CLIENT_SET_LOCAL_DIRECT', index=10, number=10,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LEDGROUP_GET', index=11, number=11,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LEDGROUP_GET_ALL', index=12, number=12,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LEDGROUP_SET_COLOR', index=13, number=13,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LEDGROUP_ADD', index=14, number=14,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=652,
serialized_end=954,
)
_sym_db.RegisterEnumDescriptor(_WRAPPERMSG_TYPE)
_LEDD = _descriptor.Descriptor(
name='LedD',
full_name='ledd.LedD',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='hostname', full_name='ledd.LedD.hostname', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='version', full_name='ledd.LedD.version', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=45,
serialized_end=86,
)
_WRAPPERMSG = _descriptor.Descriptor(
name='WrapperMsg',
full_name='ledd.WrapperMsg',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='type', full_name='ledd.WrapperMsg.type', index=0,
number=1, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='led', full_name='ledd.WrapperMsg.led', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='leds', full_name='ledd.WrapperMsg.leds', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='led_group', full_name='ledd.WrapperMsg.led_group', index=3,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='led_groups', full_name='ledd.WrapperMsg.led_groups', index=4,
number=5, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='led_perc', full_name='ledd.WrapperMsg.led_perc', index=5,
number=6, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='led_group_color', full_name='ledd.WrapperMsg.led_group_color', index=6,
number=7, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='ledd', full_name='ledd.WrapperMsg.ledd', index=7,
number=8, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='client', full_name='ledd.WrapperMsg.client', index=8,
number=9, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='clients', full_name='ledd.WrapperMsg.clients', index=9,
number=10, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='client_set_direct', full_name='ledd.WrapperMsg.client_set_direct', index=10,
number=11, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='client_led_options', full_name='ledd.WrapperMsg.client_led_options', index=11,
number=12, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='client_set_perc_all', full_name='ledd.WrapperMsg.client_set_perc_all', index=12,
number=13, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='led_group_perc', full_name='ledd.WrapperMsg.led_group_perc', index=13,
number=14, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
_WRAPPERMSG_TYPE,
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=89,
serialized_end=954,
)
_WRAPPERMSG.fields_by_name['type'].enum_type = _WRAPPERMSG_TYPE
_WRAPPERMSG.fields_by_name['led'].message_type = led__pb2._LED
_WRAPPERMSG.fields_by_name['leds'].message_type = led__pb2._LEDS
_WRAPPERMSG.fields_by_name['led_group'].message_type = led__pb2._LEDGROUP
_WRAPPERMSG.fields_by_name['led_groups'].message_type = led__pb2._LEDGROUPS
_WRAPPERMSG.fields_by_name['led_perc'].message_type = led__pb2._LEDPERCENTAGE
_WRAPPERMSG.fields_by_name['led_group_color'].message_type = led__pb2._LEDGROUPCOLOR
_WRAPPERMSG.fields_by_name['ledd'].message_type = _LEDD
_WRAPPERMSG.fields_by_name['client'].message_type = client__pb2._CLIENT
_WRAPPERMSG.fields_by_name['clients'].message_type = client__pb2._CLIENTS
_WRAPPERMSG.fields_by_name['client_set_direct'].message_type = client__pb2._CLIENTSETLOCALDIRECT
_WRAPPERMSG.fields_by_name['client_led_options'].message_type = client__pb2._CLIENTLEDOPTIONS
_WRAPPERMSG.fields_by_name['client_set_perc_all'].message_type = client__pb2._CLIENTSETPERCENTAGEALL
_WRAPPERMSG.fields_by_name['led_group_perc'].message_type = led__pb2._LEDGROUPPERCENTAGE
_WRAPPERMSG_TYPE.containing_type = _WRAPPERMSG
DESCRIPTOR.message_types_by_name['LedD'] = _LEDD
DESCRIPTOR.message_types_by_name['WrapperMsg'] = _WRAPPERMSG
LedD = _reflection.GeneratedProtocolMessageType('LedD', (_message.Message,), dict(
DESCRIPTOR=_LEDD,
__module__='ledd_pb2'
# @@protoc_insertion_point(class_scope:ledd.LedD)
))
_sym_db.RegisterMessage(LedD)
WrapperMsg = _reflection.GeneratedProtocolMessageType('WrapperMsg', (_message.Message,), dict(
DESCRIPTOR=_WRAPPERMSG,
__module__='ledd_pb2'
# @@protoc_insertion_point(class_scope:ledd.WrapperMsg)
))
_sym_db.RegisterMessage(WrapperMsg)
# @@protoc_insertion_point(module_scope)

View File

@@ -1,21 +0,0 @@
CREATE TABLE `stripes` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
`name` TEXT,
`rgb` INTEGER,
`controller_id` INTEGER,
`channel_r` INTEGER,
`channel_g` INTEGER,
`channel_b` INTEGER
);
CREATE TABLE "meta" (
`option` TEXT,
`value` TEXT
);
INSERT INTO `meta` VALUES ('db_version','1');
CREATE TABLE "controller" (
`id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
`address` TEXT,
`i2c_device` INTEGER,
`channels` INTEGER,
`pwm_freq` INTEGER
);

View File

@@ -1,68 +0,0 @@
# LEDD Project
# Copyright (C) 2015 LEDD Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from spectra import Color
class Stripe:
"""
A stripe is the smallest controllable unit.
"""
def __init__(self, controller, name, rgb, channels, sid=-1, from_db=False):
self.controller = controller
self.name = name
self.rgb = bool(rgb)
self.channels = channels
self.id = sid
self._color = None
self.gamma_correct = (2.8, 2.8, 2.8) # TODO: add to DB
self.read_color()
if not from_db:
self.save_to_db()
def save_to_db(self):
cur = self.controller.db.cursor()
if self.id == -1:
cur.execute("INSERT INTO stripes DEFAULT VALUES")
self.id = cur.lastrowid
cur.execute(
"UPDATE stripes SET channel_r = ?, channel_g = ?, channel_b = ?,controller_id = ?, name = ? WHERE id = ?",
self.channels + (self.controller.id, self.name, self.id))
cur.close()
self.controller.db.commit()
def read_color(self):
rc = tuple([float(self.controller.get_channel(channel)) for channel in self.channels])
c = Color("rgb", rc[0], rc[1], rc[2])
self._color = c.to("hsv")
def __repr__(self):
return "<Stripe id={}>".format(self.id)
@classmethod
def from_db(cls, controller, row):
return cls(controller, name=row["name"], rgb=row["rgb"],
channels=(row["channel_r"], row["channel_g"], row["channel_b"]), sid=row["id"], from_db=True)
def set_color(self, c):
self._color = c
for channel, gamma_correct, value in zip(self.channels, self.gamma_correct, c.clamped_rgb):
self.controller.set_channel(channel, value)
def get_color(self):
return self._color
color = property(get_color, set_color)

1
protobuf Submodule

Submodule protobuf added at 2d846c167d

View File

@@ -27,4 +27,8 @@ setup(name='LedD',
install_requires=[ install_requires=[
'nose', 'spectra', 'docopt', 'nose', 'spectra', 'docopt',
], ],
extras_require={
'systemd_logging': ["python-systemd"],
'colored_logging': ["coloreddlogs"]
},
zip_safe=False) zip_safe=False)

62
sql/ledd.sql Normal file
View File

@@ -0,0 +1,62 @@
CREATE TABLE `meta` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` TEXT NOT NULL,
`value` TEXT NOT NULL
);
CREATE TABLE `client` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`connect_type` INT NOT NULL,
`addr` TEXT NOT NULL,
`reso` INT NULL,
`name` TEXT NOT NULL,
`options` TEXT NULL,
`port` INT NOT NULL
);
CREATE TABLE `led` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` TEXT NULL,
`options` TEXT NULL,
`local_id` INT NULL,
`client_id` INT NOT NULL,
CONSTRAINT `fk_led_client`
FOREIGN KEY (`client_id`)
REFERENCES `client` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE INDEX `fk_led_client_idx`
ON `led` (`client_id` ASC);
CREATE TABLE IF NOT EXISTS `group` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` TEXT NOT NULL,
`type` INT NOT NULL
);
CREATE TABLE IF NOT EXISTS `led_has_group` (
`led_id` INT NOT NULL,
`group_id` INT NOT NULL,
PRIMARY KEY (`led_id`, `group_id`),
CONSTRAINT `fk_led_has_group_led1`
FOREIGN KEY (`led_id`)
REFERENCES `led` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_led_has_group_group1`
FOREIGN KEY (`group_id`)
REFERENCES `group` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE INDEX `fk_led_has_group_group1_idx`
ON `led_has_group` (`group_id` ASC);
CREATE INDEX `fk_led_has_group_led1_idx`
ON `led_has_group` (`led_id` ASC);
INSERT INTO meta ("name", "value") VALUES ("version", "1");