#! /usr/bin/env python3

import asyncio
import monome

from life import Life

class SplitterSerialOsc(monome.SerialOsc):
    def __init__(self, app1, app2, loop=None, autoconnect_app=None):
        super().__init__(loop, autoconnect_app)
        self.app1 = app1
        self.app2 = app2

    async def splitter_connect(self, port):
        transport, grid = await self.loop.create_datagram_endpoint(monome.Grid, local_addr=('127.0.0.1', 0), remote_addr=('127.0.0.1', port))

        section1 = monome.GridSection((8, 8), (0, 0))
        section2 = monome.GridSection((8, 8), (8, 0))
        splitter = monome.Splitter(grid, [section1, section2])

        self.app1.attach(section1)
        self.app2.attach(section2)

        splitter.connect()

    def on_device_added(self, id, type, port):
        if type == "monome 128":
            asyncio.async(self.splitter_connect(port))

if __name__ == "__main__":
    life1 = Life()
    life2 = Life()

    loop = asyncio.get_event_loop()
    asyncio.async(SplitterSerialOsc.create(loop=loop, app1=life1, app2=life2))

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        life1.quit()
        life2.quit()


@@ -895,17 +895,17 @@
  == 
-%22
+'
 __main__
 %22:%0A 
@@ -904,271 +904,655 @@
 in__
-%22
+'
 :%0A    l
-ife1 = Life
+oop = asyncio.get_event_loop
 ()%0A
+%0A
     
-life2 = Life()%0A%0A    loop = asyncio.get_event_loop()%0A    asyncio.async(SplitterSerialOsc.create(loop=loop, app1=life1, app2=life2))%0A%0A    try:%0A        loop.run_forever()%0A    except KeyboardInterrupt:%0A        life1.quit()%0A        life2.quit()%0A
+section1 = monome.GridSection((8, 8), (0, 0))%0A    section2 = monome.GridSection((8, 8), (8, 0))%0A    splitter = monome.GridSplitter(%5Bsection1, section2%5D)%0A%0A    life1 = Life()%0A    life1.set_grid(section1)%0A%0A    life2 = Life()%0A    life2.set_grid(section2)%0A%0A    def serialosc_device_added(id, type, port):%0A        print('connecting to %7B%7D (%7B%7D)'.format(id, type))%0A        asyncio.ensure_future(splitter.grid.connect('127.0.0.1', port))%0A%0A    serialosc = monome.SerialOsc()%0A    serialosc.device_added_event.add_handler(serialosc_device_added)%0A%0A    loop.run_until_complete(serialosc.connect())%0A%0A    loop.run_forever()
 %0A

update splitter example