-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathcp.py
More file actions
4479 lines (3743 loc) · 149 KB
/
Copy pathcp.py
File metadata and controls
4479 lines (3743 loc) · 149 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
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
"""
NCOS Communication Module (cp) (2026) - Cradlepoint SDK
A clean, module-level interface for communicating with NCOS routers.
Import and use directly without instantiation:
import cp
cp.log('Hello')
data = cp.get('status/system/uptime')
cp.alert('Something happened')
cp.register('put', 'control/my/path', my_callback)
Features:
- Router config store communication (get/put/post/delete/patch/decrypt)
- Syslog logging that works correctly on router, in containers, and locally
- NCM alerts
- Event registration and callbacks
- Appdata management
- Device info helpers (GPS, WAN, LAN, WLAN, GPIO, etc.)
- Diagnostic tools (ping, traceroute, CLI execution)
- WAN profile management
- Signal strength monitoring
Copyright (c) 2026 Ericsson Enterprise Wireless Solutions <www.cradlepoint.com>.
All rights reserved.
"""
import base64
import configparser
import hashlib
import hmac
import json
import logging
import logging.handlers
import os
import re
import select
import signal as signal_module
import socket
import string
import sys
import threading
import time
import traceback as traceback_module
import urllib.parse
import urllib.request
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
try:
import requests
except ImportError:
requests = None
# =============================================================================
# INTERNAL: Environment Detection & Configuration
# =============================================================================
def _detect_ncos() -> bool:
"""Detect if running on an NCOS router by checking for cs.sock.
Returns:
bool: True if cs.sock is reachable (running on NCOS), False otherwise.
"""
try:
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
sock.settimeout(2.0)
sock.connect('/var/tmp/cs.sock')
return True
except Exception:
return False
def _get_app_name() -> str:
"""Get app name from the first section of package.ini.
Returns:
str: App name from package.ini, or 'SDK' if not found.
"""
try:
script_dir = os.path.dirname(os.path.abspath(__file__))
ini_path = os.path.join(script_dir, 'package.ini')
if os.path.exists(ini_path):
config = configparser.ConfigParser()
config.read(ini_path)
sections = config.sections()
if sections:
return sections[0]
except Exception:
pass
return 'SDK'
# Module-level state
_app_name = _get_app_name()
_is_ncos = _detect_ncos()
_enable_logging = '/mnt/sdk/' in os.getcwd()
_logger = None
# Initialize logger for syslog on router
if _is_ncos and _enable_logging:
_handlers = [logging.handlers.SysLogHandler(address='/dev/log')]
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s %(name)s: %(message)s',
datefmt='%b %d %H:%M:%S',
handlers=_handlers
)
_logger = logging.getLogger(_app_name)
# Suppress noisy urllib3 logging
logging.getLogger('urllib3.connectionpool').setLevel(logging.WARNING)
# =============================================================================
# INTERNAL: Socket Communication (Router)
# =============================================================================
_END_OF_HEADER = b"\r\n\r\n"
_STATUS_HEADER_RE = re.compile(rb"status: \w*")
_CONTENT_LENGTH_HEADER_RE = re.compile(rb"content-length: \w*")
_MAX_PACKET_SIZE = 8192
_RECV_TIMEOUT = 2.0
def _sock_receive(sock: socket.socket) -> Optional[Dict[str, Any]]:
"""Receive and parse a response from the config store socket.
Returns:
Optional[Dict[str, Any]]: Dict with keys:
- status (str): Response status ('ok', 'error', 'timeout').
- data (Any): Parsed JSON body or stripped string.
"""
sock.settimeout(_RECV_TIMEOUT)
data = b""
eoh = -1
while eoh < 0:
try:
buf = sock.recv(_MAX_PACKET_SIZE)
except socket.timeout:
return {"status": "timeout", "data": None}
if not buf:
break
data += buf
eoh = data.find(_END_OF_HEADER)
if eoh < 0:
return {"status": "error", "data": None}
status_match = _STATUS_HEADER_RE.search(data)
content_len_match = _CONTENT_LENGTH_HEADER_RE.search(data)
if not status_match or not content_len_match:
return {"status": "error", "data": None}
status_hdr = status_match.group(0)[8:]
content_len = int(content_len_match.group(0)[16:])
remaining = content_len - (len(data) - eoh - len(_END_OF_HEADER))
while remaining > 0:
buf = sock.recv(_MAX_PACKET_SIZE)
if not buf:
break
data += buf
remaining -= len(buf)
body = data[eoh:].decode()
try:
result = json.loads(body)
except (json.JSONDecodeError, ValueError):
result = body.strip()
return {"status": status_hdr.decode(), "data": result}
def _dispatch(cmd: str) -> Optional[Dict[str, Any]]:
"""Send a command to the router config store and return the response.
Returns:
Optional[Dict[str, Any]]: Dict with keys:
- status (str): Response status ('ok', 'error', 'timeout').
- data (Any): Parsed response body.
Returns None on socket/connection failure.
"""
try:
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
sock.connect('/var/tmp/cs.sock')
sock.sendall(cmd.encode('ascii'))
return _sock_receive(sock)
except Exception as e:
log(f"Dispatch error: {e}")
return None
# =============================================================================
# INTERNAL: Remote HTTP Communication (Development)
# =============================================================================
_cached_device_ip = None
_cached_username = None
_cached_password = None
_cached_auth = None
def _get_credentials() -> Tuple[str, str, str]:
"""Load and cache device credentials from sdk_settings.ini.
Returns:
Tuple[str, str, str]: (device_ip, username, password) from
sdk_settings.ini. Empty strings if not found.
"""
global _cached_device_ip, _cached_username, _cached_password
if _cached_device_ip is not None:
return _cached_device_ip, _cached_username, _cached_password
try:
parent_ini = os.path.join(os.path.dirname(os.getcwd()), 'sdk_settings.ini')
current_ini = os.path.join(os.getcwd(), 'sdk_settings.ini')
if os.path.exists(parent_ini):
ini_path = parent_ini
elif os.path.exists(current_ini):
ini_path = current_ini
else:
ini_path = parent_ini
config = configparser.ConfigParser()
config.read(ini_path)
sdk = config['sdk'] if 'sdk' in config else {}
_cached_device_ip = sdk.get('dev_client_ip', '')
_cached_username = sdk.get('dev_client_username', '')
_cached_password = sdk.get('dev_client_password', '')
except Exception as e:
log(f"Error reading sdk_settings.ini: {e}")
_cached_device_ip = ''
_cached_username = ''
_cached_password = ''
return _cached_device_ip, _cached_username, _cached_password
def _get_auth():
"""Get the appropriate HTTP auth object (Basic or Digest) for the device.
Returns:
Auth object (HTTPBasicAuth or HTTPDigestAuth) for requests,
or None if the requests library is unavailable.
"""
global _cached_auth
if _cached_auth is not None:
return _cached_auth
if requests is None:
return None
device_ip, username, password = _get_credentials()
# Try Basic auth first (NCOS 6.5+)
try:
url = f'http://{device_ip}/api/status/product_info'
resp = requests.get(url, auth=requests.auth.HTTPBasicAuth(username, password))
if resp.status_code == 200:
_cached_auth = requests.auth.HTTPBasicAuth(username, password)
return _cached_auth
except Exception:
pass
_cached_auth = requests.auth.HTTPDigestAuth(username, password)
return _cached_auth
# =============================================================================
# CORE API: Logging, Alerts, CRUD Operations
# =============================================================================
def log(value: str = '') -> None:
"""Log a message to syslog (router), stdout (container), or console (local).
Args:
value: Message to log.
"""
if _enable_logging and _logger:
_logger.info(value)
elif _is_ncos:
try:
with open('/dev/stdout', 'w') as f:
f.write(f'{value}\n')
except Exception:
print(value)
else:
print(value)
def alert(value: str = '') -> Optional[Dict[str, Any]]:
"""Send a custom alert to NCM. Only works on the router.
Args:
value: Alert message text.
Returns:
Optional[Dict[str, Any]]: On router, dict with keys:
- status (str): 'ok' or 'error'.
- data (Any): Response payload.
Returns None when running locally.
"""
if _is_ncos:
cmd = f"alert\n{_app_name}\n{value}\n"
return _dispatch(cmd)
else:
log(f'Alert (local only): {value}')
return None
def get(base: str, query: str = '', tree: int = 0) -> Any:
"""GET data from the router config/status tree.
Args:
base: Path to resource (e.g. 'status/system/uptime').
query: Optional query string.
tree: Tree identifier (default 0).
Returns:
The data at the specified path, or None on failure.
"""
if _is_ncos:
cmd = f"get\n{base}\n{query}\n{tree}\n"
result = _dispatch(cmd)
if result:
return result.get('data')
return None
else:
if requests is None:
log("requests library not available for remote access")
return None
device_ip, _, _ = _get_credentials()
url = f'http://{device_ip}/api/{base}/{query}'
try:
resp = requests.get(url, auth=_get_auth())
return json.loads(resp.text).get('data')
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
log(f"Timeout: device at {device_ip} did not respond.")
return None
except Exception as e:
log(f"GET error: {e}")
return None
def put(base: str, value: Any = '', query: str = '', tree: int = 0) -> Optional[Dict[str, Any]]:
"""PUT (update) data in the router config/status tree.
Args:
base: Path to resource.
value: Value to set (will be JSON-serialized).
query: Optional query string.
tree: Tree identifier (default 0).
Returns:
Optional[Dict[str, Any]]: Dict with keys:
- status (str): 'ok' or 'error'.
- data (Any): Response payload from config store.
Returns None on connection/timeout failure.
"""
value_json = json.dumps(value)
if _is_ncos:
cmd = f"put\n{base}\n{query}\n{tree}\n{value_json}\n"
return _dispatch(cmd)
else:
if requests is None:
return None
device_ip, _, _ = _get_credentials()
url = f'http://{device_ip}/api/{base}/{query}'
try:
resp = requests.put(
url,
headers={"Content-Type": "application/x-www-form-urlencoded"},
auth=_get_auth(),
data={"data": value_json}
)
return json.loads(resp.text)
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
log(f"Timeout: device at {device_ip} did not respond.")
return None
except Exception as e:
log(f"PUT error: {e}")
return None
def post(base: str, value: Any = '', query: str = '') -> Optional[Dict[str, Any]]:
"""POST (create) data in the router config/status tree.
Args:
base: Path to resource.
value: Value to post (will be JSON-serialized).
query: Optional query string.
Returns:
Optional[Dict[str, Any]]: Dict with keys:
- status (str): 'ok' or 'error'.
- data (Any): Response payload (often the created resource ID).
Returns None on connection/timeout failure.
"""
value_json = json.dumps(value)
if _is_ncos:
cmd = f"post\n{base}\n{query}\n{value_json}\n"
return _dispatch(cmd)
else:
if requests is None:
return None
device_ip, _, _ = _get_credentials()
url = f'http://{device_ip}/api/{base}/{query}'
try:
resp = requests.post(
url,
headers={"Content-Type": "application/x-www-form-urlencoded"},
auth=_get_auth(),
data={"data": value_json}
)
return json.loads(resp.text)
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
log(f"Timeout: device at {device_ip} did not respond.")
return None
except Exception as e:
log(f"POST error: {e}")
return None
def patch(value: List[Any]) -> Optional[Dict[str, Any]]:
"""PATCH the router config tree (bulk add/remove).
Args:
value: List containing [adds_dict, removals_list].
Returns:
Optional[Dict[str, Any]]: Dict with keys:
- status (str): 'ok' or 'error'.
- data (Any): Response payload.
Returns None on connection/timeout failure.
"""
if _is_ncos:
if value[0].get("config"):
adds = value[0]
else:
adds = {"config": value[0]}
adds_json = json.dumps(adds)
removals_json = json.dumps(value[1])
cmd = f"patch\n{adds_json}\n{removals_json}\n"
return _dispatch(cmd)
else:
if requests is None:
return None
device_ip, _, _ = _get_credentials()
url = f'http://{device_ip}/api/'
try:
resp = requests.patch(
url,
headers={"Content-Type": "application/x-www-form-urlencoded"},
auth=_get_auth(),
data={"data": json.dumps(value)}
)
return json.loads(resp.text)
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
log(f"Timeout: device at {device_ip} did not respond.")
return None
except Exception as e:
log(f"PATCH error: {e}")
return None
def delete(base: str, query: str = '') -> Optional[Dict[str, Any]]:
"""DELETE data from the router config tree.
Args:
base: Path to resource.
query: Optional query string.
Returns:
Optional[Dict[str, Any]]: Dict with keys:
- status (str): 'ok' or 'error'.
- data (Any): Response payload.
Returns None on connection/timeout failure.
"""
if _is_ncos:
cmd = f"delete\n{base}\n{query}\n"
return _dispatch(cmd)
else:
if requests is None:
return None
device_ip, _, _ = _get_credentials()
url = f'http://{device_ip}/api/{base}/{query}'
try:
resp = requests.delete(
url,
headers={"Content-Type": "application/x-www-form-urlencoded"},
auth=_get_auth(),
data={"data": base}
)
return json.loads(resp.text)
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
log(f"Timeout: device at {device_ip} did not respond.")
return None
except Exception as e:
log(f"DELETE error: {e}")
return None
def decrypt(base: str, query: str = '', tree: int = 0) -> Any:
"""Decrypt and retrieve encrypted data from the router. Only works on router.
Args:
base: Path to encrypted resource.
query: Optional query string.
tree: Tree identifier (default 0).
Returns:
Decrypted data, or None if running locally or on failure.
"""
if _is_ncos:
cmd = f"decrypt\n{base}\n{query}\n{tree}\n"
result = _dispatch(cmd)
if result:
return result.get('data')
return None
else:
log('Decrypt is only available when running on NCOS.')
return None
# =============================================================================
# CORE API: Event Registration & Callbacks
# =============================================================================
_event_running = False
_event_sock = None
_event_file = None
_event_thread = None
_registry = {} # type: Dict[int, Dict[str, Any]]
_next_eid = 1
_event_lock = threading.Lock()
def _start_event_loop() -> None:
"""Start the background event handling loop (internal)."""
global _event_running, _event_sock, _event_file, _event_thread
if _event_running:
return
if not _is_ncos:
log('Event registration is only available on NCOS.')
return
try:
pid = os.getpid()
_event_file = f'/var/tmp/csevent_{pid}.sock'
try:
os.unlink(_event_file)
except FileNotFoundError:
pass
_event_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
_event_sock.bind(_event_file)
_event_sock.listen()
_event_sock.setblocking(False)
_event_running = True
_event_thread = threading.Thread(target=_handle_events, daemon=True)
_event_thread.start()
except Exception as e:
log(f"Error starting event loop: {e}")
_event_running = False
def _stop_event_loop() -> None:
"""Stop the event loop and unregister all callbacks (internal)."""
global _event_running, _event_sock, _event_file
if not _event_running:
return
try:
# Unregister all
for eid in list(_registry.keys()):
unregister(eid)
_event_sock.close()
os.unlink(_event_file)
except Exception as e:
log(f"Error stopping event loop: {e}")
finally:
_event_running = False
def _handle_events() -> None:
"""Background thread: poll for config store events and dispatch callbacks."""
poller = select.poll()
poller.register(_event_sock, select.POLLIN | select.POLLERR | select.POLLHUP)
while _event_running:
try:
events = poller.poll(1000)
for fd, ev in events:
if ev & (select.POLLERR | select.POLLHUP):
log("Event socket hangup/error. Stopping event loop.")
_stop_event_loop()
return
if ev & select.POLLIN:
conn, _ = _event_sock.accept()
result = _sock_receive(conn)
if not result or not result.get('data'):
continue
eid = int(result['data']['id'])
with _event_lock:
entry = _registry.get(eid)
if not entry:
log(f"No registration found for eid {eid}")
continue
cb = entry['cb']
args = entry['args']
# Parse the config value
try:
cfg = json.loads(result['data']['cfg'])
except (TypeError, json.JSONDecodeError):
cfg = result['data']['cfg']
# Invoke callback
try:
cb_return = cb(result['data']['path'], cfg, args)
except Exception:
traceback_module.print_exc()
log(f"Exception in callback for eid {eid}")
cb_return = None
# For 'get' actions, send response back
if result['data'].get('action') == 'get' and cb_return is not None:
response = json.dumps(cb_return)
conn.sendall(response.encode())
except OSError as e:
if _event_running:
log(f"Event loop OSError: {e}")
break
except Exception as e:
if _event_running:
log(f"Event loop error: {e}")
def register(action: str = 'put', path: str = '', callback: Callable = None, *args: Any) -> Optional[Dict[str, Any]]:
"""Register a callback for a config store event.
The callback signature must be: callback(path, value, args)
where args is a tuple of any extra arguments passed here.
Args:
action: Event action to listen for ('put', 'get', 'set'). Use 'put' for control tree.
path: Config store path to monitor.
callback: Function to invoke when the event fires.
*args: Additional arguments passed to the callback as a tuple.
Returns:
Optional[Dict[str, Any]]: Registration result dict with keys:
- status (str): 'ok' or 'error'.
- data (Any): Response payload.
Returns None on failure or when not running on NCOS.
Example:
def on_change(path, value, args):
cp.log(f'{path} changed to {value}')
cp.register('put', 'control/myapp/trigger', on_change)
"""
global _next_eid
if not _is_ncos:
log('Event registration is only available on NCOS.')
return None
if not _event_running:
_start_event_loop()
try:
with _event_lock:
eid = _next_eid
_next_eid += 1
_registry[eid] = {'cb': callback, 'action': action, 'path': path, 'args': args}
pid = os.getpid()
cmd = f"register\n{pid}\n{eid}\n{action}\n{path}\n"
return _dispatch(cmd)
except Exception as e:
log(f"Error registering callback for {path}: {e}")
return None
# Alias for convenience
on = register
def unregister(eid: int = 0) -> Optional[Dict[str, Any]]:
"""Unregister a previously registered callback.
Args:
eid: Event ID returned implicitly during registration (stored in _registry).
Returns:
Optional[Dict[str, Any]]: Unregistration result dict with keys:
- status (str): 'ok' or 'error'.
- data (Any): Response payload.
Returns None if eid not found or event loop not running.
"""
with _event_lock:
entry = _registry.pop(eid, None)
if not entry:
return None
if _event_running:
pid = os.getpid()
cmd = f"unregister\n{pid}\n{eid}\n{entry['action']}\n{entry['path']}\n"
return _dispatch(cmd)
return None
# =============================================================================
# APPDATA: Read/Write SDK Application Data
# =============================================================================
def get_appdata(name: str = '') -> Union[Optional[str], Optional[List[Dict[str, Any]]]]:
"""Get appdata value by name, or all appdata entries if no name given.
Args:
name: Appdata field name. If empty, returns all appdata entries.
Returns:
Union[Optional[str], Optional[List[Dict[str, Any]]]]:
- If name provided: str value of the matching entry, or None.
- If name empty: list of dicts, each with keys:
- name (str): Appdata field name.
- value (str): Appdata field value.
- _id_ (str): Internal resource ID.
Returns None on error.
"""
try:
appdata = get('config/system/sdk/appdata')
if not appdata:
return None if name else []
if not name:
return appdata
return next((x["value"] for x in appdata if x["name"].lower() == name.lower()), None)
except Exception as e:
log(f"Error getting appdata '{name}': {e}")
return None
def put_appdata(name: str, value: str) -> None:
"""Set appdata value by name. Creates the entry if it doesn't exist.
Args:
name: Appdata field name.
value: Value to set (string).
"""
try:
appdata = get('config/system/sdk/appdata')
if appdata:
for item in appdata:
if item["name"] == name:
put(f'config/system/sdk/appdata/{item["_id_"]}/value', value)
return
post('config/system/sdk/appdata', {"name": name, "value": value})
except Exception as e:
log(f"Error putting appdata '{name}': {e}")
def post_appdata(name: str, value: str) -> None:
"""Create a new appdata entry (does not check for duplicates).
Args:
name: Appdata field name.
value: Value to set.
"""
try:
post('config/system/sdk/appdata', {"name": name, "value": value})
except Exception as e:
log(f"Error posting appdata '{name}': {e}")
def delete_appdata(name: str) -> None:
"""Delete an appdata entry by name.
Args:
name: Appdata field name to delete.
"""
try:
appdata = get('config/system/sdk/appdata')
if appdata:
for item in appdata:
if item["name"] == name:
delete(f'config/system/sdk/appdata/{item["_id_"]}')
return
except Exception as e:
log(f"Error deleting appdata '{name}': {e}")
# =============================================================================
# DEVICE INFO: Product, Firmware, Identifiers
# =============================================================================
def get_name() -> Optional[str]:
"""Get the device name (system_id).
Returns:
Optional[str]: Device name string, or None on error.
"""
try:
return get('config/system/system_id')
except Exception as e:
log(f"Error getting device name: {e}")
return None
def get_mac(format_with_colons: bool = False) -> Optional[str]:
"""Get the device MAC address.
Args:
format_with_colons: If True, return with colons. If False, return raw.
Returns:
Optional[str]: MAC address string (e.g. '00:30:44:1A:2B:3C' or
'0030441A2B3C'), or None if unavailable.
"""
try:
mac = get('status/product_info/mac0')
if not mac:
return None
return mac if format_with_colons else mac.replace(':', '')
except Exception as e:
log(f"Error getting MAC: {e}")
return None
def get_serial_number() -> Optional[str]:
"""Get the device serial number.
Returns:
Optional[str]: Serial number string, or None on error.
"""
try:
return get('status/product_info/manufacturing/serial_num')
except Exception as e:
log(f"Error getting serial number: {e}")
return None
def get_product_type() -> Optional[str]:
"""Get the device product name.
Returns:
Optional[str]: Product name string (e.g. 'IBR900-600M'),
or None on error.
"""
try:
return get('status/product_info/product_name')
except Exception as e:
log(f"Error getting product type: {e}")
return None
def get_firmware_version(include_build_info: bool = False) -> str:
"""Get the firmware version string.
Args:
include_build_info: Include build metadata in the string.
Returns:
Firmware version string, or 'Unknown' on error.
"""
try:
fw = get('status/fw_info')
version = f"{fw['major_version']}.{fw['minor_version']}.{fw['patch_version']}-{fw['fw_release_tag']}"
if include_build_info and fw.get('build_info'):
version += f" ({fw['build_info']})"
return version
except Exception as e:
log(f"Error getting firmware version: {e}")
return "Unknown"
def get_uptime() -> int:
"""Get router uptime in seconds.
Returns:
int: Uptime in seconds, or 0 on error.
"""
try:
return int(get('status/system/uptime'))
except Exception as e:
log(f"Error getting uptime: {e}")
return 0
def get_router_model() -> Optional[str]:
"""Get the router model (part before first dash in product name).
Returns:
Optional[str]: Model string (e.g. 'IBR900'), or None on error.
"""
try:
product = get_product_type()
if product:
return product.split('-')[0]
return None
except Exception as e:
log(f"Error getting router model: {e}")
return None
# =============================================================================
# WAIT HELPERS
# =============================================================================
def wait_for_uptime(min_uptime_seconds: int = 60) -> None:
"""Block until router uptime exceeds the specified minimum.
Args:
min_uptime_seconds: Minimum uptime to wait for (default 60).
"""
try:
current = get_uptime()
if current < min_uptime_seconds:
sleep_time = min_uptime_seconds - current
log(f"Waiting {sleep_time}s for uptime to reach {min_uptime_seconds}s")
time.sleep(sleep_time)
except Exception as e:
log(f"Error in wait_for_uptime: {e}")
def wait_for_ntp(timeout: int = 300, check_interval: int = 1) -> bool:
"""Wait until NTP synchronization is achieved.
Args:
timeout: Max seconds to wait.
check_interval: Seconds between checks.
Returns:
True if NTP synced within timeout, False otherwise.
"""
try:
start = time.time()
while time.time() - start < timeout:
sync_age = get('status/system/ntp/sync_age')
if sync_age is not None:
log(f'NTP sync achieved, sync_age: {sync_age}')
return True
time.sleep(check_interval)
log(f'NTP sync timeout after {timeout}s')
return False
except Exception as e:
log(f"Error waiting for NTP: {e}")
return False
def wait_for_wan_connection(timeout: int = 300) -> bool:
"""Wait for WAN to reach 'connected' state.
Args:
timeout: Max seconds to wait.
Returns:
True if connected within timeout, False otherwise.
"""
try:
state = get('status/wan/connection_state')
if state == 'connected':
return True
log("Waiting for WAN connection...")
end_time = time.time() + timeout
while time.time() < end_time:
state = get('status/wan/connection_state')
if state == 'connected':
log("WAN connected.")
return True
time.sleep(1)
log(f"WAN connection timeout after {timeout}s")
return False
except Exception as e:
log(f"Error waiting for WAN: {e}")
return False