From 457b2d17671fd12e9859dbfa7d3af36a03445c95 Mon Sep 17 00:00:00 2001
From: johannes walcher <johannes.walcher@stusta.de>
Date: Thu, 3 May 2018 15:55:49 +0200
Subject: [PATCH] added babel: translation between messages

---
 babel/__init__.py |  0
 babel/__main__.py | 19 +++++++++++
 babel/babel.py    | 85 +++++++++++++++++++++++++++++++++++++++++++++++
 babel/test.py     | 53 +++++++++++++++++++++++++++++
 4 files changed, 157 insertions(+)
 create mode 100644 babel/__init__.py
 create mode 100644 babel/__main__.py
 create mode 100644 babel/babel.py
 create mode 100644 babel/test.py

diff --git a/babel/__init__.py b/babel/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/babel/__main__.py b/babel/__main__.py
new file mode 100644
index 0000000..cc39777
--- /dev/null
+++ b/babel/__main__.py
@@ -0,0 +1,19 @@
+import asyncio
+from babel.babel import Babel
+
+def main():
+    """
+    Actually start the shit
+    """
+    loop = asyncio.get_event_loop()
+    babel = Babel()
+    loop.set_debug(True)
+    try:
+        loop.run_forever()
+    except KeyboardInterrupt:
+        pass
+
+    loop.run_until_complete(babel.teardown())
+
+if __name__ == "__main__":
+    main()
diff --git a/babel/babel.py b/babel/babel.py
new file mode 100644
index 0000000..46eda61
--- /dev/null
+++ b/babel/babel.py
@@ -0,0 +1,85 @@
+import asyncio
+from hauptbahnhof import Hauptbahnhof
+
+class Babel:
+    """
+    Translate the messages that arrived into new messages and accumulate their results
+    """
+
+    def __init__(self, loop=None):
+        if not loop:
+            loop = asyncio.get_event_loop()
+
+        self.loop = loop
+        self.hbf = Hauptbahnhof(loop)
+        self.hbf.subscribe('/haspa/power', self.command_translate)
+        self.hbf.subscribe('/haspa/power/requestinfo', self.command_requestinfo)
+
+        self.ledstrip_states = [[0,0,0,0], [0,0,0,0]]
+        self.espids = ['esp1', 'esp2']
+
+        # TODO create this mapping:
+        # mapps from (color, id) ==> (self.ledstrip indexes)
+        self.idxpair = {
+            ('c',1):(0,0),
+            ('w',1):(0,1),
+            ('c',2):(0,2),
+            ('w',2):(0,3),
+            ('c',3):(1,0),
+            ('w',3):(1,1),
+            ('c',4):(1,2),
+            ('w',4):(1,3),
+            }
+
+        self.rupprecht_map = {
+            'table': 'rupprecht-table',
+            'alarm': 'rupprecht-alarm',
+            'fan': 'rupprecht-fan',
+        }
+
+    async def teardown(self):
+        await self.hbf.teardown()
+
+    async def command_translate(self, client, message, _):
+        """
+        space.get_number_of_network_devices() -> int
+        Return the number of non-stationary, connected network devices.
+        """
+        group_changed = False
+        msg = {}
+        for lamp, value in message.items():
+            ## The lamp is managed by rupprecht
+            if lamp in self.rupprecht_map:
+                msg[self.rupprecht_map[lamp]] = int(value)
+
+            ## The lamp is a led strip and needs to be aggregated
+            if lamp.startswith('ledstrip'):
+                tmp = lamp.split('-')
+                if len(tmp) == 1:
+                    for a, b in self.idxpair.values():
+                        group_changed |= self.ledstrip_states[a][b] != int(value)
+                        self.ledstrip_states[a][b] = int(value)
+
+                elif len(tmp) == 2 and tmp[1] in ('c','w'):
+                    for color, position in self.idxpair:
+                        if color == tmp[1]:
+                            idx = self.idxpair[(color, position)]
+                            group_changed |= self.ledstrip_states[idx[0]][idx[1]] != int(value)
+                            self.ledstrip_states[idx[0]][idx[1]] = int(value)
+
+                elif len(tmp) == 3 and tmp[1] in ('c', 'w') and abs(int(tmp[2])) <= 4:
+                    idx = self.idxpair[(tmp[1],abs(int(tmp[2])))]
+                    group_changed |= self.ledstrip_states[idx[0]][idx[1]] != int(value)
+                    self.ledstrip_states[idx[0]][idx[1]] = int(value)
+
+        self.hbf.log.info("Done mapping: ")
+        self.hbf.log.info(self.ledstrip_states)
+        if group_changed:
+            for idx, e in enumerate(self.espids):
+                msg[e] = self.ledstrip_states[idx]
+        await self.hbf.publish('/haspa/led', msg)
+
+    async def command_requestinfo(self, client, msg, _):
+        await self.hbf.publish('/haspa/power/info', {
+            'documentation':'too lazy to implement'
+        })
diff --git a/babel/test.py b/babel/test.py
new file mode 100644
index 0000000..7bc63e0
--- /dev/null
+++ b/babel/test.py
@@ -0,0 +1,53 @@
+import asyncio
+from hauptbahnhof import Hauptbahnhof
+
+from babel.babel import Babel
+
+
+messages = asyncio.Queue()
+async def on_message(client, message, _):
+    print("Got message: %s"%message)
+    await messages.put(message)
+
+
+async def test(loop):
+    testbf = Hauptbahnhof(loop=loop)
+    testbf.subscribe("/haspa/led", on_message)
+
+    await asyncio.sleep(2)
+    await testbf.publish("/haspa/power", {'ledstrip':1023})
+
+    # Now everythin should be set up
+    msg = await asyncio.wait_for(messages.get(), 10) # wait max 10 secs
+    for a in msg.values():
+        for lamp_value in a:
+            assert(lamp_value == 1023)
+
+    await testbf.publish("/haspa/power", {'ledstrip-c-1':42})
+    msg = await asyncio.wait_for(messages.get(), 10) # wait max 10 secs
+    for espidx, a in msg.items():
+        for lamp_idx, lamp_value in enumerate(a):
+            if espidx == 'esp1' and lamp_idx == 0:
+                assert(lamp_value == 42)
+            else:
+                assert(lamp_value == 1023)
+
+    try:
+        await testbf.teardown()
+    except asyncio.CancelledError:
+        pass
+
+def main():
+    loop = asyncio.get_event_loop()
+    lib = Babel(loop=loop)
+
+    result = loop.run_until_complete(test(loop))
+    loop.run_until_complete(lib.teardown())
+    loop.set_debug(True)
+    if result:
+        exit(0)
+    else:
+        exit(1)
+
+if __name__=="__main__":
+    main()
-- 
GitLab