pcs_client_save_data_v16_ES100CX12S
Created on Tue Nov 4 07:09:22 2025
@author: anura
append_alarm_from_entry_values(entry: dict, regs: dict, *, alarm_json_path: str = PCS_ALARM_CODE_PATH, default_display_name: str = 'Alarm', default_severity: str = 'warning', default_data_type: str = 'BITMAP32', default_registers: int = 2, debug: bool | None = None) -> bool
Builds a single alarm object from fields already present in entry and appends it as entry["alarm"].
Returns True if an alarm was appended; False otherwise.
Source code in EMS_template_codes/pcs_client_save_data_v16_ES100CX12S.py
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 | def append_alarm_from_entry_values(
entry: dict,
regs: dict,
*,
alarm_json_path: str = PCS_ALARM_CODE_PATH, # updated default path
default_display_name: str = "Alarm",
default_severity: str = "warning",
default_data_type: str = "BITMAP32",
default_registers: int = 2,
debug: bool | None = None,
) -> bool:
"""
Builds a single alarm object from fields already present in `entry` and appends it as entry["alarm"].
Returns True if an alarm was appended; False otherwise.
"""
if debug is None:
debug = DEBUG
debug_dump_alarm_fields(entry)
# try common keys
code_key_candidates = ["pcs_alarm_code", "alarm_code", "pcs_alarms"]
code_key = next((k for k in code_key_candidates if k in entry), None)
alarm_code = entry.get(code_key) if code_key else None
if debug:
print(f"[DEBUG] alarm_code search keys: {code_key_candidates}")
print(f"[DEBUG] resolved code_key: {code_key!r}, value: {alarm_code!r}")
if alarm_code is None or (isinstance(alarm_code, str) and not alarm_code.strip()):
if debug:
print("[DEBUG] No alarm_code present in entry; skip alarm append.")
return False
if isinstance(alarm_code, (int, float)):
alarm_code = str(int(alarm_code))
else:
alarm_code = str(alarm_code).strip()
# address
addr_key_candidates = ["pcs_alarm_address", "alarm_address"]
address = None
for k in addr_key_candidates:
if k in entry:
try:
address = int(entry[k])
break
except Exception:
pass
if address is None and code_key and code_key in regs:
try:
address = int(regs[code_key].get("address"))
except Exception:
address = 0
if address is None:
address = 0
# default meta
data_type = default_data_type
registers = default_registers
if code_key and code_key in regs:
meta = regs[code_key]
if isinstance(meta, dict):
dt = (meta.get("data_type") or default_data_type)
data_type = str(dt).upper()
try:
registers = int(meta.get("registers") or default_registers)
except Exception:
registers = default_registers
if debug:
print(f"[DEBUG] Using alarm_code={alarm_code}, address={address}, data_type={data_type}, registers={registers}")
# load map
try:
with open(alarm_json_path, "r", encoding="utf-8") as f:
alarm_map = json.load(f)
except Exception as e:
if debug:
print(f"[DEBUG] Unable to read '{alarm_json_path}': {e}")
return False
if not isinstance(alarm_map, dict):
if debug:
print(f"[DEBUG] Alarm map in '{alarm_json_path}' is not a dict.")
return False
raw = alarm_map.get(alarm_code)
if raw is None:
if debug:
print(f"[DEBUG] Alarm code '{alarm_code}' not found in '{alarm_json_path}'.")
return False
if isinstance(raw, dict):
message = raw.get("message") or ""
alarm_display_name = raw.get("alarm_display_name") or default_display_name
severity = (raw.get("severity") or default_severity).lower()
else:
message = str(raw)
alarm_display_name = default_display_name
severity = default_severity
alarm_obj = {
"active": True,
"alarm_display_name": alarm_display_name,
"alarm_code": alarm_code,
"severity": severity,
"message": message,
"acknowledged": "false",
"address": int(address),
"data_type": data_type,
"registers": int(registers),
}
entry["alarm"] = alarm_obj
if debug:
print(f"[DEBUG] set alarm object: {alarm_obj}")
return True
|
get_enabled_pcs_list(max_pcs: int = 12) -> list[str]
Returns enabled pcs IDs in order: ["pcs1","pcs2",...]
Uses your existing is_pcs_enabled() logic.
Source code in EMS_template_codes/pcs_client_save_data_v16_ES100CX12S.py
611
612
613
614
615
616
617
618
619
620
621 | def get_enabled_pcs_list(max_pcs: int = 12) -> list[str]:
"""
Returns enabled pcs IDs in order: ["pcs1","pcs2",...]
Uses your existing is_pcs_enabled() logic.
"""
enabled = []
for i in range(1, max_pcs + 1):
pid = f"pcs{i}"
if is_pcs_enabled(pid):
enabled.append(pid)
return enabled
|
insert_pcs_data(_buffer, table_name: str | None = None)
Insert PCS data into MariaDB.
- v2: supports table_name (pcs1..pcs12)
- v1: legacy fallback (single table)
Source code in EMS_template_codes/pcs_client_save_data_v16_ES100CX12S.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92 | def insert_pcs_data(_buffer, table_name: str | None = None):
"""
Insert PCS data into MariaDB.
- v2: supports table_name (pcs1..pcs12)
- v1: legacy fallback (single table)
"""
if _insert_pcs_data is None:
if DEBUG:
print("[DEBUG] MariaDB insert module unavailable; skipping DB insert.")
return
try:
if table_name:
return _insert_pcs_data(_buffer, table_name=table_name)
return _insert_pcs_data(_buffer)
except TypeError:
# Legacy v1 without table_name support
if DEBUG:
print("[DEBUG] Using legacy mariadb_insert_v1 (no table_name support)")
return _insert_pcs_data(_buffer)
|
is_pcs_enabled(pcs_id: str | None = None) -> bool
Enable/disable PCS polling.
Priority (highest → lowest):
1) cfg["pcsM_"] e.g. pcsM_pcs2
2) cfg["pcsM"][<n>] e.g. pcsM["2"] or pcsM[2] or pcsM["pcs2"]
3) cfg["pcsM"] (bool) legacy global switch
4) default True
Source code in EMS_template_codes/pcs_client_save_data_v16_ES100CX12S.py
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 | def is_pcs_enabled(pcs_id: str | None = None) -> bool:
"""
Enable/disable PCS polling.
Priority (highest → lowest):
1) cfg["pcsM_<pcs_id>"] e.g. pcsM_pcs2
2) cfg["pcsM"][<n>] e.g. pcsM["2"] or pcsM[2] or pcsM["pcs2"]
3) cfg["pcsM"] (bool) legacy global switch
4) default True
"""
pcs_id = (pcs_id or globals().get("PCS_ID", "pcs1")).strip().lower()
if not pcs_id.startswith("pcs"):
pcs_id = "pcs" + pcs_id
# numeric index (pcs2 -> 2)
try:
pcs_n = int(pcs_id.replace("pcs", ""))
except Exception:
pcs_n = None
try:
with open(EMS_CONFIG_PATH, "r", encoding="utf-8") as f:
cfg = json.load(f)
# 1) pcsM_pcs2 style
key1 = f"pcsM_{pcs_id}"
if key1 in cfg:
return bool(cfg.get(key1))
# 2) pcsM as dict/list style
pcsM = cfg.get("pcsM", True)
# if pcsM is a dict: {"pcs2": true} or {"2": true} etc
if isinstance(pcsM, dict):
if pcs_id in pcsM:
return bool(pcsM.get(pcs_id))
if pcs_n is not None and str(pcs_n) in pcsM:
return bool(pcsM.get(str(pcs_n)))
if pcs_n is not None and pcs_n in pcsM:
return bool(pcsM.get(pcs_n))
# fallback if dict doesn't include this pcs -> default True
return True
# if pcsM is a list: [true, true, false, ...] index 0 => pcs1
if isinstance(pcsM, list) and pcs_n is not None:
idx = pcs_n - 1
if 0 <= idx < len(pcsM):
return bool(pcsM[idx])
return True
# 3) legacy bool
return bool(pcsM)
except Exception as e:
print(f"[WARNING] Failed to load EMS config: {e}")
return True
|
load_modbus_config()
Read IP/port and pacing from the PCS Modbus config.
Source code in EMS_template_codes/pcs_client_save_data_v16_ES100CX12S.py
187
188
189
190
191
192
193
194
195
196
197
198 | def load_modbus_config():
"""
Read IP/port and pacing from the PCS Modbus config.
"""
with open(PCS_MODBUS_CONFIG_PATH, "r") as f:
cfg = json.load(f)
ip = cfg.get("ip", "127.0.0.1")
port = int(cfg.get("port", 1501))
# pacing
polling_interval_ms = int(cfg.get("poll_interval_ms", 1000))
saving_interval_s = int(max(1, cfg.get("save_interval_ms", 3000)) / 1000)
return ip, port, polling_interval_ms, saving_interval_s
|
load_pcs_registers()
Returns:
| Name | Type |
Description |
name_to_meta |
|
dict[str, dict] mapping 'pcs_' -> {
"address": int,
"data_type": "FLOAT32"|"INT32U"|"BITMAP32",
"registers": int
|
|
|
|
endianness |
|
|
Supports category-based BESS register format, with optional read_batches[].endianness.
Source code in EMS_template_codes/pcs_client_save_data_v16_ES100CX12S.py
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 | def load_pcs_registers():
"""
Returns:
name_to_meta: dict[str, dict] mapping 'pcs_<name>' -> {
"address": int,
"data_type": "FLOAT32"|"INT32U"|"BITMAP32",
"registers": int
}
endianness: "big" or "little"
Supports category-based BESS register format, with optional read_batches[].endianness.
"""
with open(PCS_REGISTER_PATH, "r") as f:
data = json.load(f)
# Endianness from optional read_batches[0].endianness
endianness = "big"
if isinstance(data, dict) and "read_batches" in data:
batches = data.get("read_batches") or []
if batches and isinstance(batches[0], dict):
endianness = (batches[0].get("endianness") or "big").lower()
name_to_meta = {}
if "categories" in data and isinstance(data["categories"], dict):
cats = data["categories"]
for _cat, cat in cats.items():
for section in ("read_only", "read_write"):
entries = cat.get(section, {})
for name, meta in entries.items():
if not isinstance(meta, dict):
continue
if "address" not in meta:
continue
try:
addr = int(meta.get("address"))
except Exception:
continue
dt = (meta.get("data_type") or "FLOAT32").upper()
regs = int(meta.get("registers") or 2)
name_to_meta[f"pcs_{name}"] = {
"address": addr,
"data_type": dt,
"registers": regs
}
else:
# Flat style fallback: keys like "active_power_register": 21021
for key, addr in data.items():
if key.endswith("_register") and isinstance(addr, int):
base = key[:-len("_register")]
name_to_meta[f"pcs_{base}"] = {
"address": int(addr),
"data_type": "FLOAT32",
"registers": 2
}
if not name_to_meta:
raise ValueError("No registers found in PCS register map (categories.* or '*_register' expected)")
return name_to_meta, endianness
|
set_paths_for_pcs(pcs_id: str)
Sets the same globals you currently set in parse_args_and_set_debug(),
but for a given pcs_id (pcs1..pcs12).
Returns (PCS_BASE_DIR, PCS_REGISTER_PATH, PCS_MODBUS_CONFIG_PATH, PCS_ALARM_CODE_PATH, DATA_DIR, LAST_VALUE_FILE)
Source code in EMS_template_codes/pcs_client_save_data_v16_ES100CX12S.py
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643 | def set_paths_for_pcs(pcs_id: str):
"""
Sets the same globals you currently set in parse_args_and_set_debug(),
but for a given pcs_id (pcs1..pcs12).
Returns (PCS_BASE_DIR, PCS_REGISTER_PATH, PCS_MODBUS_CONFIG_PATH, PCS_ALARM_CODE_PATH, DATA_DIR, LAST_VALUE_FILE)
"""
pcs_id = pcs_id.strip().lower()
if not pcs_id.startswith("pcs"):
pcs_id = "pcs" + pcs_id
base_dir = os.path.join("emsConfig/pcs", pcs_id)
reg_path = os.path.join(base_dir, "pcs_register_full.json")
mod_path = os.path.join(base_dir, "pcs_modbus_config.json")
alarm_path = os.path.join(base_dir, "pcs_alarm_code.json")
data_dir = os.path.join("pcsData", pcs_id)
os.makedirs(data_dir, exist_ok=True)
last_file = os.path.join(LAST_VALUE_DIR, f"{pcs_id}_lastValue.json")
return base_dir, reg_path, mod_path, alarm_path, data_dir, last_file
|
🔁 Simulation Flow
flowchart TD
A[Start main()] --> B[...]
⚙️ Flow with Conditional Checks
flowchart TD
A[Start main()] --> B{Check something?}
B -- Yes --> C[Do X]
B -- No --> D[Exit]
Register scaling
Every stored value is converted with the scale that applies to its register:
value = raw * (node["scale"] if "scale" in node else device.scale)
A scale declared on the register node wins over the device scale. Declare
scale: 1 on a node when its unit differs from the device default - for example SOC
and SOH are whole percent while PCS power uses the device scale of 0.1 (kW).
Omitting the device scale entirely defaults it to 1.0.