@jessicaisleep/dsh-mihome 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +141 -78
  2. package/client.js +1149 -19
  3. package/cordis.patch.yml +2 -2
  4. package/docs/REPAIR-VALIDATION.md +62 -0
  5. package/lib/bridge.js +126 -44
  6. package/lib/connections.js +46 -0
  7. package/lib/format.js +148 -0
  8. package/lib/index.js +274 -31
  9. package/lib/panel.js +138 -7
  10. package/locale/en.json +3 -3
  11. package/locale/zh.json +2 -2
  12. package/package.json +13 -4
  13. package/python/app/core/service.py +62 -31
  14. package/python/mihome_bridge.py +211 -9
  15. package/python/smart_home/__init__.py +24 -0
  16. package/python/smart_home/adapters/__init__.py +50 -0
  17. package/python/smart_home/adapters/base.py +143 -0
  18. package/python/smart_home/adapters/ble.py +100 -0
  19. package/python/smart_home/adapters/dlna.py +227 -0
  20. package/python/smart_home/adapters/home_assistant.py +454 -0
  21. package/python/smart_home/adapters/hue.py +225 -0
  22. package/python/smart_home/adapters/kasa.py +239 -0
  23. package/python/smart_home/adapters/mihome.py +342 -0
  24. package/python/smart_home/adapters/network.py +250 -0
  25. package/python/smart_home/adapters/shelly.py +289 -0
  26. package/python/smart_home/adapters/tuya.py +95 -0
  27. package/python/smart_home/adapters/tv.py +26 -0
  28. package/python/smart_home/catalog.py +336 -0
  29. package/python/smart_home/cloud.py +85 -0
  30. package/python/smart_home/discovery.py +934 -0
  31. package/python/smart_home/localize.py +787 -0
  32. package/python/smart_home/manager.py +672 -0
  33. package/python/smart_home/oui_table.py +40550 -0
  34. package/python/smart_home/scan.py +73 -0
  35. package/python/smart_home/test_discovery_repairs.py +186 -0
  36. package/python/smart_home/test_localization_repairs.py +229 -0
  37. package/python/smart_home/test_offline.py +195 -0
  38. package/python/smart_home/test_repairs.py +107 -0
  39. package/python/smart_home/util.py +320 -0
  40. package/python/tests/test_bridge_integration.py +108 -0
  41. package/python/tests/test_ha_discovery.py +260 -0
  42. package/python/tests/test_home_assistant.py +365 -0
  43. package/python/tests/test_manager_integration.py +150 -0
  44. package/python/tests/test_mihome_repairs.py +117 -0
  45. package/python/tests/test_network_read_contract.py +50 -0
  46. package/python/tests/test_power_confirmation.py +95 -0
  47. package/python/tests/test_protocol_repairs.py +369 -0
  48. package/python/tests/test_yeelight_repairs.py +70 -0
  49. package/requirements-optional.txt +4 -0
  50. package/requirements.txt +5 -0
  51. package/scripts/update-oui.py +108 -0
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env python
2
+ # SPDX-License-Identifier: GPL-3.0-or-later
3
+ """全屋扫描 CLI。
4
+
5
+ 独立运行,便于排查「插件扫不到设备」的问题:
6
+
7
+ .venv\\Scripts\\python.exe python\\smart_home\\scan.py
8
+ .venv\\Scripts\\python.exe python\\smart_home\\scan.py --subnet 192.168.1.0/24 --json
9
+
10
+ 输出每台设备的协议、类别、地址、端口与指纹,不连接云端。
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import asyncio
17
+ import json
18
+ import os
19
+ import sys
20
+ from pathlib import Path
21
+
22
+ _HERE = Path(__file__).resolve().parent
23
+ if str(_HERE.parent) not in sys.path:
24
+ sys.path.insert(0, str(_HERE.parent))
25
+
26
+
27
+ async def _run(args) -> int:
28
+ from smart_home import discovery
29
+
30
+ extra = []
31
+ if args.subnet:
32
+ extra.append(args.subnet)
33
+ devices = await discovery.discover_all(
34
+ subnets=[args.subnet] if args.subnet else None,
35
+ prefix=args.prefix,
36
+ extra_subnets=extra,
37
+ ports=args.ports,
38
+ scan_ping=not args.no_ping,
39
+ )
40
+ payload = [d.to_dict() for d in devices]
41
+ if args.json:
42
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
43
+ else:
44
+ if not payload:
45
+ print("没有发现设备。")
46
+ for device in payload:
47
+ print(
48
+ f"{device['ip'] or device['mac']:<18} {device['protocol']:<12} "
49
+ f"{device['category']:<16} {device['name'] or '-':<24} "
50
+ f"ports={device['ports']} mac={device['mac'] or '-'}"
51
+ )
52
+ print(f"\n共 {len(payload)} 台。")
53
+ return 0
54
+
55
+
56
+ def main() -> int:
57
+ parser = argparse.ArgumentParser(description="dsh-mihome 全屋设备扫描")
58
+ parser.add_argument("--subnet", help="要扫描的子网,如 192.168.1.0/24(默认扫描本机所有 /24)")
59
+ parser.add_argument("--prefix", type=int, default=24, help="子网前缀,默认 24")
60
+ parser.add_argument("--json", action="store_true", help="输出 JSON")
61
+ parser.add_argument("--no-ping", action="store_true", help="跳过 ping 扫描(只依赖 ARP)")
62
+ parser.add_argument("--ports", help="逗号分隔的端口列表,默认使用内置常见端口")
63
+ args = parser.parse_args()
64
+ if args.ports:
65
+ args.ports = [int(x) for x in args.ports.split(",") if x.strip().isdigit()]
66
+ else:
67
+ args.ports = None
68
+ os.environ.setdefault("PYTHONIOENCODING", "utf-8")
69
+ return asyncio.run(_run(args))
70
+
71
+
72
+ if __name__ == "__main__":
73
+ sys.exit(main())
@@ -0,0 +1,186 @@
1
+ #!/usr/bin/env python
2
+ """离线发现层回归;所有网络边界均为假实现。"""
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import sys
7
+ import types
8
+ from pathlib import Path
9
+ from unittest.mock import patch
10
+
11
+ HERE = Path(__file__).resolve().parent
12
+ if str(HERE.parent) not in sys.path:
13
+ sys.path.insert(0, str(HERE.parent))
14
+
15
+ from smart_home import discovery
16
+ from smart_home.adapters import ble
17
+
18
+
19
+ class FakeDevice:
20
+ def __init__(self, address, name="BLE watch", uuids=None):
21
+ self.address = address
22
+ self.name = name
23
+ self.uuids = uuids or ["180f"]
24
+
25
+
26
+ class FakeAdvertisement:
27
+ def __init__(self, rssi=-42, service_uuids=None, local_name=""):
28
+ self.rssi = rssi
29
+ self.service_uuids = service_uuids or ["180f"]
30
+ self.local_name = local_name
31
+
32
+
33
+ class FakeScanner:
34
+ @staticmethod
35
+ async def discover(**_kwargs):
36
+ return {
37
+ "AA:BB:CC:00:00:01": (FakeDevice("AA:BB:CC:00:00:01"), FakeAdvertisement()),
38
+ "AA:BB:CC:00:00:02": (FakeDevice("AA:BB:CC:00:00:02", "BLE lock"), FakeAdvertisement(-55)),
39
+ }
40
+
41
+
42
+ async def test_ble_return_adv_dict_is_supported():
43
+ fake_bleak = types.SimpleNamespace(BleakScanner=FakeScanner)
44
+ with patch.dict(sys.modules, {"bleak": fake_bleak}):
45
+ found = await ble.ble_scan(timeout=0.01)
46
+ assert {item["address"] for item in found} == {
47
+ "AA:BB:CC:00:00:01", "AA:BB:CC:00:00:02"
48
+ }, found
49
+ assert found[0]["rssi"] == -42, found
50
+ assert found[0]["uuids"] == ["180f"], found
51
+
52
+
53
+ async def test_mdns_uses_service_browser_and_resolved_ip():
54
+ class FakeInfo:
55
+ server = "cast.local."
56
+ name = "Living Room._googlecast._tcp.local."
57
+ properties = {b"model": b"Nest Audio", b"fn": b"Living Room"}
58
+
59
+ def parsed_addresses(self):
60
+ return ["192.0.2.55"]
61
+
62
+ class FakeAsyncZeroconf:
63
+ created = 0
64
+ closed = 0
65
+ def __init__(self, **_kwargs):
66
+ type(self).created += 1
67
+ self.zeroconf = object()
68
+
69
+ async def async_get_service_info(self, type_, name, timeout=3000):
70
+ assert type_ == "_googlecast._tcp.local."
71
+ assert name.endswith("._googlecast._tcp.local.")
72
+ assert timeout >= 100
73
+ return FakeInfo()
74
+
75
+ async def async_close(self):
76
+ type(self).closed += 1
77
+
78
+ class FakeBrowser:
79
+ def __init__(self, _zc, service_type, listener=None, **_kwargs):
80
+ self.listener = listener
81
+ if service_type == "_googlecast._tcp.local." and listener is not None:
82
+ listener.add_service(_zc, service_type, "Living Room._googlecast._tcp.local.")
83
+
84
+ async def async_cancel(self):
85
+ return None
86
+
87
+ fake_zeroconf = types.SimpleNamespace(
88
+ IPVersion=types.SimpleNamespace(V4Only="v4"),
89
+ InterfaceChoice=types.SimpleNamespace(All="all"),
90
+ )
91
+ fake_asyncio = types.SimpleNamespace(
92
+ AsyncZeroconf=FakeAsyncZeroconf,
93
+ AsyncServiceBrowser=FakeBrowser,
94
+ )
95
+ with patch.dict(sys.modules, {
96
+ "zeroconf": fake_zeroconf,
97
+ "zeroconf.asyncio": fake_asyncio,
98
+ }):
99
+ found = await discovery.mdns_discover(timeout=0.25)
100
+ assert found == [{
101
+ "ip": "192.0.2.55",
102
+ "service": "_googlecast._tcp.local",
103
+ "name": "Living Room._googlecast._tcp.local.",
104
+ "model": "Nest Audio",
105
+ }], found
106
+ assert FakeAsyncZeroconf.created == FakeAsyncZeroconf.closed == 1
107
+
108
+
109
+ def test_scanned_device_never_serializes_credentials():
110
+ device = discovery.ScannedDevice(
111
+ ip="192.0.2.5", protocol="tuya", requires_credentials=True,
112
+ credentials={"local_key": "must-not-leak"},
113
+ fields={"device_id": "gw-1", "nested": {"password": "no", "safe": "yes"}},
114
+ )
115
+ public = device.to_dict()
116
+ assert public["requires_credentials"] is True
117
+ assert "local_key" not in repr(public)
118
+ assert "password" not in repr(public)
119
+ assert public["fields"]["nested"] == {"safe": "yes"}
120
+
121
+
122
+ async def test_discover_all_parses_string_lists():
123
+ calls = []
124
+
125
+ async def fake_scan(subnet, **kwargs):
126
+ calls.append((subnet, kwargs))
127
+ return []
128
+
129
+ with patch.object(discovery, "scan_subnet", fake_scan), \
130
+ patch.object(discovery.util, "local_subnets", return_value=[]):
131
+ await discovery.discover_all(
132
+ subnets="192.0.2.0/24, 198.51.100.0/24",
133
+ prefix="24",
134
+ extra_subnets="203.0.113.0/24",
135
+ ports="80,443",
136
+ scan_ping="false",
137
+ )
138
+ assert [item[0] for item in calls] == ["192.0.2.0/24", "198.51.100.0/24"], calls
139
+ assert calls[0][1]["ports"] == [80, 443], calls
140
+ assert calls[0][1]["scan_ping"] is False, calls
141
+
142
+
143
+ async def test_scan_keeps_broadcast_and_ble_when_no_tcp_candidates():
144
+ async def fake_extra(_subnet):
145
+ return [{"ip": "", "address": "AA:BB:CC:00:00:09", "protocol": "ble"}]
146
+
147
+ with patch.object(discovery.util, "arp_table", return_value={}), \
148
+ patch.object(discovery.util, "ping_sweep", return_value=[]), \
149
+ patch.object(discovery, "_extra_discovery", fake_extra):
150
+ found = await discovery.scan_subnet("192.0.2.0/30", ports=[80], scan_ping=True)
151
+ assert any(device.fields.get("address") == "AA:BB:CC:00:00:09" for device in found), found
152
+
153
+
154
+ async def test_scan_merges_protocol_and_keeps_online_unknown():
155
+ async def fake_ports(*_args):
156
+ return []
157
+
158
+ async def fake_extra(_subnet):
159
+ return [{"ip": "192.0.2.1", "protocol": "tuya", "category": "plug",
160
+ "confidence": 0.9, "gw_id": "gw-1", "version": "3.3",
161
+ "local_key": "private-value", "source": "tuya-udp"}]
162
+
163
+ with patch.object(discovery.util, "arp_table", return_value={"192.0.2.1": "00:11:22:33:44:55", "192.0.2.2": ""}), \
164
+ patch.object(discovery.util, "scan_ports", fake_ports), \
165
+ patch.object(discovery, "_extra_discovery", fake_extra):
166
+ found = await discovery.scan_subnet("192.0.2.0/24", ports=[80], scan_ping=False)
167
+ assert len(found) == 2, found
168
+ target = next(d for d in found if d.ip == "192.0.2.1")
169
+ assert target.protocol == "tuya" and target.category == "plug", target
170
+ assert target.fields["gw_id"] == "gw-1" and target.fields["version"] == "3.3", target
171
+ assert target.credentials["local_key"] == "private-value"
172
+ assert "private-value" not in repr(target.to_dict())
173
+
174
+
175
+ async def main():
176
+ test_scanned_device_never_serializes_credentials()
177
+ await test_ble_return_adv_dict_is_supported()
178
+ await test_mdns_uses_service_browser_and_resolved_ip()
179
+ await test_discover_all_parses_string_lists()
180
+ await test_scan_keeps_broadcast_and_ble_when_no_tcp_candidates()
181
+ await test_scan_merges_protocol_and_keeps_online_unknown()
182
+ print("discovery repair tests passed")
183
+
184
+
185
+ if __name__ == "__main__":
186
+ asyncio.run(main())
@@ -0,0 +1,229 @@
1
+ #!/usr/bin/env python
2
+ # SPDX-License-Identifier: GPL-3.0-or-later
3
+ """Offline regressions for interface parsing, translation, classification and IEEE OUI.
4
+
5
+ Run: .venv\\Scripts\\python.exe -B python/smart_home/test_localization_repairs.py
6
+ All fixtures are synthetic; no discovery or device/network calls are made.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import copy
11
+ import hashlib
12
+ import importlib.util
13
+ import sys
14
+ import tempfile
15
+ import unittest
16
+ from pathlib import Path
17
+ from unittest.mock import patch
18
+
19
+ HERE = Path(__file__).resolve().parent
20
+ sys.path.insert(0, str(HERE.parent))
21
+ from smart_home import catalog, localize, util
22
+
23
+
24
+ class InterfaceAddressTests(unittest.TestCase):
25
+ def addresses(self, output):
26
+ # UDP source-address selection and command execution are the only external edges.
27
+ with patch.object(util.socket, "socket", side_effect=OSError), patch.object(util, "_run", return_value=output):
28
+ return util.own_ipv4_addresses()
29
+
30
+ def test_windows_only_interface_fields_are_addresses(self):
31
+ output = """
32
+ IPv4 Address. . . . . . . . . . . : 192.0.2.10(Preferred)
33
+ Subnet Mask . . . . . . . . . . . : 255.255.255.0
34
+ Default Gateway . . . . . . . . . : 192.0.2.1
35
+ DNS Servers . . . . . . . . . . . : 8.8.8.8
36
+ 1.1.1.1
37
+ IPv4 地址 . . . . . . . . . . . . : 198.51.100.9(首选)
38
+ 子网掩码 . . . . . . . . . . . . : 255.255.0.0
39
+ """
40
+ self.assertEqual(self.addresses(output), ["192.0.2.10", "198.51.100.9"])
41
+
42
+ def test_linux_excludes_broadcast_and_invalid_addresses(self):
43
+ output = """
44
+ 2: eth0: <BROADCAST,MULTICAST,UP>
45
+ inet 192.0.2.25/24 brd 192.0.2.255 scope global eth0
46
+ inet 127.0.0.2/8 scope host lo
47
+ inet 169.254.3.4/16 scope link eth1
48
+ inet 0.0.0.0/0 scope global eth2
49
+ inet 224.0.0.1/4 scope global eth3
50
+ inet 999.0.0.1/24 scope global eth4
51
+ """
52
+ self.assertEqual(self.addresses(output), ["192.0.2.25"])
53
+
54
+
55
+ class CategoryTests(unittest.TestCase):
56
+ def test_explicit_network_switch_beats_electrical_switch(self):
57
+ for text in ("network switch", "Ethernet switch", "managed switch", "Gigabit PoE switch", "交换机"):
58
+ with self.subTest(text=text):
59
+ self.assertEqual(catalog.guess_category(text), "net_switch")
60
+
61
+ def test_electrical_and_word_boundaries_are_preserved(self):
62
+ for text, expected in (("wall switch", "switch"), ("smart switch", "switch"), ("开关", "switch"),
63
+ ('<meta content="font-family">', "other"), ("ONT GPON", "onu")):
64
+ with self.subTest(text=text):
65
+ self.assertEqual(catalog.guess_category(text), expected)
66
+
67
+
68
+ class TranslationTests(unittest.TestCase):
69
+ def sample(self):
70
+ return {
71
+ "props": [{"name": "mode", "type": "uint8", "readable": True, "writable": True,
72
+ "range": [0, 4, 1], "value_list": [
73
+ {"value": 0, "description": "Auto", "extra": {"unit": "raw"}},
74
+ {"value": 1, "description": "Cool"},
75
+ {"value": "1", "description": "自定义模式"},
76
+ ]}],
77
+ "actions": [{"name": "start", "in": [1], "desc": "开始清扫"}],
78
+ }
79
+
80
+ def test_device_localization_does_not_mutate_input(self):
81
+ source = self.sample()
82
+ before = copy.deepcopy(source)
83
+ result = localize.localize_device(source, "mihome")
84
+ self.assertEqual(source, before)
85
+ result["props"][0]["value_list"][0]["extra"]["unit"] = "changed"
86
+ self.assertEqual(source, before)
87
+
88
+ def test_device_localization_is_idempotent_and_preserves_enum_values(self):
89
+ once = localize.localize_device(self.sample(), "mihome")
90
+ self.assertEqual(localize.localize_device(once, "mihome"), once)
91
+ enums = once["props"][0]["value_list"]
92
+ self.assertEqual([e["value"] for e in enums], [0, 1, "1"])
93
+ self.assertEqual([type(e["value"]) for e in enums], [int, int, str])
94
+ self.assertEqual([e["zh"] for e in enums], ["自动", "制冷", "自定义模式"])
95
+ self.assertEqual(enums[0]["description"], "Auto")
96
+ self.assertEqual(once["props"][0]["range"], [0, 4, 1])
97
+
98
+ def test_scalar_enum_translation_preserves_wire_types(self):
99
+ values = [0, 1, "0", "1", True, False]
100
+ translated = localize.translate_value_list(values, "mode")
101
+ self.assertEqual([entry["value"] for entry in translated], values)
102
+ self.assertEqual([type(entry["value"]) for entry in translated], [int, int, str, str, bool, bool])
103
+ self.assertEqual([entry["zh"] for entry in translated], ["0", "1", "0", "1", "开", "关"])
104
+
105
+ def test_boolean_numeric_translation_requires_context(self):
106
+ self.assertEqual(localize.translate_value(0, "mode"), "0")
107
+ self.assertEqual(localize.translate_value(1, "mode"), "1")
108
+ self.assertEqual(localize.translate_value("false", "mode"), "false")
109
+ self.assertEqual(localize.translate_value(0, "power"), "关")
110
+ self.assertEqual(localize.translate_value(True), "开")
111
+
112
+ def test_official_description_and_generic_fallback_are_reached(self):
113
+ result = localize.localize_device({"props": [
114
+ {"name": "power", "desc": "实际耗电功率"},
115
+ {"name": "wifi_signal"}, {"name": "color-temperature"},
116
+ {"name": "target-temperature"},
117
+ ]}, "mihome")
118
+ self.assertEqual([p["zh"] for p in result["props"]],
119
+ ["实际耗电功率", "无线 信号", "色温", "设定温度"])
120
+ self.assertEqual(localize.translate_name("unknown", "厂家中文名称"), "厂家中文名称")
121
+ self.assertEqual(localize.translate_name("targetTemperature"), "目标温度")
122
+ self.assertEqual(localize.translate_name("unrecognisedThing"), "unrecognisedThing")
123
+
124
+ def test_controls_normalize_common_schema_without_discarding_specs(self):
125
+ controls = [
126
+ {"key": "color_temp", "name": "color-temperature", "type": "uint16", "kind": "range",
127
+ "range": [1700, 6500, 1], "unit": "K", "writable": True, "readable": False,
128
+ "vendor": {"siid": 2, "piid": 3}},
129
+ {"key": "mode", "kind": "enum", "values": [{"value": 1, "description": "Auto"}], "writable": False},
130
+ {"name": "brightness", "kind": "range", "min": 1, "max": 1000, "step": 1},
131
+ {"name": "wifi_signal", "type": "int8", "readable": True},
132
+ ]
133
+ before = copy.deepcopy(controls)
134
+ out = localize.localize_controls(controls, "mihome")
135
+ self.assertEqual(controls, before)
136
+ for entry in out:
137
+ self.assertTrue({"key", "name", "kind", "range", "value_list", "writable"} <= entry.keys())
138
+ self.assertEqual(out[0]["range"], [1700, 6500, 1])
139
+ self.assertEqual(out[0]["unit"], "K")
140
+ self.assertIs(out[0]["readable"], False)
141
+ self.assertEqual(out[0]["vendor"], {"siid": 2, "piid": 3})
142
+ self.assertEqual(out[1]["name"], "mode")
143
+ self.assertEqual(out[1]["value_list"][0]["value"], 1)
144
+ self.assertEqual(out[1]["value_list"][0]["zh"], "自动")
145
+ self.assertIs(out[1]["writable"], False)
146
+ self.assertEqual(out[2]["range"], [1, 1000, 1])
147
+ self.assertIs(out[2]["writable"], False)
148
+ self.assertEqual(out[3]["zh"], "无线 信号")
149
+ self.assertEqual(localize.localize_controls(out, "mihome"), out)
150
+ out[0]["vendor"]["siid"] = 99
151
+ self.assertEqual(controls, before)
152
+
153
+
154
+ class OuiTests(unittest.TestCase):
155
+ def test_audited_prefixes_use_ieee_organizations(self):
156
+ expected = {
157
+ "000862": "NEC Eluminant Technologies, Inc.", "0016E8": "Lumissil Microsystems",
158
+ "0022FE": "Advanced Illumination", "00234F": "Luminous Power Technologies Pvt. Ltd.",
159
+ "18C23C": "Lumi United Technology Co., Ltd", "284992": "Luminator Technology Group Global LLC",
160
+ "284D92": "Luminator Technology Group Global LLC", "3042A1": "ilumisys Inc. DBA Toggled",
161
+ "54EF44": "Lumi United Technology Co., Ltd", "80435E": "Luminys Systems Corporation",
162
+ "84F883": "Luminar Technologies", "AC40B5": "Lumiva Inc.", "B461FF": "Lumigon A/S",
163
+ "D0699E": "LUMINEX Lighting Control Equipment", "E85D6B": "Luminate Wireless",
164
+ }
165
+ for prefix, organization in expected.items():
166
+ with self.subTest(prefix=prefix):
167
+ self.assertEqual(util.mac_vendor(prefix + "000001"), organization)
168
+
169
+ def test_mac_lookup_rejects_non_global_or_incomplete_addresses(self):
170
+ for mac in ("000862", "00:08:62:00:00", "00:08:62:00:00:GG", "00:08-62:00:00:01",
171
+ "00:08:62:00:00:01:02", "FF:FF:FF:FF:FF:FF", "02:08:62:00:00:01",
172
+ "01:08:62:00:00:01", "00:00:00:00:00:00"):
173
+ with self.subTest(mac=mac):
174
+ self.assertEqual(util.mac_vendor(mac), "")
175
+ for mac in ("00:08:62:00:00:01", "00-08-62-00-00-01", "0008.6200.0001", "000862000001"):
176
+ with self.subTest(mac=mac):
177
+ self.assertEqual(util.mac_vendor(mac), "NEC Eluminant Technologies, Inc.")
178
+
179
+ def test_generator_excludes_ambiguous_assignments_and_supports_csv(self):
180
+ script = HERE.parent.parent / "scripts" / "update-oui.py"
181
+ spec = importlib.util.spec_from_file_location("update_oui_ambiguity_test", script)
182
+ module = importlib.util.module_from_spec(spec)
183
+ spec.loader.exec_module(module)
184
+ raw = ("Registry,Assignment,Organization Name,Organization Address\n"
185
+ 'MA-L,000862,"NEC Eluminant Technologies, Inc.",US\n'
186
+ "MA-L,080030,NETWORK RESEARCH CORPORATION,US\n"
187
+ "MA-L,080030,CERN,CH\n"
188
+ "MA-S,ABCDEF,Outside this registry,US\n").encode()
189
+ with tempfile.TemporaryDirectory() as tmp:
190
+ source, output = Path(tmp) / "oui.csv", Path(tmp) / "table.py"
191
+ source.write_bytes(raw)
192
+ self.assertEqual(module.main(["--input", str(source), "--output", str(output),
193
+ "--snapshot-date", "2026-11-22", "--sha256", hashlib.sha256(raw).hexdigest()]), 0)
194
+ namespace = {}
195
+ exec(compile(output.read_bytes(), str(output), "exec"), namespace)
196
+ self.assertEqual(namespace["OUI_TABLE"], {"000862": "NEC Eluminant Technologies, Inc."})
197
+ self.assertEqual(namespace["AMBIGUOUS_ASSIGNMENTS"], {"080030": ["CERN", "NETWORK RESEARCH CORPORATION"]})
198
+
199
+ def test_generator_reproduces_real_names_and_rejects_unverified_source(self):
200
+ script = HERE.parent.parent / "scripts" / "update-oui.py"
201
+ self.assertTrue(script.is_file(), "a reproducible generator must ship with the table")
202
+ spec = importlib.util.spec_from_file_location("update_oui_test", script)
203
+ module = importlib.util.module_from_spec(spec)
204
+ spec.loader.exec_module(module)
205
+ raw = ("OUI/MA-L Organization\n"
206
+ "00-08-62 (hex)\tNEC Eluminant Technologies, Inc.\r\n"
207
+ "000862 (base 16)\tNEC Eluminant Technologies, Inc.\r\n"
208
+ "0016E8 (base 16)\tLumissil Microsystems\r\n"
209
+ "000862 (base 16)\tNEC Eluminant Technologies, Inc.\r\n").encode()
210
+ with tempfile.TemporaryDirectory() as tmp:
211
+ source, output = Path(tmp) / "ieee.txt", Path(tmp) / "table.py"
212
+ source.write_bytes(raw)
213
+ args = ["--input", str(source), "--output", str(output), "--snapshot-date", "2026-11-22",
214
+ "--sha256", hashlib.sha256(raw).hexdigest()]
215
+ self.assertEqual(module.main(args), 0)
216
+ namespace = {}
217
+ first = output.read_bytes()
218
+ exec(compile(first, str(output), "exec"), namespace)
219
+ self.assertEqual(namespace["OUI_TABLE"], {"000862": "NEC Eluminant Technologies, Inc.", "0016E8": "Lumissil Microsystems"})
220
+ self.assertEqual(namespace["SOURCE_SHA256"], hashlib.sha256(raw).hexdigest())
221
+ self.assertEqual(module.main(args), 0)
222
+ self.assertEqual(output.read_bytes(), first)
223
+ with self.assertRaises(ValueError):
224
+ module.main(args[:-1] + ["0" * 64])
225
+ self.assertEqual(output.read_bytes(), first)
226
+
227
+
228
+ if __name__ == "__main__":
229
+ unittest.main(verbosity=2)