Bulb discovery code in python

Hello. I tested the python library at https://github.com/skorokithakis/python-yeelight and I added options to properly call multicast. This is my code based on main.py discover_bulbs function that allows properly discover:

import socket

try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse

timeout = 4
msg = ‘M-SEARCH * HTTP/1.1\r\n ST:wifi_bulb\r\n MAN:“ssdp:discover”\r\n’

Set up UDP socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
s.settimeout(timeout)
s.sendto(msg.encode(), (‘239.255.255.250’, 1982))

bulbs = []
bulb_ips = set()
while True:
try:
data, addr = s.recvfrom(65507)
except socket.timeout:
print(“socket timeout”)
break

capabilities = dict([x.strip("\r").split(": ") for x in data.decode().split("\n") if ":" in x])
parsed_url = urlparse(capabilities["Location"])

bulb_ip = (parsed_url.hostname, parsed_url.port)
if bulb_ip in bulb_ips:
    continue

capabilities = {key: value for key, value in capabilities.items() if key.islower()}
bulbs.append({"ip": bulb_ip[0], "port": bulb_ip[1], "capabilities": capabilities})
bulb_ips.add(bulb_ip)

print(bulbs)
print(bulb_ips)

1 Like

Establishment
To introduce yeelight, you can utilize pip:

pip introduce yeelight
That is all that is expected to introduce the library.

Utilization
Most importantly, you want to find your bulb’s IP. Assuming you definitely know it, you can jump to the following area.

Finding every one of the gadgets on your organization and their abilities is simple with discover_bulbs:

from yeelight import discover_bulbs
discover_bulbs()
[{‘capacities’: {‘bright’: ‘50’,
‘color_mode’: ‘1’,
‘ct’: ‘2700’,
‘fw_ver’: ‘45’,
‘tint’: ‘359’,
‘id’: ‘0x0000000002dfb19a’,
‘model’: ‘shading’,
‘name’: ‘room’,
‘power’: ‘off’,
‘rgb’: ‘16711935’,
‘sat’: ‘100’,
‘support’: 'get_prop set_default set_power switch ’
'set_bright start_cf stop_cf set_scene cron_add ’
'cron_get cron_del set_ct_abx set_rgb set_hsv ’
‘set_adjust set_music set_name’},
‘ip’: ‘192.168.0.19’,
‘port’: 55443},
{‘capacities’: {‘bright’: ‘50’,
‘color_mode’: ‘1’,
‘ct’: ‘2700’,
‘fw_ver’: ‘45’,
‘tint’: ‘359’,
‘id’: ‘0x0000000002dfb2f1’,
‘model’: ‘shading’,
‘name’: ‘livingroom’,
‘power’: ‘off’,
‘rgb’: ‘16711935’,
‘sat’: ‘100’,
‘support’: 'get_prop set_default set_power switch ’
'set_bright start_cf stop_cf set_scene cron_add ’
'cron_get cron_del set_ct_abx set_rgb set_hsv ’
‘set_adjust set_music set_name’},
‘ip’: ‘192.168.0.23’,
‘port’: 55443}]

For More Visit: Python course in Pune