-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSmartBlindController.py
470 lines (343 loc) · 15.3 KB
/
SmartBlindController.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# python3.6
####################################################################################
#
# `_` `_,_` _' `,`
# -#@@- >O#@@@@u B@@> 8@E
# :)ilc}` `=|}uccccVu}r" VQz `@@#Mhzk= |8M `=v}ucccccuY), `~v}uVVcccccV#@$
# ^Q@#EMqK.I#@QRdMqqMdRQ@@Q, Q@B `@@BqqqW^ W@@` e@@QRdMMMMbEQ@@8: i#@BOMqqqqqqqM#@$
# D@@` )@@x <@@T Q@B `@@q W@@`>@@l :@@z`#@d Q@$
# D@# ?@@@##########@@@} Q@B `@@q W@@`^@@@##########@@@y`#@W Q@$
# 0@# )@@d!::::::::::::` Q@B `@@M W@@`<@@E!::::::::::::``#@b `B@$
# D@# `m@@#bGPP} Q@B `@@q W@@` 3@@BbPPPV y@@QZPPPPPGME#@8=
# *yx .*icywwv )yv }y> ~yT .^icywyL .*]uywwwwycL^-
#
# (c) 2021 Reified Ltd. W: www.reified.co.uk E: [email protected]
#
####################################################################################
#
# Present a stepper motor, driven by the Adafruit Stepper Motor Bonnet on a
# Raspberry Pi, as an IoT device over MQTT, controllable and monitorable via MQTT
# messages when connected to a MQTT broker.
#
####################################################################################
import random
import time
import json
import queue
import logging
import sys
import chronos
from enum import Enum
from datetime import datetime
from paho.mqtt import client as mqtt_client
import AsyncStepperMotor
from adafruit_motor import stepper
########################################################################################
#
# class MotionEvent
#
########################################################################################
class MotionEvent(Enum):
STARTING = 1
MOVING = 2
STOPPED = 3
####################################################################################
#
# class BlindSteppingStyle
#
####################################################################################
class BlindSteppingStyle(Enum):
SINGLE = stepper.SINGLE
DOUBLE = stepper.DOUBLE
INTERLEAVE = stepper.INTERLEAVE
MICROSTEP = stepper.MICROSTEP
########################################################################################
#
# class SmartBlindController
#
########################################################################################
class SmartBlindController:
####################################################################################
#
# __init__(self, blindNo, steppingStyle, loggingLevel)
#
####################################################################################
def __init__(self,
blindNo = 1,
steppingStyle = AsyncStepperMotor.MotorSteppingStyle.DOUBLE,
loggingLevel = logging.NOTSET
):
self._debugLevel = loggingLevel
self._logger = logging.getLogger('SmartBlindController')
self._logger.setLevel(self._debugLevel)
self._blindNo = blindNo
# Initialisation.
# Note: the motor ID is set to he same as the blind ID.
self._stepperNo = blindNo
self._steppingStyle = steppingStyle
self._stepSize = 50 # Semi-arbitrary, but only used during calibration.
# Anything called "position" refers to the raw motor position (effectively
# in arbitary units).
self._openedPosition = None
self._closedPosition = None
self._motorCurrentPosition = 0
self._targetPercentage = 0
self._actualPercentage = 0
self._openIs100 = True # Position 100% could be top or bottom (user preference).
# Create a connection to the stepper motor and register to observe
# any motion of the motor as it occurs.
self._motorController = AsyncStepperMotor.AsyncStepperMotor(
stepperNo = self._blindNo,
loggingLevel = logging.NOTSET
)
self._motorController.observe(self._onMotionUpdate) # We want to observe the motion.
self._observer = None
####################################################################################
#
# observe(self, observer)
#
####################################################################################
def observe(self, observer):
self._observer = observer
####################################################################################
#
# start(self)
#
####################################################################################
def start(self):
self._motorController.start()
####################################################################################
#
# stop()
#
####################################################################################
def stop(self):
self._motorController.stop()
####################################################################################
#
# tryStart(self)
#
####################################################################################
def tryStart(self) -> bool:
return self._motorController.tryStart()
####################################################################################
#
# tryStop()
#
####################################################################################
def tryStop(self) -> bool:
return self._motorController.tryStop()
####################################################################################
#
# run(self)
#
####################################################################################
def run(self):
try:
self._motorController.run() # Begin the stepper motor controller (blocking).
except KeyboardInterrupt:
self._logger.info("*** Interrupted.")
####################################################################################
#
# wind(self, noOfSteps)
#
####################################################################################
def wind(self, noOfSteps):
self._motorController.moveBy(noOfSteps * self._stepSize)
self._logger.info(f"Wind by {noOfSteps} step{'s' if (noOfSteps > 1) else ''}.")
####################################################################################
#
# counterWind(self, noOfSteps)
#
####################################################################################
def counterWind(self, noOfSteps):
self._motorController.moveBy(noOfSteps * -self._stepSize)
self._logger.info(f"Counter wind by {noOfSteps} step{'s' if (noOfSteps > 1) else ''}.")
####################################################################################
#
# setOpenedPoint(self)
#
####################################################################################
def setOpenedPoint(self):
self._openedPosition = self._motorCurrentPosition
self._logger.debug(f"Set opened position to {self._openedPosition}.")
####################################################################################
#
# setClosedPoint(self)
#
####################################################################################
def setClosedPoint(self):
self._closedPosition = self._motorCurrentPosition
self._logger.debug(f"Set closed position to {self._closedPosition}.")
####################################################################################
#
# open(self)
#
####################################################################################
def open(self):
if (self._openedPosition == None):
raise Exception("Opened point not yet calibrated.")
self._motorController.moveTo(self._openedPosition)
self._logger.debug(f"Opening blind (moving to position of {self._openedPosition}).")
####################################################################################
#
# close(self)
#
####################################################################################
def close(self):
if (self._closedPosition == None):
raise Exception("Closed point not yet calibrated.")
self._motorController.moveTo(self._closedPosition)
self._logger.debug(f"Closing blind (moving to position of {self._closedPosition}).")
####################################################################################
#
# moveTo(self, percentage)
#
####################################################################################
def moveTo(self, percentage):
if (self._openedPosition == None):
raise Exception("Opened point not yet calibrated.")
if (self._closedPosition == None):
raise Exception("Closed point not yet calibrated.")
if (self._openedPosition == self._closedPosition): # Avoid div zero, etc.
raise Exception("Opened and closed points are the same.")
position = self._calculatePositionFromPercentage(
percentage,
self._openedPosition,
self._closedPosition,
self._openIs100
)
self._motorController.moveTo(position)
self._logger.info(f"Moving to {percentage}%.")
####################################################################################
#
# halt(self)
#
####################################################################################
def halt(self):
self._motorController.halt()
self._logger.info(f"Halt.")
####################################################################################
#
# stepSize(self, stepSize)
#
####################################################################################
def stepSize(self, stepSize):
self._stepSize = stepSize;
self._logger.info(f"Set step size to {stepSize}.")
####################################################################################
#
# setPolarity(self, payload)
#
####################################################################################
def setPolarity(self, openIs100):
self._openIs100 = openIs100
self._logger.info(f"Interpret 100% as fully " + ("open" if self._openIs100 else "closed") + ".")
####################################################################################
#
# setSpeed(self, speed)
#
####################################################################################
def setSpeed(self, speed): # 0.1 - 1.0 (arbitrary units)
speed = _forceInRange(speed, 0.1, 1.0)
# TODO: Convert a single speed factor to an associated step delay.
# self._motorController.motionStepDelay(self, delaySecs)
raise NotImplementedError("Not (yet) implemented.")
####################################################################################
#
# _onMotionUpdate(self, targetPosition, actualPosition)
#
####################################################################################
def _onMotionUpdate(self, targetPosition, actualPosition):
# This is a callback invoked from the motor client upon a motion update.
# As its not our own thread, don't let any exceptions propagate (as we can't be
# sure how the motor client code will manage it, if at all and how/if we manage
# a context-specific message is not of its concern).
try:
self._processMotionUpdate(targetPosition, actualPosition);
except Exception as ex: # Catch all errors as its not our thread!
self._logger.error(f"Error processing stepper motor motion update: {ex}.")
except: # Catch all errors as this is not our thread!
self._logger.error("Error processing message.")
####################################################################################
#
# _processMotionUpdate(self, targetPosition, actualPosition)
#
####################################################################################
def _processMotionUpdate(self, targetPosition, actualPosition):
# This is a callback invoked from the async motor controller when motion occurs.
self._motorCurrentPosition = actualPosition # Note how far the motor has travelled so far.
calibrating = (self._openedPosition == None) or (self._closedPosition == None)
if (not calibrating):
# We get informed (from the motor controller) of new positions, but
# clients deal in percentage of distance bewtween fully-opened and
# fully-closed, hence we need to transform positions originating
# from the motor to a percentage.
targetPercentage = self._calculatePercentageFromPosition(
targetPosition,
self._openedPosition,
self._closedPosition,
self._openIs100
)
actualPercentage = self._calculatePercentageFromPosition(
actualPosition,
self._openedPosition,
self._closedPosition,
self._openIs100
)
# We publish the target as well as the current position as this may be
# useful to any clients. It also allows a client to determine when the
# target has been changed (e.g. by another client and what that new
# target is), which is particularly useful when the new target value is
# otherwise not published nor knowable by subscribing to all positional
# commands on the message-bus (e.g. because of a "stop motion" command).
# Besides which, delivering the two pieces of information synchronously
# may make for simpler client logic.
# For clients that want to know *only* of resting positions (and not
# motion progress) or wish to have motion completion reported separately,
# we publish that information too here.
prevTargetPercentage = self._targetPercentage
prevActualPercentage = self._actualPercentage
wasMoving = (prevTargetPercentage != prevActualPercentage)
nowMoving = (targetPercentage != actualPercentage)
if (not wasMoving and nowMoving):
self._observer(targetPercentage, actualPercentage, MotionEvent.STARTING)
if (wasMoving and not nowMoving):
self._observer(targetPercentage, actualPercentage, MotionEvent.STOPPED)
else: # mid-journey ongoing motion.
self._observer(targetPercentage, actualPercentage, MotionEvent.MOVING)
self._targetPercentage = targetPercentage
self._actualPercentage = actualPercentage
else:
self._logger.debug(f"Calibration not yet complete: Opened is {self._openedPosition}. Closed is {self._closedPosition}.")
####################################################################################
#
# _calculatePositionFromPercentage(self, percentage, openedPosition, closedPosition, topIs100)
#
####################################################################################
def _calculatePositionFromPercentage(self, percentage, openedPosition, closedPosition, topIs100) -> int:
max = openedPosition if topIs100 else closedPosition
min = closedPosition if topIs100 else openedPosition
position = min + ((max - min) / 100.0 * percentage)
## TODO; Ensure/force in range min..max
return int(position) # Positions are integral.
####################################################################################
#
# _calculatePercentageFromPosition(self, position, openedPosition, closedPosition, topIs100)
#
####################################################################################
def _calculatePercentageFromPosition(self, position, openedPosition, closedPosition, topIs100) -> float:
max = openedPosition if topIs100 else closedPosition
min = closedPosition if topIs100 else openedPosition
percentage = (position - min) / (max - min) * 100.0
## TODO; Ensure/force in range 0..100
return percentage
####################################################################################
#
# _forceInRange(self, value, min, max)
#
####################################################################################
def _forceInRange(value, min, max):
result = min if value < min else value
result = max if value > max else value
return result