-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimport.py
More file actions
676 lines (564 loc) · 28.3 KB
/
import.py
File metadata and controls
676 lines (564 loc) · 28.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
"""
ChirpStack v4 Device Import Script
────────────────────────────────────────────────────────────────────────────────
Run interactively — no flags needed. The script will prompt for all settings
and remember previously used credentials in import_profiles.json.
python3 import.py
python3 import.py --source my_backup.json # skip file picker
"""
import argparse
import json
import os
import sys
import time
import requests
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Confirm, Prompt
from rich.table import Table
from rich import box
console = Console()
TARGET_URL = "https://chirpstack-rest-api.udp.senseering.io"
PROFILES_FILE = os.path.join(os.path.dirname(__file__), "import_profiles.json")
# ─── Saved profiles ───────────────────────────────────────────────────────────
def load_profiles() -> list[dict]:
if os.path.exists(PROFILES_FILE):
with open(PROFILES_FILE) as f:
return json.load(f)
return []
def save_profiles(profiles: list[dict]):
with open(PROFILES_FILE, "w") as f:
json.dump(profiles, f, indent=2)
def prompt_credentials() -> dict:
"""Ask for (or recall) API key + tenant ID. Returns the chosen profile dict."""
profiles = load_profiles()
if profiles:
console.print("\n[bold]Saved profiles:[/bold]")
tbl = Table(box=box.SIMPLE, show_header=True)
tbl.add_column("#", justify="right", style="dim", width=3)
tbl.add_column("Label", style="cyan")
tbl.add_column("Tenant ID", style="dim")
tbl.add_column("API key (preview)", style="dim")
for i, p in enumerate(profiles, 1):
key_preview = p["api_key"][:16] + "…"
tbl.add_row(str(i), p.get("label", "—"), p["tenant_id"], key_preview)
tbl.add_row("n", "[yellow]Enter new credentials[/yellow]", "", "")
console.print(tbl)
choices = [str(i) for i in range(1, len(profiles) + 1)] + ["n"]
answer = Prompt.ask(" Select profile", choices=choices, default="n")
if answer != "n":
return profiles[int(answer) - 1]
# New credentials
console.print()
label = Prompt.ask(" Profile label (e.g. 'staging-max')", default="unnamed")
api_key = Prompt.ask(" API key", password=False)
tenant_id = Prompt.ask(" Tenant ID")
profile = {"label": label, "api_key": api_key, "tenant_id": tenant_id}
# Avoid exact duplicates
if profile not in profiles:
profiles.append(profile)
save_profiles(profiles)
console.print(f" [dim]Profile '{label}' saved to {PROFILES_FILE}[/dim]")
return profile
# ─── API helpers ──────────────────────────────────────────────────────────────
def make_headers(api_key: str) -> dict:
return {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"Accept": "application/json",
}
def paginate(base_url: str, headers: dict, path: str, result_key: str, params: dict = None):
offset, limit = 0, 100
params = params or {}
while True:
params.update({"limit": limit, "offset": offset})
r = requests.get(f"{base_url}{path}", headers=headers, params=params)
r.raise_for_status()
data = r.json()
items = data.get(result_key, [])
if not items:
break
yield from items
total = int(data.get("totalCount", 0))
offset += len(items)
if offset >= total:
break
def fetch_applications(base_url: str, headers: dict, tenant_id: str) -> list[dict]:
return list(paginate(base_url, headers, "/api/applications", "result", {"tenantId": tenant_id}))
def fetch_device_profiles(base_url: str, headers: dict, tenant_id: str) -> list[dict]:
return list(paginate(base_url, headers, "/api/device-profiles", "result", {"tenantId": tenant_id}))
def create_device_profile(base_url: str, headers: dict, dp: dict, tenant_id: str) -> requests.Response:
# Strip source-specific fields; let the target assign a new ID
payload = {k: v for k, v in dp.items() if k not in ("id", "tenantId", "createdAt", "updatedAt")}
payload["tenantId"] = tenant_id
return requests.post(f"{base_url}/api/device-profiles", headers=headers, json={"deviceProfile": payload})
def create_device(base_url: str, headers: dict, device: dict, app_id: str, profile_id: str, extra_tags: dict = None):
dev = {
"applicationId": app_id,
"devEui": device["devEui"],
"name": device["name"],
"description": device.get("description", ""),
"isDisabled": False,
"skipFcntCheck": False,
"tags": {**(device.get("tags") or {}), **(extra_tags or {})},
}
if profile_id:
dev["deviceProfileId"] = profile_id
return requests.post(f"{base_url}/api/devices", headers=headers, json={"device": dev})
_ALL_ZERO_KEY = "0" * 32
def _clean_key(k: str) -> str:
"""Return empty string for absent or all-zero placeholder keys."""
k = (k or "").strip()
return "" if k == _ALL_ZERO_KEY else k
def set_device_keys(base_url: str, headers: dict, dev_eui: str, app_key: str, nwk_key: str):
app_key = _clean_key(app_key)
nwk_key = _clean_key(nwk_key)
effective_nwk = nwk_key or app_key
if not effective_nwk:
return None # nothing to set
payload = {
"deviceKeys": {
"devEui": dev_eui,
"nwkKey": effective_nwk,
"appKey": app_key or effective_nwk,
}
}
return requests.post(f"{base_url}/api/devices/{dev_eui}/keys", headers=headers, json=payload)
# ─── UI helpers ───────────────────────────────────────────────────────────────
def print_header():
console.print(Panel.fit(
"[bold cyan]ChirpStack v4 — Device Import Tool[/bold cyan]\n"
f"[dim]Target: [bold]{TARGET_URL}[/bold][/dim]\n"
"[dim]Dry-run by default — you will confirm before any writes.[/dim]",
border_style="cyan",
))
def pick_source_file(default: str | None) -> str:
"""Let user pick or confirm the backup JSON to import from."""
# Find all backup JSON files in the same directory
here = os.path.dirname(__file__) or "."
candidates = sorted(
f for f in os.listdir(here)
if f.endswith(".json") and "backup" in f.lower() or f == "test_backup.json"
)
if not candidates:
return default or Prompt.ask("\n Path to source JSON backup file")
console.print("\n[bold]Available backup files:[/bold]")
tbl = Table(box=box.SIMPLE, show_header=False)
tbl.add_column("#", justify="right", style="dim", width=3)
tbl.add_column("File", style="cyan")
for i, name in enumerate(candidates, 1):
tbl.add_row(str(i), name)
tbl.add_row("m", "[yellow]Enter path manually[/yellow]")
console.print(tbl)
choices = [str(i) for i in range(1, len(candidates) + 1)] + ["m"]
answer = Prompt.ask(" Select file", choices=choices, default="1")
if answer == "m":
return Prompt.ask(" Path to JSON backup")
return os.path.join(here, candidates[int(answer) - 1])
def show_source_summary(devices: list[dict]):
apps: dict[str, int] = {}
for d in devices:
apps[d["applicationName"]] = apps.get(d["applicationName"], 0) + 1
table = Table(title="Source — Applications in backup", box=box.ROUNDED, border_style="blue")
table.add_column("#", justify="right", style="dim", width=3)
table.add_column("Application", style="cyan")
table.add_column("Devices", justify="right", style="green")
for i, (app_name, count) in enumerate(sorted(apps.items()), 1):
table.add_row(str(i), app_name, str(count))
console.print(table)
return sorted(apps.keys())
def pick_source_apps(app_names: list[str]) -> list[str] | None:
"""Ask which source applications to include. None = all."""
console.print(
"\n Import [bold]all[/bold] applications, or select specific ones?\n"
" Enter comma-separated numbers (e.g. 1,3) or press Enter for all."
)
answer = Prompt.ask(" Your choice", default="all").strip()
if answer.lower() in ("", "all"):
return None
indices = [int(x.strip()) - 1 for x in answer.split(",") if x.strip().isdigit()]
chosen = [app_names[i] for i in indices if 0 <= i < len(app_names)]
return chosen or None
def _fmt_tags(tags: dict | None) -> str:
if not tags:
return "–"
return " ".join(f"{k}={v}" for k, v in tags.items())
def show_import_preview(
devices: list[dict],
app_map: dict[str, str],
app_id_to_name: dict[str, str],
profile_map: dict[str, str],
profile_id_to_name: dict[str, str],
):
table = Table(
title=f"Import Preview — {len(devices)} device(s)",
box=box.ROUNDED,
border_style="green",
show_lines=False,
)
table.add_column("#", justify="right", style="dim", width=4)
table.add_column("DevEUI", style="bold white", width=18)
table.add_column("Name", style="cyan")
table.add_column("Source App", style="yellow")
table.add_column("Target App", style="green")
table.add_column("Target Profile",style="magenta")
table.add_column("Tags", style="dim", max_width=28)
table.add_column("Key", style="dim", max_width=5)
for i, d in enumerate(devices, 1):
target_app_id = app_map.get(d["applicationName"], "")
target_app_name = app_id_to_name.get(target_app_id, "[red]UNMAPPED[/red]")
target_profile_id = profile_map.get(d.get("deviceProfileName", ""), "")
target_profile_name = profile_id_to_name.get(target_profile_id, "–") if target_profile_id else "–"
has_key = "✓" if d.get("appKey") or d.get("nwkKey") else "–"
table.add_row(
str(i),
d["devEui"],
d["name"],
d["applicationName"],
target_app_name,
target_profile_name,
_fmt_tags(d.get("tags")),
has_key,
)
console.print(table)
unmapped_app = [d for d in devices if d["applicationName"] not in app_map]
if unmapped_app:
console.print(f"[bold red]\u26a0 {len(unmapped_app)} device(s) have no target app \u2192 will be SKIPPED.[/bold red]")
unmapped_profile = [d for d in devices if d["applicationName"] in app_map and not profile_map.get(d.get("deviceProfileName", ""))]
if unmapped_profile:
console.print(
f"[bold yellow]\u26a0 {len(unmapped_profile)} device(s) have no mapped device profile \u2192 will be SKIPPED "
f"(ChirpStack requires a device profile).[/bold yellow]"
)
def prompt_extra_tags() -> dict[str, str]:
"""Ask the user for additional tags to merge onto every device being imported."""
console.print(
"\n Add extra tags to [bold]all[/bold] imported devices?\n"
" Enter as [cyan]key=value[/cyan] pairs separated by commas (e.g. [cyan]roaming_enabled=true,env=prod[/cyan])\n"
" or press Enter to skip."
)
answer = Prompt.ask(" Extra tags", default="").strip()
if not answer:
return {}
tags: dict[str, str] = {}
for part in answer.split(","):
part = part.strip()
if "=" in part:
k, _, v = part.partition("=")
tags[k.strip()] = v.strip()
elif part:
tags[part] = "true"
if tags:
console.print(" Adding tags: " + " ".join(f"[cyan]{k}={v}[/cyan]" for k, v in tags.items()))
return tags
def pick_devices_early(devices: list[dict]) -> list[dict]:
"""Show a simple numbered list and let the user pick specific devices
before connecting to the API. No target info needed here."""
tbl = Table(box=box.SIMPLE, show_header=True)
tbl.add_column("#", justify="right", style="dim", width=4)
tbl.add_column("DevEUI", style="bold white", width=18)
tbl.add_column("Name", style="cyan")
tbl.add_column("App", style="yellow")
tbl.add_column("Profile", style="magenta", max_width=22)
tbl.add_column("Tags", style="dim", max_width=28)
for i, d in enumerate(devices, 1):
tbl.add_row(
str(i),
d["devEui"],
d["name"],
d["applicationName"],
d.get("deviceProfileName", "–"),
_fmt_tags(d.get("tags")),
)
console.print(tbl)
console.print(
" Select [bold]specific rows[/bold] to import (e.g. [cyan]1,3,5[/cyan]) "
"or press Enter for [bold]all[/bold]."
)
answer = Prompt.ask(" Your choice", default="all").strip()
if answer.lower() in ("", "all"):
return devices
indices = [int(p.strip()) - 1 for p in answer.split(",") if p.strip().isdigit()]
chosen = [devices[i] for i in indices if 0 <= i < len(devices)]
if not chosen:
console.print(" [yellow]No valid rows — keeping all.[/yellow]")
return devices
console.print(f" Selected [green]{len(chosen)}[/green] device(s)")
return chosen
def build_profile_map_interactive(
source_profile_names: list[str], target_profiles: list[dict]
) -> dict[str, str]:
"""Map source device-profile names → target profile IDs.
Returns an empty dict if the user opts to skip profile mapping entirely."""
console.print("\n[bold]Map device profiles → target profiles:[/bold]")
console.print(" Press Enter to [yellow]skip profile mapping[/yellow] (devices will be created without a profile).\n")
# Auto-match by name
name_to_id = {p["name"]: p["id"] for p in target_profiles}
mapping: dict[str, str] = {}
if not target_profiles:
console.print(" [yellow]No device profiles found on target — skipping profile mapping.[/yellow]")
return mapping
tbl = Table(box=box.SIMPLE, show_header=True)
tbl.add_column("#", justify="right", style="dim", width=3)
tbl.add_column("Target profile", style="cyan")
tbl.add_column("ID", style="dim")
for i, p in enumerate(target_profiles, 1):
tbl.add_row(str(i), p["name"], p["id"])
console.print(tbl)
choices = [str(i) for i in range(1, len(target_profiles) + 1)] + ["skip"]
for src_name in source_profile_names:
# Auto-match
if src_name in name_to_id:
mapping[src_name] = name_to_id[src_name]
console.print(f" [green]Auto-matched:[/green] {src_name} → {src_name}")
continue
answer = Prompt.ask(
f" [yellow]{src_name}[/yellow] → target # (or skip)",
choices=choices, default="skip",
)
if answer != "skip":
chosen = target_profiles[int(answer) - 1]
mapping[src_name] = chosen["id"]
console.print(f" [green]→ {chosen['name']}[/green]")
else:
console.print(f" [dim]No profile set for {src_name}[/dim]")
return mapping
def build_app_map_interactive(source_app_names: list[str], target_apps: list[dict]) -> dict[str, str]:
console.print("\n[bold]Map source applications → target applications:[/bold]")
tbl = Table(box=box.SIMPLE, show_header=True)
tbl.add_column("#", justify="right", style="dim", width=3)
tbl.add_column("Target application", style="cyan")
tbl.add_column("ID", style="dim")
for i, a in enumerate(target_apps, 1):
tbl.add_row(str(i), a["name"], a["id"])
console.print(tbl)
mapping: dict[str, str] = {}
for src_app in source_app_names:
choices = [str(i) for i in range(1, len(target_apps) + 1)] + ["skip"]
answer = Prompt.ask(
f" [yellow]{src_app}[/yellow] → target #",
choices=choices, default="skip",
)
if answer == "skip":
console.print(f" [dim]Skipping {src_app}[/dim]")
else:
chosen = target_apps[int(answer) - 1]
mapping[src_app] = chosen["id"]
console.print(f" [green]→ {chosen['name']}[/green]")
return mapping
# ─── Main ─────────────────────────────────────────────────────────────────────
def parse_args():
p = argparse.ArgumentParser(description="ChirpStack v4 interactive device import tool.")
p.add_argument("--source", default=None, help="Path to device JSON backup file (skips file picker)")
p.add_argument("--profiles", default=None, help="Path to device-profiles JSON backup to import profiles only")
return p.parse_args()
def run_profile_import(source_path: str):
"""Standalone flow: import device profiles from a backup JSON."""
console.print(f"\n[bold]Loading profiles:[/bold] {source_path}")
with open(source_path) as f:
all_profiles: list[dict] = json.load(f)
console.print(f" Loaded [green]{len(all_profiles)}[/green] device profiles")
# Selection table
tbl = Table(box=box.SIMPLE, show_header=True)
tbl.add_column("#", justify="right", style="dim", width=3)
tbl.add_column("Name", style="cyan", max_width=36)
tbl.add_column("Region", style="yellow", width=8)
tbl.add_column("MAC", style="dim", max_width=18)
tbl.add_column("OTAA", style="green", width=6)
tbl.add_column("Codec", style="dim", width=6)
for i, dp in enumerate(all_profiles, 1):
tbl.add_row(
str(i),
dp.get("name", ""),
dp.get("region", ""),
dp.get("macVersion", ""),
"✓" if dp.get("supportsOtaa") else "–",
dp.get("payloadCodecRuntime", "–") or "–",
)
console.print(tbl)
console.print(
"\n Select profiles to import (e.g. [cyan]1,3[/cyan]) or press Enter for [bold]all[/bold]."
)
answer = Prompt.ask(" Your choice", default="all").strip()
if answer.lower() not in ("", "all"):
indices = [int(x.strip()) - 1 for x in answer.split(",") if x.strip().isdigit()]
all_profiles = [all_profiles[i] for i in indices if 0 <= i < len(all_profiles)]
console.print(f" Selected [green]{len(all_profiles)}[/green] profile(s)")
profile = prompt_credentials()
api_key = profile["api_key"]
tenant_id = profile["tenant_id"]
headers = make_headers(api_key)
console.print(f"\n[bold]Connecting to:[/bold] {TARGET_URL} [dim](tenant {tenant_id})[/dim]")
existing = fetch_device_profiles(TARGET_URL, headers, tenant_id)
existing_names = {p["name"] for p in existing}
console.print(f" [green]{len(existing)}[/green] profiles already on target")
if not Confirm.ask(f"[bold yellow]Create {len(all_profiles)} profile(s) on {TARGET_URL}?[/bold yellow]"):
console.print("[red]Aborted.[/red]")
return
created = skipped = failed = 0
results = []
with console.status("[bold green]Importing profiles...") as status:
for dp in all_profiles:
name = dp.get("name", "?")
status.update(f"[bold green]Creating profile: {name}")
if name in existing_names:
skipped += 1
results.append({"name": name, "status": "already exists"})
continue
r = create_device_profile(TARGET_URL, headers, dp, tenant_id)
if r.status_code in (200, 201):
created += 1
new_id = r.json().get("id", "?")
results.append({"name": name, "status": f"created ({new_id})"})
else:
failed += 1
results.append({"name": name, "status": f"error {r.status_code}: {r.text[:120]}"})
time.sleep(0.05)
res_tbl = Table(title="Profile Import Results", box=box.ROUNDED)
res_tbl.add_column("Name", style="cyan")
res_tbl.add_column("Status", style="green")
for row in results:
s = row["status"]
color = "green" if s.startswith("created") else ("yellow" if "exists" in s else "red")
res_tbl.add_row(row["name"], f"[{color}]{s}[/{color}]")
console.print(res_tbl)
console.print(
f"\n[bold]Done.[/bold] Created: [green]{created}[/green] "
f"Already existed: [yellow]{skipped}[/yellow] "
f"Failed: [red]{failed}[/red]"
)
def main():
args = parse_args()
print_header()
# ── Profile-only mode ─────────────────────────────────────────────────────
if args.profiles:
run_profile_import(args.profiles)
sys.exit(0)
# ── Source file ───────────────────────────────────────────────────────────
source_path = args.source or pick_source_file(None)
console.print(f"\n[bold]Loading:[/bold] {source_path}")
with open(source_path) as f:
all_devices: list[dict] = json.load(f)
console.print(f" Loaded [green]{len(all_devices)}[/green] devices")
app_names = show_source_summary(all_devices)
# ── Filter source apps ────────────────────────────────────────────────────
selected_apps = pick_source_apps(app_names)
if selected_apps:
all_devices = [d for d in all_devices if d["applicationName"] in selected_apps]
console.print(f" Filtered to [green]{len(all_devices)}[/green] devices")
if not all_devices:
console.print("[red]No devices selected. Exiting.[/red]")
sys.exit(0)
# ── Early device selection ────────────────────────────────────────────────
all_devices = pick_devices_early(all_devices)
if not all_devices:
console.print("[red]No devices selected. Exiting.[/red]")
sys.exit(0)
# ── Extra tags ────────────────────────────────────────────────────────────
extra_tags = prompt_extra_tags()
# ── Credentials ───────────────────────────────────────────────────────────
profile = prompt_credentials()
api_key = profile["api_key"]
tenant_id = profile["tenant_id"]
headers = make_headers(api_key)
console.print(f"\n[bold]Connecting to:[/bold] {TARGET_URL} [dim](tenant {tenant_id})[/dim]")
try:
target_apps = fetch_applications(TARGET_URL, headers, tenant_id)
target_profiles = fetch_device_profiles(TARGET_URL, headers, tenant_id)
except requests.HTTPError as e:
console.print(f"[red]Connection failed: {e}[/red]")
sys.exit(1)
console.print(
f" [green]{len(target_apps)}[/green] applications, "
f"[green]{len(target_profiles)}[/green] device profiles found on target"
)
app_id_to_name = {a["id"]: a["name"] for a in target_apps}
# ── Map apps ──────────────────────────────────────────────────────────────
source_app_names = sorted(set(d["applicationName"] for d in all_devices))
if len(target_apps) == 1:
# Only one target app — use it automatically
app_map = {name: target_apps[0]["id"] for name in source_app_names}
console.print(f" Auto-selected only target app: [green]{target_apps[0]['name']}[/green]")
else:
app_map = build_app_map_interactive(source_app_names, target_apps)
# ── Map device profiles ───────────────────────────────────────────────────
source_profile_names = sorted(set(d.get("deviceProfileName", "") for d in all_devices if d.get("deviceProfileName")))
profile_map = build_profile_map_interactive(source_profile_names, target_profiles)
profile_id_to_name = {p["id"]: p["name"] for p in target_profiles}
# ── Preview ───────────────────────────────────────────────────────────────
# Only devices with both app and profile mapped can be created
importable = [
d for d in all_devices
if d["applicationName"] in app_map
and profile_map.get(d.get("deviceProfileName", ""))
]
console.print()
show_import_preview(all_devices, app_map, app_id_to_name, profile_map, profile_id_to_name)
if not importable:
console.print("[red]Nothing to import (check app & profile mapping).[/red]")
sys.exit(0)
console.print(f"\n[bold]Summary:[/bold]")
console.print(f" Devices to import : [green]{len(importable)}[/green]")
console.print(f" Devices skipped : [yellow]{len(all_devices) - len(importable)}[/yellow]")
# ── Confirm & execute ─────────────────────────────────────────────────────
console.print()
confirmed = Confirm.ask(
f"[bold yellow]Create {len(importable)} device(s) on {TARGET_URL}?[/bold yellow]"
)
if not confirmed:
console.print("[red]Aborted — no changes made.[/red]")
sys.exit(0)
created = skipped = failed = 0
results: list[dict] = []
with console.status("[bold green]Importing devices...") as status:
for i, device in enumerate(importable, 1):
status.update(f"[bold green]Importing {i}/{len(importable)}: {device['name']}")
app_id = app_map[device["applicationName"]]
dev_eui = device["devEui"]
profile_id = profile_map.get(device.get("deviceProfileName", ""), "")
r = create_device(TARGET_URL, headers, device, app_id, profile_id, extra_tags)
if r.status_code in (200, 201):
key_status = ""
kr = set_device_keys(
TARGET_URL, headers, dev_eui,
device.get("appKey", ""), device.get("nwkKey", "")
)
if kr is not None and kr.status_code not in (200, 201):
key_status = f" (key error {kr.status_code}: {kr.text[:120]})"
created += 1
results.append({"devEui": dev_eui, "name": device["name"], "status": f"created{key_status}"})
elif r.status_code == 409:
skipped += 1
results.append({"devEui": dev_eui, "name": device["name"], "status": "already exists"})
else:
failed += 1
results.append({"devEui": dev_eui, "name": device["name"], "status": f"error {r.status_code}: {r.text[:200]}"})
time.sleep(0.05)
# ── Results ───────────────────────────────────────────────────────────────
res_table = Table(title="Import Results", box=box.ROUNDED)
res_table.add_column("DevEUI", style="white")
res_table.add_column("Name", style="cyan")
res_table.add_column("Status", style="green")
for row in results:
s = row["status"]
if s == "created":
color = "green"
elif "created" in s: # created with key warning
color = "yellow"
elif "exists" in s:
color = "yellow"
else:
color = "red"
res_table.add_row(row["devEui"], row["name"], f"[{color}]{s}[/{color}]")
console.print(res_table)
console.print(
f"\n[bold]Done.[/bold] Created: [green]{created}[/green] "
f"Already existed: [yellow]{skipped}[/yellow] "
f"Failed: [red]{failed}[/red]"
)
log_file = "import_results.json"
with open(log_file, "w") as f:
json.dump(results, f, indent=2)
console.print(f"[dim]Results log saved: {log_file}[/dim]")
if __name__ == "__main__":
main()