This repository has been archived by the owner on Nov 12, 2019. It is now read-only.
forked from comawill/pyEventdistr
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patheventdistr.py
79 lines (63 loc) · 1.85 KB
/
eventdistr.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python
# -*- coding: utf8 -*-
import socket
import re
EVENTDISTR_IP = "192.168.179.255"
EVENTDISTR_PORT = 31337
EVENTDISTR_MAGIC = "EVENTDISTR"
EVENTDISTR_COMMAND = "%sv%%d;%%s" % EVENTDISTR_MAGIC
EVENTDISTR_RE = re.compile("^%sv(\d);([^=]*)(|=(.*))$" % EVENTDISTR_MAGIC)
EVENT_DOOR_UNTEN = "DoorUnten"
EVENT_DING_DONG = "DingDong"
EVENT_NOW_PLAYING = "NowPlaying"
EVENT_VIRTUAL_MSG = "VirtualMsg"
EVENT_SPACE_CLOSED = "SpaceClosed"
EVEMT_SPACE_OPENED = "SpaceOpened"
AREA_FRICKEL = "A"
AREA_LOUNGE = "B"
AREA_BATH = "0"
AREA_KITCHEN = "K"
def send_event(name, data=None,version=1):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
if data:
data = "%s=%s" % (name, data)
else:
data = name
s.sendto(EVENTDISTR_COMMAND % (version, data) , (EVENTDISTR_IP,
EVENTDISTR_PORT))
s.close()
def parse_event(data):
if not data:
return None
match = EVENTDISTR_RE.match(data)
if not match:
return None
version, cmd, donotuse, data = match.groups()
return (int(version), cmd, data)
def send_clock(cmd):
send_event(cmd, "RISING")
def open_door():
send_clock(EVENT_DOOR_UNTEN)
def ring():
send_clock(EVENT_DING_DONG)
def check_utf8(string):
if isinstance(string, unicode):
return string.encode("utf8")
return string
def now_playing(artist, title, area=AREA_LOUNGE):
artist = check_utf8(artist)
title = check_utf8(title)
send_event(EVENT_NOW_PLAYING, "%s\x00%s\x00%s\x00" % (area, artist, title))
def playback_stopped(area=AREA_LOUNGE):
send_event(EVENT_NOW_PLAYING, "%s\x00\x00\x00" % area)
def virtual_msg(msg):
send_event(EVENT_VIRTUAL_MSG, msg)
def run_listener(callback):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((EVENTDISTR_IP, EVENTDISTR_PORT))
while True:
data, addr = sock.recvfrom(1024)
result = parse_event(data)
if result:
callback(*result)