-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathicharger.py
More file actions
947 lines (794 loc) · 32.3 KB
/
Copy pathicharger.py
File metadata and controls
947 lines (794 loc) · 32.3 KB
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
#!/usr/bin/env python3
"""
iCharger 308 DUO High-Level API
Complete implementation based on iCharger MODBUS Protocol V2.1
Supports all operations: device info, channel monitoring, control commands,
system settings, and memory profile management.
"""
import struct
import time
from dataclasses import dataclass, field
from enum import IntEnum
from typing import List, Optional, Dict, Any
from modbus_rtu import ModbusRTU
# =============================================================================
# Register Addresses
# =============================================================================
# Read-only areas (function code 0x04)
REG_DEVICE_BASE = 0x0000 # Device info
REG_CH1_BASE = 0x0100 # Channel 1 data
REG_CH2_BASE = 0x0200 # Channel 2 data
# Read/Write areas (function codes 0x03/0x10)
REG_CONTROL_BASE = 0x8000 # Control registers
REG_SYSTEM_BASE = 0x8400 # System settings
REG_MEM_HEAD_BASE = 0x8800 # Memory index
REG_MEMORY_BASE = 0x8C00 # Memory profiles
# =============================================================================
# Enumerations
# =============================================================================
class Operation(IntEnum):
"""Charging operation types"""
CHARGE = 0
STORAGE = 1
DISCHARGE = 2
CYCLE = 3
BALANCE = 4
MEASURE_IR = 5 # Internal resistance measurement
class DeviceID(IntEnum):
"""Known iCharger device IDs"""
DUO_4010 = 64 # 0x40
DUO_308 = 66 # 0x42
DUO_406 = 67 # 0x43
class Order(IntEnum):
"""Control commands"""
STOP = 0
RUN = 1
MODIFY = 2
WRITE_SYS = 3
WRITE_MEM_HEAD = 4
WRITE_MEM = 5
TRANS_LOG_ON = 6
TRANS_LOG_OFF = 7
MSGBOX_YES = 8
MSGBOX_NO = 9
class BatteryType(IntEnum):
"""Battery chemistry types"""
LIPO = 0
LILO = 1
LIFE = 2
NIMH = 3
NICD = 4
PB = 5
NIZN = 6
class RunStatus(IntEnum):
"""Channel run status (offset 55 in channel data)
Note: Values 5, 6, 14 observed during startup but not documented.
"""
IDLE = 0
RUNNING = 1
PAUSED = 2
FINISHED = 3
ERROR = 4
class GeneralStatus:
"""General status word bit flags (offset 11 in channel data)"""
RUN = 0x01 # Bit 0: running flag
ERROR = 0x02 # Bit 1: error flag
CONTROL_STATUS = 0x04 # Bit 2: control status
RUN_STATUS = 0x08 # Bit 3: run status
DLG_BOX_STATUS = 0x10 # Bit 4: dialog box status
CELL_VOLTAGE = 0x20 # Bit 5: cell voltage valid
BALANCE = 0x40 # Bit 6: balancing active
class BalanceSpeed(IntEnum):
"""Balance speed setting"""
SLOW = 0
NORMAL = 1
FAST = 2
class BalanceStartMode(IntEnum):
"""When to start balancing"""
ALWAYS = 0
CV_PHASE = 1
BY_VOLTAGE = 2
class LiBalEndMode(IntEnum):
"""Li-battery balance end current detection mode"""
END_CURRENT_OFF_DETECT_ON = 0
END_CURRENT_ON_DETECT_OFF = 1
END_CURRENT_OR_DETECT = 2
END_CURRENT_AND_DETECT = 3
# Order unlock value
ORDER_UNLOCK = 0x55AA
# =============================================================================
# Data Classes
# =============================================================================
@dataclass
class DeviceInfo:
"""Device identification and version info"""
device_id: int = 0
serial_number: str = ""
sw_version: int = 0
hw_version: int = 0
system_length: int = 0
memory_length: int = 0
ch1_status_word: int = 0
ch2_status_word: int = 0
def sw_version_str(self) -> str:
major = (self.sw_version >> 8) & 0xFF
minor = self.sw_version & 0xFF
return f"{major}.{minor}"
def hw_version_str(self) -> str:
major = (self.hw_version >> 8) & 0xFF
minor = self.hw_version & 0xFF
return f"{major}.{minor}"
@dataclass
class StatusWord:
"""Channel status word bit fields"""
run_flag: bool = False
error_flag: bool = False
control_status: bool = False
run_status: bool = False
dialog_box: bool = False
cell_voltage: bool = False
balance: bool = False
@classmethod
def from_value(cls, value: int) -> 'StatusWord':
return cls(
run_flag=bool(value & 0x01),
error_flag=bool(value & 0x02),
control_status=bool(value & 0x04),
run_status=bool(value & 0x08),
dialog_box=bool(value & 0x10),
cell_voltage=bool(value & 0x20),
balance=bool(value & 0x40)
)
@dataclass
class ChannelData:
"""Channel real-time data"""
timestamp: int = 0
output_power: int = 0 # mW
output_current: int = 0 # 10mA units (signed)
input_voltage: int = 0 # 10mV units
output_voltage: int = 0 # 10mV units
output_capacity: int = 0 # mAh (signed)
temp_internal: int = 0 # 0.1°C (signed)
temp_external: int = 0 # 0.1°C (signed)
cell_voltage: List[int] = field(default_factory=lambda: [0]*16) # mV
cell_balance: List[int] = field(default_factory=lambda: [0]*16) # balance status
cell_ir: List[int] = field(default_factory=lambda: [0]*16) # mOhm
total_ir: int = 0 # mOhm
line_ir: int = 0 # mOhm
cycle_count: int = 0
control_status: int = 0
run_status: int = 0
run_error: int = 0
dialog_box_id: int = 0
# Computed properties
def power_watts(self) -> float:
return self.output_power / 1000.0
def current_amps(self) -> float:
# Current is signed, stored as 10mA units
return self.output_current / 100.0
def voltage_volts(self) -> float:
return self.output_voltage / 1000.0
def input_voltage_volts(self) -> float:
return self.input_voltage / 1000.0
def capacity_mah(self) -> int:
return self.output_capacity
def temp_internal_c(self) -> float:
return self.temp_internal / 10.0
def temp_external_c(self) -> float:
return self.temp_external / 10.0
def cell_voltage_v(self, idx: int) -> float:
return self.cell_voltage[idx] / 1000.0
def is_running(self) -> bool:
return self.run_status == RunStatus.RUNNING
def is_idle(self) -> bool:
return self.run_status == RunStatus.IDLE
def has_error(self) -> bool:
return self.run_error != 0
# GeneralStatus bit helpers
def is_control_running(self) -> bool:
"""Check if running flag set in control_status"""
return bool(self.control_status & GeneralStatus.RUN)
def is_control_error(self) -> bool:
"""Check if error flag set in control_status"""
return bool(self.control_status & GeneralStatus.ERROR)
def is_balancing(self) -> bool:
"""Check if balancing flag set in control_status"""
return bool(self.control_status & GeneralStatus.BALANCE)
def has_dialog(self) -> bool:
"""Check if dialog box flag set in control_status"""
return bool(self.control_status & GeneralStatus.DLG_BOX_STATUS)
def detected_cells(self) -> int:
"""Count cells with realistic voltage (>2.0V and <5.0V)"""
count = 0
for v in self.cell_voltage:
if 2000 <= v <= 5000: # 2.0V - 5.0V = valid cell
count += 1
return count
def get_active_cells(self) -> List[int]:
"""Get indices of cells with valid voltage"""
return [i for i, v in enumerate(self.cell_voltage) if 2000 <= v <= 5000]
@dataclass
class SystemSettings:
"""System-wide settings"""
temp_unit: int = 0 # 0=Celsius, 1=Fahrenheit
temp_stop: int = 750 # 0.1°C, cut-off temperature
temp_fans_on: int = 400 # 0.1°C, fans on temperature
temp_reduce: int = 100 # 0.1°C, power reduce delta
fans_off_delay: int = 2 # minutes
lcd_contrast: int = 16 # 0-32
backlight: int = 17 # 1-33
beep_type: List[int] = field(default_factory=lambda: [0]*4)
beep_enable: List[int] = field(default_factory=lambda: [1]*4)
beep_volume: List[int] = field(default_factory=lambda: [50]*4)
calibration_select: int = 0 # 0=system, 1=user
input_source: int = 0 # 0=DC, 1=Battery
dc_input_low_volt: int = 100 # 0.1V
dc_input_over_volt: int = 505 # 0.1V (fixed)
dc_input_current_limit: int = 650 # 0.1A
bat_input_low_volt: int = 100
bat_input_over_volt: int = 505
bat_input_current_limit: int = 650
regen_enable: int = 0 # 0=off, 1=on
regen_volt_limit: int = 145 # 0.1V
regen_current_limit: int = 100 # 0.1A
ch1_charge_power: int = 1400 # W
ch2_charge_power: int = 1400
ch1_discharge_power: int = 130 # W
ch2_discharge_power: int = 130
power_priority: int = 0 # 0=average, 1=CH1, 2=CH2
ch1_log_interval: int = 10 # 0.1s units
ch2_log_interval: int = 10
ch1_log_to_sd: int = 0
ch2_log_to_sd: int = 0
servo_type: int = 0
servo_center: int = 15000
servo_rate: int = 150
servo_angle: int = 5000
modbus_mode: int = 2 # 0=off, 1=HID, 2=Serial
modbus_address: int = 1
modbus_baudrate: int = 4 # 0=9600, 4=115200
modbus_parity: int = 0 # 0=None, 1=Even, 2=Odd
@dataclass
class MemoryProfile:
"""Battery memory profile settings"""
use_flag: int = 0xFFFF # 0xFFFF=empty, 0x55AA=used, 0x0000=fixed
name: str = ""
capacity: int = 0 # mAh
auto_save: int = 0
li_bal_end_mode: int = 0
op_enable: int = 0x3F # Bitmask for enabled operations
channel_mode: int = 0 # 0=async, 1=sync
save_to_sd: int = 0
log_interval: int = 10 # 0.1s
run_counter: int = 0
bat_type: int = 0 # BatteryType enum
li_cells: int = 0
ni_cells: int = 0
pb_cells: int = 0
li_mode_charge: int = 0
li_mode_discharge: int = 0
ni_mode_charge: int = 0
ni_mode_discharge: int = 0
pb_mode_charge: int = 0
pb_mode_discharge: int = 0
balance_speed: int = 1 # BalanceSpeed enum
balance_start_mode: int = 0
balance_start_volt: int = 0
balance_diff: int = 5 # mV
balance_over_point: int = 0
balance_set_point: int = 5 # mV
balance_delay: int = 1 # minutes
keep_charge_enable: int = 0
lipo_charge_volt: int = 4200 # mV/cell
lilo_charge_volt: int = 4350
life_charge_volt: int = 3600
lipo_storage_volt: int = 3850
lilo_storage_volt: int = 3750
life_storage_volt: int = 3300
lipo_discharge_volt: int = 3000
lilo_discharge_volt: int = 2500
life_discharge_volt: int = 2800
charge_current: int = 2000 # mA
discharge_current: int = 2000
end_charge_current: int = 100 # mA (C/10)
end_discharge_current: int = 500
regen_discharge_mode: int = 0
ni_peak: int = 3 # mV
ni_peak_delay: int = 3 # minutes
ni_trickle_enable: int = 0
ni_trickle_current: int = 50 # mA
ni_trickle_time: int = 5 # minutes
ni_zero_enable: int = 0
ni_discharge_volt: int = 100 # mV/cell
pb_charge_volt: int = 2400 # mV/cell
pb_discharge_volt: int = 1800
restore_volt: int = 1000 # mV/cell
restore_time: int = 3 # minutes
restore_current: int = 100 # mA
cycle_count: int = 3
cycle_delay: int = 3 # minutes
cycle_mode: int = 0
safety_time_charge: int = 0 # minutes, 0=off
safety_cap_charge: int = 120 # % of capacity
safety_temp_charge: int = 450 # 0.1°C
safety_time_discharge: int = 0
safety_cap_discharge: int = 120
safety_temp_discharge: int = 450
regen_ch_mode: int = 0
regen_ch_volt: int = 120 # 0.1V
regen_ch_current: int = 10 # 0.1A
fast_storage: int = 0
storage_compensation: int = 10 # mV
nizn_charge_volt: int = 1900 # mV/cell
nizn_discharge_volt: int = 1000
nizn_cells: int = 0
# =============================================================================
# Error codes
# =============================================================================
RUN_ERRORS = {
0x00: "None",
0x01: "Control error",
0x02: "Cell voltage low",
0x03: "Balance connect",
0x04: "Battery full",
0x05: "Cell high",
0x06: "Cell low",
0x07: "Cell difference",
0x08: "Balance difference",
0x09: "Input low",
0x0A: "Input high",
0x0B: "Temperature cut",
0x0C: "Internal temp",
0x0D: "External temp",
0x0E: "Capacity cut",
0x0F: "Time cut",
0x10: "Current error",
0x11: "Break down",
0x12: "Battery check",
0x13: "Internal error",
0x14: "Reverse polarity",
0x15: "Balance error",
}
# =============================================================================
# iCharger Class
# =============================================================================
class ICharger:
"""High-level API for iCharger 308 DUO"""
def __init__(self, port: str, baudrate: int = 115200, slave_addr: int = 1,
debug: bool = False):
"""
Initialize iCharger connection
Args:
port: Serial port
baudrate: Baud rate (must match charger settings)
slave_addr: Modbus address (default 1)
debug: Enable debug output
"""
self.modbus = ModbusRTU(port, baudrate, slave_addr, debug=debug)
self.debug = debug
self._connected = False
def connect(self) -> bool:
"""Connect to charger"""
if self.modbus.connect():
self._connected = True
return True
return False
def disconnect(self):
"""Disconnect from charger"""
self.modbus.disconnect()
self._connected = False
@property
def connected(self) -> bool:
return self._connected
# =========================================================================
# Device Info
# =========================================================================
def read_device_info(self) -> Optional[DeviceInfo]:
"""Read device identification and version info"""
regs = self.modbus.read_input_registers(REG_DEVICE_BASE, 13)
if regs is None:
return None
info = DeviceInfo()
info.device_id = regs[0]
# Serial number: 12 chars in 6 registers (big-endian)
sn_bytes = b''
for i in range(1, 7):
sn_bytes += struct.pack('>H', regs[i])
info.serial_number = sn_bytes.decode('ascii', errors='replace').strip('\x00')
info.sw_version = regs[7]
info.hw_version = regs[8]
info.system_length = regs[9]
info.memory_length = regs[10]
info.ch1_status_word = regs[11]
info.ch2_status_word = regs[12]
return info
# =========================================================================
# Channel Data
# =========================================================================
def read_channel(self, channel: int) -> Optional[ChannelData]:
"""
Read channel real-time data
Args:
channel: 0 for CH1, 1 for CH2
Returns:
ChannelData object or None on error
"""
if channel not in (0, 1):
raise ValueError("Channel must be 0 or 1")
base_addr = REG_CH1_BASE if channel == 0 else REG_CH2_BASE
# Read all channel registers (need multiple reads due to 30 reg limit)
# First read: 0-29 (timestamp, power, current, voltage, capacity, temps, cells 0-9)
regs1 = self.modbus.read_input_registers(base_addr, 30)
if regs1 is None:
return None
# Second read: 30-57 (cells 10-15, balance, IR, status)
regs2 = self.modbus.read_input_registers(base_addr + 30, 28)
if regs2 is None:
return None
# Combine
regs = regs1 + regs2
data = ChannelData()
# Parse data
data.timestamp = (regs[0] << 16) | regs[1]
data.output_power = (regs[2] << 16) | regs[3]
data.output_current = self._to_signed16(regs[4])
data.input_voltage = regs[5]
data.output_voltage = regs[6]
data.output_capacity = self._to_signed32((regs[7] << 16) | regs[8])
data.temp_internal = self._to_signed16(regs[9])
data.temp_external = self._to_signed16(regs[10])
# Cell voltages (16 cells, regs 11-26)
for i in range(16):
data.cell_voltage[i] = regs[11 + i]
# Cell balance status (packed as bytes in regs 27-34)
for i in range(16):
reg_idx = 27 + (i // 2)
if i % 2 == 0:
data.cell_balance[i] = (regs[reg_idx] >> 8) & 0xFF
else:
data.cell_balance[i] = regs[reg_idx] & 0xFF
# Cell internal resistance (16 cells, regs 35-50)
for i in range(16):
data.cell_ir[i] = regs[35 + i]
data.total_ir = regs[51]
data.line_ir = regs[52]
data.cycle_count = regs[53]
data.control_status = regs[54]
data.run_status = regs[55]
data.run_error = regs[56]
data.dialog_box_id = regs[57]
return data
# =========================================================================
# Control Commands
# =========================================================================
def start_charge(self, channel: int, memory_slot: int = 0) -> bool:
"""Start charging on specified channel"""
return self._send_order(channel, Operation.CHARGE, memory_slot, Order.RUN)
def start_storage(self, channel: int, memory_slot: int = 0) -> bool:
"""Start storage charge on specified channel"""
return self._send_order(channel, Operation.STORAGE, memory_slot, Order.RUN)
def start_discharge(self, channel: int, memory_slot: int = 0) -> bool:
"""Start discharge on specified channel"""
return self._send_order(channel, Operation.DISCHARGE, memory_slot, Order.RUN)
def start_cycle(self, channel: int, memory_slot: int = 0) -> bool:
"""Start cycle (charge/discharge) on specified channel"""
return self._send_order(channel, Operation.CYCLE, memory_slot, Order.RUN)
def start_balance(self, channel: int, memory_slot: int = 0) -> bool:
"""Start balance-only on specified channel"""
return self._send_order(channel, Operation.BALANCE, memory_slot, Order.RUN)
def start_measure_ir(self, channel: int, memory_slot: int = 0) -> bool:
"""Start internal resistance measurement on specified channel"""
return self._send_order(channel, Operation.MEASURE_IR, memory_slot, Order.RUN)
def stop(self, channel: int) -> bool:
"""Stop operation on specified channel"""
return self._unlock_and_send_order(channel, Order.STOP)
def respond_yes(self, channel: int) -> bool:
"""Respond YES to dialog box"""
return self._unlock_and_send_order(channel, Order.MSGBOX_YES)
def respond_no(self, channel: int) -> bool:
"""Respond NO to dialog box"""
return self._unlock_and_send_order(channel, Order.MSGBOX_NO)
def modify_limit_current(self, channel: int, current_ma: int) -> bool:
"""Modify charge/discharge current limit during operation"""
# Select channel, unlock, modify order, and set current
values = [
channel, # Select channel
ORDER_UNLOCK, # Unlock
Order.MODIFY, # Modify order
current_ma # Limit current
]
return self.modbus.write_multiple_registers(REG_CONTROL_BASE + 2, values)
def modify_limit_voltage(self, channel: int, voltage_mv: int) -> bool:
"""Modify voltage limit during operation"""
values = [
channel,
ORDER_UNLOCK,
Order.MODIFY,
]
if not self.modbus.write_multiple_registers(REG_CONTROL_BASE + 2, values):
return False
# Write voltage separately
return self.modbus.write_multiple_registers(REG_CONTROL_BASE + 6, [voltage_mv])
def enable_log_transmission(self) -> bool:
"""Enable LogView log transmission"""
return self._unlock_and_send_order(0, Order.TRANS_LOG_ON)
def disable_log_transmission(self) -> bool:
"""Disable LogView log transmission"""
return self._unlock_and_send_order(0, Order.TRANS_LOG_OFF)
# =========================================================================
# System Settings
# =========================================================================
def read_system_settings(self) -> Optional[SystemSettings]:
"""Read system settings from device"""
# System settings area at 0x8400, read in chunks
regs1 = self.modbus.read_holding_registers(REG_SYSTEM_BASE, 30)
if regs1 is None:
return None
regs2 = self.modbus.read_holding_registers(REG_SYSTEM_BASE + 30, 29)
if regs2 is None:
return None
regs = regs1 + regs2
settings = SystemSettings()
settings.temp_unit = regs[0]
settings.temp_stop = regs[1]
settings.temp_fans_on = regs[2]
settings.temp_reduce = regs[3]
# regs[4] reserved
settings.fans_off_delay = regs[5]
settings.lcd_contrast = regs[6]
settings.backlight = regs[7]
# regs[8] reserved
settings.beep_type = list(regs[9:13])
settings.beep_enable = list(regs[13:17])
settings.beep_volume = list(regs[17:21])
# regs[21] reserved
settings.calibration_select = regs[22]
# regs[23] system param version
settings.input_source = regs[24]
settings.dc_input_low_volt = regs[25]
settings.dc_input_over_volt = regs[26]
settings.dc_input_current_limit = regs[27]
settings.bat_input_low_volt = regs[28]
settings.bat_input_over_volt = regs[29]
settings.bat_input_current_limit = regs[30]
settings.regen_enable = regs[31]
settings.regen_volt_limit = regs[32]
settings.regen_current_limit = regs[33]
settings.ch1_charge_power = regs[34]
settings.ch2_charge_power = regs[35]
settings.ch1_discharge_power = regs[36]
settings.ch2_discharge_power = regs[37]
settings.power_priority = regs[38]
settings.ch1_log_interval = regs[39]
settings.ch2_log_interval = regs[40]
settings.ch1_log_to_sd = regs[41]
settings.ch2_log_to_sd = regs[42]
settings.servo_type = regs[43]
settings.servo_center = regs[44]
settings.servo_rate = regs[45]
settings.servo_angle = regs[46]
settings.modbus_mode = regs[47]
settings.modbus_address = regs[48]
settings.modbus_baudrate = regs[49]
settings.modbus_parity = regs[50]
return settings
def write_system_settings(self, settings: SystemSettings) -> bool:
"""Write system settings to device RAM (use save_system() to persist)"""
# Build register values
regs = [
settings.temp_unit,
settings.temp_stop,
settings.temp_fans_on,
settings.temp_reduce,
0, # reserved
settings.fans_off_delay,
settings.lcd_contrast,
settings.backlight,
0, # reserved
]
regs.extend(settings.beep_type)
regs.extend(settings.beep_enable)
regs.extend(settings.beep_volume)
regs.append(0) # reserved
regs.extend([
settings.calibration_select,
0, # system param version
settings.input_source,
settings.dc_input_low_volt,
settings.dc_input_over_volt,
settings.dc_input_current_limit,
settings.bat_input_low_volt,
settings.bat_input_over_volt,
settings.bat_input_current_limit,
])
# Write first chunk (max 28 registers)
if not self.modbus.write_multiple_registers(REG_SYSTEM_BASE, regs[:28]):
return False
# Build second chunk
regs2 = [
settings.regen_enable,
settings.regen_volt_limit,
settings.regen_current_limit,
settings.ch1_charge_power,
settings.ch2_charge_power,
settings.ch1_discharge_power,
settings.ch2_discharge_power,
settings.power_priority,
settings.ch1_log_interval,
settings.ch2_log_interval,
settings.ch1_log_to_sd,
settings.ch2_log_to_sd,
settings.servo_type,
settings.servo_center,
settings.servo_rate,
settings.servo_angle,
settings.modbus_mode,
settings.modbus_address,
settings.modbus_baudrate,
settings.modbus_parity,
]
return self.modbus.write_multiple_registers(REG_SYSTEM_BASE + 31, regs2)
def save_system_settings(self) -> bool:
"""Save system settings from RAM to flash"""
return self._unlock_and_send_order(0, Order.WRITE_SYS)
# =========================================================================
# Memory Profiles
# =========================================================================
def read_memory_index(self) -> Optional[Dict[str, Any]]:
"""Read memory index (which profiles are active)"""
# MEM_HEAD structure: count(u16) + index[64](u8)
# = 1 + 32 = 33 registers
regs1 = self.modbus.read_holding_registers(REG_MEM_HEAD_BASE, 30)
if regs1 is None:
return None
regs2 = self.modbus.read_holding_registers(REG_MEM_HEAD_BASE + 30, 3)
if regs2 is None:
return None
regs = regs1 + regs2
count = regs[0]
index = []
for i in range(32):
reg = regs[1 + i]
index.append((reg >> 8) & 0xFF)
index.append(reg & 0xFF)
return {
'count': count,
'index': index[:64]
}
def read_memory_profile(self, slot: int) -> Optional[MemoryProfile]:
"""
Read a battery memory profile
Args:
slot: Memory slot (0-63)
"""
if slot < 0 or slot > 63:
raise ValueError("Slot must be 0-63")
# Each memory profile is at REG_MEMORY_BASE + slot * profile_size
# Profile size is approximately 100 registers
# Need to select the slot first by writing to a specific register
# According to protocol, reading from 0x8C00 reads the currently selected memory
# First, we need to understand the memory structure better
# For now, read raw registers
regs1 = self.modbus.read_holding_registers(REG_MEMORY_BASE, 30)
if regs1 is None:
return None
regs2 = self.modbus.read_holding_registers(REG_MEMORY_BASE + 30, 30)
if regs2 is None:
return None
regs3 = self.modbus.read_holding_registers(REG_MEMORY_BASE + 60, 30)
if regs3 is None:
return None
regs = regs1 + regs2 + regs3
profile = MemoryProfile()
profile.use_flag = regs[0]
# Name: 38 chars (19 registers), stored as packed bytes
name_bytes = b''
for i in range(1, 20):
name_bytes += struct.pack('>H', regs[i])
profile.name = name_bytes.decode('ascii', errors='replace').strip('\x00')
# Capacity is 32-bit
profile.capacity = (regs[20] << 16) | regs[21]
# Parse remaining fields (simplified)
# Full parsing would require exact field offsets from the protocol
return profile
def save_memory_index(self) -> bool:
"""Save memory index from RAM to flash"""
return self._unlock_and_send_order(0, Order.WRITE_MEM_HEAD)
def save_memory_profile(self) -> bool:
"""Save current memory profile from RAM to flash"""
return self._unlock_and_send_order(0, Order.WRITE_MEM)
# =========================================================================
# Utility Methods
# =========================================================================
@staticmethod
def get_error_name(error_code: int) -> str:
"""Get human-readable error name"""
return RUN_ERRORS.get(error_code, f"Unknown error 0x{error_code:02X}")
@staticmethod
def get_operation_name(op: int) -> str:
"""Get operation name"""
names = {
Operation.CHARGE: "Charge",
Operation.STORAGE: "Storage",
Operation.DISCHARGE: "Discharge",
Operation.CYCLE: "Cycle",
Operation.BALANCE: "Balance"
}
return names.get(op, f"Unknown ({op})")
@staticmethod
def get_battery_type_name(bat_type: int) -> str:
"""Get battery type name"""
names = {
BatteryType.LIPO: "LiPo",
BatteryType.LILO: "LiLo",
BatteryType.LIFE: "LiFe",
BatteryType.NIMH: "NiMH",
BatteryType.NICD: "NiCd",
BatteryType.PB: "Pb",
BatteryType.NIZN: "NiZn"
}
return names.get(bat_type, f"Unknown ({bat_type})")
@staticmethod
def get_run_status_name(status: int) -> str:
"""Get run status name"""
names = {
RunStatus.IDLE: "Idle",
RunStatus.RUNNING: "Running",
RunStatus.PAUSED: "Paused",
RunStatus.FINISHED: "Finished",
RunStatus.ERROR: "Error"
}
return names.get(status, f"Unknown ({status})")
# =========================================================================
# Private Methods
# =========================================================================
def _send_order(self, channel: int, operation: int, memory_slot: int, order: int) -> bool:
"""Send a control order with full parameters"""
values = [
operation, # Select operation
memory_slot, # Select memory
channel, # Select channel
ORDER_UNLOCK, # Unlock
order # Order command
]
return self.modbus.write_multiple_registers(REG_CONTROL_BASE, values)
def _unlock_and_send_order(self, channel: int, order: int) -> bool:
"""Send a simple order (stop, msgbox response, etc.)"""
# First select channel
if not self.modbus.write_multiple_registers(REG_CONTROL_BASE + 2, [channel]):
return False
time.sleep(0.05)
# Then unlock and send order
values = [ORDER_UNLOCK, order]
return self.modbus.write_multiple_registers(REG_CONTROL_BASE + 3, values)
@staticmethod
def _to_signed16(val: int) -> int:
"""Convert unsigned 16-bit to signed"""
if val >= 0x8000:
return val - 0x10000
return val
@staticmethod
def _to_signed32(val: int) -> int:
"""Convert unsigned 32-bit to signed"""
if val >= 0x80000000:
return val - 0x100000000
return val
# =============================================================================
# Quick Test
# =============================================================================
if __name__ == "__main__":
charger = ICharger('/dev/cu.usbserial-A50285BI', baudrate=115200, debug=True)
if charger.connect():
print("Connected to iCharger!")
# Read device info
info = charger.read_device_info()
if info:
print(f"\nDevice ID: 0x{info.device_id:04X}")
print(f"Serial: {info.serial_number}")
print(f"SW Version: {info.sw_version_str()}")
print(f"HW Version: {info.hw_version_str()}")
else:
print("Failed to read device info")
charger.disconnect()
else:
print("Failed to connect")