-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathicharger_core.py
More file actions
251 lines (200 loc) · 7.8 KB
/
Copy pathicharger_core.py
File metadata and controls
251 lines (200 loc) · 7.8 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
"""
iCharger Core Utilities
Shared functions for reading channel data, detecting cells, and status interpretation.
"""
from typing import Optional, List, Dict, Tuple
from icharger_const import (
ADDR_CHANNEL_1, ADDR_CHANNEL_2,
CH_CURRENT, CH_OUTPUT_VOLTAGE, CH_INT_TEMP, CH_EXT_TEMP,
CH_CELL_VOLTAGE, CH_CELL_IR, CH_RUN_STATUS, CH_RUN_ERROR, CH_DIALOG_ID,
get_status_name, get_channel_base
)
def read_channel(modbus, channel: int = 0) -> Optional[Dict]:
"""
Read channel data from iCharger.
Args:
modbus: ModbusUSB instance (must be connected)
channel: 0 for Channel 1, 1 for Channel 2
Returns:
Dictionary with channel data or None on error:
- timestamp_ms: Timestamp in milliseconds
- power_mw: Power in milliwatts
- current_ma: Current in milliamps (signed, negative = discharge)
- input_v_mv: Input voltage in millivolts
- output_v_mv: Output/pack voltage in millivolts
- capacity_mah: Capacity in milliamp-hours
- int_temp: Internal temperature in °C
- ext_temp: External temperature in °C
- cells: List of 8 cell voltages in mV
"""
base = get_channel_base(channel)
# Read first 20 registers: timestamp(2), power(2), current(1), input_v(1),
# output_v(1), capacity(2), int_temp(1), ext_temp(1), cells(8)
regs = modbus.read_input_registers(base, 20)
if not regs or len(regs) < 20:
return None
# Current is signed 16-bit
current = regs[CH_CURRENT]
if current >= 0x8000:
current = current - 0x10000
return {
'timestamp_ms': regs[0] | (regs[1] << 16),
'power_mw': regs[2] | (regs[3] << 16),
'current_ma': current * 10,
'input_v_mv': regs[5] * 10,
'output_v_mv': regs[CH_OUTPUT_VOLTAGE],
'capacity_mah': regs[7] | (regs[8] << 16),
'int_temp': regs[CH_INT_TEMP] / 10.0,
'ext_temp': regs[CH_EXT_TEMP] / 10.0,
'cells': list(regs[CH_CELL_VOLTAGE:CH_CELL_VOLTAGE + 8]),
}
def read_status(modbus, channel: int = 0) -> Tuple[int, int, int]:
"""
Read run status, error code, and dialog ID.
Args:
modbus: ModbusUSB instance
channel: 0 for Channel 1, 1 for Channel 2
Returns:
Tuple of (status_code, error_code, dialog_id)
Returns (-1, 0, 0) on error.
"""
base = get_channel_base(channel)
regs = modbus.read_input_registers(base + CH_RUN_STATUS, 3)
if regs and len(regs) >= 3:
return regs[0], regs[1], regs[2]
return -1, 0, 0
def read_cell_ir(modbus, channel: int = 0) -> Optional[List[float]]:
"""
Read cell internal resistance values.
Args:
modbus: ModbusUSB instance
channel: 0 for Channel 1, 1 for Channel 2
Returns:
List of 8 IR values in milliohms, or None on error.
"""
base = get_channel_base(channel)
regs = modbus.read_input_registers(base + CH_CELL_IR, 8)
if regs and len(regs) >= 8:
return [v / 10.0 for v in regs]
return None
def detect_cells(cells: List[int], min_v: int = 2500, max_v: int = 4500) -> int:
"""
Count active cells in a cell voltage list.
Cells are counted from index 0 until a cell outside the valid range is found.
This works because iCharger reports cells in order.
Args:
cells: List of cell voltages in mV
min_v: Minimum valid cell voltage (default 2500mV = 2.5V)
max_v: Maximum valid cell voltage (default 4500mV = 4.5V)
Returns:
Number of active cells (0-8)
"""
count = 0
for v in cells:
if min_v < v < max_v:
count += 1
else:
break
return count
def get_active_cells(cells: List[int], min_v: int = 2500, max_v: int = 4500) -> List[int]:
"""
Get only the active cell voltages.
Args:
cells: List of cell voltages in mV
min_v: Minimum valid cell voltage
max_v: Maximum valid cell voltage
Returns:
List of active cell voltages
"""
count = detect_cells(cells, min_v, max_v)
return cells[:count]
def signed16(value: int) -> int:
"""Convert unsigned 16-bit to signed."""
if value >= 0x8000:
return value - 0x10000
return value
def format_cells(cells: List[int], count: Optional[int] = None) -> str:
"""
Format cell voltages for display.
Args:
cells: List of cell voltages in mV
count: Number of cells to show (auto-detect if None)
Returns:
Formatted string like "[3850, 3848, 3852, 3849]"
"""
if count is None:
count = detect_cells(cells)
return str(cells[:count])
def calculate_ir(ocv_cells: List[int], load_cells: List[int],
current_ma: int, temp_c: float = 25.0,
temp_coeff: float = 0.004) -> Dict:
"""
Calculate cell internal resistance from OCV and load measurements.
Uses Ohm's law: IR = ΔV / I
Applies temperature compensation to normalize to 25°C.
Args:
ocv_cells: Open circuit voltages in mV
load_cells: Voltages under load in mV
current_ma: Discharge current in mA (absolute value)
temp_c: Temperature during measurement in °C
temp_coeff: Temperature coefficient (default 0.4%/°C)
Returns:
Dictionary with:
- ir_raw: Raw IR values in mΩ
- ir_normalized: Temperature-compensated IR in mΩ
- ir_ratio: IR relative to average (fingerprint)
- avg_ir: Average raw IR
- temp_factor: Temperature compensation factor
"""
if len(ocv_cells) != len(load_cells) or len(ocv_cells) == 0:
return None
if current_ma <= 0:
return None
current_a = current_ma / 1000.0
# Calculate raw IR
ir_raw = []
for ocv, load in zip(ocv_cells, load_cells):
delta_v = ocv - load
ir = delta_v / current_a
ir_raw.append(ir)
avg_ir = sum(ir_raw) / len(ir_raw)
# Temperature compensation (normalize to 25°C)
temp_factor = 1 + temp_coeff * (temp_c - 25.0)
ir_normalized = [ir / temp_factor for ir in ir_raw]
# IR Ratio (fingerprint)
avg_norm = sum(ir_normalized) / len(ir_normalized)
ir_ratio = [ir / avg_norm for ir in ir_normalized]
return {
'ir_raw': ir_raw,
'ir_normalized': ir_normalized,
'ir_ratio': ir_ratio,
'avg_ir': avg_ir,
'temp_factor': temp_factor,
}
def print_ir_table(ocv_cells: List[int], load_cells: List[int],
current_ma: int, temp_c: float = 25.0):
"""
Print formatted IR calculation table.
Args:
ocv_cells: Open circuit voltages in mV
load_cells: Voltages under load in mV
current_ma: Discharge current in mA
temp_c: Temperature in °C
"""
result = calculate_ir(ocv_cells, load_cells, current_ma, temp_c)
if not result:
print("Cannot calculate IR: invalid data")
return
print(f"\n{'Cell':<6} {'OCV':>8} {'Load':>8} {'ΔV':>6} {'IR':>10}")
print("-" * 45)
for i, (ocv, load, ir) in enumerate(zip(ocv_cells, load_cells, result['ir_raw'])):
delta_v = ocv - load
print(f" {i+1:<4} {ocv:>7}mV {load:>7}mV {delta_v:>5}mV {ir:>8.1f}mΩ")
print(f"\nAverage IR: {result['avg_ir']:.1f} mΩ")
print(f"Temperature: {temp_c:.1f}°C (factor: {result['temp_factor']:.3f})")
print(f"Normalized (@25°C): {[f'{ir:.1f}' for ir in result['ir_normalized']]} mΩ")
print(f"\n🔑 IR RATIO (fingerprint):")
for i, ratio in enumerate(result['ir_ratio']):
dev = (ratio - 1) * 100
marker = " ← UNIQUE" if abs(dev) > 5 else ""
print(f" Cell {i+1}: {ratio:.3f} ({dev:+.1f}%){marker}")