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 switch_off(ipaddress): flux_bulb = WifiLedBulb(ipaddr=ipaddress) flux_bulb.turnOff() # if __name__ == '__main__': # ipaddr = scan_bulb() # switch_on(ipaddr) # switch_off(ipaddr)
def getBulbStatus(self, deviceId): # Get device status. try: device = indigo.devices[deviceId] bulb = WifiLedBulb(device.address) bulb.refreshState() self.debugLog(str(bulb)) except Exception: t, v, tb = sys.exc_info() self.handle_exception(t,v,tb)
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 _connect(self): """Connect to Flux light.""" self._bulb = WifiLedBulb(self._ipaddr, timeout=5) if self._protocol: self._bulb.setProtocol(self._protocol) # After bulb object is created the status is updated. We can # now set the correct mode if it was not explicitly defined. if not self._mode: if self._bulb.rgbwcapable: self._mode = MODE_RGBW else: self._mode = MODE_RGB
def setBrightness(self, action, device): try: self.debugLog(u"setBrightness: device: " + device.name + u", action:\n" + unicode(action)) bulb = WifiLedBulb(device.address) bulb.refreshState() # get RGB rgb = bulb.getRgb() self.debugLog("RGB Read as: " + str(rgb)) r=rgb[0] g=rgb[1] b=rgb[2] #Convert RGB to HSV #hsb = RGBColor(red, green, blue, rgb_type='wide_gamut_rgb').convert_to('hsv') #hue = int(round(hsb.hsv_h * 1.0)) #saturation = int(round(hsb.hsv_s * 100.0)) #brightness = int(round(hsb.hsv_v * 100.0)) #Change V #Update bulb self.debugLog(u"Setting RGB: " + str(r) + "|" + str(g) + "|" + str(b) ) bulb.setRgb(r,g,b,True,action.actionValue * 2.55) except Exception: t, v, tb = sys.exc_info() self.handle_exception(t,v,tb)
def _add_device(self, dev): """ Add the given device, if necessary. dev -- the device object """ _id = 'magichome-' + dev['id'] if _id not in self.devices: device = MagicHomeBulb(self, _id, WifiLedBulb(dev['ipaddr'])) self.handle_device_added(device)
def __init__(self, driver, display_name, ip, logger=None): super().__init__(driver, display_name) self.logger = logger self._wifi_bulb = WifiLedBulb(ip) service = self.add_preload_service('Lightbulb', chars=[ 'On', 'Brightness', 'Hue', 'Saturation', ]) # configure callbacks service.configure_char( 'On', setter_callback=self.set_on, ) # Set our instance variables self.on = 0
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)
def setPreset(self, action, device): try: self.debugLog(u"setPreset: device: " + device.name + ", action:\n" + unicode(action)) preset = int(action.props.get('preset', 0),0) speed = int(action.props.get('speed', 0),0) bulb = WifiLedBulb(device.address) bulb.refreshState() bulb.setPresetPattern(preset, speed) bulb.turnOn() except Exception: t, v, tb = sys.exc_info() self.handle_exception(t,v,tb)
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
class FluxLED(Accessory): category = CATEGORY_LIGHTBULB def __init__(self, driver, display_name, ip, logger=None): super().__init__(driver, display_name) self.logger = logger self._wifi_bulb = WifiLedBulb(ip) service = self.add_preload_service('Lightbulb', chars=[ 'On', 'Brightness', 'Hue', 'Saturation', ]) # configure callbacks service.configure_char( 'On', setter_callback=self.set_on, ) # Set our instance variables self.on = 0 def __getstate__(self): state = super().__getstate__() return state def set_on(self, value): if self.logger: self.logger.debug(f'Set On: {value}') self.on = value if value == 1: self._wifi_bulb.turnOn() elif value == 0: self._wifi_bulb.turnOff()
def updateStatus(self, device): #self.debugLog(u"Updating device: " + device.name) try: keyValueList = [] bulb = WifiLedBulb(device.address) keyValueList.append({'key':"online", 'value':True}) currentRGBW = bulb.getRgbw() device.pluginProps["supportsWhite"] = bulb.rgbwcapable device.pluginProps["supportsWhiteTemperature"] = False #self.debugLog(str(currentRGBW)) channelKeys = [] if bulb.rgbwcapable: channelKeys.extend(['whiteLevel']) brightness= int(round(RGBColor(currentRGBW[0],currentRGBW[1],currentRGBW[2]).convert_to('hsv').hsv_v*100)) keyValueList.append({'key':"onOffState", 'value':bulb.isOn()}) keyValueList.append({'key':"redLevel", 'value':currentRGBW[0]}) keyValueList.append({'key':"greenLevel", 'value':currentRGBW[1]}) keyValueList.append({'key':"blueLevel", 'value':currentRGBW[2]}) keyValueList.append({'key':'brightnessLevel','value':brightness}) if bulb.rgbwcapable: keyValueList.append({'key':"whiteLevel", 'value':currentRGBW[3]}) device.updateStatesOnServer(keyValueList) except Exception,e: self.errorLog("Error updating device: " + device.name +". Is the IP address correct?") t, v, tb = sys.exc_info() self.handle_exception(t,v,tb)
def connectLED(ip): try: #led_to_connect = scanner.getBulbInfoByID(args.led_mac) #bulb = WifiLedBulb(led_to_connect['ipaddr']) bulb = WifiLedBulb(ip) print("Connected to LED strip with IP: " + ip) ipAddress.set("IP: " + ip) except: print( "No valid MAC address provided, attempting to use first one discovered: " + scanner.found_bulbs[0]['id']) print("Unable to connect to " + ip) #first_discovered_bulb = scanner.getBulbInfoByID(scanner.found_bulbs[0]['id']) #bulb = WifiLedBulb(first_discovered_bulb['ipaddr']) return bulb
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 setRGB(self, action, device): try: self.debugLog(u"setRGB: device: " + device.name + ", action:\n" + unicode(action)) red = action.props.get('red', 0) green = action.props.get('green', 0) blue = action.props.get('blue', 0) bulb = WifiLedBulb(device.address) bulb.mode = 'color' bulb.pattern_code = 0x61 if red+green+blue >0: bulb.turnOn() bulb.setRgb(red, green, blue) except Exception: t, v, tb = sys.exc_info() self.handle_exception(t,v,tb)
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 _addNode(self, d): try: name = 'mh ' + d['ipaddr'].replace('.',' ') address = str(d['id']).lower() address = address[-14:] if address not in self.nodes: led = WifiLedBulb(d['ipaddr']) if led.rgbwcapable: LOGGER.info('Adding new MagicHome RGBW LED: %s(%s)', name, address) self.addNode(MagicHomeLED(self, self.address, address, name, device = led)) #Two node types merged, both kept herein for backwards compatability BF 30Jan2020 else: LOGGER.info('Adding new MagicHome RGB LED: %s(%s)', name, address) self.addNode(MagicHomeLED(self, self.address, address, name, device = led)) else: LOGGER.debug('MagicHome LED with IP address "%s" and MAC address "%s" already in ISY', name, address) return False except Exception as ex: LOGGER.error('Error adding Bulb: %s', str(ex)) return False return True
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 actionControlDimmerRelay(self, action, device): try: try: self.debugLog(u"actionControlDimmerRelay called for device " + device.name + u". actionValue: " + str(action) ) except Exception, e: self.debugLog(u"actionControlDimmerRelay called for device " + device.name + u". (Unable to display action or device data due to error: " + str(e) + u")") currentBrightness = device.states['brightnessLevel'] currentOnState = device.states['onOffState'] self.debugLog("current brightness: " + str(currentBrightness)) bulb = WifiLedBulb(device.address) bulb.refreshState() self.debugLog(str(bulb)) # Get key variables command = action.deviceAction ##### TURN ON ##### if command == indigo.kDeviceAction.TurnOn: try: self.debugLog(u"device on:\n%s" % action) except Exception, e: self.debugLog(u"device on: (Unable to display action data due to error: " + str(e) + u")") # Turn it on. bulb.turnOn()
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 switch_on(ipaddress): flux_bulb = WifiLedBulb(ipaddr=ipaddress) flux_bulb.turnOn()
def main(): device = WifiLedBulb('<ip>') print(hex(device.raw_state[1]))
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] dataR = data[1::2] peakL = np.abs(np.max(dataL) - np.min(dataL)) / maxValue peakR = np.abs(np.max(dataR) - np.min(dataR)) / maxValue #print("L:%00.02f \tR:%00.02f"%(peakL*100, peakR*100)) data = data * np.hanning(len(data)) # smooth the FFT by windowing data fft = abs(np.fft.fft(data).real) fft = fft[:int(len(fft) / 2)] # keep only first half freq = np.fft.fftfreq(CHUNK, 1.0 / RATE)
class FluxLight(Light): """Representation of a Flux light.""" def __init__(self, device): """Initialize the light.""" self._name = device["name"] self._ipaddr = device["ipaddr"] self._protocol = device[CONF_PROTOCOL] self._mode = device[ATTR_MODE] self._custom_effect = device[CONF_CUSTOM_EFFECT] self._bulb = None self._error_reported = False def _connect(self): """Connect to Flux light.""" self._bulb = WifiLedBulb(self._ipaddr, timeout=5) if self._protocol: self._bulb.setProtocol(self._protocol) # After bulb object is created the status is updated. We can # now set the correct mode if it was not explicitly defined. if not self._mode: if self._bulb.rgbwcapable: self._mode = MODE_RGBW else: self._mode = MODE_RGB def _disconnect(self): """Disconnect from Flux light.""" self._bulb = None @property def available(self) -> bool: """Return True if entity is available.""" return self._bulb is not None @property def name(self): """Return the name of the device if any.""" return self._name @property def is_on(self): """Return true if device is on.""" return self._bulb.isOn() @property def brightness(self): """Return the brightness of this light between 0..255.""" if self._mode == MODE_WHITE: return self.white_value return self._bulb.brightness @property def hs_color(self): """Return the color property.""" return color_util.color_RGB_to_hs(*self._bulb.getRgb()) @property def supported_features(self): """Flag supported features.""" if self._mode == MODE_RGBW: return SUPPORT_FLUX_LED | SUPPORT_WHITE_VALUE | SUPPORT_COLOR_TEMP if self._mode == MODE_WHITE: return SUPPORT_BRIGHTNESS return SUPPORT_FLUX_LED @property def white_value(self): """Return the white value of this light between 0..255.""" return self._bulb.getRgbw()[3] @property def effect_list(self): """Return the list of supported effects.""" if self._custom_effect: return FLUX_EFFECT_LIST + [EFFECT_CUSTOM] return FLUX_EFFECT_LIST @property def effect(self): """Return the current effect.""" current_mode = self._bulb.raw_state[3] if current_mode == EFFECT_CUSTOM_CODE: return EFFECT_CUSTOM for effect, code in EFFECT_MAP.items(): if current_mode == code: return effect return None def turn_on(self, **kwargs): """Turn the specified or all lights on.""" if not self.is_on: self._bulb.turnOn() hs_color = kwargs.get(ATTR_HS_COLOR) if hs_color: rgb = color_util.color_hs_to_RGB(*hs_color) else: rgb = None brightness = kwargs.get(ATTR_BRIGHTNESS) effect = kwargs.get(ATTR_EFFECT) white = kwargs.get(ATTR_WHITE_VALUE) color_temp = kwargs.get(ATTR_COLOR_TEMP) # handle special modes if color_temp is not None: if brightness is None: brightness = self.brightness if color_temp > COLOR_TEMP_WARM_VS_COLD_WHITE_CUT_OFF: self._bulb.setRgbw(w=brightness) else: self._bulb.setRgbw(w2=brightness) return # Show warning if effect set with rgb, brightness, or white level if effect and (brightness or white or rgb): _LOGGER.warning("RGB, brightness and white level are ignored when" " an effect is specified for a flux bulb") # Random color effect if effect == EFFECT_RANDOM: self._bulb.setRgb(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) return if effect == EFFECT_CUSTOM: if self._custom_effect: self._bulb.setCustomPattern( self._custom_effect[CONF_COLORS], self._custom_effect[CONF_SPEED_PCT], self._custom_effect[CONF_TRANSITION], ) return # Effect selection if effect in EFFECT_MAP: self._bulb.setPresetPattern(EFFECT_MAP[effect], 50) return # Preserve current brightness on color/white level change if brightness is None: brightness = self.brightness # Preserve color on brightness/white level change if rgb is None: rgb = self._bulb.getRgb() if white is None and self._mode == MODE_RGBW: white = self.white_value # handle W only mode (use brightness instead of white value) if self._mode == MODE_WHITE: self._bulb.setRgbw(0, 0, 0, w=brightness) # handle RGBW mode elif self._mode == MODE_RGBW: self._bulb.setRgbw(*tuple(rgb), w=white, brightness=brightness) # handle RGB mode else: self._bulb.setRgb(*tuple(rgb), brightness=brightness) def turn_off(self, **kwargs): """Turn the specified or all lights off.""" self._bulb.turnOff() def update(self): """Synchronize state with bulb.""" if not self.available: try: self._connect() self._error_reported = False except OSError: self._disconnect() if not self._error_reported: _LOGGER.warning("Failed to connect to bulb %s, %s", self._ipaddr, self._name) self._error_reported = True return self._bulb.update_state(retry=2)
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) 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)
print sys.argv try: address = sys.argv[1] id = sys.argv[2] action = sys.argv[3].lower() values = sys.argv[4:] except: sys.exit(1) #scanner = BulbScanner() #scanner.scan(timeout=4) #bulb_info = scanner.getBulbInfoByID(address) #address = bulb_info['ipaddr'] bulb = WifiLedBulb(address) msg = 'MagicLED bulb at %s ' % address if action == 'on': val = int(values[0]) if val > 0: msg += 'turned on' bulb.turnOn() else: msg += 'turned off' bulb.turnOff() if action == 'color': r = int(values[0]) g = int(values[1]) b = int(values[2])
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)
from scapy.all import * import subprocess from flux_led import WifiLedBulb, BulbScanner import datetime import os import sys version = "1.0.3 " # assign version number for debugging bulb = WifiLedBulb('192.168.XX.XX') # assign bulb IP #bulb.refreshState() # refresh state to collect accurate staus logfile = r"/home/pi/SANDBOX/Dash/logfiles.log" # name of my log file WHITE_MAC_ADDRESS = 'XX:XX:XX:XX:XX:XX' # enter Dash Button's MAC Address here. testMAC = 'XX:XX:XX:XX:XX:XX' dashButton = { "whiteDash" : 'XX:XX:XX:XX:XX:XX', "redDash" : 'XX:XX:XX:XX:XX:XX' } whiteBulb = (0,0,0,191) redBulb = (15,0,0,0) #sniff for packets sent from button press def detect_button(pkt): for mac in dashButton:
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 do_command(self, e, cmd, test_str): c = self.connection # Poll the API to get current game. if cmd == "game": url = 'https://api.twitch.tv/kraken/channels/' + self.channel_id headers = { 'Client-ID': self.client_id, 'Accept': 'application/vnd.twitchtv.v5+json' } r = requests.get(url, headers=headers).json() c.privmsg(self.channel, r['display_name'] + ' is currently playing ' + r['game']) # Poll the API the get the current status of the stream elif cmd == "title": url = 'https://api.twitch.tv/kraken/channels/' + self.channel_id headers = { 'Client-ID': self.client_id, 'Accept': 'application/vnd.twitchtv.v5+json' } r = requests.get(url, headers=headers).json() c.privmsg( self.channel, r['display_name'] + ' channel title is currently ' + r['status']) # Provide basic information to viewers for specific commands # OLD WAY TO DO HEX CODE # Hex input as command # elif cmd[0] == '#': # if len(cmd) == 7: # newcmd = cmd.replace("#", "") # try: # int(newcmd, 16) # bulb_info = autoScan() # message = "Bulb color changed to " + cmd # c.privmsg(self.channel, message) # if bulb_info: # bulb = WifiLedBulb(bulb_info['ipaddr']) # bulb.turnOn() # rgb = struct.unpack('BBB', newcmd.decode('hex')) #convert hex to tuple # bulb.setRgb(rgb[0], rgb[1], rgb[2], persist=False) # except ValueError: # c.privmsg(self.channel, cmd + " is not a valid color code!") # else: # message = "Invalid command: color format example: #12D4F6" # c.privmsg(self.channel, message) # Test Color Change elif cmd == "off": message = "Bulb has been turned off" bulb_info = autoScan() if bulb_info: bulb = WifiLedBulb(bulb_info['ipaddr']) bulb.turnOff() c.privmsg(self.channel, message) elif cmd == "warm": # Warm white big-command bulb_info = autoScan() if bulb_info: bulb = WifiLedBulb(bulb_info['ipaddr']) bulb.turnOn() # Will Be Direct Color Command or Fail else: try: rgb = generateRGB(cmd) # try to turn it into RGB bulb_info = autoScan() # at this point it worked if bulb_info: # change the bulb colors bulb = WifiLedBulb(bulb_info['ipaddr']) bulb.turnOn() bulb.setRgb(rgb[0], rgb[1], rgb[2], persist=False) message = "Bulb color changed to " + cmd c.privmsg(self.channel, message) except ValueError: # If value doesn't exist, it's neither a color or a command c.privmsg(self.channel, cmd + " is not a color!") c.privmsg(self.channel, "Did not understand command: " + cmd)
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 = 5 # seconds on each color def crossFade(bulb, color1, color2): r1, g1, b1 = color1 r2, g2, b2 = color2 steps = 100 for i in range(1, steps + 1): r = r1 - int(i * float(r1 - r2) / steps) g = g1 - int(i * float(g1 - g2) / steps) b = b1 - int(i * float(b1 - b2) / steps) # (use non-persistent mode to help preserve flash)