-
Notifications
You must be signed in to change notification settings - Fork 104
/
pijuice.py
1574 lines (1404 loc) · 58.2 KB
/
pijuice.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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
from __future__ import division, print_function
__version__ = "1.5"
import ctypes
import sys
import threading
import time
from smbus import SMBus
pijuice_hard_functions = ['HARD_FUNC_POWER_ON', 'HARD_FUNC_POWER_OFF', 'HARD_FUNC_RESET']
pijuice_sys_functions = ['SYS_FUNC_HALT', 'SYS_FUNC_HALT_POW_OFF', 'SYS_FUNC_SYS_OFF_HALT', 'SYS_FUNC_REBOOT']
pijuice_user_functions = ['USER_EVENT'] + ['USER_FUNC' + str(i+1) for i in range(0, 15)]
class PiJuiceInterface(object):
def __init__(self, bus=1, address=0x14):
"""Create a new PiJuice instance. Bus is an optional parameter that
specifies the I2C bus number to use, for example 1 would use device
/dev/i2c-1. If bus is not specified then the open function should be
called to open the bus.
"""
self.i2cbus = SMBus(bus)
self.addr = address
self.t = None
self.comError = False
self.errTime = 0
def __del__(self):
"""Clean up any resources used by the PiJuice instance."""
self.i2cbus = None
def __enter__(self):
"""Context manager enter function."""
# Just return this object so it can be used in a with statement
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager exit function, ensures resources are cleaned up."""
self.i2cbus = None
return False # Don't suppress exceptions
def GetAddress(self):
return self.addr
def _GetChecksum(self, data):
fcs = 0xFF
for x in data[:]:
fcs = fcs ^ x
return fcs
def _Read(self):
try:
d = self.i2cbus.read_i2c_block_data(self.addr, self.cmd, self.length)
self.d = d
self.comError = False
except: # IOError:
self.comError = True
self.errTime = time.time()
self.d = None
def _Write(self):
try:
self.i2cbus.write_i2c_block_data(self.addr, self.cmd, self.d)
self.comError = False
except: # IOError:
self.comError = True
self.errTime = time.time()
def _DoTransfer(self, oper):
if (self.t != None and self.t.isAlive()) or (self.comError and (time.time()-self.errTime) < 4):
return False
self.t = threading.Thread(target=oper, args=())
self.t.start()
# wait for transfer to finish or timeout
n = 0
while self.t.isAlive() and n < 2:
time.sleep(0.05)
n = n + 1
if self.comError or self.t.isAlive():
return False
return True
def ReadData(self, cmd, length):
d = []
self.cmd = cmd
self.length = length + 1
if not self._DoTransfer(self._Read):
return {'error': 'COMMUNICATION_ERROR'}
d = self.d
if self._GetChecksum(d[0:-1]) != d[-1]:
return {'error': 'DATA_CORRUPTED'}
del d[-1]
return {'data': d, 'error': 'NO_ERROR'}
def WriteData(self, cmd, data):
fcs = self._GetChecksum(data)
d = data[:]
d.append(fcs)
self.cmd = cmd
self.d = d
if not self._DoTransfer(self._Write):
return {'error': 'COMMUNICATION_ERROR'}
return {'error': 'NO_ERROR'}
def WriteDataVerify(self, cmd, data, delay=None):
wresult = self.WriteData(cmd, data)
if wresult['error'] != 'NO_ERROR':
return wresult
else:
if delay != None:
try:
time.sleep(delay*1)
except:
time.sleep(0.1)
result = self.ReadData(cmd, len(data))
if result['error'] != 'NO_ERROR':
return result
else:
if (data == result['data']):
return {'error': 'NO_ERROR'}
else:
return {'error': 'WRITE_FAILED'}
class PiJuiceStatus(object):
STATUS_CMD = 0x40
FAULT_EVENT_CMD = 0x44
CHARGE_LEVEL_CMD = 0x41
BUTTON_EVENT_CMD = 0x45
BATTERY_TEMPERATURE_CMD = 0x47
BATTERY_VOLTAGE_CMD = 0x49
BATTERY_CURRENT_CMD = 0x4b
IO_VOLTAGE_CMD = 0x4d
IO_CURRENT_CMD = 0x4f
LED_STATE_CMD = 0x66
LED_BLINK_CMD = 0x68
IO_PIN_ACCESS_CMD = 0x75
def __init__(self, interface):
self.interface = interface
def __enter__(self):
# Just return this object so it can be used in a with statement
return self
def __exit__(self, exc_type, exc_val, exc_tb):
return False # Don't suppress exceptions.
def GetStatus(self):
result = self.interface.ReadData(self.STATUS_CMD, 1)
if result['error'] != 'NO_ERROR':
return result
else:
d = result['data'][0]
status = {}
status['isFault'] = bool(d & 0x01)
status['isButton'] = bool(d & 0x02)
batStatusEnum = ['NORMAL', 'CHARGING_FROM_IN',
'CHARGING_FROM_5V_IO', 'NOT_PRESENT']
status['battery'] = batStatusEnum[(d >> 2) & 0x03]
powerInStatusEnum = ['NOT_PRESENT', 'BAD', 'WEAK', 'PRESENT']
status['powerInput'] = powerInStatusEnum[(d >> 4) & 0x03]
status['powerInput5vIo'] = powerInStatusEnum[(d >> 6) & 0x03]
return {'data': status, 'error': 'NO_ERROR'}
def GetChargeLevel(self):
result = self.interface.ReadData(self.CHARGE_LEVEL_CMD, 1)
if result['error'] != 'NO_ERROR':
return result
else:
return {'data': result['data'][0], 'error': 'NO_ERROR'}
faultEvents = ['button_power_off', 'forced_power_off',
'forced_sys_power_off', 'watchdog_reset']
faults = ['battery_profile_invalid', 'charging_temperature_fault']
def GetFaultStatus(self):
result = self.interface.ReadData(self.FAULT_EVENT_CMD, 1)
if result['error'] != 'NO_ERROR':
return result
else:
d = result['data'][0]
fault = {}
if d & 0x01:
fault['button_power_off'] = True
if d & 0x02:
fault['forced_power_off'] = True # bool(d & 0x02)
if d & 0x04:
fault['forced_sys_power_off'] = True
if d & 0x08:
fault['watchdog_reset'] = True
if d & 0x20:
fault['battery_profile_invalid'] = True
batChargingTempEnum = ['NORMAL', 'SUSPEND', 'COOL', 'WARM']
if (d >> 6) & 0x03:
fault['charging_temperature_fault'] = batChargingTempEnum[(d >> 6) & 0x03]
return {'data': fault, 'error': 'NO_ERROR'}
def ResetFaultFlags(self, flags):
d = 0xFF
for ev in flags:
try:
d = d & ~(0x01 << self.faultEvents.index(ev))
except:
ev
self.interface.WriteData(self.FAULT_EVENT_CMD, [d]) # clear fault events
buttonEvents = ['NO_EVENT', 'PRESS', 'RELEASE',
'SINGLE_PRESS', 'DOUBLE_PRESS', 'LONG_PRESS1', 'LONG_PRESS2']
def GetButtonEvents(self):
result = self.interface.ReadData(self.BUTTON_EVENT_CMD, 2)
if result['error'] != 'NO_ERROR':
return result
else:
d = result['data']
event = {}
try:
event['SW1'] = self.buttonEvents[d[0] & 0x0F]
except:
event['SW1'] = 'UNKNOWN'
try:
event['SW2'] = self.buttonEvents[(d[0] >> 4) & 0x0F]
except:
event['SW2'] = 'UNKNOWN'
try:
event['SW3'] = self.buttonEvents[d[1] & 0x0F]
except:
event['SW3'] = 'UNKNOWN'
#event['SW4'] = self.buttonEvents[(d[1] >> 4) & 0x0F]
return {'data': event, 'error': 'NO_ERROR'}
buttons = ['SW' + str(i+1) for i in range(0, 3)]
def AcceptButtonEvent(self, button):
b = None
try:
b = self.buttons.index(button)
except ValueError:
return {'error': 'BAD_ARGUMENT'}
d = [0xF0, 0xFF] if b == 0 else [0x0F, 0xFF] if b == 1 else [0xFF, 0xF0]
self.interface.WriteData(self.BUTTON_EVENT_CMD, d) # clear button events
def GetBatteryTemperature(self):
result = self.interface.ReadData(self.BATTERY_TEMPERATURE_CMD, 2)
if result['error'] != 'NO_ERROR':
return result
else:
d = result['data']
temp = d[1]
temp = temp << 8
temp = temp | d[0]
return {'data': temp, 'error': 'NO_ERROR'}
def GetBatteryVoltage(self):
result = self.interface.ReadData(self.BATTERY_VOLTAGE_CMD, 2)
if result['error'] != 'NO_ERROR':
return result
else:
d = result['data']
return {'data': (d[1] << 8) | d[0], 'error': 'NO_ERROR'}
def GetBatteryCurrent(self):
result = self.interface.ReadData(self.BATTERY_CURRENT_CMD, 2)
if result['error'] != 'NO_ERROR':
return result
else:
d = result['data']
i = (d[1] << 8) | d[0]
if (i & (1 << 15)):
i = i - (1 << 16)
return {'data': i, 'error': 'NO_ERROR'}
def GetIoVoltage(self):
result = self.interface.ReadData(self.IO_VOLTAGE_CMD, 2)
if result['error'] != 'NO_ERROR':
return result
else:
d = result['data']
return {'data': (d[1] << 8) | d[0], 'error': 'NO_ERROR'}
def GetIoCurrent(self):
result = self.interface.ReadData(self.IO_CURRENT_CMD, 2)
if result['error'] != 'NO_ERROR':
return result
else:
d = result['data']
i = (d[1] << 8) | d[0]
if (i & (1 << 15)):
i = i - (1 << 16)
return {'data': i, 'error': 'NO_ERROR'}
leds = ['D1', 'D2']
def SetLedState(self, led, rgb):
i = None
try:
i = self.leds.index(led)
except:
return {'error': 'BAD_ARGUMENT'}
return self.interface.WriteData(self.LED_STATE_CMD + i, rgb)
def GetLedState(self, led):
i = None
try:
i = self.leds.index(led)
except:
return {'error': 'BAD_ARGUMENT'}
return self.interface.ReadData(self.LED_STATE_CMD + i, 3)
def SetLedBlink(self, led, count, rgb1, period1, rgb2, period2):
i = None
d = None
try:
i = self.leds.index(led)
d = [count & 0xFF] + rgb1*1 + \
[(period1//10) & 0xFF] + rgb2*1 + [(period2//10) & 0xFF]
except:
return {'error': 'BAD_ARGUMENT'}
return self.interface.WriteData(self.LED_BLINK_CMD + i, d)
def GetLedBlink(self, led):
i = None
try:
i = self.leds.index(led)
except:
return {'error': 'BAD_ARGUMENT'}
ret = self.interface.ReadData(self.LED_BLINK_CMD + i, 9)
if ret['error'] != 'NO_ERROR':
return ret
else:
d = ret['data']
return {
'data': {
'count': d[0],
'rgb1': d[1:4],
'period1': d[4] * 10,
'rgb2': d[5:8],
'period2': d[8] * 10
},
'error': 'NO_ERROR'
}
def GetIoDigitalInput(self, pin):
if not (pin == 1 or pin == 2):
return {'error': 'BAD_ARGUMENT'}
ret = self.interface.ReadData(self.IO_PIN_ACCESS_CMD + (pin-1)*5, 2)
if ret['error'] != 'NO_ERROR':
return ret
else:
d = ret['data']
b = 1 if d[0] == 0x01 else 0
return {'data': b, 'error': 'NO_ERROR'}
def SetIoDigitalOutput(self, pin, value):
if not (pin == 1 or pin == 2):
return {'error': 'BAD_ARGUMENT'}
d = [0x00, 0x00]
d[1] = 0x00 if value == 0 else 0x01
return self.interface.WriteData(self.IO_PIN_ACCESS_CMD + (pin-1)*5, d)
def GetIoDigitalOutput(self, pin):
if not (pin == 1 or pin == 2):
return {'error': 'BAD_ARGUMENT'}
ret = self.interface.ReadData(self.IO_PIN_ACCESS_CMD + (pin-1)*5, 2)
if ret['error'] != 'NO_ERROR':
return ret
else:
d = ret['data']
b = 1 if d[1] == 0x01 else 0
return {'data': b, 'error': 'NO_ERROR'}
def GetIoAnalogInput(self, pin):
if not (pin == 1 or pin == 2):
return {'error': 'BAD_ARGUMENT'}
ret = self.interface.ReadData(self.IO_PIN_ACCESS_CMD + (pin-1)*5, 2)
if ret['error'] != 'NO_ERROR':
return ret
else:
d = ret['data']
return {'data': (d[1] << 8) | d[0], 'error': 'NO_ERROR'}
def SetIoPWM(self, pin, dutyCycle):
if not (pin == 1 or pin == 2):
return {'error': 'BAD_ARGUMENT'}
d = [0xFF, 0xFF]
try:
dc = float(dutyCycle)
except:
return {'error': 'BAD_ARGUMENT'}
if dc < 0 or dc > 100:
return {'error': 'INVALID_DUTY_CYCLE'}
elif dc < 100:
dci = int(round(dc * 65534 // 100))
d[0] = dci & 0xFF
d[1] = (dci >> 8) & 0xFF
return self.interface.WriteData(self.IO_PIN_ACCESS_CMD + (pin-1)*5, d)
def GetIoPWM(self, pin):
if not (pin == 1 or pin == 2):
return {'error': 'BAD_ARGUMENT'}
ret = self.interface.ReadData(self.IO_PIN_ACCESS_CMD + (pin-1)*5, 2)
if ret['error'] != 'NO_ERROR':
return ret
else:
d = ret['data']
dci = d[0] | (d[1] << 8)
dc = float(dci) * 100 // 65534 if dci < 65535 else 100
return {'data': dc, 'error': 'NO_ERROR'}
class PiJuiceRtcAlarm(object):
RTC_ALARM_CMD = 0xB9
RTC_TIME_CMD = 0xB0
RTC_CTRL_STATUS_CMD = 0xC2
def __init__(self, interface):
self.interface = interface
def __enter__(self):
# Just return this object so it can be used in a with statement
return self
def __exit__(self, exc_type, exc_val, exc_tb):
return False # Don't suppress exceptions.
def GetControlStatus(self):
ret = self.interface.ReadData(self.RTC_CTRL_STATUS_CMD, 2)
if ret['error'] != 'NO_ERROR':
return ret
d = ret['data']
r = {}
if (d[0] & 0x01) and (d[0] & 0x04):
r['alarm_wakeup_enabled'] = True
else:
r['alarm_wakeup_enabled'] = False
if d[1] & 0x01:
r['alarm_flag'] = True
else:
r['alarm_flag'] = False
return {'data': r, 'error': 'NO_ERROR'}
def ClearAlarmFlag(self):
ret = self.interface.ReadData(self.RTC_CTRL_STATUS_CMD, 2)
if ret['error'] != 'NO_ERROR':
return ret
d = ret['data']
if d[1] & 0x01:
d[1] = d[1] & 0xFE
return self.interface.WriteDataVerify(self.RTC_CTRL_STATUS_CMD, d)
else:
return {'error': 'NO_ERROR'}
def SetWakeupEnabled(self, status):
ret = self.interface.ReadData(self.RTC_CTRL_STATUS_CMD, 2)
if ret['error'] != 'NO_ERROR':
return ret
d = ret['data']
if (d[0] & 0x01) and (d[0] & 0x04):
if status == True:
return {'error': 'NO_ERROR'}
else:
d[0] = d[0] & 0xFE
else:
if status == False:
return {'error': 'NO_ERROR'}
else:
d[0] = d[0] | 0x01 | 0x04
return self.interface.WriteDataVerify(self.RTC_CTRL_STATUS_CMD, d)
def GetTime(self):
ret = self.interface.ReadData(self.RTC_TIME_CMD, 9)
if ret['error'] != 'NO_ERROR':
return ret
d = ret['data']
dt = {}
dt['second'] = ((d[0] >> 4) & 0x07) * 10 + (d[0] & 0x0F)
dt['minute'] = ((d[1] >> 4) & 0x07) * 10 + (d[1] & 0x0F)
if (d[2] & 0x40):
# hourFormat = '12'
ampm = 'PM' if (d[2] & 0x20) else 'AM'
dt['hour'] = str(((d[2] >> 4) & 0x01) * 10 + (d[2] & 0x0F)) + ' ' + ampm
else:
# hourFormat = '24'
dt['hour'] = ((d[2] >> 4) & 0x03) * 10 + (d[2] & 0x0F)
dt['weekday'] = d[3] & 0x07
dt['day'] = ((d[4] >> 4) & 0x03) * 10 + (d[4] & 0x0F)
dt['month'] = ((d[5] >> 4) & 0x01) * 10 + (d[5] & 0x0F)
dt['year'] = ((d[6] >> 4) & 0x0F) * 10 + (d[6] & 0x0F) + 2000
dt['subsecond'] = d[7] // 256
if (d[8] & 0x03) == 2:
dt['daylightsaving'] = 'SUB1H'
elif (d[8] & 0x03) == 1:
dt['daylightsaving'] = 'ADD1H'
else:
dt['daylightsaving'] = 'NONE'
if d[8] & 0x04:
dt['storeoperation'] = True
else:
dt['storeoperation'] = False
return {'data': dt, 'error': 'NO_ERROR'}
def SetTime(self, dateTime):
d = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
if dateTime == None or dateTime == {}:
dt = {}
else:
dt = dateTime
if 'second' in dt:
try:
s = int(dt['second'])
except:
return {'error': 'INVALID_SECOND'}
if s < 0 or s > 60:
return {'error': 'INVALID_SECOND'}
d[0] = ((s // 10) & 0x0F) << 4
d[0] = d[0] | ((s % 10) & 0x0F)
if 'minute' in dt:
try:
m = int(dt['minute'])
except:
return {'error': 'INVALID_MINUTE'}
if m < 0 or m > 60:
return {'error': 'INVALID_MINUTE'}
d[1] = ((m // 10) & 0x0F) << 4
d[1] = d[1] | ((m % 10) & 0x0F)
if 'hour' in dt:
try:
h = dt['hour']
if isinstance(h, str):
if (h.find('AM') > -1) or (h.find('PM') > -1):
if (h.find('PM') > -1):
hi = int(h.split('PM')[0])
if hi < 1 or hi > 12:
return {'error': 'INVALID_HOUR'}
d[2] = (((hi // 10) & 0x03) << 4)
d[2] = d[2] | ((hi % 10) & 0x0F)
d[2] = d[2] | 0x20 | 0x40
else:
hi = int(h.split('AM')[0])
if hi < 1 or hi > 12:
return {'error': 'INVALID_HOUR'}
d[2] = (((hi // 10) & 0x03) << 4)
d[2] = d[2] | ((hi % 10) & 0x0F)
d[2] = d[2] | 0x40
else:
h = int(h)
if h < 0 or h > 23:
return {'error': 'INVALID_HOUR'}
d[2] = (((h // 10) & 0x03) << 4)
d[2] = d[2] | ((h % 10) & 0x0F)
elif isinstance(h, int):
#assume 24 hour format
if h < 0 or h > 23:
return {'error': 'INVALID_HOUR'}
d[2] = (((int(h) // 10) & 0x03) << 4)
d[2] = d[2] | ((int(h) % 10) & 0x0F)
except:
return {'error': 'INVALID_HOUR'}
if 'weekday' in dt:
try:
day = int(dt['weekday'])
except:
return {'error': 'INVALID_WEEKDAY'}
if day < 1 or day > 7:
return {'error': 'INVALID_WEEKDAY'}
d[3] = day & 0x07
if 'day' in dt:
try:
da = int(dt['day'])
except:
return {'error': 'INVALID_DAY'}
if da < 1 or da > 31:
return {'error': 'INVALID_DAY'}
d[4] = ((da // 10) & 0x03) << 4
d[4] = d[4] | ((da % 10) & 0x0F)
if 'month' in dt:
try:
m = int(dt['month'])
except:
return {'error': 'INVALID_MONTH'}
if m < 1 or m > 12:
return {'error': 'INVALID_MONTH'}
d[5] = ((m // 10) & 0x01) << 4
d[5] = d[5] | ((m % 10) & 0x0F)
if 'year' in dt:
try:
y = int(dt['year']) - 2000
except:
return {'error': 'INVALID_YEAR'}
if y < 0 or y > 99:
return {'error': 'INVALID_YEAR'}
d[6] = ((y // 10) & 0x0F) << 4
d[6] = d[6] | ((y % 10) & 0x0F)
if 'subsecond' in dt:
try:
s = int(dt['subsecond']) * 256
except:
return {'error': 'INVALID_SUBSECOND'}
if s < 0 or s > 255:
return {'error': 'INVALID_SUBSECOND'}
d[7] = s
if 'daylightsaving' in dt:
if dt['daylightsaving'] == 'SUB1H':
d[8] |= 2
elif dt['daylightsaving'] == 'ADD1H':
d[8] |= 1
if 'storeoperation' in dt and dt['storeoperation'] == True:
d[8] |= 0x04
ret = self.interface.WriteData(self.RTC_TIME_CMD, d)
if ret['error'] != 'NO_ERROR':
return ret
# verify
time.sleep(0.2)
ret = self.interface.ReadData(self.RTC_TIME_CMD, 9)
if ret['error'] != 'NO_ERROR':
return ret
if (d == ret['data']):
return {'error': 'NO_ERROR'}
else:
if abs(ret['data'][0] - d[0]) < 2:
ret['data'][0] = d[0]
ret['data'][7] = d[7]
if (d == ret['data']):
return {'error': 'NO_ERROR'}
else:
return {'error': 'WRITE_FAILED'}
else:
return {'error': 'WRITE_FAILED'}
def GetAlarm(self):
ret = self.interface.ReadData(self.RTC_ALARM_CMD, 9)
if ret['error'] != 'NO_ERROR':
return ret
d = ret['data']
alarm = {}
if (d[0] & 0x80) == 0x00:
alarm['second'] = ((d[0] >> 4) & 0x07) * 10 + (d[0] & 0x0F)
if (d[1] & 0x80) == 0x00:
alarm['minute'] = ((d[1] >> 4) & 0x07) * 10 + (d[1] & 0x0F)
else:
alarm['minute_period'] = d[7]
if (d[2] & 0x80) == 0x00:
if (d[2] & 0x40):
# hourFormat = '12'
ampm = 'PM' if (d[2] & 0x20) else 'AM'
alarm['hour'] = str(((d[2] >> 4) & 0x01) * 10 + (d[2] & 0x0F)) + ' ' + ampm
else:
# hourFormat = '24'
alarm['hour'] = ((d[2] >> 4) & 0x03) * 10 + (d[2] & 0x0F)
else:
if d[4] == 0xFF and d[5] == 0xFF and d[6] == 0xFF:
alarm['hour'] = 'EVERY_HOUR'
else:
h = ''
n = 0
for i in range(0, 3):
for j in range(0, 8):
if d[i+4] & ((0x01 << j) & 0xFF):
if (d[2] & 0x40):
if (i*8+j) == 0:
h12 = '12AM'
elif (i*8+j) == 12:
h12 = '12PM'
else:
h12 = (str(i*8+j+1)+'AM') if ((i*8+j) < 12) else (str(i*8+j-11)+'PM')
h = (h + ';') if n > 0 else h
h = h + h12
else:
h = (h + ';') if n > 0 else h
h = h + str(i*8+j)
n = n + 1
alarm['hour'] = h
if (d[3] & 0x40):
if (d[3] & 0x80) == 0x00:
alarm['weekday'] = d[3] & 0x07
else:
if d[8] == 0xFF:
alarm['weekday'] = 'EVERY_DAY'
else:
day = ''
n = 0
for j in range(1, 8):
if d[8] & ((0x01 << j) & 0xFF):
day = (day + ';') if n > 0 else day
day = day + str(j)
n = n + 1
alarm['weekday'] = day
else:
if (d[3] & 0x80) == 0x00:
alarm['day'] = ((d[3] >> 4) & 0x03) * 10 + (d[3] & 0x0F)
else:
alarm['day'] = 'EVERY_DAY'
return {'data': alarm, 'error': 'NO_ERROR'}
def SetAlarm(self, alarm):
d = [0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF]
if alarm == None or alarm == {}:
#disable alarm
return self.interface.WriteDataVerify(self.RTC_ALARM_CMD, d, 0.2)
if 'second' in alarm:
try:
s = int(alarm['second'])
except:
return {'error': 'INVALID_SECOND'}
if s < 0 or s > 60:
return {'error': 'INVALID_SECOND'}
d[0] = ((s // 10) & 0x0F) << 4
d[0] = d[0] | ((s % 10) & 0x0F)
if 'minute' in alarm:
try:
m = int(alarm['minute'])
except:
return {'error': 'INVALID_MINUTE'}
if m < 0 or m > 60:
return {'error': 'INVALID_MINUTE'}
d[1] = ((m // 10) & 0x0F) << 4
d[1] = d[1] | ((m % 10) & 0x0F)
else:
d[1] = d[1] | 0x80 # every minute
#d[1] = d[1] | (0x80 if alarm['mask']['minutes'] else 0x00)
if 'minute_period' in alarm:
d[1] = d[1] | 0x80
try:
s = int(alarm['minute_period'])
except:
return {'error': 'INVALID_MINUTE_PERIOD'}
if s < 1 or s > 60:
return {'error': 'INVALID_MINUTE_PERIOD'}
d[7] = s
d[4] = 0xFF
d[5] = 0xFF
d[6] = 0xFF
if 'hour' in alarm:
try:
h = alarm['hour']
if h == 'EVERY_HOUR':
d[2] = 0x80
elif isinstance(h, str) and h.find(';') < 0:
if (h.find('AM') > -1) or (h.find('PM') > -1):
if (h.find('PM') > -1):
hi = int(h.split('PM')[0])
d[2] = (((hi // 10) & 0x03) << 4)
d[2] = d[2] | ((hi % 10) & 0x0F)
d[2] = d[2] | 0x20 | 0x40
else:
hi = int(h.split('AM')[0])
d[2] = (((hi // 10) & 0x03) << 4)
d[2] = d[2] | ((hi % 10) & 0x0F)
d[2] = d[2] | 0x40
else:
d[2] = (((int(h) // 10) & 0x03) << 4)
d[2] = d[2] | ((int(h) % 10) & 0x0F)
elif isinstance(h, int):
#assume 24 hour format
d[2] = (((int(h) // 10) & 0x03) << 4)
d[2] = d[2] | ((int(h) % 10) & 0x0F)
elif (isinstance(h, str) and h.find(';') >= 0):
hs = 0x00000000
# hFormat = ''
hl = h.split(';')
# remove ending empty string if there is ; at the end of list
hl = hl[0:-1] if (not bool(hl[-1].strip())) else hl
for i in hl:
if (i.find('AM') > -1) or (i.find('PM') > -1):
if i.find('AM') > -1:
ham = int(i.split('AM')[0])
if ham < 12:
hs = hs | (0x00000001 << (ham))
else:
hs = hs | 0x00000001
else:
hpm = int(i.split('PM')[0])
if hpm < 12:
hs = hs | (0x00000001 << (hpm+12))
else:
hs = hs | (0x00000001 << (12))
else:
hs = hs | (0x00000001 << int(i))
#d[2] = d[2] | (0x40 if hFormat == '12' else 0x00)
d[2] = 0x80
d[4] = hs & 0x000000FF
hs = hs >> 8
d[5] = hs & 0x000000FF
hs = hs >> 8
d[6] = hs & 0x000000FF
except:
return {'error': 'INVALID_HOUR'}
else:
d[2] = 0x80 # every hour
d[8] = 0xFF
if 'weekday' in alarm:
try:
day = alarm['weekday']
if day == 'EVERY_DAY':
d[3] = 0x80 | 0x40
elif isinstance(day, str) and day.find(';') < 0:
dw = int(day)
d[3] = d[3] | (dw & 0x0F) | 0x40
elif isinstance(day, int):
dw = int(day)
d[3] = d[3] | (dw & 0x0F) | 0x40
elif (isinstance(day, str) and day.find(';') >= 0):
d[3] = 0x40 | 0x80
ds = 0x00
dl = day.split(';')
dl = dl[0:-1] if (not bool(dl[-1].strip())) else dl
for i in dl:
ds = ds | (0x01 << int(i))
d[8] = ds
except:
return {'error': 'INVALID_WEEKDAY'}
elif 'day' in alarm:
try:
day = alarm['day']
if day == 'EVERY_DAY':
d[3] = 0x80
else:
dm = int(day)
d[3] = (((dm // 10) & 0x03) << 4)
d[3] = d[3] | ((dm % 10) & 0x0F)
except:
return {'error': 'INVALID_DAY_OF_MONTH'}
else:
d[3] = 0x80 # every day
ret = self.interface.WriteData(self.RTC_ALARM_CMD, d)
if ret['error'] != 'NO_ERROR':
return ret
# verify
time.sleep(0.2)
ret = self.interface.ReadData(self.RTC_ALARM_CMD, 9)
if ret['error'] != 'NO_ERROR':
return ret
if (d == ret['data']):
return {'error': 'NO_ERROR'}
else:
h1 = d[2]
h2 = ret['data'][2]
if (h1 & 0x40): # convert to 24 hour format
h1Bin = ((h1 >> 4) & 0x01) * 10 + (h1 & 0x0F)
h1Bin = h1Bin if h1Bin < 12 else 0
h1Bin = h1Bin + (12 if h1 & 0x20 else 0)
else:
h1Bin = ((h1 >> 4) & 0x03) * 10 + (h1 & 0x0F)
if (h2 & 0x40): # convert to 24 hour format
h2Bin = ((h2 >> 4) & 0x01) * 10 + (h2 & 0x0F)
h2Bin = h2Bin if h2Bin < 12 else 0
h2Bin = h2Bin + (12 if h2 & 0x20 else 0)
else:
h2Bin = ((h2 >> 4) & 0x03) * 10 + (h2 & 0x0F)
d[2] = h1Bin | (d[2] & 0x80)
ret['data'][2] = h2Bin | (ret['data'][2] & 0x80)
if (d == ret['data']):
return {'error': 'NO_ERROR'}
else:
return {'error': 'WRITE_FAILED'}
class PiJuicePower(object):
WATCHDOG_ACTIVATION_CMD = 0x61
POWER_OFF_CMD = 0x62
WAKEUP_ON_CHARGE_CMD = 0x63
SYSTEM_POWER_SWITCH_CTRL_CMD = 0x64
def __init__(self, interface):
self.interface = interface
def __enter__(self):
# Just return this object so it can be used in a with statement
return self
def __exit__(self, exc_type, exc_val, exc_tb):
return False # Don't suppress exceptions.
def SetPowerOff(self, delay):
return self.interface.WriteData(self.POWER_OFF_CMD, [delay])
def GetPowerOff(self):
return self.interface.ReadData(self.POWER_OFF_CMD, 1)
def SetWakeUpOnCharge(self, arg):
try:
if arg == 'DISABLED':
d = 0x7F
elif int(arg) >= 0 and int(arg) <= 100:
d = int(arg)
except:
return {'error': 'BAD_ARGUMENT'}
return self.interface.WriteDataVerify(self.WAKEUP_ON_CHARGE_CMD, [d])
def GetWakeUpOnCharge(self):
ret = self.interface.ReadData(self.WAKEUP_ON_CHARGE_CMD, 1)
if ret['error'] != 'NO_ERROR':
return ret
else:
d = ret['data'][0]
if d == 0xFF:
return {'data': 'DISABLED', 'error': 'NO_ERROR'}
else:
return {'data': d, 'error': 'NO_ERROR'}
# input argument 1 - 65535 minutes activates watchdog, 0 disables watchdog
def SetWatchdog(self, minutes):
try:
d = int(minutes) & 0xFFFF
except:
return {'error': 'BAD_ARGUMENT'}
return self.interface.WriteData(self.WATCHDOG_ACTIVATION_CMD, [d & 0xFF, (d >> 8) & 0xFF])
def GetWatchdog(self):
ret = self.interface.ReadData(self.WATCHDOG_ACTIVATION_CMD, 2)
if ret['error'] != 'NO_ERROR':
return ret
else:
d = ret['data']
return {'data': (d[1] << 8) | d[0], 'error': 'NO_ERROR'}
def SetSystemPowerSwitch(self, state):
try:
d = int(state) // 100
except:
return {'error': 'BAD_ARGUMENT'}
return self.interface.WriteData(self.SYSTEM_POWER_SWITCH_CTRL_CMD, [d])
def GetSystemPowerSwitch(self):
ret = self.interface.ReadData(self.SYSTEM_POWER_SWITCH_CTRL_CMD, 1)
if ret['error'] != 'NO_ERROR':
return ret
else:
return {'data': ret['data'][0] * 100, 'error': 'NO_ERROR'}
class PiJuiceConfig(object):
CHARGING_CONFIG_CMD = 0x51
BATTERY_PROFILE_ID_CMD = 0x52
BATTERY_PROFILE_CMD = 0x53
BATTERY_EXT_PROFILE_CMD = 0x54
BATTERY_TEMP_SENSE_CONFIG_CMD = 0x5D
POWER_INPUTS_CONFIG_CMD = 0x5E
RUN_PIN_CONFIG_CMD = 0x5F
POWER_REGULATOR_CONFIG_CMD = 0x60
LED_CONFIGURATION_CMD = 0x6A
BUTTON_CONFIGURATION_CMD = 0x6E
IO_CONFIGURATION_CMD = 0x72
I2C_ADDRESS_CMD = 0x7C
ID_EEPROM_WRITE_PROTECT_CTRL_CMD = 0x7E
ID_EEPROM_ADDRESS_CMD = 0x7F
RESET_TO_DEFAULT_CMD = 0xF0
FIRMWARE_VERSION_CMD = 0xFD
def __init__(self, interface):
self.interface = interface