Skip to content

Commit

Permalink
Merge pull request #4 from FoamyGuy/scanning_and_mac_map
Browse files Browse the repository at this point in the history
Scanning and mac map
  • Loading branch information
FoamyGuy authored Dec 30, 2024
2 parents 4488669 + 4c95b1b commit 101d97b
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
39 changes: 39 additions & 0 deletions adafruit_wiz.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,45 @@
MODE_SCENE = 2


def scan(radio=None, timeout=3):
"""
Scan the network for Wiz lights
:param radio: The wifi radio object
:param timeout: Time in seconds to wait for responses to the scan broadcast
:return: List of dictionaries containing info about found lights
"""
if radio is None:
try:
import wifi
except ImportError:
raise RuntimeError(
"Must pass radio argument during initialization for non built-in wifi."
)
radio = wifi.radio
pool = adafruit_connection_manager.get_radio_socketpool(radio)
with pool.socket(pool.AF_INET, pool.SOCK_DGRAM) as scan_socket:
scan_socket.settimeout(timeout)
data = json.dumps({"method": "getPilot", "params": {}})
udp_message = bytes(data, "utf-8")

scan_socket.sendto(udp_message, ("255.255.255.255", 38899))
scan_complete = False
results = []
while not scan_complete:
try:
buf = bytearray(400)
data_len, (ip, port) = scan_socket.recvfrom_into(buf)
resp_json = json.loads(buf.rstrip(b"\x00").decode("utf-8"))
resp_json["ip"] = ip
results.append(resp_json)
except OSError:
# timeout
scan_complete = True
pass
return results


class WizConnectedLight:
"""
Helper class to control Wiz connected light over WIFI via UDP.
Expand Down
29 changes: 29 additions & 0 deletions examples/wiz_scan_multiple_lights.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# SPDX-FileCopyrightText: Copyright (c) 2024 Tim Cocks for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
Scan the network for Wiz lights. Print out the MAC addresses of any lights found.
Set each light to a different random RGB color.
"""

import random

import wifi

from adafruit_wiz import WizConnectedLight, scan

udp_port = 38899 # Default port is 38899
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (0, 255, 255), (255, 0, 255)]
mac_to_light_map = {}

found_lights = scan(wifi.radio, timeout=1)
for light_info in found_lights:
mac_to_light_map[light_info["result"]["mac"]] = WizConnectedLight(
light_info["ip"], udp_port, wifi.radio
)
print(f"Found Light with MAC: {light_info['result']['mac']}")

for mac, light in mac_to_light_map.items():
chosen_color = random.choice(colors)
print(f"Setting light with MAC: {mac} to {chosen_color}")
light.rgb_color = chosen_color

0 comments on commit 101d97b

Please sign in to comment.