commit c8630735c4ce97d2b985a5aa5f6a8929e06f5668 Author: Franziska Kunsmann Date: Mon Aug 7 13:39:15 2023 +0200 initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..68bc17f --- /dev/null +++ b/.gitignore @@ -0,0 +1,160 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ diff --git a/dmx_queue.py b/dmx_queue.py new file mode 100644 index 0000000..96c87c7 --- /dev/null +++ b/dmx_queue.py @@ -0,0 +1,103 @@ +import logging +from queue import Empty +from threading import Thread +from time import sleep + +from sacn import sACNsender + +LOG = logging.getLogger('DMXQueue') + +class DMXQueue: + def __init__(self, args, queue, lights): + self.args = args + self.queue = queue + self.lights = lights + + self.worker = Thread(target=self._worker) + self.worker_should_be_running = False + + self.sacn = sACNsender() + + def start(self): + self.sacn.start() + self.sacn.activate_output(1) + + self.sacn[1].multicast = self.args.sacn_multicast + if not self.args.sacn_multicast: + self.sacn[1].destination = self.args.sacn_target + + self.dmx_data = 512*[0] + for i in range(1, 513): + self._dmx(i, 0) + + self.worker_should_be_running = True + self.worker.start() + + def stop(self): + LOG.info('Waiting for worker to terminate ...') + self.worker_should_be_running = False + self.worker.join() + self.sacn.stop() + + def _dmx(self, addr, data): + self.dmx_data[addr-1] = data + self.sacn[1].dmx_data = tuple(self.dmx_data) + + def _bulk(self, start_addr, values): + for idx, value in enumerate(values): + self._dmx(start_addr+idx, value) + + def _update_all(self, intensity, red, green, blue, white=0): + for light in self.lights: + light.intensity = intensity + light.red = red + light.green = green + light.blue = blue + light.white = white + self._bulk(*light.dump()) + + def _worker(self): + LOG.info('Worker startup') + while self.worker_should_be_running: + try: + level, component, text = self.queue.get_nowait() + + forward = list(range(17)) + reverse = list(range(17)) + reverse.reverse() + + if level == 'error': + # three instances of two flashes each + for i in range(3): + for j in range(4): + self._update_all(255, 255, 0, 0, 50) + sleep(0.1) + self._update_all(0, 255, 0, 0) + sleep(0.1) + sleep(0.2) + elif level == 'warn': + # warning: blink alternate, but slow + for i in range(6): + for idx, light in enumerate(self.lights): + light.red = 255 + light.green = 150 + light.blue = 0 + light.white = 0 + + if (idx + i) % 2: + light.intensity = 255 + else: + light.intensity = 0 + + self._bulk(*light.dump()) + sleep(0.5) + self._update_all(0, 0, 0, 0) + elif level == 'info': + for i in range(2): + for intensity_multiplier in forward + reverse: + self._update_all(intensity_multiplier*15, 0, 50, 255) + sleep(0.03) + self.queue.task_done() + except Empty: + sleep(0.1) + LOG.info('Worker shutdown') diff --git a/lights/__init__.py b/lights/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/lights/common.py b/lights/common.py new file mode 100644 index 0000000..ad0a516 --- /dev/null +++ b/lights/common.py @@ -0,0 +1,23 @@ +import logging + +LOG = logging.getLogger('DMX') + +class BaseDMXLight: + def __init__(self, address): + self.address = address + self.intensity = 0 + self.red = 0 + self.green = 0 + self.blue = 0 + self.white = 0 + + def __str__(self): + return f'{self.name} ({self.address})' + + def _dump(self): + raise NotImplementedError + + def dump(self): + ret = self._dump() + LOG.info(f'{str(self)} -> {ret[1]}') + return ret diff --git a/lights/ignition_wal_l710.py b/lights/ignition_wal_l710.py new file mode 100644 index 0000000..5029297 --- /dev/null +++ b/lights/ignition_wal_l710.py @@ -0,0 +1,14 @@ +from .common import BaseDMXLight + +class IgnitionWALL710(BaseDMXLight): + name = "Ignition WAL-L710 PAR" + + def _dump(self): + return self.address, [ + self.intensity, + self.red, + self.green, + self.blue, + self.white, + 0, # program + ] diff --git a/lights/varytec_hero_wash_zoom_712.py b/lights/varytec_hero_wash_zoom_712.py new file mode 100644 index 0000000..50e0d23 --- /dev/null +++ b/lights/varytec_hero_wash_zoom_712.py @@ -0,0 +1,23 @@ +from .common import BaseDMXLight + +class VarytecHeroWashZoom712(BaseDMXLight): + name = "Varytec Hero Wash 712 Z RGBW Zoom" + + def _dump(self): + return self.address, [ + 128, # pan + 128, # pan fine + 128, # tilt + 128, # tilt fine + 0, # speed + self.intensity, + 0, # shutter + self.red, + self.green, + self.blue, + self.white, + 0, # colortemp + 0, # color macro + 0, # zoom + 0, # auto run + ] diff --git a/lights/wled.py b/lights/wled.py new file mode 100644 index 0000000..2b22a92 --- /dev/null +++ b/lights/wled.py @@ -0,0 +1,12 @@ +from .common import BaseDMXLight + +class WLED(BaseDMXLight): + name = "WLED" + + def _dump(self): + offset = self.intensity / 255 + return self.address, [ + int(self.red * offset), + int(self.green * offset), + int(self.blue * offset), + ] diff --git a/main.py b/main.py new file mode 100755 index 0000000..9954196 --- /dev/null +++ b/main.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 + +import logging +from argparse import ArgumentParser +from queue import Queue +from sys import exit +from time import sleep + +from dmx_queue import DMXQueue +from mqtt_queue import MQTTQueue + +from lights.wled import WLED +from lights.ignition_wal_l710 import IgnitionWALL710 +from lights.varytec_hero_wash_zoom_712 import VarytecHeroWashZoom712 + +logging.basicConfig( + level=logging.DEBUG, + format='%(asctime)s %(name)20s [%(levelname)-8s] %(message)s', +) + +LOG = logging.getLogger('main') + +def main(): + + parser = ArgumentParser() + + # MQTT + parser.add_argument('--mqtt-host', required=True) + parser.add_argument('--mqtt-port', type=int, default=1883) + parser.add_argument('--mqtt-user') + parser.add_argument('--mqtt-pass', '--mqtt-password') + parser.add_argument('--mqtt-topic', default='/voc/alert') + + # sACN + sacn = parser.add_mutually_exclusive_group(required=True) + sacn.add_argument('--sacn-multicast', action='store_true') + sacn.add_argument('--sacn-target') + + # Lights + parser.add_argument('--ignition-wal-l710', nargs='+', type=int) + parser.add_argument('--varytec-wash-zoom-712', nargs='+', type=int) + parser.add_argument('--wled', nargs='+', type=int) + + args = parser.parse_args() + + LOG.info('Welcome to Voc2DMX') + LOG.debug(args) + + queue = Queue() + + lights = [] + for addr in args.ignition_wal_l710: + lights.append(IgnitionWALL710(addr)) + for addr in args.varytec_wash_zoom_712: + lights.append(VarytecHeroWashZoom712(addr)) + for addr in args.wled: + lights.append(WLED(addr)) + + if not lights: + LOG.error('No lights configured, please add atleast one fixture') + exit(1) + + LOG.info('') + LOG.info('Configured lights:') + for light in lights: + LOG.info(light) + LOG.info('') + + LOG.info('Initializing worker queues ...') + + mqttq = MQTTQueue(args, queue) + dmxq = DMXQueue(args, queue, lights) + + mqttq.start() + dmxq.start() + + LOG.info('initialization done, now running. Press Ctrl-C to stop') + + try: + while True: + sleep(1) + except KeyboardInterrupt: + LOG.warning('Got interrupt, stopping queues ...') + mqttq.stop() + dmxq.stop() + + LOG.info('Bye!') + +if __name__ == '__main__': + main() diff --git a/mqtt_queue.py b/mqtt_queue.py new file mode 100644 index 0000000..c413d08 --- /dev/null +++ b/mqtt_queue.py @@ -0,0 +1,53 @@ +import json +import logging +import re +from queue import Queue + +import paho.mqtt.client as mqtt +from sacn import sACNsender + +LOG = logging.getLogger('MQTTQueue') + +class MQTTQueue: + def __init__(self, args, queue): + self.args = args + self.client = mqtt.Client() + self.queue = queue + + self.client.on_connect = self.on_connect + self.client.on_disconnect = self.on_disconnect + self.client.on_message = self.on_mqtt_message + + def start(self): + if self.args.mqtt_user and self.args.mqtt_pass: + self.client.username_pw_set(self.args.mqtt_user, self.args.mqtt_pass) + + self.client.connect(self.args.mqtt_host, self.args.mqtt_port, 60) + self.client.loop_start() + + def stop(self): + self.client.loop_stop() + self.client.disconnect() + + def on_connect(self, client, userdata, flags, rc): + LOG.info(f'Connected to {self.args.mqtt_host} with code {rc}') + + self.client.subscribe(self.args.mqtt_topic) + LOG.info(f'Subscribed to {self.args.mqtt_topic}') + + def on_disconnect(self, client, userdata, rc): + LOG.warning(f'Disconnected from {self.args.mqtt_host} with code {rc}') + + def on_mqtt_message(self, client, userdata, msg): + try: + data = json.loads(msg.payload.decode('utf-8')) + + text = re.sub(r'\<[a-z\/]+\>', '', data['msg']) + + self.queue.put(( + data['level'].lower(), + data['component'], + text, + )) + except Exception as e: + LOG.exception(msg.payload)