-
Notifications
You must be signed in to change notification settings - Fork 4
/
__init__.py
264 lines (229 loc) · 9.55 KB
/
__init__.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
from asyncio.exceptions import CancelledError
from time import sleep
import sys
import asyncio
import logging
import json
from bleak import BleakClient, BleakScanner
from bleak.exc import BleakError
from bleak import _logger as logger
service_uuid = "58300001-0023-4BD4-BBD5-A6920E4C5653"
tx_char_uuid = "58300002-0023-4BD4-BBD5-A6920E4C5653"
rx_char_uuid = "58300003-0023-4BD4-BBD5-A6920E4C5653"
from odo.models import BaseMqttDeviceModel
from .models import LovenseStateModel
from .patterns import *
# Linux
logging.getLogger("bleak.backends.bluezdbus.client").setLevel(logging.WARNING)
logging.getLogger("bleak.backends.bluezdbus.scanner").setLevel(logging.WARNING)
# MacOS
logging.getLogger("bleak.backends.corebluetooth.client").setLevel(logging.WARNING)
logging.getLogger("bleak.backends.corebluetooth.PeripheralDelegate").setLevel(logging.WARNING)
logging.getLogger("bleak.backends.corebluetooth.CentralManagerDelegate").setLevel(logging.WARNING)
class Lovense(BaseMqttDeviceModel):
def __init__(self, events=event_patterns, default_pattern=foho, *args, **kwargs):
super(Lovense, self).__init__(*args, **kwargs)
self.logger = logging.getLogger('odo.lovense.Lovense')
self.event_loop = asyncio.new_event_loop()
self.queue = asyncio.Queue()
self.client = None
self.restart = True
self.vibrating = False # Poor man's semaphore
self._event = None
self.state = LovenseStateModel()
self.event_patterns = event_patterns
self.default_pattern = default_pattern
self._subscribe_topics = [
self.credential_topic["seen"],
self.credential_topic["selected"],
self.credential_topic["written"],
self.command_topic
]
"""Overloads _send_state() to not call self.mqtt_client.loop()"""
def _send_state(self):
self.mqtt_client.publish(self.state_topic, self.state.to_json())
def _handle_credential(self, msg=None):
self.logger.debug(msg)
topic = msg.topic.split('/')
self.logger.debug(topic)
pattern = self.default_pattern
if msg.topic == self.credential_topic['written']:
self.logger.debug("cred written")
message = json.loads(msg.payload)
self.logger.debug(message)
if "payload" in message:
if "status" in message["payload"]:
status = message["payload"]["status"]
self.logger.debug(status)
if status in self.event_patterns[topic[1]]:
pattern = self.event_patterns[topic[1]][status]
else:
pattern = None
elif topic[1] in self.event_patterns:
pattern = self.event_patterns[topic[1]]
if pattern is not None:
self.event_loop.create_task(self.vibe_pattern(pattern))
def _handle_command(self, msg=None):
# message = json.loads(msg.payload)
self.logger.error(f"Command parsing not implemented")
def _on_message(self, client, userdata, msg):
self.logger.debug(f"MQTT message received-> {msg.topic} {str(msg.payload)}")
if msg.topic in list(self.credential_topic.values()):
self._handle_credential(msg=msg)
if msg.topic == self.command_topic:
self._handle_command(msg=msg)
async def vibe_pattern(self, pattern):
try:
self.vibrating = True
for vibe, duration in pattern:
await self.write_cmd(vibe)
sleep(duration)
await self.write_cmd(vibe_off)
except Exception as e:
self.logger.error(e)
finally:
self.vibrating = False
async def write_cmd(self, data):
self.logger.debug(f"BLE Send: {data}")
await self.queue.put(data)
try:
await self.client.write_gatt_char(tx_char_uuid,bytes(data, encoding="UTF-8"))
except BleakError:
self.state = LovenseStateModel()
self._send_state()
raise ConnectionError
async def process_ble_response(self, response):
cmd = await self.queue.get()
if cmd.startswith("DeviceType"):
values = response.split(':')
self.logger.debug(f"Type: {values[0]} Version: {values[1]} MAC: {values[2]}")
self.state.payload.device_type = values[0]
self.state.payload.version = values[1]
self.state.payload.mac_addr = values[2]
self._send_state()
elif cmd.startswith("GetBatch"):
values = response.split(';')
self.logger.debug(f"Batch: {values[0]}")
self.state.payload.batch = values[0]
self._send_state()
elif cmd.startswith("Battery"):
values = response.split(';')
self.logger.debug(f"Battery: {values[0]}")
self.state.payload.battery = int(values[0])
self._send_state()
elif cmd.startswith("Vibrate"):
if response == "OK;":
self.logger.debug("Response from vibrate")
else:
raise ValueError
else:
self.logger.debug(f"Unknown command: {cmd} and response: {response}")
def ble_callback(self, sender: int, data: bytearray):
response = data.decode(encoding="UTF-8")
self.logger.debug(f"BLE Recv: {sender}: {response}")
if response.endswith(";"):
self.event_loop.create_task(self.process_ble_response(response))
async def ble_disconnect(self):
await self.client.stop_notify(rx_char_uuid)
await self.client.disconnect()
self._disconnect()
async def connect_to_device(self, address):
self.logger.info(f"Starting loop for {address}")
try:
async with BleakClient(address, loop=self.event_loop, timeout=60) as self.client:
self.logger.info(f"Connecting to: {address}")
self.state.payload.status = "connected"
try:
await self.client.start_notify(rx_char_uuid, self.ble_callback)
await self.write_cmd("DeviceType;")
await self.write_cmd("GetBatch;")
await self.vibe_pattern(foho)
await asyncio.sleep(1)
except Exception as e:
self.logger.error(e)
raise e
self._send_state()
self._event = asyncio.Event()
await self._event.wait()
await self.ble_disconnect()
except Exception as e:
self.logger.error("Error connecting")
self.logger.info(f"Disconnect from: {address}")
async def mqtt_loop(self):
while True:
if self.state.payload.status == "connected":
self.mqtt_client.loop()
await asyncio.sleep(0.5)
else:
await asyncio.sleep(10)
async def get_battery(self):
while True:
if (self.state.payload.status == "connected") and (self.state.payload.device_type is not None) and (self.vibrating is False):
await self.write_cmd("Battery;")
await asyncio.sleep(10)
else:
await asyncio.sleep(1)
async def scanner(self):
while True:
got_device = False
tasks = []
tasks.append(self.event_loop.create_task(self.mqtt_loop()))
tasks.append(self.event_loop.create_task(self.get_battery()))
try:
devices = await BleakScanner.discover()
except BleakError as e:
self.logger.error(f"BLE Error: {e}")
sys.exit(1)
for d in devices:
if str(d.name).startswith("LVS-"):
task = self.event_loop.create_task(self.connect_to_device(d))
tasks.append(task)
got_device = True
if got_device:
pass
else:
self.logger.info("No devices found, sleeping before next scan")
for t in tasks:
self.logger.debug(f"Canceling: {t}")
t.cancel()
for t in tasks:
try:
await t
except CancelledError:
self.logger.debug(f"Canceled: {t}")
finally:
await asyncio.sleep(3)
if self.restart:
continue
else:
break
try:
await asyncio.gather(*tasks)
except ConnectionError:
self.logger.error('Disconnected: cancelling all tasks')
for t in tasks:
self.logger.debug(f"Canceling: {t}")
t.cancel()
for t in tasks:
try:
await t
except CancelledError:
self.logger.debug(f"Canceled: {t}")
finally:
await asyncio.sleep(3)
finally:
await asyncio.sleep(5)
if self.restart:
self.logger.info('Restarting scan')
else:
self.logger.info('Exiting')
break
def _cleanup(self):
self.restart = False
if self._event is not None:
self._event.set()
def loop(self):
self._send_state()
asyncio.set_event_loop(self.event_loop)
self.event_loop.run_until_complete(self.scanner())
self.event_loop.close()