def handle_nano_leaf_on_intent(self, message): silent_kw = message.data.get("SilentKeyword") MyPanels = Aurora(self.IPstring, self.tokenString) MyPanels.on = True MyPanels.brightness = 100 if not silent_kw: self.speak_dialog("light.on")
def HyperLeaf(my_panels): PanelIDs = my_panels[1:-1] lower_panel = my_panels[0] upper_panel = my_panels[len(my_panels) - 1] first_panel = PanelIDs[0] last_panel = PanelIDs[len(PanelIDs) - 1] print(my_panels) print(lower_panel) print(first_panel) print(upper_panel) print(last_panel) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP sock.bind((UDP_IP, UDP_PORT)) my_aurora = Aurora(IPstring, tokenString) # IP address and key for nanoleaf Aurora my_aurora.on = True #Turn nanoleaf on my_aurora.brightness = 50 #set brightness sleep(1) strm = my_aurora.effect_stream( ) #set nanoleaf to streaming mode, this only works with bharat's fork of nanoleaf LOG.info(strm.addr) while True: data = sock.recvfrom( 21 ) # hyperion sends 3 bytes (R,G,B) for each configured light (3*7=21) now = datetime.datetime.now() # retrieve time for debuging new = bytearray(data[0]) # retrieve hyperion byte array RGBList = list(new) # great R-G-B list # print(RGBList) # for debuging only PanelCount = 0 # initial condition for Panel in PanelIDs: # itterate through the configured PanleID's above firstByteIndex = PanelCount * 3 # Red Index secondByteIndex = firstByteIndex + 1 # Green Index thirdByteIndex = secondByteIndex + 1 # Blue Index intPanelID = PanelIDs[ PanelCount] # This Panel ID ***could this not just be "Panel" intRedValue = RGBList[firstByteIndex] intGreenValue = RGBList[secondByteIndex] intBlueValue = RGBList[thirdByteIndex] # print(str(intPanelID) + " " + str(intRedValue) + " " + str(intGreenValue) + " " + str(intBlueValue)) if intPanelID == lower_panel or intPanelID == first_panel: # condition to handle two panels on the same vertical axis, or configure hyperion to drive this as well strm.panel_set(lower_panel, intRedValue, intGreenValue, intBlueValue) strm.panel_set(first_panel, intRedValue, intGreenValue, intBlueValue) else: if intPanelID == upper_panel or intPanelID == last_panel: # condition to handle two panels on the same vertical axis, or configure hyperion to drive this as well strm.panel_set(upper_panel, intRedValue, intGreenValue, intBlueValue) strm.panel_set(last_panel, intRedValue, intGreenValue, intBlueValue) else: strm.panel_set(intPanelID, intRedValue, intGreenValue, intBlueValue) # set the current panel color PanelCount += 1 # next panel
def show_temperature(self, temp): my_aurora = Aurora(self.IP, self.AUTH_TOKEN) red = Color("blue") colors = list(red.range_to(Color("red"), 50)) color = colors[int(temp) + 10] hex = color.get_hex_l()[1:] my_aurora.rgb = hex my_aurora.brightness = 40 sleep(2) my_aurora.on = False
def setup_platform(hass, config, add_devices, discovery_info=None): host = config.get(CONF_HOST) apikey = config.get(CONF_API_KEY) name = config.get(CONF_NAME) my_aurora = Aurora(host, apikey) my_aurora.hass_name = name if my_aurora.on is None: _LOGGER.error("Could not connect to Nanoleaf Aurora: " + name) add_devices([AuroraLight(my_aurora)])
def __init__(self): super().__init__('aurora') self.subscription = self.create_subscription(Bool, 'onoff', self.listener_callback, 10) self.subscription self.aurora = Aurora("192.168.1.12", "55AcCZriAkQuoehjzWTyQSY8dxPgS9dM")
def update_effect(effect_name): aurora = Aurora(support.get_nanoleaf_ip(), support.get_nanoleaf_token()) aurora.on = True if effect_name == "Random\n": effect_name = aurora.effect_random() aurora.effect = effect_name return "Random - " + effect_name elif effect_name == "Flash Twice": aurora.identify() else: aurora.effect = effect_name return effect_name
def handle_nano_leaf_set_intent(self, message): silent_kw = message.data.get("SilentKeyword") str_remainder = str(message.utterance_remainder()).lower() message_words = [] scene_words = [] scene_match = False message_words = str_remainder.split() for each_scene in self.retrieve_scenes(): scene_words = re.findall(r"\w+", str(each_scene).lower()) LOGGER.info('List Compare: ' + str(message_words) + ' : ' + str(each_scene)) scene_match = bool(set(message_words).intersection(scene_words)) if scene_match: self.set_scene(each_scene) LOG.info('Scene Found!') if not silent_kw: self.speak_dialog( "light.set", data={"result": str(each_scene) + ", scene"}) break if not scene_match: LOG.info('Scene not Found!') for findcolor in Valid_Color: mypos = str_remainder.find(findcolor) if mypos > 0: if findcolor == 'read': findcolor = 'red' if findcolor == 'toronto': myRed = 0 myGreen = 62 myBlue = 126 else: myRed = math.trunc(Color(findcolor).get_red() * 255) myGreen = math.trunc( Color(findcolor).get_green() * 255) myBlue = math.trunc(Color(findcolor).get_blue() * 255) myHex = Color(findcolor).hex_l if not silent_kw: self.speak_dialog("light.set", data={"result": findcolor}) MyPanels = Aurora(self.IPstring, self.tokenString) MyPanels.rgb = myHex[1:] break dim_level = re.findall('\d+', str_remainder) if dim_level: MyPanels = Aurora(self.IPstring, self.tokenString) MyPanels.brightness = int(dim_level[0]) if not silent_kw: self.speak_dialog( "light.set", data={"result": str(dim_level[0]) + ", percent"})
from nanoleaf import Aurora from nanoleaf import setup import nanoleaf1 from nanoleaf1 import setHue IP = "192.168.0.199" TOKEN = "fVMeVawqyiquFcIn7fDKN4bZNz0BnhUS" PANEL_ID = ["1 141 1 ", "1 242 1 ", "1 223 1 ", "1 91 1 ", "1 228 1 "] my_aurora = Aurora(IP, TOKEN) my_aurora.on = True T = 20 def testFuntion(): R1 = 255 G1 = 0 B1 = 0 R2 = 0 G2 = 255 B2 = 0 R3 = 0 G3 = 0 B3 = 255 R4 = 255
def handle_nano_leaf_off_intent(self, message): silent_kw = message.data.get("SilentKeyword") MyPanels = Aurora(self.IPstring, self.tokenString) MyPanels.on = False if not silent_kw: self.speak_dialog("light.off")
def get_panels(self): all_panels = Aurora(self.IPstring, self.tokenString) all_panel_ids = [x['panelId'] for x in all_panels.panel_positions] LOG.info(all_panel_ids) return all_panel_ids
def do_cinema_mode(self, my_id, terminate): addr = self.get_ifaces() if len(addr) == 0: LOG.info("no UDP network connection detected") elif len(addr) == 1: iface, my_ip = addr.popitem() LOG.info("UDP network connection found") self.UDP_IP = my_ip LOG.info("Starting Nanoleaf Cinema Mode: " + str(my_id)) all_panels = self.get_panels() panel_ids = all_panels[1:-1] lower_panel = all_panels[0] upper_panel = all_panels[len(all_panels) - 1] first_panel = panel_ids[0] last_panel = panel_ids[len(panel_ids) - 1] try: LOG.info('Attempting to open the socket connection') sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP sock.bind((self.UDP_IP, self.UDP_PORT)) sock.settimeout(5) socket_open = True except Exception as e: LOG.error(e) LOG.info('Socket Connection Failed') socket_open = False LOG.info('Connecting to Aurora at: ' + self.IPstring + " : " + self.tokenString) my_aurora = Aurora( self.IPstring, self.tokenString) # IP address and key for nanoleaf Aurora my_aurora.on = True # Turn nanoleaf on my_aurora.brightness = 50 # set brightness sleep(1) LOG.info('Attempting to switch to cinema mode') try: strm = my_aurora.effect_stream() # set nanoleaf to streaming mode LOG.info('Aurora Successfully switched to cinema mode') LOG.info('waiting for udp data') while True: if not socket_open: break try: raw_data = sock.recvfrom( 21 ) # hyperion sends 3 bytes (R,G,B) for each configured light (3*7=21) byte_data = bytearray( raw_data[0]) # retrieve hyperion byte array rgb_list = list(byte_data) # great R-G-B list # LOG.info(rgb_list) # for debuging only panel_count = 0 # initial condition for each_panel in panel_ids: # itterate through the configured PanleID's above # Todo - Determine if I can use Panel instead of PanelID's # Todo - If we can use Panel then the PanelCount should not be required # LOG.info('Panel: ' + str(each_panel) + " - Panel ID:" + str(panel_ids[panel_count])) first_byte_index = panel_count * 3 # Red Index second_byte_index = first_byte_index + 1 # Green Index third_byte_index = second_byte_index + 1 # Blue Index int_panel_id = panel_ids[ panel_count] # This Panel ID ***could this not just be "Panel" # int_panel_id = each_panel int_red_value = rgb_list[first_byte_index] int_green_value = rgb_list[second_byte_index] int_blue_value = rgb_list[third_byte_index] if int_panel_id == lower_panel or int_panel_id == first_panel: # condition to handle two panels on the same vertical axis, or configure hyperion to drive this as well strm.panel_set(lower_panel, int_red_value, int_green_value, int_blue_value) strm.panel_set(first_panel, int_red_value, int_green_value, int_blue_value) else: if int_panel_id == upper_panel or int_panel_id == last_panel: # condition to handle two panels on the same vertical axis, or configure hyperion to drive this as well strm.panel_set(upper_panel, int_red_value, int_green_value, int_blue_value) strm.panel_set(last_panel, int_red_value, int_green_value, int_blue_value) else: strm.panel_set(int_panel_id, int_red_value, int_green_value, int_blue_value ) # set the current panel color panel_count += 1 # next panel except Exception as e: LOG.error(e) LOG.info('Socket Timeout Error - No Data Received') break if terminate(): LOG.info('Stop Signal Received') break except Exception as e: LOG.error(e) LOG.info('Aurora Failed to launch cinema mode') my_aurora.on = False # Turn nanoleaf off try: sock.close() LOG.info('Socket Closed') except Exception as e: LOG.error(e) LOG.info('Socket Closure Failed!') LOG.info("Nanoleaf Cinema Mode Ended: " + str(my_id))
def TestPanel(panel_id): MyPanelID = panel_id MyPanels = Aurora(IPstring, tokenString) Mystrm = MyPanels.effect_stream() Mystrm.panel_set(MyPanelID, 0, 0, 0)
def initialize_aurora(): my_aurora = Aurora(IP, TOKEN) PANEL_ID = update_panel_IDs(my_aurora) return my_aurora
from nanoleaf import setup from nanoleaf import Aurora import time as tm import sys import myfunc # auroraのip addressを見つけてトークンを作成する. # 日によってip addressは異なる場合がある #ipAddressList = setup.find_auroras() #token = setup.generate_auth_token("10.0.1.2") # auroraと接続する #my_aurora = Aurora("10.0.1.3", "b2UeRO2H2aImB4uHYbDKtYCHJDIxuE4W") my_aurora = Aurora("10.0.1.3", "ufeEL3sFsRYJB92XH6gDG6O5oXRIJPhB") my_aurora.on = True #for panel in my_aurora.panel_positions: # print(panel['panelId']) # panel index # 218, 113, 23, 101, 77, 87, 86, 209, 53 # 色の指定を行う # animDataに入れるのは,'(panel数) (panel index) (frame数) (R) (G) (B) (W) (遷移時間)' # (panel数)だけ最初に一つ指定 # list[0]はpanel index # index[1]はindex + frame数 index = [['23', '53', '77', '86', '87', '101', '113', '209', '218'], [ '23 1 ', '53 1 ', '77 1 ', '86 1 ', '87 1 ', '101 1 ', '113 1 ', '209 1 ', '218 1 ' ]]
def handle_nano_leaf_dim_intent(self, message): silent_kw = message.data.get("SilentKeyword") MyPanels = Aurora(self.IPstring, self.tokenString) MyPanels.brightness = 5 self.speak_dialog("light.dim")
def nanoAction(message): global settings print(" < %s in queue" % q.qsize()) part = 1 # for Mixer and YouTube events if len(json.loads(message)["event"].split("_")) == 3: part = 2 event = json.loads(message)["event"].split("_")[part].lower() try: host = settings["nanoleaf"] token = settings["nanoleaf_token"] host2 = settings["nanoleaf2"] token2 = settings["nanoleaf2_token"] device = nl12 if event + "_device" in settings: device = settings[event + "_device"] if event == "connected": print(" + devices") if host != "": print(" o " + nl1 + " (" + host + ")") if host2 != "": print(" o " + nl2 + " (" + host2 + ")") print(" + waiting for events ...") return elif event == "naec": data = json.loads( json.loads(message, encoding='utf-8-sig')["data"]) effect_new = data["effect_new"] duration = int(data["effect_duration"]) effect_default = data["effect_default"] parameter = data["effect_parameter"] elif event == "naecupdate": readSettings() return elif settings[event + "_effect"] != '': effect_new = settings[event + "_effect"] duration = int(settings[event + "_effectduration"]) effect_default = settings["default_effect"] if (event == "host"): data = json.loads( json.loads(message, encoding='utf-8-sig')["data"]) if (int(data["viewers"]) < int( settings["host_minviewers"])): return elif (event == "cheer"): data = json.loads( json.loads(message, encoding='utf-8-sig')["data"]) if (int(data["bits"]) < int(settings["cheer_minbits"])): return else: return if (event == "host"): print(" + " + event + " (" + str(data["viewers"]) + " viewers)") elif (event == "cheer"): print(" + " + event + " (" + str(data["bits"]) + " bits)") else: print(" + " + event) print(" + actions") if host != "" and '1' in device: my_aurora = Aurora(host, token) my_aurora.on = True my_aurora.effect = effect_new else: print("no '1' in " + device) if host2 != "" and '2' in device: my_aurora2 = Aurora(host2, token2) my_aurora2.on = True my_aurora2.effect = effect_new if duration > 0: durationtext = " for " + str(duration) + " seconds" else: durationtext = "" print(" o change effect to '" + effect_new + "'" + durationtext) if duration > 0: time.sleep(duration) if host != "" and '1' in device: my_aurora.effect = effect_default if host2 != "" and '2' in device: my_aurora2.effect = effect_default print(" o change effect to '" + effect_default + "'") except KeyError: pass except ValueError: print("Could not convert data to an integer.") except: print("Unexpected error:", sys.exc_info()[0]) raise
# Function from the python API my_aurora.effect_set_raw(effect_data) def set_rgb_panel(my_aurora, panel, color, layout='horizontal', T=20): # Get the right panel_ID panel_ID = my_aurora.panel_positions_horizontal[panel]['panelId'] (R, G, B) = color animData = "1 {} 1 {} {} {} 0 {}".format(panel_ID, color[0], color[1], color[2], T) effect_data = { "command": "add", "animName": "RGB layout", "animType": "static", "animData": animData, "loop": False } my_aurora.effect_set_raw(effect_data) if __name__ == '__main__': from setup import * from nanoleaf import Aurora aur = Aurora(IP, TOKEN) set_rgb_all_panels(aur, (color_tier[0], color_tier[1], color_tier[2], color_tier[3], color_tier[4], color_tier[5], color_tier[6], color_tier[7], color_tier[7]))
from nanoleaf import Aurora import requests ip = '192.168.88.254' auth_token = 'ZGW3EHNvScT8vpDLDs3T2T8VS6lFeQYC' my_aurora = Aurora(ip, auth_token) my_aurora.on = True url = "http://" + ip + ":16021/api/v1/" + auth_token + "/rhythm/rhythmActive" r = requests.get(url) print(r)
from nanoleaf import setup from nanoleaf import Aurora from time import sleep IPaddress = '192.168.0.10' token = setup.generate_auth_token(IPaddress) myAurora = Aurora(IPaddress, token) index = 0 while index < 4: myAurora.rgb = [255,0,0] # Red sleep(1) # Red delay myAurora.rgb = [255,255,255] # White sleep(1) # White delay index = index + 1 myAurora.effect = "Flames"
def GetPanels(): MyPanels = Aurora(IPstring, tokenString) MyPanelIDs = [x['panelId'] for x in MyPanels.panel_positions ] # retreive nanoleaf panel ID's for information only # print(MyPanelIDs) return (MyPanelIDs)
def retrieve_scenes(self): LOG.info("Retrieving Aurora Scenes at: " + self.IPstring, ) MyPanels = Aurora(self.IPstring, self.tokenString) my_effects = MyPanels.effects_list LOG.info("Found Aurora Effects: ") # + my_effects) return my_effects
# Creates link for current game's live feed. def get_live(url): default = "https://statsapi.web.nhl.com" liveURL = default + url return liveURL # Runs the goal light. def goal(): for x in range(0, 4): myAurora.rgb = [255, 0, 0] # Red sleep(1) # Red delay myAurora.rgb = [255, 255, 255] # White sleep(1) # White delay # Resets to previous colors and brightness. def reset(teamEffect, brightness): myAurora.effect = teamEffect myAurora.brightness = brightness if __name__ == "__main__": ########################## ipAddress = '192.168.0.10' ########################## token = setup.generate_auth_token(ipAddress) myAurora = Aurora(ipAddress, token) main()
def set_scene(self, scene_name): LOG.info('Attempting to set scene: ' + scene_name) MyPanels = Aurora(self.IPstring, self.tokenString) MyPanels.effect = scene_name
from nanoleaf import setup from nanoleaf import Aurora import time as tm import sys import myfunc # auroraのip addressを見つけてトークンを作成する. # 日によってip addressは異なる場合がある #ipAddressList = setup.find_auroras() #token = setup.generate_auth_token("10.0.1.2") # auroraと接続する my_aurora = Aurora("10.0.1.2", "eComgYFRbkya8PMdhyPAqDoj6Xh05HYi") my_aurora.on = True my_aurora.brightness_raise(100) #for panel in my_aurora.panel_positions: # print(panel['panelId']) # panel index # 218, 113, 23, 101, 77, 87, 86, 209, 53 # 色の指定を行う # animDataに入れるのは,'(panel数) (panel index) (frame数) (R) (G) (B) (W) (遷移時間)' # (panel数)だけ最初に一つ指定 # list[0]はpanel index # index[1]はindex + frame数 index = [['23', '53', '77', '86', '87', '101', '113', '209', '218'], ['23 1 ', '53 1 ', '77 1 ', '86 1 ', '87 1 ', '101 1 ', '113 1 ', '209 1 ', '218 1 ']] color = [] for i in range(len(index[1])): color.append('255 255 255 0 0 ')
def main(): #the device to configure (ip, accesskey) see manual how to retrieve key) my_aurora = Aurora("IP of your NanoLeaf", "AccessKey generated from Nanoleaf insert here") #example my_aurora = Aurora("10.1.1.20", "loremipsumloremipsum") #if check_ping("10.1.1.20"): #need a try catch weil es errored wenn das gerät gar nicht vverfügbar ist #if my_aurora.on(): if True: # set you screen resultion screen_size_width = 1920 screen_size_height = 1080 # how much shall we ignore, dueto black bars in movies, suggestion 20%, so set 20 percent_to_ignore = 20 # in % means, 10 = 10 % of all pixels, increases performance dramatically, 100 = all pixels pixels_2_analyse = 1.0 # wait time when screen does not change wait_time = 0.1 # time to incease each time nothing happens wait_time_increase = 0.25 # maximum wait time to increase to, before aurora gets turned off, # will be turned on again automatically after wait_time interval wait_time_maximum = 4.0 # if something is wrong, debug = True can help to see why, check C:\out.txt debug = False ################################################################### ################################################################### ############ No need to change any settings below here ############ ################################################################### ################################################################### if debug: from time import time import time sys.stdout = open("C:\\out.txt", "w") screen_dimensions = { "top": int(screen_size_width * (percent_to_ignore / 100)), "left": int(screen_size_height * (percent_to_ignore / 100)), "width": int(screen_size_width * (1 - percent_to_ignore * 2 / 100)), "height": int(screen_size_height * (1 - percent_to_ignore * 2 / 100)) } x = screen_dimensions["width"] - screen_dimensions["left"] y = screen_dimensions["height"] - screen_dimensions["top"] every_x_pixels = int(100 / pixels_2_analyse) old_img = bytearray() color_old = np.array([0, 0, 0]) darken_threshold = 50 flag_aurora_off = False while True: if debug: start = time.time() with mss.mss() as sct: # Grab the screen data sct_img = sct.grab(screen_dimensions) # if screen was not changed, sleep if sct_img.raw == old_img: sleep(wait_time) # increase sleep time as long as nothing happens and maximum limit not reached if wait_time < wait_time_maximum: wait_time += wait_time_increase if debug: print("Sleeping for ", wait_time) else: # check if aurora was already sent to go offline, if not go off if (not flag_aurora_off): if debug: print("Sent Shutdown Signal to Aurora. Flag: ", flag_aurora_off) my_aurora.off = True flag_aurora_off = True continue else: if debug: print("Reset sleep ", wait_time) wait_time = 0.1 # flag_aurora_off = False old_img[:] = sct_img.raw # get list of all colors from img, but exclude colors darker than 50 rgb combined rgb_list = [[r, g, b] for r, g, b in zip( sct_img.raw[2::4][::every_x_pixels], sct_img.raw[1::4] [::every_x_pixels], sct_img.raw[0::4][::every_x_pixels]) if (r + g + b > darken_threshold)] # calculates blacknessfactor based on all black pixels / total pixels blacknessfactor = (len(sct_img.raw[2::4][::every_x_pixels]) - len(rgb_list)) / float( len(sct_img.raw[2::4][::every_x_pixels])) # verify rgb_list contains more than 1 color set, otherwise cant calculate dominant color if len(rgb_list) > 1: # use dominant color: color_new = get_dominant_color(rgb_list, color_old) else: continue # make sure it is only a one Dimensional Array color_new = np.squeeze(color_new) #convert array to single values r, g, b = color_new #if debug: print("Before ",color_new) # if colors are too close to each other, they may be gray, white or black, so dont touch them if ((abs(r - g) + abs(r - b)) > darken_threshold): # if color is darker than darken_threshold, black is domminant # reduce brightness of 2. color to 60% # if black is not dominant, but distance > 50, increase by 50% brightness if ((blacknessfactor * 100) > darken_threshold): rgb_list = [[r, g, b] for r, g, b in rgb_list if r + g + b >= 20] color_new = get_dominant_color(rgb_list, color_old) brightness_factor = 0.3 else: brightness_factor = 0.6 r, g, b = color_new / 255. h, s, v = colorsys.rgb_to_hsv(r, g, b) #if debug: print("S:",s," V:",v) # multiple hsv with factor, clamp makes sure it is not larger as 3.arg and not smaller as 2.arg s = clamp(s * 1.2, 0.5, 1.0) #farbsättigung v = clamp(v * brightness_factor, 0.1, 0.5) #helligkeit #if debug: print("S:",s," V:",v) #convert hsv back to rgb % and then real 255 numbers color_new = np.array([colorsys.hsv_to_rgb(h, s, v)]) * 255 else: color_new[:] = [r / 2., g / 2., b / 2.] #if debug: print("After ",color_new) # make sure it is only a one Dimensional Array color_new = np.squeeze(color_new) # catch white color wakeups when screen goes standby, so only flashes up and doest not show picuture if debug: print("new color ", color_new) if flag_aurora_off: if np.array_equal(np.array([255, 255, 255]), color_new): continue else: flag_aurora_off = False # if it is a new color, sent it to aurora, if not leave it as it is if not np.array_equal(color_old, color_new): try: my_aurora.rgb = color_new color_old = color_new except: print("Erroneous color ", color_new)
from nanoleaf import setup, Aurora from tkinter import * ips = None while not ips: # Continuously search for an Aurora until it finds one. There have been issues with the Aurora not appearing even # after searching for a while. Retrying the statement fixes those issues. ips = setup.find_auroras(1) # Authorization token to access the Aurora. Specific to the device. token = 'Rljgmwi2CuWQwfAU98X0EFRnofS3GAjf' # Authorize the Aurora using the IP address and token aurora = Aurora(ips[0], token) def get_effects(): """ Get a list of all the effects currently loaded on my Aurora and their details. Parse through the effects and split the list into passive effects and effects that make use of the Rhythm module on the Aurora. Return these lists. :return: """ # Returns a JSON of all the effects and their details all_effects = aurora.effect_details_all() rhythm_effects = [] effects = [] for effect in all_effects['animations']: try: # 'pluginType' is only present for Rhythm effects, so this will be the attribute the list is split around # If 'pluginType' is not present this statement will fail and it will go to the except
from setup import * from effects import * from nanoleaf import Aurora import time sys.path.append('/Users/erling/Projects/') sys.path.append('/Users/erling/Projects/Yr') sys.path.append('/Users/erling/Projects/ttt') sys.path.append('/Users/erling/Projects/CryptoExchange') from weather import * from crypto_exchange import * from ttt.main import * coins = ('BTC', 'ETH', 'IOT', 'NEO') my_aurora = Aurora(IP, TOKEN) my_aurora.on = True my_aurora.effect = 'Inner Peace' def translate(value, leftMin, leftMax, rightMin, rightMax): # Figure out how 'wide' each range is leftSpan = leftMax - leftMin rightSpan = rightMax - rightMin # Convert the left range into a 0-1 range (float) valueScaled = float(value - leftMin) / float(leftSpan) # Convert the 0-1 range into a value in the right range. return rightMin + (valueScaled * rightSpan)
except KeyError: logger.exception(f"""No known animation for https://weather.gc.ca/weathericons/{forecast}.gif""") animations.append(UNKNOWN_CONDITION) # Break the animations down into per-panel instructions anim_data = [] for animation, cluster in zip(animations, PANEL_CLUSTERS): for index, panel in enumerate(cluster): panel_animation = [ frame[0] + [round(frame[1] * DURATION_IN_SECONDS * 10)] for frame in animation[len(anim_data) % len(animation)] ] anim_data.append([panel, len(panel_animation)] + list(panel_animation)) # Composite the instructions into an Aurora command aurora = Aurora(IP_ADDRESS, AUTH_TOKEN) effect = { "command": "add", "animName": "Forecast", "animType": "custom", "animData": " ".join(map(str, [len(anim_data)] + list(flatten(anim_data)))), "loop": True, } # Set the effect aurora.effect_set_raw(effect) # Error handling except Exception as e: logger.exception(e)
from nanoleaf import Aurora import argparse import json try: # Argument parsing parser = argparse.ArgumentParser("Aurora Controller") parser.add_argument("--effect") parser.add_argument("--brightness", type=int) parser.add_argument("--identify", action="store_true") parser.add_argument("--info", action="store_true") args = parser.parse_args() logger.info(args) # Connect to Aurora aurora = Aurora(IP_ADDRESS, AUTH_TOKEN) if args.brightness is not None: aurora.brightness = args.brightness if args.effect: if args.effect == "random": aurora.effect_random() else: aurora.effect = args.effect if args.identify: aurora.identify() if args.info: print(json.dumps(aurora.info, sort_keys=True, indent=4)) # Error handling except Exception as e:
from nanoleaf import Aurora backsplash = Aurora("nanoleaf", "gsFyJGvYGQzs818SsmBgn9eVyYe51WFg") #backsplash.on = True #backsplash.effect_random() info = backsplash.info print(info)