-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlight.py
90 lines (79 loc) · 2.78 KB
/
light.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
80
81
82
83
84
85
86
87
88
89
90
import asyncio
import json
import logging
import socket
import time
import asyncio_dgram
from pywizlight.rgbcw import hs2rgbcw, rgb2rgbcw, rgbcw2hs
from pywizlight import PilotBuilder
_LOGGER = logging.getLogger(__name__)
class Light:
def __init__(self, ip, position, port=38899):
self.p = position
self.ip = ip
self.port = port
self.state = None
self.next_message_id = 1
self.id_of_last_change = 0
self.id_to_look_for = 0
self.in_sync = False
self.staleness = 0
async def connect(self):
self.stream = await asyncio_dgram.connect((self.ip, self.port))
def generate_update_message(self):
if self.state:
params = self.state
if 'brightness' not in params:
params['brightness'] = 255
params['state'] = True
return json.dumps({
'method': 'setPilot',
'id': self.next_message_id,
'params': params
})
else:
message = json.dumps({
'method': 'setPilot',
'id': self.next_message_id,
'params': {
'state': False
}
})
self.next_message_id += 1
return message
async def send_update(self):
if not self.in_sync or self.staleness >= 10:
await self.stream.send(
bytes(self.generate_update_message(), "utf-8"))
self.staleness = -60
else:
self.staleness += 1
async def comm_loop(self):
next_frame_time = time.perf_counter()
while True:
next_frame_time += 0.05
now = time.perf_counter()
try:
data, remote_addr = await asyncio.wait_for(
self.stream.recv(), next_frame_time - now)
response = json.loads(data.decode())
if 'result' in response and 'success' in response[
'result'] and response['result'][
'success'] and 'id' in response:
if response['id'] >= self.id_to_look_for:
self.in_sync = True
elif response['id'] < self.id_of_last_change:
self.id_to_look_for = self.next_message_id
self.in_sync = False
except asyncio.TimeoutError:
pass
await self.send_update()
def get_state(self):
return self.state
def set_state(self, state):
if self.state != state:
self.previous_state = self.state
self.in_sync = False
self.id_of_last_change = self.next_message_id
self.id_to_look_for = self.next_message_id
self.state = state