Skip to content

Commit 101d97b

Browse files
authored
Merge pull request #4 from FoamyGuy/scanning_and_mac_map
Scanning and mac map
2 parents 4488669 + 4c95b1b commit 101d97b

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

Diff for: adafruit_wiz.py

+39
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,45 @@
127127
MODE_SCENE = 2
128128

129129

130+
def scan(radio=None, timeout=3):
131+
"""
132+
Scan the network for Wiz lights
133+
134+
:param radio: The wifi radio object
135+
:param timeout: Time in seconds to wait for responses to the scan broadcast
136+
:return: List of dictionaries containing info about found lights
137+
"""
138+
if radio is None:
139+
try:
140+
import wifi
141+
except ImportError:
142+
raise RuntimeError(
143+
"Must pass radio argument during initialization for non built-in wifi."
144+
)
145+
radio = wifi.radio
146+
pool = adafruit_connection_manager.get_radio_socketpool(radio)
147+
with pool.socket(pool.AF_INET, pool.SOCK_DGRAM) as scan_socket:
148+
scan_socket.settimeout(timeout)
149+
data = json.dumps({"method": "getPilot", "params": {}})
150+
udp_message = bytes(data, "utf-8")
151+
152+
scan_socket.sendto(udp_message, ("255.255.255.255", 38899))
153+
scan_complete = False
154+
results = []
155+
while not scan_complete:
156+
try:
157+
buf = bytearray(400)
158+
data_len, (ip, port) = scan_socket.recvfrom_into(buf)
159+
resp_json = json.loads(buf.rstrip(b"\x00").decode("utf-8"))
160+
resp_json["ip"] = ip
161+
results.append(resp_json)
162+
except OSError:
163+
# timeout
164+
scan_complete = True
165+
pass
166+
return results
167+
168+
130169
class WizConnectedLight:
131170
"""
132171
Helper class to control Wiz connected light over WIFI via UDP.

Diff for: examples/wiz_scan_multiple_lights.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# SPDX-FileCopyrightText: Copyright (c) 2024 Tim Cocks for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: MIT
4+
"""
5+
Scan the network for Wiz lights. Print out the MAC addresses of any lights found.
6+
Set each light to a different random RGB color.
7+
"""
8+
9+
import random
10+
11+
import wifi
12+
13+
from adafruit_wiz import WizConnectedLight, scan
14+
15+
udp_port = 38899 # Default port is 38899
16+
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (0, 255, 255), (255, 0, 255)]
17+
mac_to_light_map = {}
18+
19+
found_lights = scan(wifi.radio, timeout=1)
20+
for light_info in found_lights:
21+
mac_to_light_map[light_info["result"]["mac"]] = WizConnectedLight(
22+
light_info["ip"], udp_port, wifi.radio
23+
)
24+
print(f"Found Light with MAC: {light_info['result']['mac']}")
25+
26+
for mac, light in mac_to_light_map.items():
27+
chosen_color = random.choice(colors)
28+
print(f"Setting light with MAC: {mac} to {chosen_color}")
29+
light.rgb_color = chosen_color

0 commit comments

Comments
 (0)