def main(): # init logger logger = logging.getLogger('homekit-flux-led') formatter = logging.Formatter('[%(levelname)s %(asctime)s]: %(message)s') ch = logging.StreamHandler() ch.setFormatter(formatter) logger.addHandler(ch) # parse cli-arguments parser = argparse.ArgumentParser() parser.add_argument( '-v', '--verbose', help='DEBUG logging mode', action='store_true', ) args = parser.parse_args() # set loggin level if args.verbose: logger.setLevel(logging.DEBUG) logger.info('Logging level: DEBUG') else: logger.setLevel(logging.INFO) logger.info('Logging level: INFO') # scan for bulbs logger.debug('Scanning for lightbulbs') scanner = BulbScanner() scanner.scan() logger.debug(f'Found lightbulbs:') logger.debug(scanner.found_bulbs) # initialize AccessoryServer logger.debug('Create HomeKit-AccessoryServer...') driver = AccessoryDriver() bridge = Bridge(driver, 'MagicHome') logger.debug('HomeKit-AccessoryServer created successful.') for bulb in scanner.found_bulbs: # add bulbs to bridge logger bridge.add_accessory( FluxLED( driver, bulb['id'], bulb['ipaddr'], logger=logger, ), ) # add bridge to the driver driver.add_accessory(bridge) try: # start the server logger.info('Start server...') driver.start() except KeyboardInterrupt: logger.info('Stopping server...') driver.stop()
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Flux lights.""" lights = [] light_ips = [] for ipaddr, device_config in config.get(CONF_DEVICES, {}).items(): device = {} device["name"] = device_config[CONF_NAME] device["ipaddr"] = ipaddr device[CONF_PROTOCOL] = device_config.get(CONF_PROTOCOL) device[ATTR_MODE] = device_config[ATTR_MODE] device[CONF_CUSTOM_EFFECT] = device_config.get(CONF_CUSTOM_EFFECT) light = FluxLight(device) lights.append(light) light_ips.append(ipaddr) if not config.get(CONF_AUTOMATIC_ADD, False): add_entities(lights, True) return # Find the bulbs on the LAN scanner = BulbScanner() scanner.scan(timeout=10) for device in scanner.getBulbInfo(): ipaddr = device["ipaddr"] if ipaddr in light_ips: continue device["name"] = f"{device['id']} {ipaddr}" device[ATTR_MODE] = None device[CONF_PROTOCOL] = None device[CONF_CUSTOM_EFFECT] = None light = FluxLight(device) lights.append(light) add_entities(lights, True)
def scan_bulb(): scanner = BulbScanner() scanner.scan() print scanner.found_bulbs ipaddr = scanner.found_bulbs[0]['ipaddr'] return ipaddr
def main(): # Find the bulb on the LAN scanner = BulbScanner() scanner.scan(timeout=4) # Specific ID/MAC of the bulb to set bulb_info = scanner.getBulbInfoByID('ACCF235FFFFF') if bulb_info: bulb = WifiLedBulb(bulb_info['ipaddr']) color_time = 5 # seconds on each color red = (255,0,0) orange = (255,125,0) yellow = (255, 255, 0) springgreen = (125,255,0) green = (0,255,0) turquoise = (0,255,125) cyan = (0, 255, 255) ocean = (0,125,255) blue = (0,0,255) violet = (125, 0, 255) magenta = (255, 0, 255) raspberry = (255, 0, 125) colorwheel = [red, orange, yellow, springgreen, green, turquoise, cyan, ocean, blue, violet, magenta, raspberry] # use cycle() to treat the list in a circular fashion colorpool = cycle(colorwheel) # get the first color before the loop color = next(colorpool) while True: bulb.refreshState() if not bulb.isOn(): # if the bulb isn't on, don't do anything time.sleep(60) continue # set to color and wait bulb.setRgb(*color) time.sleep(color_time) #fade from color to next color next_color = next(colorpool) crossFade(bulb, color, next_color) # ready for next loop color = next_color else: print "Can't find bulb"
def discover(self, *args, **kwargs): _success = False try: LOGGER.info('Discovering MagicHome LED Controllers...') _scanner = BulbScanner() _scanner.scan(timeout=5) _devices = _scanner.getBulbInfo() LOGGER.info('%i bulbs found. Checking status and adding to ISY', len(_devices)) for d in _devices: self._addNode(d) _success = True except Exception as ex: LOGGER.error('Error running magichome discovery (%s)', str(ex)) try: _items = 0 self.discoveryTries = 0 _params = self.polyConfig['customParams'] for key,value in _params.items(): _key = key.lower() if _key.startswith('led'): _items += 1 try: if 'ip' in value and 'mac' in value: _value = json.loads(value) _ip = _value['ip'] _mac = _value['mac'].lower().replace(':','') d = {'ipaddr': _ip, 'id': _mac} self._addNode(d) except Exception as ex: LOGGER.error('Error adding node from Polyglot configuration (%s): %s', str(value), str(ex)) if _items == 0: LOGGER.info('NOTE: LED Controllers can be specified for addition even if not detected via discovery. Add a custom configuration parameter to Polyglot for each LED controller with a key starting with "LED". The value should be in the following format, note the use of double quotes: {"ip":"192.168.0.84", "mac":"F0FEAF241937"} "mac" is the MAC address without colons.') except Exception as ex: LOGGER.error('Error processing custom node addition from Polyglot configuration: %s', str(ex)) try: _params = self.polyConfig['customParams'] global UPDATE_DELAY if 'delay' in _params: UPDATE_DELAY = float(_params['delay']) else: LOGGER.info("NOTE: A delay can be specified to wait a bit for the LED controller to process commands before querying them to update the controller's state in the ISY. Defaults to %s sec.", str(UPDATE_DELAY)) except Exception as ex: LOGGER.error('Error obtaining device delay value from Polyglot configuration: %s',str(ex)) try: _params = self.polyConfig['customParams'] global QUERY_BEFORE_CMD if 'query_before_cmd' in _params: QUERY_BEFORE_CMD = bool(_params['query_before_cmd']) except Exception as ex: LOGGER.error('Error obtaining query_before_cmd flag from Polyglot configuration: %s',str(ex)) self.firstRun = False return _success
def main(): # Find the bulb on the LAN scanner = BulbScanner() scanner.scan(timeout=4) # Specific ID/MAC of the bulb to set bulb_info = scanner.getBulbInfoByID('ACCF235FFFFF') if bulb_info: bulb = WifiLedBulb(bulb_info['ipaddr']) color_time = 5 # seconds on each color red = (255, 0, 0) orange = (255, 125, 0) yellow = (255, 255, 0) springgreen = (125, 255, 0) green = (0, 255, 0) turquoise = (0, 255, 125) cyan = (0, 255, 255) ocean = (0, 125, 255) blue = (0, 0, 255) violet = (125, 0, 255) magenta = (255, 0, 255) raspberry = (255, 0, 125) colorwheel = [ red, orange, yellow, springgreen, green, turquoise, cyan, ocean, blue, violet, magenta, raspberry ] # use cycle() to treat the list in a circular fashion colorpool = cycle(colorwheel) # get the first color before the loop color = next(colorpool) while True: bulb.refreshState() # set to color and wait # (use non-persistent mode to help preserve flash) bulb.setRgb(*color, persist=False) time.sleep(color_time) #fade from color to next color next_color = next(colorpool) crossFade(bulb, color, next_color) # ready for next loop color = next_color else: print "Can't find bulb"
def __init__(self, sensorId, sensorName, macAddr): super().__init__(sensorId, sensorName) self.sensorType = "led" self.brightness = 0.0 self.macAddr = macAddr self.ledDevice = None # Find the bulb on the LAN self.scanner = BulbScanner() self.connect()
def __init__(self, bulb_map, period, fake=False): self._bulb_map = bulb_map self._period = period self._fake = fake self._thread = None self._lock = threading.Lock() self._stop = threading.Event() self._scanner = BulbScanner() self._lights = {} self._thread = threading.Thread(target=self._scan) self._thread.start()
def scan(): global choices scanner = BulbScanner() scanner.scan(timeout=4) scanner_results = [] for found_bulb in scanner.found_bulbs: print("Found a bulb: " + found_bulb['ipaddr'] + " with MAC: " + found_bulb['id']) scanner_results.append(found_bulb['ipaddr']) # Connect to the LED controller if len(scanner.found_bulbs) == 0: scanner_results.append("No controllers found :(") choices = scanner_results print(choices)
def __init__(self, mode: LEDControlMode = LEDControlMode.AUDIO_STEREO_MIX, rgb_buffer_len: int = 8, alpha_buffer_length=8, silence_buffer_length=1.5): self.mode = mode if self.mode == LEDControlMode.AUDIO_STEREO_MIX: self.controller = AudioController() self.audio_stream = AudioStream( audio_device=AudioInputDevices.STEREO_MIX, chunk=self.controller.nperseg) elif self.mode == LEDControlMode.MONITOR_COLOR: self.controller = MonitorColorController() rgb_buffer_len = 2 self.hue_buffer = deque([0 for _ in range(rgb_buffer_len)], maxlen=rgb_buffer_len) self.alpha_buffer = deque([2 for _ in range(alpha_buffer_length)], maxlen=alpha_buffer_length) self.silence_buffer = deque( [ 'music' for _ in range( int(silence_buffer_length / self.controller.nperseg * self.controller.fs)) ], maxlen=int(silence_buffer_length / self.controller.nperseg * self.controller.fs)) self.state = 'music' # scan available LED devices scanner = BulbScanner() scanner.scan(timeout=4) print("Found LED controllers:") [print(bulb) for bulb in scanner.found_bulbs] self.bulbs = [] for bulb in scanner.found_bulbs: bulb_info = scanner.getBulbInfoByID(bulb['id']) self.bulbs.append(WifiLedBulb(bulb_info['ipaddr']))
def start_pairing(self, timeout): """ Start the pairing process. timeout -- Timeout in seconds at which to quit pairing """ if self.pairing: return self.pairing = True self._add_from_config() scanner = BulbScanner() for device in scanner.scan(timeout=min(timeout, _TIMEOUT)): if not self.pairing: break self._add_device(device) self.pairing = False
def command_handler(sentence, info): scanner = BulbScanner() coms, classify = commands() msg = sentence + " is not a know flux lightbulb command" function = None print("scanner scan: ", end="") print(scanner.scan(timeout=4)) try: #specific ID/MAC of bulb my_light = scanner.getBulbInfoByID("D8F15BA2EE72") except: msg = "flux lightbulb not detected!" return msg, function print("success!") bulb = WifiLedBulb(my_light["ipaddr"]) for i in coms[0]: #lightbulb color changer res = parse(i, sentence) if res: msg, function = colorChanger(bulb, res[0]) return msg, function if sentence in coms[1]: #turn lightbulb off msg = "turning the flux lightbulb off" function = bulb.turnOff() return msg, function if sentence in coms[2]: #turn the lightbulb on msg = "turning the flux lightbulb on" function = bulb.turnOn() return msg, function for i in coms[3]: #change brightness of lightbulb res = parse(i, sentence) if res: msg, function = brightnessChanger(bulb, res[0]) return msg, function return msg, function
def __init__(self, mode: LEDControlMode = LEDControlMode.AUDIO_STEREO_MIX, rgb_buffer_len: int = 5): self.mode = mode if self.mode == LEDControlMode.AUDIO_STEREO_MIX: self.controller = AudioController() self.audio_stream = AudioStream( audio_device=AudioInputDevices.STEREO_MIX, chunk=self.controller.nperseg) elif self.mode == LEDControlMode.MONITOR_COLOR: self.controller = MonitorColorController() rgb_buffer_len = 2 self.rgb_buffer = { 'r': deque([255 for _ in range(rgb_buffer_len)], maxlen=rgb_buffer_len), 'g': deque([255 for _ in range(rgb_buffer_len)], maxlen=rgb_buffer_len), 'b': deque([255 for _ in range(rgb_buffer_len)], maxlen=rgb_buffer_len) } # scan available LED devices scanner = BulbScanner() scanner.scan(timeout=4) print("Found LED controllers:") [print(bulb) for bulb in scanner.found_bulbs] self.bulbs = [] for bulb in scanner.found_bulbs: bulb_info = scanner.getBulbInfoByID(bulb['id']) self.bulbs.append(WifiLedBulb(bulb_info['ipaddr']))
def _scan_with_timeout() -> list[dict[str, str]]: scanner = BulbScanner() discovered: list[dict[str, str]] = scanner.scan(timeout=timeout) return discovered
class Scanner(object): def __init__(self, bulb_map, period, fake=False): self._bulb_map = bulb_map self._period = period self._fake = fake self._thread = None self._lock = threading.Lock() self._stop = threading.Event() self._scanner = BulbScanner() self._lights = {} self._thread = threading.Thread(target=self._scan) self._thread.start() def stop(self): self._stop.set() self._thread.join() def lights(self): with self._lock: return self._lights def lock(self): return self._lock def _scan(self): while not self._stop.is_set(): with self._lock: new_lights = {} print('Scanning for bulbs') old_names = tuple(self._lights.keys()) found_names = [] if not self._fake: self._scanner.scan(timeout=4) for scanned in self._scanner.getBulbInfo(): bid = scanned['id'] if bid in self._bulb_map: print('Found real bulb: %s' % (self._bulb_map[bid], )) new_lights[self._bulb_map[bid]] = {'info': scanned} found_names.append(self._bulb_map[bid]) else: for i, id in enumerate(self._bulb_map): print('Found fake bulb: %s' % (self._bulb_map[id], )) new_lights[self._bulb_map[id]] = { 'info': { 'ipaddr': '10.0.0.%d' % i } } found_names.append(self._bulb_map[id]) # Clear out any bulbs that went missing for name in old_names: if name not in found_names: print('Removing missing light: ', name) for name in found_names: if name not in old_names: print('Adding new bulb: ', name) for name, l in new_lights.items(): if not l['info']: print('Did not find expected bulb', name) sys.exit(1) if not self._fake: l['bulb'] = WifiLedBulb(l['info']['ipaddr']) else: l['bulb'] = FakeBulb(name) if len(new_lights) != len(self._bulb_map): print("Warning: didn't find all the lights") self._lights = new_lights # Sleep, but keep checking for quit while we do. for i in range(0, self._period): if self._stop.is_set(): return time.sleep(1)
between. Assumes the bulb is already on. The python file with the Flux LED wrapper classes should live in the same folder as this script """ import os import sys import time from itertools import cycle this_folder = os.path.dirname(os.path.realpath(__file__)) sys.path.append(this_folder) from flux_led import WifiLedBulb, BulbScanner, LedTimer scanner = BulbScanner() scanner.scan(timeout=4) # Specific ID/MAC of the bulb to set bulb_info = scanner.getBulbInfoByID('6001948A4F89') print "bulb_info: " + str(bulb_info) bulb = WifiLedBulb(bulb_info['ipaddr']) color_time = 2 # seconds on each color red = (255, 0, 0) orange = (255, 125, 0) yellow = (255, 255, 0) springgreen = (125, 255, 0) green = (0, 255, 0)
class Led_Strip(switch_base.Switch_Base): def __init__(self, sensorId, sensorName, macAddr): super().__init__(sensorId, sensorName) self.sensorType = "led" self.brightness = 0.0 self.macAddr = macAddr self.ledDevice = None # Find the bulb on the LAN self.scanner = BulbScanner() self.connect() def connect(self): self.scanner.scan(timeout=4) # Specific ID/MAC of the bulb to set bulb_info = self.scanner.getBulbInfoByID(self.macAddr) if bulb_info: self.ledDevice = WifiLedBulb(bulb_info["ipaddr"]) self.ledDevice.refreshState() def reportBrightness(self): if self.mqttClient and self.mqttClient.is_connected(): self.mqttClient.publish( self.mqttHeader + self.sensorId + "/aux/brightness", self.brightness, qos=1, retain=True, ) def setBrightness(self, brightness): self.brightness = brightness newState = brightness > 0.0 if newState != self.state: super().setState(newState) self.reportBrightness() def setState(self, newState, retry=2): if self.ledDevice: if not newState: self.ledDevice.turnOff() self.brightness = 0.0 else: self.ledDevice.turnOn() self.state = newState self.reportState() elif retry: self.connect() self.setState(newState, retry=(retry - 1)) def init(self, mqttHeader, mqttClient): super().init(mqttHeader, mqttClient) self.reportBrightness() topic = self.mqttHeader + self.sensorId + "/aux/setBrightness" mqttClient.subscribe(topic) def on_message(client, obj, msg): try: brightness = utils.parseFloat(msg.payload) assert 0.0 <= brightness <= 1.0 except: logger.error(f"Invalid brightness value: {msg.payload}") return self.setBrightness(brightness) mqttClient.message_callback_add(topic, on_message)
def autoScan(): scanner = BulbScanner() scanner.scan(timeout=4) bulb_info = scanner.getBulbInfoByID('ACCF235FFFFF') return bulb_info
def main(): syslog.openlog(sys.argv[0]) # Change location to nearest city. location = 'San Diego' # Get the local sunset/sunrise times a = Astral() a.solar_depression = 'civil' city = a[location] timezone = city.timezone sun = city.sun(date=datetime.datetime.now(), local=True) if debug: print 'Information for {}/{}\n'.format(location, city.region) print 'Timezone: {}'.format(timezone) print 'Latitude: {:.02f}; Longitude: {:.02f}\n'.format(city.latitude, city.longitude) print('Dawn: {}'.format(sun['dawn'])) print('Sunrise: {}'.format(sun['sunrise'])) print('Noon: {}'.format(sun['noon'])) print('Sunset: {}'.format(sun['sunset'])) print('Dusk: {}'.format(sun['dusk'])) # Find the bulbs on the LAN scanner = BulbScanner() scanner.scan(timeout=4) # Specific ID/MAC of the bulbs to set porch_info = scanner.getBulbInfoByID('ACCF235FFFEE') livingroom_info = scanner.getBulbInfoByID('ACCF235FFFAA') if porch_info: bulb = WifiLedBulb(porch_info['ipaddr']) bulb.refreshState() timers = bulb.getTimers() # Set the porch bulb to turn on at dusk using timer idx 0 syslog.syslog(syslog.LOG_ALERT, "Setting porch light to turn on at {}:{:02d}".format(sun['dusk'].hour, sun['dusk'].minute)) dusk_timer = LedTimer() dusk_timer.setActive(True) dusk_timer.setRepeatMask(LedTimer.Everyday) dusk_timer.setModeWarmWhite(35) dusk_timer.setTime(sun['dusk'].hour, sun['dusk'].minute) timers[0] = dusk_timer # Set the porch bulb to turn off at dawn using timer idx 1 syslog.syslog(syslog.LOG_ALERT, "Setting porch light to turn off at {}:{:02d}".format(sun['dawn'].hour, sun['dawn'].minute)) dawn_timer = LedTimer() dawn_timer.setActive(True) dawn_timer.setRepeatMask(LedTimer.Everyday) dawn_timer.setModeTurnOff() dawn_timer.setTime(sun['dawn'].hour, sun['dawn'].minute) timers[1] = dawn_timer bulb.sendTimers(timers) else: print "Can't find porch bulb" if livingroom_info: bulb = WifiLedBulb(livingroom_info['ipaddr']) bulb.refreshState() timers = bulb.getTimers() # Set the living room bulb to turn on at sunset using timer idx 0 syslog.syslog(syslog.LOG_ALERT, "Setting LR light to turn on at {}:{:02d}".format(sun['sunset'].hour, sun['sunset'].minute)) sunset_timer = LedTimer() sunset_timer.setActive(True) sunset_timer.setRepeatMask(LedTimer.Everyday) sunset_timer.setModeWarmWhite(50) sunset_timer.setTime(sun['sunset'].hour, sun['sunset'].minute) timers[0] = sunset_timer # Set the living room bulb to turn off at a fixed time off_timer = LedTimer() off_timer.setActive(True) off_timer.setRepeatMask(LedTimer.Everyday) off_timer.setModeTurnOff() off_timer.setTime(23,30) timers[1] = off_timer bulb.sendTimers(timers) else: print "Can't find living room bulb"
def main(): syslog.openlog(sys.argv[0]) # Change location to nearest city. location = 'San Diego' # Get the local sunset/sunrise times a = Astral() a.solar_depression = 'civil' city = a[location] timezone = city.timezone sun = city.sun(date=datetime.datetime.now(), local=True) if debug: print 'Information for {}/{}\n'.format(location, city.region) print 'Timezone: {}'.format(timezone) print 'Latitude: {:.02f}; Longitude: {:.02f}\n'.format( city.latitude, city.longitude) print('Dawn: {}'.format(sun['dawn'])) print('Sunrise: {}'.format(sun['sunrise'])) print('Noon: {}'.format(sun['noon'])) print('Sunset: {}'.format(sun['sunset'])) print('Dusk: {}'.format(sun['dusk'])) # Find the bulbs on the LAN scanner = BulbScanner() scanner.scan(timeout=4) # Specific ID/MAC of the bulbs to set porch_info = scanner.getBulbInfoByID('ACCF235FFFEE') livingroom_info = scanner.getBulbInfoByID('ACCF235FFFAA') if porch_info: bulb = WifiLedBulb(porch_info['ipaddr']) bulb.refreshState() timers = bulb.getTimers() # Set the porch bulb to turn on at dusk using timer idx 0 syslog.syslog( syslog.LOG_ALERT, "Setting porch light to turn on at {}:{:02d}".format( sun['dusk'].hour, sun['dusk'].minute)) dusk_timer = LedTimer() dusk_timer.setActive(True) dusk_timer.setRepeatMask(LedTimer.Everyday) dusk_timer.setModeWarmWhite(35) dusk_timer.setTime(sun['dusk'].hour, sun['dusk'].minute) timers[0] = dusk_timer # Set the porch bulb to turn off at dawn using timer idx 1 syslog.syslog( syslog.LOG_ALERT, "Setting porch light to turn off at {}:{:02d}".format( sun['dawn'].hour, sun['dawn'].minute)) dawn_timer = LedTimer() dawn_timer.setActive(True) dawn_timer.setRepeatMask(LedTimer.Everyday) dawn_timer.setModeTurnOff() dawn_timer.setTime(sun['dawn'].hour, sun['dawn'].minute) timers[1] = dawn_timer bulb.sendTimers(timers) else: print "Can't find porch bulb" if livingroom_info: bulb = WifiLedBulb(livingroom_info['ipaddr']) bulb.refreshState() timers = bulb.getTimers() # Set the living room bulb to turn on at sunset using timer idx 0 syslog.syslog( syslog.LOG_ALERT, "Setting LR light to turn on at {}:{:02d}".format( sun['sunset'].hour, sun['sunset'].minute)) sunset_timer = LedTimer() sunset_timer.setActive(True) sunset_timer.setRepeatMask(LedTimer.Everyday) sunset_timer.setModeWarmWhite(50) sunset_timer.setTime(sun['sunset'].hour, sun['sunset'].minute) timers[0] = sunset_timer # Set the living room bulb to turn off at a fixed time off_timer = LedTimer() off_timer.setActive(True) off_timer.setRepeatMask(LedTimer.Everyday) off_timer.setModeTurnOff() off_timer.setTime(23, 30) timers[1] = off_timer bulb.sendTimers(timers) else: print "Can't find living room bulb"
np.set_printoptions(suppress=True) # don't use scientific notation CHUNK = 1024 * 4 # number of data points to read at a time RATE = 44100 # time resolution of the recording device (Hz) maxValue = 2**16 p = pyaudio.PyAudio() # start the PyAudio class stream = p.open(format=pyaudio.paInt16, channels=1, rate=RATE, input=True, frames_per_buffer=CHUNK) #uses default input device # Find the bulb on the LAN scanner = BulbScanner() scanner.scan(timeout=4) r = 0 g = 0 b = 0 # Specific ID/MAC of the bulb to set bulb_info = scanner.getBulbInfoByID('ACCF235FFFFF') if bulb_info: bulb = WifiLedBulb(bulb_info['ipaddr']) bulb.setRgb(255, 0, 0, persist=False) # create a numpy array holding a single read of audio data while True: #to it a few times just to see data = np.fromstring(stream.read(CHUNK), dtype=np.int16) dataL = data[0::2]