-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmc3000usb.py
418 lines (346 loc) · 13.5 KB
/
mc3000usb.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
import json
import struct
import sys
import usb.core
from usb.core import USBError
from shared import calculate_checksum, compare_checksum
# protocol source
# https://github.com/gitGNU/gnu_dataexplorer/blob/master/SkyRC/src/gde/device/skyrc/MC3000UsbPort.java
# https://github.com/gitGNU/gnu_dataexplorer/blob/master/SkyRC/src/gde/device/skyrc/MC3000.java
class MC3000Usb:
VID = 0x0000
PID = 0x0001
ENDPOINT_OUT = 0x01
ENDPOINT_IN = 0x81
MESSAGE_SIZE = 64
def __init__(self):
self.device = None
self.read_thread = None
self.running = None
def open(self):
if self.device is None:
self.device = usb.core.find(idVendor=self.VID, idProduct=self.PID)
if not self.device:
raise DeviceNotFoundException()
# MC3000 seems to be already configured by OS but pyusb says to always call set_configuration() so we will
try:
self.device.get_active_configuration() # will throw if not set
except USBError:
self.device.set_configuration()
def write(self, data):
self.open()
while len(data) < self.MESSAGE_SIZE:
data.append(0x00)
self.device.write(self.ENDPOINT_OUT, bytes(data))
def read(self, checksum=None):
self.open()
data = self.device.read(self.ENDPOINT_IN, self.MESSAGE_SIZE)
if compare_checksum(data, checksum):
raise ChecksumException(data)
return data
def close(self):
self.running = False
class Definitions:
BATTERY_TYPES = ["LiIon", "LiFe", "LiIo4.35", "NiMH", "NiCd", "NiZn", "Eneloop", "RAM"]
OPERATION_MODES_LI = ["Charge", "Refresh", "Storage", "Discharge", "Cycle"]
OPERATION_MODES_NI = ["Charge", "Refresh", "Break_in", "Discharge", "Cycle"]
OPERATION_MODES_ZN_RAM = ["Charge", "Refresh", "Discharge", "Cycle"]
CAPACITIES = [
0, 600, 720, 800, 960, 900, 1080, 1000, 1200, 2000, 2400, 2200, 2640, 2500, 3000, 3200, 3840, 6000, 7200
]
CYCLE_MODES = ["C > D", "C > D > C", "D > C", "D > C > D"]
TRICKLE_TIMES = ["OFF", "End", "Rest"]
FIELD_ALIASES = {
"number_cycle": "Cycle count",
}
FIELD_UNITS = {
"charge_current": "mA",
"discharge_current": "mA",
"discharge_cut_voltage": "mV",
"charge_end_voltage": "mV",
"charge_end_current": "mA",
"discharge_reduce_current": "mA",
"charge_resting_time": "min",
"peak_sense_voltage": "mV",
"trickle_current": "mA",
"restart_voltage": "mV",
"discharge_resting_time": "min",
}
DONT_VALIDATE_FIELDS = ["id", "name"]
class SlotSettings:
def __init__(self):
self.slot_number = None
self.busy_tag = None
self.battery_type = None
self.operation_mode = None
self.capacity = None
self.charge_current = None
self.discharge_current = None
self.discharge_cut_voltage = None
self.charge_end_voltage = None
self.charge_end_current = None
self.discharge_reduce_current = None
self.number_cycle = None
self.charge_resting_time = None
self.cycle_mode = None
self.peak_sense_voltage = None
self.trickle_current = None
self.restart_voltage = None
self.cut_temperature = None
self.cut_time = None
self.temperature_unit = None
self.trickle_time = None
self.discharge_resting_time = None
# extra metadata
self.raw = None
self.id = None
self.name = None
def get_slot(self):
return self.slot_number + 1
def get_description(self, include_name=False):
pieces = [self.get_battery_type_label()]
mode = self.get_operation_mode_label()
pieces.append(mode)
if mode != "Discharge":
pieces.append("%sA" % (self.charge_current / 1000))
if mode != "Charge":
pieces.append("%sA" % (self.discharge_current / 1000))
description = " ".join(pieces)
if include_name and self.name:
return "%s (%s)" % (self.name, description)
return description
def get_battery_type_label(self):
if self.battery_type >= 0 and self.battery_type < len(Definitions.BATTERY_TYPES):
return Definitions.BATTERY_TYPES[self.battery_type]
return "Type%s" % self.battery_type
def get_operation_mode_label(self):
if self.battery_type in [0, 1, 2]:
modes = Definitions.OPERATION_MODES_LI
elif self.battery_type in [3, 4, 6]:
modes = Definitions.OPERATION_MODES_NI
else:
modes = Definitions.OPERATION_MODES_ZN_RAM
if self.operation_mode >= 0 and self.operation_mode < len(modes):
return modes[self.operation_mode]
return "Mode%s" % self.operation_mode
def get_capacity_label(self):
if self.capacity == 0:
return "OFF"
elif self.capacity in Definitions.CAPACITIES:
return Definitions.CAPACITIES[self.capacity]
return "Capacity%s" % self.capacity
def get_cycle_mode_label(self):
if self.cycle_mode == 0:
return "OFF"
elif self.cycle_mode in Definitions.CYCLE_MODES:
return Definitions.CYCLE_MODES[self.cycle_mode]
return "CycleMode%s" % self.cycle_mode
def get_temperature_unit_label(self):
if self.temperature_unit == 0:
return "°C"
elif self.temperature_unit == 1:
return "°F"
return "TemperatureUnit%s" % self.temperature_unit
def get_trickle_time_label(self):
if self.trickle_time == 0:
return "OFF"
elif self.trickle_time in Definitions.TRICKLE_TIMES:
return Definitions.TRICKLE_TIMES[self.trickle_time]
return "TrickleTime%s" % self.trickle_time
def get_fields(self):
dict = self.__dict__.copy()
del dict["raw"]
return dict
def fill_fields(self, fields):
for name in self.get_fields().keys():
if name in fields:
value = fields[name]
if name not in DONT_VALIDATE_FIELDS:
try:
value = int(value)
except (TypeError, ValueError):
raise Exception("field '%s' has invalid value '%s'" % (name, value))
setattr(self, name, value)
def to_json(self):
return json.dumps(self.get_fields(), indent=True)
def from_json(self, payload):
try:
fields = json.loads(payload)
except (json.JSONDecodeError, TypeError, ValueError):
raise JsonException("JSON decode failed")
for name in self.get_fields().keys():
if name in fields:
value = fields[name]
if name in ["id"]:
continue
if name not in DONT_VALIDATE_FIELDS:
try:
value = int(value)
except (TypeError, ValueError):
raise JsonException("field '%s' has invalid value '%s'" % (name, value))
setattr(self, name, value)
for name, value in self.get_fields().items():
if value is None and name not in ["id"]:
raise JsonException("field '%s' is missing" % name)
try:
MC3000Encoder().prepare_slot_settings_write(self)
except Exception as e:
raise JsonException("malformed values: %s" % e)
def get_display_fields(self):
fields = []
for name, value in self.get_fields().items():
if name in ["slot_number", "busy_tag", "id", "name"]:
continue
raw_value = value
if name == "battery_type":
value = self.get_battery_type_label()
elif name == "operation_mode":
value = self.get_operation_mode_label()
elif name == "capacity":
value = self.get_capacity_label()
elif name == "cycle_mode":
value = self.get_cycle_mode_label()
elif name == "temperature_unit":
value = self.get_temperature_unit_label()
elif name == "trickle_time":
value = self.get_trickle_time_label()
if name in Definitions.FIELD_ALIASES:
alias = Definitions.FIELD_ALIASES[name]
else:
alias = name.replace("_", " ").capitalize()
if name in Definitions.FIELD_UNITS:
value = "%s %s" % (value, Definitions.FIELD_UNITS[name])
elif name.endswith("_temperature"):
value = "%s %s" % (value, self.get_temperature_unit_label())
item = {
"name": name,
"alias": alias,
"value": value,
"raw_value": raw_value,
}
fields.append(item)
return fields
class MC3000Encoder:
SLOT_READS = [
[0x0F, 0x04, 0x5F, 0x00, 0x00, 0x5F, 0xFF, 0xFF],
[0x0F, 0x04, 0x5F, 0x00, 0x01, 0x60, 0xFF, 0xFF],
[0x0F, 0x04, 0x5F, 0x00, 0x02, 0x61, 0xFF, 0xFF],
[0x0F, 0x04, 0x5F, 0x00, 0x03, 0x62, 0xFF, 0xFF],
]
def prepare_slot_settings_read(self, slot_number):
return self.SLOT_READS[slot_number]
def decode_slot_settings(self, data):
slot = SlotSettings()
slot.raw = list(data)
slot.slot_number = data[1]
slot.busy_tag = data[2]
slot.battery_type = data[3]
slot.operation_mode = data[4]
slot.capacity = self.decode_int(data, 5)
# 6 = second byte
slot.charge_current = self.decode_int(data, 7)
# 8 = second byte
slot.discharge_current = self.decode_int(data, 9)
# 10 = second byte
slot.discharge_cut_voltage = self.decode_int(data, 11)
# 12 = second byte
slot.charge_end_voltage = self.decode_int(data, 13)
# 14 = second byte
slot.charge_end_current = self.decode_int(data, 15)
# 16 = second byte
slot.discharge_reduce_current = self.decode_int(data, 17)
# 18 = second byte
slot.number_cycle = data[19]
slot.charge_resting_time = data[20]
slot.cycle_mode = data[21]
slot.peak_sense_voltage = data[22]
slot.trickle_current = data[23]
slot.restart_voltage = self.decode_int(data, 24)
# 25 = second byte
slot.cut_temperature = data[26]
slot.cut_time = self.decode_int(data, 27)
# 28 = second byte
slot.temperature_unit = data[29]
slot.trickle_time = data[30]
slot.discharge_resting_time = data[31]
return slot
def prepare_slot_settings_write(self, slot: SlotSettings):
data = [0x0F, 0x20, 0x11, 0x00] # header
data.extend([0x00] * 32)
data[4] = slot.slot_number
data[5] = slot.battery_type
self.encode_int(data, 6, slot.capacity)
# 7 = second byte
data[8] = slot.operation_mode
self.encode_int(data, 9, slot.charge_current)
# 10 = second byte
self.encode_int(data, 11, slot.discharge_current)
# 12 = second byte
self.encode_int(data, 13, slot.discharge_cut_voltage)
# 14 = second byte
self.encode_int(data, 15, slot.charge_end_voltage)
# 16 = second byte
self.encode_int(data, 17, slot.charge_end_current)
# 18 = second byte
self.encode_int(data, 19, slot.discharge_reduce_current)
# 20 = second byte
data[21] = slot.number_cycle
data[22] = slot.charge_resting_time
data[23] = slot.discharge_resting_time
data[24] = slot.cycle_mode
data[25] = slot.peak_sense_voltage
data[26] = slot.trickle_current
data[27] = slot.trickle_time
data[28] = slot.cut_temperature
self.encode_int(data, 29, slot.cut_time)
# 30 = second byte
self.encode_int(data, 31, slot.restart_voltage)
# 32 = second byte
data[33] = calculate_checksum(data[2:])
data[34] = 0xFF
data[35] = 0xFF
return data
def prepare_system_settings_read(self):
data = [0x0f, 0x04, 0x5a, 0x00] # header
data.extend([0x00] * 4)
data[5] = calculate_checksum(data[2:])
data[6] = 0xFF
data[7] = 0xFF
return data
def decode_int(self, data, index):
return struct.unpack(">H", data[index:index + 2])[0]
def encode_int(self, data, index, value):
[first, second] = struct.pack(">H", value)
data[index] = first
data[index + 1] = second
class MC3000UsbException(Exception):
pass
class DeviceNotFoundException(MC3000UsbException):
pass
class ChecksumException(MC3000UsbException):
pass
class JsonException(MC3000UsbException):
pass
if __name__ == "__main__":
coms = MC3000Usb()
coms.open()
encoder = MC3000Encoder()
path = "slot-0.json"
task = sys.argv[1] if len(sys.argv) > 1 else "save"
if task == "save":
coms.write(encoder.prepare_slot_settings_read(0))
data = coms.read()
slot = encoder.decode_slot_settings(data)
with open(path, "w") as file:
file.write(slot.to_json())
print("successfully saved: %s" % path)
elif task == "load":
slot = SlotSettings()
with open(path, "r") as file:
slot.from_json(file.read())
data = encoder.prepare_slot_settings_write(slot)
print(data)
coms.write(data)
print("successfully loaded: %s" % path)
else:
print("ERROR: unknown task: %s" % task)