def init_strip( numpixels , brightness , datapin , clockpin): strip = Adafruit_DotStar(numpixels , 125000000) #strip = Adafruit_DotStar(numpixels, datapin , clockpin) #Initialize pins for output strip.begin() strip.setBrightness(brightness) return strip
def main(): # set up audio input... recorder = alsaaudio.PCM(alsaaudio.PCM_CAPTURE) recorder.setchannels(CHANNELS) recorder.setrate(RATE) recorder.setformat(INFORMAT) recorder.setperiodsize(FRAMESIZE) # Set up off button GPIO.setmode(GPIO.BCM) GPIO.setup(23,GPIO.IN,pull_up_down = GPIO.PUD_UP) # Initialize colors of each LED... strip = Adafruit_DotStar(numpixels) strip.begin() for i in range(15): time.sleep(float(1.0/float(i+1))) strip.setBrightness(int(stripBright*(i+1)/15)) strip.setPixelColor(i,colors[i][0],colors[i][1],colors[i][2]) strip.setPixelColor(29-i,colors[29-i][0],colors[29-i][1],colors[29-i][2]) strip.show() time.sleep(1) # MAIN LOOP: i=0 bigtime = 0.0 valsold = [] print "IN MAIN LOOP" try: while True: # Check for off button press on = GPIO.input(23) if on == False: shutdown(strip) # Read music and get magnitudes for FRAMESIZE length Y = getMagnitudes(recorder) if Y != None: # Update LED strip based on magnitudes vals = controlLights(strip,Y,valsold) # Update valsold list which is used by my smoothAvg function # to make a running average of brightnesses rather than actual brightnesses valsold.insert(0,vals) if len(valsold) > 20: valsold.pop() if i % 1000 == 0: print "TIME:",time.time()-bigtime print "ITERATION: ",i bigtime = time.time() i+=1 except KeyboardInterrupt: pass
def rgbStrip(R, G, B): numpixels = 30; # Number of LEDs in strip # strip = Adafruit_DotStar(numpixels, rgb_strip_datapin, rgb_strip_clockpin) strip = Adafruit_DotStar(numpixels) # SPI @ ~32 MHz strip.begin() # Initialize pins for output strip.setBrightness(64) # Limit brightness to ~1/4 duty cycle # Runs 10 LEDs at a time along strip, cycling through red, green and blue. # This requires about 200 mA for all the 'on' pixels + 1 mA per 'off' pixel. led = 0 # Index of first 'on' pixel while (led != 30): # Loop for each light strip.setPixelColor(led, R, G, B) # Set pin color strip.show() # Refresh strip led += 1 # Advance head position\
class Blinkt: def __init__(self, host): self.host = host self.strip = Adafruit_DotStar(numpixels, datapin, clockpin) self.strip.begin() self.strip.setBrightness(32) green = self.to_rgb(0,255,0) self.show_all(green) def to_rgb(self,r,g,b): return (g << 16) + (r << 8) + b def show(self, colour, pixel): self.strip.setPixelColor(pixel, colour) self.strip.show() def show_all(self, colour): for x in range(0,8): self.strip.setPixelColor(x, colour) self.strip.show()
def rgbStripTest(): numpixels = 30; # Number of LEDs in strip # strip = Adafruit_DotStar(numpixels, datapin, clockpin) strip = Adafruit_DotStar(numpixels, 12000000) # SPI @ ~32 MHz strip.begin() # Initialize pins for output strip.setBrightness(64) # Limit brightness to ~1/4 duty cycle # Runs 10 LEDs at a time along strip, cycling through red, green and blue. # This requires about 200 mA for all the 'on' pixels + 1 mA per 'off' pixel. head = 0 # Index of first 'on' pixel tail = -10 # Index of last 'off' pixel color = 0xFF0000 # 'On' color (starts red) repeat = 0 while True: # Loop forever strip.setPixelColor(head, color) # Turn on 'head' pixel strip.setPixelColor(tail, 0) # Turn off 'tail' strip.show() # Refresh strip time.sleep(1.0 / 50) # Pause 20 milliseconds (~50 fps) head += 1 # Advance head position if(head >= numpixels): # Off end of strip? head = 0 # Reset to start color >>= 8 # Red->green->blue->black if(color == 0): color = 0xFF0000 # If black, reset to red tail += 1 # Advance tail position if(tail >= numpixels): tail = 0 # Off end? Reset repeat += 1 if(repeat == 10): rgbStripOff(strip) break;
import time from dotstar import Adafruit_DotStar # imports library/module mopi3 = mopi_api.mopiapi() Volt = mopi3.getVoltage() #CurrentVoltage = # takes value from currently running MoPi file numpixels = 8 # Amount of LEDs datapin = 23 # GPIO pin 23 clockpin = 24 # GPIO pin 24 strip = Adafruit_DotStar(numpixels, datapin, clockpin) strip.begin() # initialize pins for output strip.setBrightness(10) # limit brightness to ~1/4 duty cycle #while CurrentVoltage >= 6000: print "Current voltage reading is: %d" % Volt; if Volt > 8100: # initialize the entire LED bar to show full charge strip.setPixelColor(0, 255, 0, 0) strip.setPixelColor(1, 255, 0, 0) strip.setPixelColor(2, 255, 0, 0) strip.setPixelColor(3, 255, 0, 0) strip.setPixelColor(4, 255, 0, 0) strip.setPixelColor(5, 255, 255, 0) strip.setPixelColor(6, 255, 255, 0) strip.setPixelColor(7, 0, 255, 0) strip.show()
class Bartender(MenuDelegate): def __init__(self): self.running = False # set the oled screen height self.screen_width = SCREEN_WIDTH self.screen_height = SCREEN_HEIGHT self.btn1Pin = LEFT_BTN_PIN self.btn2Pin = RIGHT_BTN_PIN # configure interrups for buttons GPIO.setup(self.btn1Pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.btn2Pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # configure screen spi_bus = 0 spi_device = 0 # Very important... This lets py-gaugette 'know' what pins to use in order to reset the display self.led = disp = Adafruit_SSD1306.SSD1306_128_64( rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000) ) # Change rows & cols values depending on your display dimensions. # Initialize library. self.led.begin() # Clear display. self.led.clear() self.led.display() # Create image buffer. # Make sure to create image with mode '1' for 1-bit color. self.image = Image.new('1', (self.screen_width, self.screen_height)) # Load default font. self.font = ImageFont.truetype("FreeMono.ttf", 15) # Create drawing object. self.draw = ImageDraw.Draw(self.image) # load the pump configuration from file self.pump_configuration = Bartender.readPumpConfiguration() for pump in self.pump_configuration.keys(): GPIO.setup(self.pump_configuration[pump]["pin"], GPIO.OUT, initial=GPIO.HIGH) # setup pixels: self.numpixels = NUMBER_NEOPIXELS # Number of LEDs in strip # Here's how to control the strip from any two GPIO pins: datapin = NEOPIXEL_DATA_PIN clockpin = NEOPIXEL_CLOCK_PIN self.strip = Adafruit_DotStar(self.numpixels, datapin, clockpin) self.strip.begin() # Initialize pins for output self.strip.setBrightness( NEOPIXEL_BRIGHTNESS) # Limit brightness to ~1/4 duty cycle # Set the Default or "StandBy Light" to Blue in this case for i in range(0, self.numpixels): self.strip.setPixelColor(i, COLOR_BLUE) self.strip.show() print "Done initializing" @staticmethod def readPumpConfiguration(): return json.load(open('pump_config.json')) @staticmethod def writePumpConfiguration(configuration): with open("pump_config.json", "w") as jsonFile: json.dump(configuration, jsonFile) def startInterrupts(self): self.running = True GPIO.add_event_detect(self.btn1Pin, GPIO.FALLING, callback=self.left_btn, bouncetime=LEFT_PIN_BOUNCE) time.sleep(1) GPIO.add_event_detect(self.btn2Pin, GPIO.FALLING, callback=self.right_btn, bouncetime=RIGHT_PIN_BOUNCE) time.sleep(1) self.running = False def buildMenu(self, drink_list, drink_options): # create a new main menu m = Menu("Main Menu") # add drink options drink_opts = [] for d in drink_list: drink_opts.append( MenuItem('drink', d["name"], {"ingredients": d["ingredients"]})) configuration_menu = Menu("Configure") # add pump configuration options pump_opts = [] for p in sorted(self.pump_configuration.keys()): config = Menu(self.pump_configuration[p]["name"]) # add fluid options for each pump for opt in drink_options: # star the selected option selected = "*" if opt["value"] == self.pump_configuration[p][ "value"] else "" config.addOption( MenuItem('pump_selection', opt["name"], { "key": p, "value": opt["value"], "name": opt["name"] })) # add a back button so the user can return without modifying config.addOption(Back("Back")) config.setParent(configuration_menu) pump_opts.append(config) # add pump menus to the configuration menu configuration_menu.addOptions(pump_opts) # add a back button to the configuration menu configuration_menu.addOption(Back("Back")) # adds an option that cleans all pumps to the configuration menu configuration_menu.addOption(MenuItem('clean', 'Clean')) configuration_menu.setParent(m) m.addOptions(drink_opts) m.addOption(configuration_menu) # create a menu context self.menuContext = MenuContext(m, self) def filterDrinks(self, menu): """ Removes any drinks that can't be handled by the pump configuration """ for i in menu.options: if (i.type == "drink"): i.visible = False ingredients = i.attributes["ingredients"] presentIng = 0 for ing in ingredients.keys(): for p in self.pump_configuration.keys(): if (ing == self.pump_configuration[p]["value"]): presentIng += 1 if (presentIng == len(ingredients.keys())): i.visible = True elif (i.type == "menu"): self.filterDrinks(i) def selectConfigurations(self, menu): """ Adds a selection star to the pump configuration option """ for i in menu.options: if (i.type == "pump_selection"): key = i.attributes["key"] if (self.pump_configuration[key]["value"] == i.attributes["value"]): i.name = "%s %s" % (i.attributes["name"], "*") else: i.name = i.attributes["name"] elif (i.type == "menu"): self.selectConfigurations(i) def prepareForRender(self, menu): self.filterDrinks(menu) self.selectConfigurations(menu) return True def menuItemClicked(self, menuItem): if (menuItem.type == "drink"): self.makeDrink(menuItem.name, menuItem.attributes["ingredients"]) return True elif (menuItem.type == "pump_selection"): self.pump_configuration[menuItem.attributes["key"]][ "value"] = menuItem.attributes["value"] Bartender.writePumpConfiguration(self.pump_configuration) return True elif (menuItem.type == "clean"): self.clean() return True return False def clean(self): waitTime = 20 pumpThreads = [] # cancel any button presses while the drink is being made # self.stopInterrupts() self.running = True for pump in self.pump_configuration.keys(): pump_t = threading.Thread( target=self.pour, args=(self.pump_configuration[pump]["pin"], waitTime)) pumpThreads.append(pump_t) # start the pump threads for thread in pumpThreads: thread.start() # start the progress bar self.progressBar(waitTime) # wait for threads to finish for thread in pumpThreads: thread.join() # show the main menu self.menuContext.showMenu() # sleep for a couple seconds to make sure the interrupts don't get triggered time.sleep(2) def displayMenuItem(self, menuItem): print menuItem.name self.led.clear() self.draw.rectangle((0, 0, self.screen_width, self.screen_height), outline=0, fill=0) self.draw.text((0, 20), str(menuItem.name), font=self.font, fill=255) self.led.image(self.image) self.led.display() def cycleLights(self): t = threading.currentThread() head = 0 # Index of first 'on' pixel tail = -10 # Index of last 'off' pixel color = COLOR_RED # 'On' color (starts red) while getattr(t, "do_run", True): self.strip.setPixelColor(head, color) # Turn on 'head' pixel self.strip.setPixelColor(tail, 0) # Turn off 'tail' self.strip.show() # Refresh strip time.sleep(1.0 / 50) # Pause 20 milliseconds (~50 fps) head += 1 # Advance head position if (head >= self.numpixels): # Off end of strip? head = 0 # Reset to start if (color == COLOR_RED): color = COLOR_YELLOW # if red,set to yellow elif (color == COLOR_YELLOW): color = COLOR_BLUE # if yellow,set to blue elif (color == COLOR_BLUE): color = COLOR_RED # if blue,set back to red tail += 1 # Advance tail position if (tail >= self.numpixels): tail = 0 # Off end? Reset def lightsEndingSequence(self): # make lights yellow for i in range(0, self.numpixels): self.strip.setPixelColor(i, COLOR_YELLOW) self.strip.show() os.system("mpg123 " + DONESOUND) # time.sleep(5) # set them back to blue "StandBy Light" for i in range(0, self.numpixels): self.strip.setPixelColor(i, COLOR_BLUE) self.strip.show() def pour(self, pin, waitTime): GPIO.output(pin, GPIO.LOW) time.sleep(waitTime) GPIO.output(pin, GPIO.HIGH) # other way of dealing with Display delay, Thanks Yogesh def progressBar(self, waitTime): #-with the outcommented version, it updates faster, but there is a limit with the delay, you have to figure out-# #mWaitTime = waitTime - 7 #interval = mWaitTime/ 100.0 #if interval < 0.07: # interval = 0 #for x in range(1, 101): interval = waitTime / 10.0 for x in range(1, 11): self.led.clear() self.draw.rectangle((0, 0, self.screen_width, self.screen_height), outline=0, fill=0) # self.updateProgressBar(x, y=35) self.updateProgressBar(x * 10, y=35) self.led.image(self.image) self.led.display() time.sleep(interval) def makeDrink(self, drink, ingredients): # cancel any button presses while the drink is being made # self.stopInterrupts() os.system("mpg123 " + DRINKME) self.running = True # launch a thread to control lighting lightsThread = threading.Thread(target=self.cycleLights) lightsThread.start() # Parse the drink ingredients and spawn threads for pumps maxTime = 0 pumpThreads = [] for ing in ingredients.keys(): for pump in self.pump_configuration.keys(): if ing == self.pump_configuration[pump]["value"]: vWaitTime = self.pump_configuration[pump]["flowrate"] waitTime = ingredients[ing] * vWaitTime if (waitTime > maxTime): maxTime = waitTime pump_t = threading.Thread( target=self.pour, args=(self.pump_configuration[pump]["pin"], waitTime)) pumpThreads.append(pump_t) # start the pump threads for thread in pumpThreads: thread.start() #Show in Console how long the Pumps running print("The pumps run for", maxTime, "seconds") # start the progress bar self.progressBar(maxTime) # wait for threads to finish for thread in pumpThreads: thread.join() # show the main menu self.menuContext.showMenu() # stop the light thread lightsThread.do_run = False lightsThread.join() # show the ending sequence lights self.lightsEndingSequence() # sleep for a couple seconds to make sure the interrupts don't get triggered # time.sleep(2); # reenable interrupts # self.startInterrupts() self.running = False def left_btn(self, ctx): print("LEFT_BTN pressed") if not self.running: self.running = True self.menuContext.advance() print("Finished processing button press") self.running = False def right_btn(self, ctx): print("RIGHT_BTN pressed") if not self.running: self.running = True self.menuContext.select() print("Finished processing button press") self.running = 2 print("Starting button timeout") def updateProgressBar(self, percent, x=15, y=15): height = 25 width = self.screen_width - 2 * x for w in range(0, width): self.draw.point((w + x, y), fill=255) self.draw.point((w + x, y + height), fill=255) for h in range(0, height): self.draw.point((x, h + y), fill=255) self.draw.point((self.screen_width - x, h + y), fill=255) for p in range(0, percent): p_loc = int(p / 100.0 * width) self.draw.point((x + p_loc, h + y), fill=255) def run(self): self.startInterrupts() # main loop try: try: while True: letter = raw_input(">") if letter == "l": self.left_btn(False) if letter == "r": self.right_btn(False) except EOFError: while True: time.sleep(0.1) if self.running not in (True, False): self.running -= 0.1 if self.running == 0: self.running = False print("Finished button timeout") except KeyboardInterrupt: GPIO.cleanup() # clean up GPIO on CTRL+C exit GPIO.cleanup() # clean up GPIO on normal exit traceback.print_exc()
class Elevator(threading.Thread): def __init__(self, kill_event, loop_time=1.0 / 60.0): self.status = "INIT" self.q = Queue() self.kill_event = kill_event self.timeout = loop_time self.baudrate = BAUDRATE self.dev = DEVICE self.strip = Adafruit_DotStar(NUMPIXELS, DATAPIN, CLOCKPIN) self.strip.begin() self.strip.setBrightness(255) self.serial = serial.Serial(self.dev) self.serial.baudrate = 115200 # Initial state self.send_elevator_command(ELEVATOR_DOWN) self.status = "DOWN" self.set_lights(OFF) super(Elevator, self).__init__() def onThread(self, function, *args, **kwargs): self.q.put((function, args, kwargs)) def run(self): self.down() while True: if self.kill_event.is_set(): self.close() return try: function, args, kwargs = self.q.get(timeout=self.timeout) function(*args, **kwargs) except Empty: pass def send_elevator_command(self, command): self.serial.flushInput() # avoids that the input buffer overfloats self.serial.write(command) self.serial.flush() def up(self): self.status = "GOING_UP" self.send_elevator_command(ELEVATOR_UP) time.sleep(TIME_UP_S) self.status = "UP" self.set_lights(GREEN) def down(self): self.status = "GOING_DOWN" self.send_elevator_command(ELEVATOR_DOWN) self.set_lights(OFF) time.sleep(TIME_DOWN_S) self.status = "DOWN" time.sleep(TIME_TO_LEAVE_ELEVATOR_S) self.status = "FREE" def close(self): self.serial.close() def set_lights(self, color): for i in range(NUMPIXELS): self.strip.setPixelColor(i, color) if color == OFF: self.strip.setBrightness(0) else: self.strip.setBrightness(255) self.strip.show()
clear(strip) for i in range(dots): index = randint(0, numpixels - 1) color = colorsys.hsv_to_rgb(color_index, 1.0, 1.0) leds[index][0] = int(color[0] * 255) leds[index][1] = int(color[1] * 255) leds[index][2] = int(color[2] * 255) for j, l in enumerate(leds): set_color(strip, j, leds[j][0], leds[j][1], leds[j][2]) strip.show() sleep(.05) color_index += color_inc for i in range(numpixels): leds[i][0] >>= 1 leds[i][1] >>= 1 leds[i][2] >>= 1 strip = Adafruit_DotStar(numpixels, order='bgr') strip.begin() strip.setBrightness(70) startup(strip) try: main_loop(strip) except KeyboardInterrupt: off(strip) sys.exit(0)
def init_led(num_pixels): global strip strip = Adafruit_DotStar(num_pixels, 12000000) strip.begin() strip.setBrightness(48) return strip
config.LED_FREQ_HZ, config.LED_DMA, config.LED_INVERT, config.BRIGHTNESS) elif config.LED_TYPE == 'apa102': from dotstar import Adafruit_DotStar # Use SPI bus to communicate with the APA102 if config.APA102_DATA_PIN == '10': strip = Adafruit_DotStar(config.N_PIXELS, config.APA102_SPI_SPEED, order='config.APA102_ORDER') # Communicate with APA102 using normal GPIO pins else: strip = Adafruit_DotStar(config.N_PIXELS, config.APA102_DATA_PIN, config.APA102_CLK_PIN) strip.begin() strip.setBrightness(config.BRIGHTNESS) elif config.DEVICE == 'blinkstick': from blinkstick import blinkstick import signal import sys #Will turn all leds off when invoked. def signal_handler(signal, frame): all_off = [0] * (config.N_PIXELS * 3) stick.set_led_data(0, all_off) sys.exit(0) stick = blinkstick.find_first() # Create a listener that turns the leds off when the program terminates signal.signal(signal.SIGTERM, signal_handler) signal.signal(signal.SIGINT, signal_handler)
# Here's how to control the strip from any two GPIO pins: datapin = 2 #BCM - Orange clockpin = 3 #BCM - Gul strip = Adafruit_DotStar(numpixels, datapin, clockpin) # Alternate ways of declaring strip: # strip = Adafruit_DotStar(numpixels) # Use SPI (pins 10=MOSI, 11=SCLK) # strip = Adafruit_DotStar(numpixels, 32000000) # SPI @ ~32 MHz # strip = Adafruit_DotStar() # SPI, No pixel buffer # strip = Adafruit_DotStar(32000000) # 32 MHz SPI, no pixel buf # See image-pov.py for explanation of no-pixel-buffer use. # Append "order='gbr'" to declaration for proper colors w/older DotStar strips) strip.begin() # Initialize pins for output #strip.setBrightness(64) # Limit brightness to ~1/4 duty cycle strip.setBrightness(255) # Runs 10 LEDs at a time along strip, cycling through red, green and blue. # This requires about 200 mA for all the 'on' pixels + 1 mA per 'off' pixel. head = 0 # Index of first 'on' pixel tail = -32 # Index of last 'off' pixel color = 0xFF0000 # 'On' color (starts red) while True: # Loop forever strip.setPixelColor(head, color) # Turn on 'head' pixel strip.setPixelColor(tail, 0) # Turn off 'tail' strip.show() # Refresh strip #time.sleep(1.0 / 50) # Pause 20 milliseconds (~50 fps) time.sleep(1.0 / 75)
def main(): # Build playlist of songs os.system("rm -f /home/pi/playlist.pls; find " + song_location + " | grep 'flac\|ogg\|mp3' | shuf > playlist.pls") global num_lines try: num_lines = sum(1 for line in open('playlist.pls')) except: num_lines = 0 turnOff() if num_lines == 0: demoMode() # No file/Empty file. Do demo mode! while True: # Loops continuously until unplugged queueNext() turnOff() # Currently an issue with skipping back, should be a nonissue in the future. if mixer.music.get_busy(): mixer.music.stop() os.system('umount /mnt/usb; umount /dev/sdb1') turnOff() GPIO.cleanup() def mountDevice(): os.system('mount /dev/sdb1 /mnt/usb') if __name__ == "__main__": # Wow this is pretty ugly - I'm in a hurry, though. mountDevice() strip = Adafruit_DotStar(numPixels, datapin, clockpin) strip.begin() strip.setBrightness(64) mixer.init(48000, -16, 1, 1024) main()
color = (red << 16 | green << 8 | blue) strip.setPixelColor(numpixels - row, color) strip.show() sleep(.0004) clear(strip) if time() > timeout: break sleep(.05) if len(sys.argv) < 2: print "Usage: %s: <png file> [png file] ..." % sysargv[0] sys.exit(-1) strip = Adafruit_DotStar(numpixels, order='bgr') strip.begin() strip.setBrightness(70) startup(strip) images = load_files(sys.argv[1:]) try: main_loop(strip, images) except KeyboardInterrupt: clear(strip) sys.exit(0)
0xFF00FF, 0xFF00FF, 0xFF00FF, ] # Contains all of the Information which the user sets up at beginning of setup button_pin = 12 # BCM GPIO Pin number that the button is connected to GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Set as an input numpixels = 30 # Number of LEDs in strip LINK = "http://192.168.0.3:8080" # Address of the Server:8080 BRIGHTNESS = 200 # 0-255 how bright the LEDs should be 255 = 100% duty cycle strip = Adafruit_DotStar(numpixels, 12000000) strip.begin() # Initialize pins for output strip.setBrightness(BRIGHTNESS) # Limit brightness to ~1/4 duty cycle (0-255) color = 0xFF0000 # 'On' color (starts Green) print "Setup: ButtonPin: ", button_pin, "\nNumber of LEDs: ", numpixels # Enters this on Button Press. It returns how long the button was held (Waits for release). # If the button is held for more than 3.1 seconds, stop waiting and return. def pushAndHoldTime(pTimeStart): # This is an interrupt that waits for the rising edge (button released) # OR 3 seconds to pass to continue with the program if GPIO.input(button_pin, ) == 1: # if button was released before we got to this point time_release = time.time() # take time reading of 'button release' return time_release - pTimeStart # return amount of time button was held for else:
class Bartender(MenuDelegate): def __init__(self): GPIO.setmode(GPIO.BCM) self.running = False # set the oled screen height self.screen_width = SCREEN_WIDTH self.screen_height = SCREEN_HEIGHT self.btnMenuPlusPin = MENU_PLUS_BTN_PIN self.btnMenuMinPin = MENU_MIN_BTN_PIN self.btnSelectPin = SELECT_BTN_PIN self.btnAdminPin = ADMIN_BTN_PIN self.btnAlcoholPin = ALCOHOL_BTN_PIN # vars for toggle self.alcohol_enabled = False self.admin_enabled = False self.weborders = False # configure interrups for buttons GPIO.setup(self.btnMenuPlusPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.btnMenuMinPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.btnSelectPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.btnAdminPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.btnAlcoholPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # configure screen spi_bus = 0 spi_device = 0 gpio = gaugette.gpio.GPIO() spi = gaugette.spi.SPI(spi_bus, spi_device) # Very important... This lets py-gaugette 'know' what pins to use in order to reset the display self.led = gaugette.ssd1306.SSD1306( gpio, spi, reset_pin=OLED_RESET_PIN, dc_pin=OLED_DC_PIN, rows=self.screen_height, cols=self.screen_width ) # Change rows & cols values depending on your display dimensions. self.led.begin() self.led.clear_display() self.led.display() self.led.invert_display() time.sleep(0.5) self.led.normal_display() time.sleep(0.5) # load the pump configuration from file self.pump_configuration = Bartender.readPumpConfiguration() for pump in self.pump_configuration.keys(): GPIO.setup(self.pump_configuration[pump]["pin"], GPIO.OUT, initial=GPIO.HIGH) # setup pixels: self.numpixels = NUMBER_NEOPIXELS # Number of LEDs in strip # Here's how to control the strip from any two GPIO pins: datapin = NEOPIXEL_DATA_PIN clockpin = NEOPIXEL_CLOCK_PIN self.strip = Adafruit_DotStar(self.numpixels, datapin, clockpin) self.strip.begin() # Initialize pins for output self.strip.setBrightness( NEOPIXEL_BRIGHTNESS) # Limit brightness to ~1/4 duty cycle # turn everything off for i in range(0, self.numpixels): self.strip.setPixelColor(i, 0) self.strip.show() # add var so the system can go back self.lastpagecommand = "" print("Done initializing") @staticmethod def readPumpConfiguration(): return json.load(open('hardware/pump_config.json')) @staticmethod def writePumpConfiguration(configuration): with open("hardware/pump_config.json", "w") as jsonFile: json.dump(configuration, jsonFile) def startInterrupts(self): GPIO.add_event_detect(self.btnMenuPlusPin, GPIO.FALLING, callback=self.menu_plus_btn, bouncetime=MENU_PLUS_BTN_BOUNCE) GPIO.add_event_detect(self.btnMenuMinPin, GPIO.FALLING, callback=self.menu_min_btn, bouncetime=MENU_MIN_BTN_BOUNCE) GPIO.add_event_detect(self.btnSelectPin, GPIO.FALLING, callback=self.select_btn, bouncetime=SELECT_PIN_BOUNCE) GPIO.add_event_detect(self.btnAlcoholPin, GPIO.FALLING, callback=self.alcohol_btn, bouncetime=ALCOHOL_PIN_BOUNCE) GPIO.add_event_detect(self.btnAdminPin, GPIO.FALLING, callback=self.admin_btn, bouncetime=ADMIN_PIN_BOUNCE) def stopInterrupts(self): GPIO.remove_event_detect(self.btnAlcoholPin) GPIO.remove_event_detect(self.btnAdminPin) GPIO.remove_event_detect(self.btnSelectPin) GPIO.remove_event_detect(self.btnMenuMinPin) GPIO.remove_event_detect(self.btnMenuPlusPin) def buildMenu(self, drink_list, drink_options, alcoholic_drinks_enabled=False, admin_options_enabled=False): # create a new main menu m = Menu("Main Menu") # add drink options drink_opts = [] for d in drink_list: # check if allowed by admin button if alcoholic_drinks_enabled == False: # check if the drink has alcohol if d["alcoholic"] == False: # -----!!!!----- drink_opts.append( MenuItem('drink', d["name"], {"ingredients": d["ingredients"] })) # -----!!!!----- else: drink_opts.append( MenuItem('drink', d["name"], {"ingredients": d["ingredients"]})) configuration_menu = Menu("Configure") # add pump configuration options pump_opts = [] for p in sorted(self.pump_configuration.keys()): config = Menu(self.pump_configuration[p]["name"]) # add fluid options for each pump for opt in drink_options: # star the selected option selected = "*" if opt["value"] == self.pump_configuration[p][ "value"] else "" config.addOption( MenuItem('pump_selection', opt["name"], { "key": p, "value": opt["value"], "name": opt["name"] })) # add a back button so the user can return without modifying config.addOption(Back("Back")) config.setParent(configuration_menu) pump_opts.append(config) # add pump menus to the configuration menu configuration_menu.addOptions(pump_opts) # add a back button to the configuration menu configuration_menu.addOption(Back("Back")) # adds an option that cleans all pumps to the configuration menu configuration_menu.addOption(MenuItem('clean', 'Clean')) # adds the option to power off configuration_menu.addOption(MenuItem('poweroff', 'Power off')) configuration_menu.setParent(m) # add drinks to options m.addOptions(drink_opts) # check if admin is enabled if admin_options_enabled == True: m.addOption(configuration_menu) # create a menu context self.menuContext = MenuContext(m, self) def filterDrinks(self, menu): """ Removes any drinks that can't be handled by the pump configuration """ for i in menu.options: if (i.type == "drink"): i.visible = False ingredients = i.attributes["ingredients"] presentIng = 0 for ing in ingredients.keys(): for p in self.pump_configuration.keys(): if (ing == self.pump_configuration[p]["value"]): presentIng += 1 if (presentIng == len(ingredients.keys())): i.visible = True elif (i.type == "menu"): self.filterDrinks(i) def selectConfigurations(self, menu): """ Adds a selection star to the pump configuration option """ for i in menu.options: if (i.type == "pump_selection"): key = i.attributes["key"] if (self.pump_configuration[key]["value"] == i.attributes["value"]): i.name = "%s %s" % (i.attributes["name"], "*") else: i.name = i.attributes["name"] elif (i.type == "menu"): self.selectConfigurations(i) def prepareForRender(self, menu): self.filterDrinks(menu) self.selectConfigurations(menu) return True def menuItemClicked(self, menuItem): if (menuItem.type == "drink"): self.makeDrink(menuItem.name, menuItem.attributes["ingredients"]) return True elif (menuItem.type == "pump_selection"): self.pump_configuration[menuItem.attributes["key"]][ "value"] = menuItem.attributes["value"] Bartender.writePumpConfiguration(self.pump_configuration) return True elif (menuItem.type == "clean"): self.clean() return True elif (menuItem.type == "poweroff"): self.shutdown() return True return False def clean(self): waitTime = 20 pumpThreads = [] # cancel any button presses while the drink is being made # self.stopInterrupts() self.running = True for pump in self.pump_configuration.keys(): pump_t = threading.Thread( target=self.pour, args=(self.pump_configuration[pump]["pin"], waitTime)) pumpThreads.append(pump_t) # start the pump threads for thread in pumpThreads: thread.start() # start the progress bar self.progressBar(waitTime) # wait for threads to finish for thread in pumpThreads: thread.join() # show the main menu self.menuContext.showMenu() # sleep for a couple seconds to make sure the interrupts don't get triggered time.sleep(2) # ; # reenable interrupts # self.startInterrupts() self.running = False def shutdown(self): print("system will go off") os.system("sudo shutdown -h now") def displayMenuItem(self, menuItem): print menuItem.name self.led.clear_display() self.led.draw_text2(0, 20, menuItem.name, 2) self.led.display() print("set on oled") print(menuItem.type) print(menuItem.name) self.displayInBrowser(menuItem) def displayInBrowser(self, menuItem): # check the type and open the matching page if (menuItem.type == "drink"): path = "/drink?drink={0}".format(base64.encodestring( menuItem.name)) self.create_exectute_display_command(path) else: path = "/basic-menu?item={0}&type={1}".format( base64.encodestring(menuItem.name), base64.encodestring(menuItem.type)) self.create_exectute_display_command(path) def create_exectute_display_command(self, webpath): # makes the command with the given parms command = "DISPLAY=:0 firefox '{0}:{1}{2}' &".format( server_host, server_port, webpath) # execute os.system(command) def cycleLights(self): t = threading.currentThread() head = 0 # Index of first 'on' pixel tail = -10 # Index of last 'off' pixel color = 0xFF0000 # 'On' color (starts red) while getattr(t, "do_run", True): self.strip.setPixelColor(head, color) # Turn on 'head' pixel self.strip.setPixelColor(tail, 0) # Turn off 'tail' self.strip.show() # Refresh strip time.sleep(1.0 / 50) # Pause 20 milliseconds (~50 fps) head += 1 # Advance head position if (head >= self.numpixels): # Off end of strip? head = 0 # Reset to start color >>= 8 # Red->green->blue->black if (color == 0): color = 0xFF0000 # If black, reset to red tail += 1 # Advance tail position if (tail >= self.numpixels): tail = 0 # Off end? Reset def lightsEndingSequence(self): # make lights green for i in range(0, self.numpixels): self.strip.setPixelColor(i, 0xFF0000) self.strip.show() time.sleep(5) # turn lights off for i in range(0, self.numpixels): self.strip.setPixelColor(i, 0) self.strip.show() def pour(self, pin, waitTime): GPIO.output(pin, GPIO.LOW) time.sleep(waitTime) GPIO.output(pin, GPIO.HIGH) def progressBar(self, waitTime): interval = waitTime / 100.0 for x in range(1, 101): self.led.clear_display() self.updateProgressBar(x, y=35) self.led.display() time.sleep(interval) def makeDrink(self, drink, ingredients): # cancel any button presses while the drink is being made # self.stopInterrupts() self.running = True # show a page so the user knows it's buzzy self.create_exectute_display_command("/making?drink={0}".format( base64.encodestring(drink))) self.served_drink = drink # launch a thread to control lighting lightsThread = threading.Thread(target=self.cycleLights) lightsThread.start() # Parse the drink ingredients and spawn threads for pumps maxTime = 0 pumpThreads = [] # store the longes wait time to sleep later longestWaitTime = 0 for ing in ingredients.keys(): for pump in self.pump_configuration.keys(): if ing == self.pump_configuration[pump]["value"]: waitTime = ingredients[ing] * FLOW_RATE if (waitTime > maxTime): maxTime = waitTime pump_t = threading.Thread( target=self.pour, args=(self.pump_configuration[pump]["pin"], waitTime)) pumpThreads.append(pump_t) # chek waiting time if longestWaitTime < waitTime: longestWaitTime = waitTime # start the pump threads for thread in pumpThreads: thread.start() # start the progress bar self.progressBar(maxTime) # wait for threads to finish for thread in pumpThreads: thread.join() # sleep(longestWaitTime) # show the main menu self.menuContext.showMenu() # stop the light thread lightsThread.do_run = False lightsThread.join() # show the ending sequence lights self.lightsEndingSequence() # sleep for a couple seconds to make sure the interrupts don't get triggered time.sleep(4) # ; # reenable interrupts # self.startInterrupts() self.running = False def menu_plus_btn(self, ctx): print("plus hit") if not self.running: self.menuContext.advance() def menu_min_btn(self, ctx): print("min hit") if not self.running: self.menuContext.previous() def select_btn(self, ctx): if not self.running: print("cocktail selected") self.menuContext.select() else: #could be better but due the fact: # thread can't be stopped # error ignored #no better solution print("Cancel selected") self.create_exectute_display_command("/cancel?drink={0}".format( base64.encodestring(self.served_drink))) for pump in self.pump_configuration.keys(): GPIO.output(self.pump_configuration[pump]["pin"], GPIO.HIGH) print("cancel done") def alcohol_btn(self, ctx): print("alcohol hit") # rebuild the menu self.alcohol_enabled = self.alcohol_enabled ^ 1 self.buildMenu(drink_list, drink_options, self.alcohol_enabled, self.admin_enabled) # -----!!!!----- def admin_btn(self, ctx): print("admin hit") # rebuild the menu self.admin_enabled = self.admin_enabled ^ 1 self.buildMenu(drink_list, drink_options, self.alcohol_enabled, self.admin_enabled) # -----!!!!----- def updateProgressBar(self, percent, x=15, y=15): height = 10 width = self.screen_width - 2 * x for w in range(0, width): self.led.draw_pixel(w + x, y) self.led.draw_pixel(w + x, y + height) for h in range(0, height): self.led.draw_pixel(x, h + y) self.led.draw_pixel(self.screen_width - x, h + y) for p in range(0, percent): p_loc = int(p / 100.0 * width) self.led.draw_pixel(x + p_loc, h + y) def run(self): self.startInterrupts() def start_operation(self): self.buildMenu(drink_list, drink_options) self.run() @staticmethod def set_gpio(): GPIO.setmode(GPIO.BCM) def clean_gpio(self): self.stopInterrupts() GPIO.cleanup()
import time from dotstar import Adafruit_DotStar numpixels = 8 datapin = 16 clockpin = 20 strip = Adafruit_DotStar(numpixels, datapin, clockpin) strip.begin() strip.setBrightness(64) #while True: strip.setPixelColor(0, 255, 0, 0) strip.setPixelColor(1, 255, 0, 0) strip.setPixelColor(2, 255, 0, 0) strip.setPixelColor(3, 255, 0, 0) strip.setPixelColor(4, 255, 0, 0) strip.setPixelColor(5, 255, 255, 0) strip.setPixelColor(6, 255, 255, 0) strip.setPixelColor(7, 0, 255, 0) strip.show() #except KeyboardInterrupt: #strip.setPixelColor(0, 0, 0, 0) #break
if (STRIP_LIBRARY == STRIP_LIBRARY_DOTSTAR): from dotstar import Adafruit_DotStar elif (STRIP_LIBRARY == STRIP_LIBRARY_WS2813): from neopixel import Adafruit_NeoPixel from neopixel import ws # Setup if (STRIP_LIBRARY == STRIP_LIBRARY_DOTSTAR): STRIP = Adafruit_DotStar(STRIP_NUMBER_OF_PIXELS, STRIP_DATA_PIN, STRIP_CLOCK_PIN) elif (STRIP_LIBRARY == STRIP_LIBRARY_WS2813): STRIP = Adafruit_NeoPixel(STRIP_NUMBER_OF_PIXELS, STRIP_DATA_PIN, STRIP_FREQ_HZ, STRIP_DMA, STRIP_INVERT, STRIP_BRIGHTNESS, STRIP_CHANNEL, STRIP_TYPE) else: sys.exit ("Unknown Strip Type in config.py") STRIP.begin() STRIP.setBrightness(STRIP_BRIGHTNESS) def set_brightness(b): STRIP.setBrightness(b) def _set_pixel_color (strip,p,r,g,b): rgb = r*256*256 + g*256 + b if (STRIP_LIBRARY == STRIP_LIBRARY_DOTSTAR): strip.setPixelColor(p,r,g,b) elif (STRIP_LIBRARY == STRIP_LIBRARY_WS2813): strip.setPixelColor(p,rgb) def fade(current_state, target_state): 'Sets the colours of the lights to be closer to the target colour'
import json import atexit from dotstar import Adafruit_DotStar NUM_PIXELS = 324 DATA_PIN = 23 CLOCK_PIN = 24 ANIMATION_PATH = "/opt/hat_server/animations/" STATUS_FILE = "{}current.status".format(ANIMATION_PATH) hat = Adafruit_DotStar(NUM_PIXELS, DATA_PIN, CLOCK_PIN, order='bgr') hat.begin() hat.setBrightness(16) while True: status = None with open(STATUS_FILE, 'r') as statusfile: status = json.loads(statusfile.read()) if (status['type'] == "off"): hat.clear() hat.show() time.sleep(2) continue annimation = None animation_file = "{}{}.json".format(ANIMATION_PATH, status['name'])
NUM_LEDS = 100 DATAPIN = 15 CLOCKPIN = 14 strip = Adafruit_DotStar(NUM_LEDS, DATAPIN, CLOCKPIN) RED = (255, 0, 0) GREEN = (0, 255, 0) OFF = (0, 0, 0) strip.begin() brightness = 255 strip.setBrightness(brightness) go(OFF) print("done") def main(): while True: print("green") go(GREEN, 0.1) print("red") go(RED, 0.1) if __name__ == '__main__': main()
#!/usr/bin/env python2.7 import ephem import time from dotstar import Adafruit_DotStar #INITIALIZE AND CLEAR DOTSTAR numpixels = 72 # Number of LEDs in strip # Here's how to control the strip from any two GPIO pins: datapin = 23 clockpin = 24 strip = Adafruit_DotStar(numpixels, datapin, clockpin) strip.begin() # Initialize pins for output strip.setBrightness(32) # Limit brightness to ~1/4 duty cycle #turn all leds to black (off) offspot = 1 offcolor = 0x000000 nump = 73 while offspot < nump: strip.setPixelColor(offspot, offcolor) offspot += 1 strip.show() #PYEPHEM PART--GET MOON SPOTS moons = ((ephem.Io(), 'i'), (ephem.Europa(), 'e'), (ephem.Ganymede(), 'g'), (ephem.Callisto(), 'c'))
# Set the strip to all white, and strobe it on and off. import time from dotstar import Adafruit_DotStar WHITE = 0xFFFFFF # 8-bit GRB MAX_BRIGHTNESS = 255 n_pixels = 72 # Number of LEDs in strip strip = Adafruit_DotStar(n_pixels) # Use SPI (pins 10=MOSI, 11=SCLK) strip.begin() # Initialize pins for output frequency = 12 # Hz period = 1.0/frequency # seconds duty_cycle = 0.125 on_period = duty_cycle * period off_period = period - on_period for p in range(n_pixels): strip.setPixelColor(p, WHITE) while True: # Turn strobe on. strip.setBrightness(MAX_BRIGHTNESS) strip.show() time.sleep(on_period) # Turn strobe off. strip.setBrightness(0) strip.show() time.sleep(off_period) # Note that the actual period will be the specified period PLUS compute time.
class Bartender(MenuDelegate): def __init__(self): self.running = False # set the oled screen height self.screen_width = SCREEN_WIDTH self.screen_height = SCREEN_HEIGHT self.btn1Pin = LEFT_BTN_PIN self.btn2Pin = RIGHT_BTN_PIN # configure interrups for buttons GPIO.setup(self.btn1Pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.btn2Pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # configure screen spi_bus = 0 spi_device = 0 gpio = gaugette.gpio.GPIO() spi = gaugette.spi.SPI(spi_bus, spi_device) # Very important... This lets py-gaugette 'know' what pins to use in order to reset the display self.led = gaugette.ssd1306.SSD1306( gpio, spi, reset_pin=OLED_RESET_PIN, dc_pin=OLED_DC_PIN, rows=self.screen_height, cols=self.screen_width ) # Change rows & cols values depending on your display dimensions. self.led.begin() self.led.clear_display() self.led.display() self.led.invert_display() time.sleep(0.5) self.led.normal_display() time.sleep(0.5) # load the pump configuration from file self.pump_configuration = Bartender.readPumpConfiguration() for pump in self.pump_configuration.keys(): GPIO.setup(self.pump_configuration[pump]["pin"], GPIO.OUT, initial=GPIO.HIGH) # setup pixels: self.numpixels = NUMBER_NEOPIXELS # Number of LEDs in strip # Here's how to control the strip from any two GPIO pins: datapin = NEOPIXEL_DATA_PIN clockpin = NEOPIXEL_CLOCK_PIN self.strip = Adafruit_DotStar(self.numpixels, datapin, clockpin) self.strip.begin() # Initialize pins for output self.strip.setBrightness( NEOPIXEL_BRIGHTNESS) # Limit brightness to ~1/4 duty cycle # turn everything off for i in range(0, self.numpixels): self.strip.setPixelColor(i, 0) self.strip.show() print "Done initializing" @staticmethod def readPumpConfiguration(): return json.load(open('pump_config.json')) @staticmethod def writePumpConfiguration(configuration): with open("pump_config.json", "w") as jsonFile: json.dump(configuration, jsonFile) def startInterrupts(self): GPIO.add_event_detect(self.btn1Pin, GPIO.FALLING, callback=self.left_btn, bouncetime=LEFT_PIN_BOUNCE) GPIO.add_event_detect(self.btn2Pin, GPIO.FALLING, callback=self.right_btn, bouncetime=RIGHT_PIN_BOUNCE) def stopInterrupts(self): GPIO.remove_event_detect(self.btn1Pin) GPIO.remove_event_detect(self.btn2Pin) def buildMenu(self, drink_list, drink_options): # create a new main menu m = Menu("Main Menu") # add drink options drink_opts = [] for d in drink_list: drink_opts.append( MenuItem('drink', d["name"], {"ingredients": d["ingredients"]})) configuration_menu = Menu("Configure") # add pump configuration options pump_opts = [] for p in sorted(self.pump_configuration.keys()): config = Menu(self.pump_configuration[p]["name"]) # add fluid options for each pump for opt in drink_options: # star the selected option selected = "*" if opt["value"] == self.pump_configuration[p][ "value"] else "" config.addOption( MenuItem('pump_selection', opt["name"], { "key": p, "value": opt["value"], "name": opt["name"] })) # add a back button so the user can return without modifying config.addOption(Back("Back")) config.setParent(configuration_menu) pump_opts.append(config) # add pump menus to the configuration menu configuration_menu.addOptions(pump_opts) # add a back button to the configuration menu configuration_menu.addOption(Back("Back")) # adds an option that cleans all pumps to the configuration menu configuration_menu.addOption(MenuItem('clean', 'Clean')) configuration_menu.setParent(m) m.addOptions(drink_opts) m.addOption(configuration_menu) # create a menu context self.menuContext = MenuContext(m, self) def filterDrinks(self, menu): """ Removes any drinks that can't be handled by the pump configuration """ for i in menu.options: if (i.type == "drink"): i.visible = False ingredients = i.attributes["ingredients"] presentIng = 0 for ing in ingredients.keys(): for p in self.pump_configuration.keys(): if (ing == self.pump_configuration[p]["value"]): presentIng += 1 if (presentIng == len(ingredients.keys())): i.visible = True elif (i.type == "menu"): self.filterDrinks(i) def selectConfigurations(self, menu): """ Adds a selection star to the pump configuration option """ for i in menu.options: if (i.type == "pump_selection"): key = i.attributes["key"] if (self.pump_configuration[key]["value"] == i.attributes["value"]): i.name = "%s %s" % (i.attributes["name"], "*") else: i.name = i.attributes["name"] elif (i.type == "menu"): self.selectConfigurations(i) def prepareForRender(self, menu): self.filterDrinks(menu) self.selectConfigurations(menu) return True def menuItemClicked(self, menuItem): if (menuItem.type == "drink"): self.makeDrink(menuItem.name, menuItem.attributes["ingredients"]) return True elif (menuItem.type == "pump_selection"): self.pump_configuration[menuItem.attributes["key"]][ "value"] = menuItem.attributes["value"] Bartender.writePumpConfiguration(self.pump_configuration) return True elif (menuItem.type == "clean"): self.clean() return True return False def clean(self): waitTime = 20 pumpThreads = [] # cancel any button presses while the drink is being made # self.stopInterrupts() self.running = True for pump in self.pump_configuration.keys(): pump_t = threading.Thread( target=self.pour, args=(self.pump_configuration[pump]["pin"], waitTime)) pumpThreads.append(pump_t) # start the pump threads for thread in pumpThreads: thread.start() # start the progress bar self.progressBar(waitTime) # wait for threads to finish for thread in pumpThreads: thread.join() # show the main menu self.menuContext.showMenu() # sleep for a couple seconds to make sure the interrupts don't get triggered time.sleep(2) # reenable interrupts # self.startInterrupts() self.running = False def displayMenuItem(self, menuItem): print menuItem.name self.led.clear_display() self.led.draw_text2(0, 20, menuItem.name, 2) self.led.display() def cycleLights(self): t = threading.currentThread() head = 0 # Index of first 'on' pixel tail = -10 # Index of last 'off' pixel color = 0xFF0000 # 'On' color (starts red) while getattr(t, "do_run", True): self.strip.setPixelColor(head, color) # Turn on 'head' pixel self.strip.setPixelColor(tail, 0) # Turn off 'tail' self.strip.show() # Refresh strip time.sleep(1.0 / 50) # Pause 20 milliseconds (~50 fps) head += 1 # Advance head position if (head >= self.numpixels): # Off end of strip? head = 0 # Reset to start color >>= 8 # Red->green->blue->black if (color == 0): color = 0xFF0000 # If black, reset to red tail += 1 # Advance tail position if (tail >= self.numpixels): tail = 0 # Off end? Reset def lightsEndingSequence(self): # make lights green for i in range(0, self.numpixels): self.strip.setPixelColor(i, 0xFF0000) self.strip.show() time.sleep(5) # turn lights off for i in range(0, self.numpixels): self.strip.setPixelColor(i, 0) self.strip.show() def pour(self, pin, waitTime): GPIO.output(pin, GPIO.LOW) time.sleep(waitTime) GPIO.output(pin, GPIO.HIGH) def progressBar(self, waitTime): interval = waitTime / 100.0 for x in range(1, 101): self.led.clear_display() self.updateProgressBar(x, y=35) self.led.display() time.sleep(interval) def makeDrink(self, drink, ingredients): # cancel any button presses while the drink is being made # self.stopInterrupts() self.running = True # launch a thread to control lighting lightsThread = threading.Thread(target=self.cycleLights) lightsThread.start() # Parse the drink ingredients and spawn threads for pumps maxTime = 0 pumpThreads = [] for ing in ingredients.keys(): for pump in self.pump_configuration.keys(): if ing == self.pump_configuration[pump]["value"]: waitTime = ingredients[ing] * FLOW_RATE if (waitTime > maxTime): maxTime = waitTime pump_t = threading.Thread( target=self.pour, args=(self.pump_configuration[pump]["pin"], waitTime)) pumpThreads.append(pump_t) # start the pump threads for thread in pumpThreads: thread.start() # start the progress bar self.progressBar(maxTime) # wait for threads to finish for thread in pumpThreads: thread.join() # show the main menu self.menuContext.showMenu() # stop the light thread lightsThread.do_run = False lightsThread.join() # show the ending sequence lights self.lightsEndingSequence() # sleep for a couple seconds to make sure the interrupts don't get triggered time.sleep(2) # reenable interrupts # self.startInterrupts() self.running = False def left_btn(self, ctx): if not self.running: self.menuContext.advance() def right_btn(self, ctx): if not self.running: self.menuContext.select() def updateProgressBar(self, percent, x=15, y=15): height = 10 width = self.screen_width - 2 * x for w in range(0, width): self.led.draw_pixel(w + x, y) self.led.draw_pixel(w + x, y + height) for h in range(0, height): self.led.draw_pixel(x, h + y) self.led.draw_pixel(self.screen_width - x, h + y) for p in range(0, percent): p_loc = int(p / 100.0 * width) self.led.draw_pixel(x + p_loc, h + y) def run(self): self.startInterrupts() # main loop try: while True: time.sleep(0.1) except KeyboardInterrupt: GPIO.cleanup() # clean up GPIO on CTRL+C exit GPIO.cleanup() # clean up GPIO on normal exit traceback.print_exc()
class DotStar(DriverBase): """ A device driver must implement each of the methods in the DriverBase class. The driver class name is arbitrary and generally is not exposed. Add the driver to the app by modifying the manager.get_driver() method (the driver factory). """ def __init__(self): DriverBase.__init__(self) @property def name(self): return "DotstarDriver" def open(self, num_pixels, order='rgb'): """ Open the device :param num_pixels: Total number of pixels on the strip/string. :param order: The order of colors as expected by the strip/string. :return: """ self._strip = Adafruit_DotStar(num_pixels, order=order.encode('utf-8')) # print self._strip self._numpixels = num_pixels return self._begin() def _begin(self): # The begin() method does not return a useful value self._strip.begin() return True def show(self): return self._strip.show() == 0 def numPixels(self): return self._numpixels def setBrightness(self, brightness): self._strip.setBrightness(brightness) return True def setPixelColor(self, index, color_value): self._strip.setPixelColor(index, color_value) return True def clear(self): for i in range(self._numpixels): self._strip.setPixelColor(i, 0) self._strip.show() return True def close(self): """ Close and release the current device. :return: None """ del self._strip self._strip = None return True def color(self, r, g, b, gamma=False): """ Create a composite RGB color value :param r: 0-255 :param g: 0-255 :param b: 0-255 :param gamma: If True, gamma correction is applied. :return: """ # Note that this IS NOT the same order as the DotStar if gamma: return (DotStar._gamma8[r] << 16) | ( DotStar._gamma8[g] << 8) | DotStar._gamma8[b] return (r << 16) | (g << 8) | b
17: 5, 4: 6, 18: 7, 19: 8, 13: 9, 26: 10, 23: 11 } # Pin Number : Effect ID effect_id = [0] # Keeps track of effects, index 0 reserved for solo effects, # all other indices are for "supplemental" effects supplementals = [8, 9, 10, 11] # List of supplemental effect id's strip = Adafruit_DotStar(num_pixels, 12000000, order='bgr') # Initialize strip strip.begin() max_brightness = 20 # Save my eyes strip.setBrightness(max_brightness) effect.update_brightness(max_brightness) effect.set_strip(strip, num_pixels) # Set up effects module # Set up button pins GPIO.setmode(GPIO.BCM) for pin in pins.keys(): GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) while True: strip.show() # Update strip # Get button states, and execute appropriate effects for pin, e_id in pins.items(): active = not GPIO.input(pin)
CONNECTIVITY_TIMER = 15 # seconds PRECIP_PROBABILITY = 0.2 GLOBAL_BRIGHTNESS = 0.25 # color settings clear_day = rain = Color(15, 50, 255) clear_night = Color(0, 0, 255, 0.1) fog = cloudy = Color(255, 255, 255, 0.4) snow = Color(255, 255, 255) # setup LEDs datapin = 10 clockpin = 11 strip = Adafruit_DotStar(LED_COUNT, datapin, clockpin) strip.begin() # Initialize pins for output strip.setBrightness(int(GLOBAL_BRIGHTNESS * 255.0)) # Limit brightness to ~1/4 duty cycle precipHours = [] loopCount = 0 thread = None connectThread = None data = None logger = None active = False isInit = False def init(): # logger = firelog(data['product_name'], data['guid'], data) internetOn(True)
import time import random from dotstar import Adafruit_DotStar numpixels = 80 # Number of LEDs in strip # Here's how to control the strip from any two GPIO pins: datapins = [16, 13] clockpin = 27 a = Adafruit_DotStar(numpixels, datapins[0], clockpin, order='bgr') a.begin() a.setBrightness(100) b = Adafruit_DotStar(numpixels, datapins[1], clockpin, order='bgr') b.begin() b.setBrightness(100) a.setPixelColor(68, 0x0000FF) a.show() time.sleep(2) b.setPixelColor(68, 0x0000FF) b.show()
fireplacestart = False soundstart = False soundplaying = False #Setting color to: 0xFF0000 # Green #Setting color to: 0xCC00CC # Bright Teal #Setting color to: 0x66CC00 # Orange #Setting color to: 0x33FFFF # Magenta #Setting color to: 0xFF00 # Red #Setting color to: 0x330099 # Lightish Blue #Setting color to: 0xFFFF00 # YEllow #Setting color to: 0xFF # Bright Blue #Setting color to: 0xFF9900 # YEllower Gren #Setting color to: 0x33 # Dark BLue strip = Adafruit_DotStar(numpixels, datapin, clockpin) strip.setBrightness(255) strip.begin() # Initialize pins for output def main(): global strip global allcolors global firecolors logevent("startup", "startup", "Just started and ready to run") for x in range(len(fire_colors)): if x == len(fire_colors) - 1: pass else: print("Adding gradient for %s (%s) to %s (%s) with %s colors" % (fire_colors[x], hex_to_RGB( fire_colors[x]), fire_colors[x + 1],
import sys import struct import math from dotstar import Adafruit_DotStar numpixels = 60 # Number of LEDs in strip # Here's how to control the strip from any two GPIO pins: datapin = 23 clockpin = 24 defaultColor = 0x0000FF defaultBright = 32 flashColor = 0xF0F0FF flashBright = 255 strip = Adafruit_DotStar(numpixels, datapin, clockpin) strip.setBrightness(defaultBright) strip.begin() # Initialize pins for output hi_thres = 200 low_thres = 100 lightning = False def main(): global strip global lightning sounds = [0, 0, 0] channels = 2
def run_strip(mode="off", brightness=255): numpixels = 240 # Number of LEDs in strip print("run_strip inbound mode:", mode) # Here's how to control the strip from any two GPIO pins: datapin = 10 clockpin = 11 strip = Adafruit_DotStar(numpixels, datapin, clockpin) # brightness is an integer from 1 to 255 # mode, in time, should enable other things besides just being full on # strip.begin() # Initialize pins for output # strip.setBrightness(brightness) # Limit brightness to ~1/4 duty cycle # used for mode: comet # head = 0 # Index of first 'on' pixel # tail = -10 # Index of last 'off' pixel color = 0xFFFFFF # 'On' color (starts red) # some control variables for light power on/off easing _pow = 3 _frames = 50 _maxb = 255 # _max_brightness, might change when brightness configuration is enabled if mode == "off": print("run_strip: turn off strip") try: count = 0 const = _maxb**(1 / (_pow * 1.0)) is_turning_off = True strip.begin() while is_turning_off: count += 1 if count == _frames: is_turning_off = False strip.setBrightness(_maxb) # now that ramping is done set # to max configured brightness else: brightness = int(_maxb - (count / (_frames * 1.0) * const)**_pow) strip.setBrightness(brightness) for idx in range(numpixels): strip.setPixelColor(idx, color) strip.show() # Refresh strip time.sleep(1.0 / 50) except KeyboardInterrupt: print("cleaning up") GPIO.cleanup() strip.clear() strip.show() print("done") # try to set color to black/off before turning off to prevent final flash for idx in range(numpixels): strip.setPixelColor(idx, 0x000000) strip.setBrightness(0) # clean up interrupts? # GPIO.cleanup() # strip.clear() strip.show() # print("done") elif mode == "on": print("run_strip: starting strip") try: count = 0 const = _maxb**(1 / (_pow * 1.0)) is_turning_on = True strip.begin() while True: # Loop forever if is_turning_on: count += 1.0 if count == _frames: is_turning_on = False strip.setBrightness( _maxb) # now that ramping is done set # to max configured brightness else: brightness = int( (count / (_frames * 1.0) * const)**_pow) strip.setBrightness(brightness) for idx in range(numpixels): strip.setPixelColor(idx, color) # strip.setPixelColor(head, color) # Turn on 'head' pixel # strip.setPixelColor(tail, 0) # Turn off 'tail' strip.show() # Refresh strip time.sleep(1.0 / 50) # Pause 20 milliseconds (~50 fps) # head += 1 # Advance head position # if(head >= numpixels): # Off end of strip? # head = 0 # Reset to start # color >>= 8 # Red->green->blue->black # if(color == 0): color = 0xFF0000 # If black, reset to red # tail += 1 # Advance tail position # if(tail >= numpixels): tail = 0 # Off end? Reset except KeyboardInterrupt: print("cleaning up") GPIO.cleanup() strip.clear() strip.show() print("done") except SystemError as err: print("SystemError:", err)
#! /usr/bin/python import time from random import randint from dotstar import Adafruit_DotStar # set up our strip numpixels = 144 strip = Adafruit_DotStar(numpixels, 12000000, order='bgr') # start our strip strip.begin() strip.setBrightness(32) def finish(): # finished, clear the pixels strip.clear() strip.show() def wormChase(startLength): # start with a chase like the strandtest # but with the chase getting longer each time head = 0 tail = -startLength color = 0xFF0000 # repeat nine times across all pixels for i in range(numpixels * 9): strip.setPixelColor(head, color) strip.setPixelColor(tail, 0)
elif t != now: print str(ephem.date(t))[5:16] ################ #DotStar section------> Make a fuction, then call it after getting positions ################ numpixels = 72 # Number of LEDs in strip # Here's how to control the strip from any two GPIO pins: datapin = 23 clockpin = 24 strip = Adafruit_DotStar(numpixels, datapin, clockpin) strip.begin() # Initialize pins for output strip.setBrightness(128) # Limit brightness to ~1/4 duty cycle #First, turn all black offspot = 1 offcolor = 0x000000 while offspot >= 1: strip.setPixelColor(offspot, offcolor) offspot += 1 if offspot == 72: break #set initial spots and colors of Jupiter and moons jupspot = 36 #jupiter position jupcolor = 0xFF8801 #jupiter color
class Bartender(MenuDelegate): def __init__(self): self.running = False # set the oled screen height self.screen_width = SCREEN_WIDTH self.screen_height = SCREEN_HEIGHT self.make_drink = MAKE_DRINK self.btn1Pin = LEFT_BTN_PIN self.btn2Pin = RIGHT_BTN_PIN self.clk = CLK_PIN self.dt = DT_PIN # configure interrupts for buttons #GPIO.setup(self.btn1Pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(self.btn2Pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # configure interrupts for encoder GPIO.setup(self.clk, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(self.dt, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #Pi config RST = 21 DC = 20 SPI_PORT = 0 SPI_DEVICE = 0 # configure screen self.disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST) self.disp.begin() self.disp.clear() self.disp.display() #draw self.image = Image.new('1', (SCREEN_WIDTH, SCREEN_HEIGHT)) self.draw = ImageDraw.Draw(self.image) self.draw.rectangle((0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), outline=0, fill=0) self.font = ImageFont.load_default() # Very important... This lets py-gaugette 'know' what pins to use in order to reset the display # Change rows & cols values depending on your display dimensions. # load the pump configuration from file self.pump_configuration = Bartender.readJson( '/home/pi/Documents/PiDrink/static/json/pump_config.json') for pump in self.pump_configuration.keys(): GPIO.setup(self.pump_configuration[pump]["pin"], GPIO.OUT, initial=GPIO.HIGH) # load the current drink list self.drink_list = Bartender.readJson( '/home/pi/Documents/PiDrink/static/json/drink_list.json') self.drink_list = self.drink_list["drink_list"] # load the current drink options self.drink_options = Bartender.readJson( '/home/pi/Documents/PiDrink/static/json/drink_options.json') self.drink_options = self.drink_options["drink_options"] # setup pixels: self.numpixels = NUMBER_NEOPIXELS # Number of LEDs in strip # Here's how to control the strip from any two GPIO pins: datapin = NEOPIXEL_DATA_PIN clockpin = NEOPIXEL_CLOCK_PIN self.strip = Adafruit_DotStar(self.numpixels, datapin, clockpin) self.strip.begin() # Initialize pins for output self.strip.setBrightness( NEOPIXEL_BRIGHTNESS) # Limit brightness to ~1/4 duty cycle # turn everything off for i in range(0, self.numpixels): self.strip.setPixelColor(i, 0) self.strip.show() print('Done initializing') # def check_email(self): # status, email_ids = self.imap_server.search(None, '(UNSEEN)') # if email_ids == ['']: # mail_list = [] # else: # mail_list = self.get_subjects(email_ids) #FYI when calling the get_subjects function, the email is marked as 'read' # self.imap_server.close() # return mail_list # def get_subjects(self, email_ids): # subjects_list = [] # for e_id in email_ids[0].split(): # resp, data = self.imap_server.fetch(e_id, '(RFC822)') # perf = HeaderParser().parsestr(data[0][1]) # subjects_list.append(perf['Subject']) # return subjects_list def voice_command(self, mail_list): for mail in mail_list: found = False while (found == False): currmen = self.menuContext.currentMenu.getSelection() if (currmen.name == mail): self.makeDrink(currmen.name, currmen.attributes["ingredients"]) self.make_drink = False found = True else: self.menuContext.currentMenu.nextSelection() found = False @staticmethod def readJson(file): return json.load(open(file)) @staticmethod def writePumpConfiguration(configuration): with open("/home/pi/Documents/PiDrink/static/json/pump_config.json", "w") as jsonFile: json.dump(configuration, jsonFile) def startInterrupts(self): #GPIO.add_event_detect(self.btn1Pin, GPIO.FALLING, callback=self.left_btn, bouncetime=LEFT_PIN_BOUNCE) GPIO.add_event_detect(self.btn2Pin, GPIO.FALLING, callback=self.right_btn, bouncetime=RIGHT_PIN_BOUNCE) GPIO.add_event_detect(self.clk, GPIO.BOTH, callback=self.rotary_on_change, bouncetime=1000) def stopInterrupts(self): #GPIO.remove_event_detect(self.btn1Pin) GPIO.remove_event_detect(self.btn2Pin) GPIO.remove_event_detect(self.clk) def buildMenu(self): # create a new main menu m = Menu("Main Menu") # add drink options drink_opts = [] for d in self.drink_list: drink_opts.append( MenuItem('drink', d["name"], {"ingredients": d["ingredients"]})) configuration_menu = Menu("Configure") # add pump configuration options pump_opts = [] for p in sorted(self.pump_configuration.keys()): config = Menu(self.pump_configuration[p]["name"]) # add fluid options for each pump for opt in self.drink_options: # star the selected option selected = "*" if opt["value"] == self.pump_configuration[p][ "value"] else "" config.addOption( MenuItem('pump_selection', opt["name"], { "key": p, "value": opt["value"], "name": opt["name"] })) # add a back button so the user can return without modifying config.addOption(Back("Back")) config.setParent(configuration_menu) pump_opts.append(config) # add pump menus to the configuration menu configuration_menu.addOptions(pump_opts) # add a back button to the configuration menu configuration_menu.addOption(Back("Back")) # adds an option that cleans all pumps to the configuration menu configuration_menu.addOption(MenuItem('clean', 'Clean')) configuration_menu.setParent(m) m.addOptions(drink_opts) m.addOption(configuration_menu) # create a menu context self.menuContext = MenuContext(m, self) def filterDrinks(self, menu): """ Removes any drinks that can't be handled by the pump configuration """ for i in menu.options: if (i.type == "drink"): i.visible = False ingredients = i.attributes["ingredients"] presentIng = 0 for ing in ingredients.keys(): for p in self.pump_configuration.keys(): if (ing == self.pump_configuration[p]["value"]): presentIng += 1 if (presentIng == len(ingredients.keys())): i.visible = True elif (i.type == "menu"): self.filterDrinks(i) def selectConfigurations(self, menu): """ Adds a selection star to the pump configuration option """ for i in menu.options: if (i.type == "pump_selection"): key = i.attributes["key"] if (self.pump_configuration[key]["value"] == i.attributes["value"]): i.name = "%s %s" % (i.attributes["name"], "*") else: i.name = i.attributes["name"] elif (i.type == "menu"): self.selectConfigurations(i) def prepareForRender(self, menu): self.filterDrinks(menu) self.selectConfigurations(menu) return True def menuItemClicked(self, menuItem): if (menuItem.type == "drink"): if self.make_drink: self.makeDrink(menuItem.name, menuItem.attributes["ingredients"]) self.make_drink = False return True elif (menuItem.type == "pump_selection"): self.pump_configuration[menuItem.attributes["key"]][ "value"] = menuItem.attributes["value"] Bartender.writePumpConfiguration(self.pump_configuration) return True elif (menuItem.type == "clean"): if self.make_drink: self.clean() self.make_drink = False return True return False def changeConfiguration(self, pumps): # Change configuration of every pump for i in range(1, 7): self.pump_configuration["pump_" + str(i)]["value"] = pumps[i - 1] Bartender.writePumpConfiguration(self.pump_configuration) def clean(self): waitTime = 30 pumpProcesses = [] # cancel any button presses while the drink is being made # self.stopInterrupts() self.running = True for pump in self.pump_configuration.keys(): pump_p = threading.Thread(target=self.pour, args=( self.pump_configuration[pump]["pin"], waitTime, )) pumpProcesses.append(pump_p) disp_process = threading.Thread(target=self.progressBar, args=(waitTime, )) pumpProcesses.append(disp_process) # start the pump threads for process in pumpProcesses: process.start() # wait for threads to finish for process in pumpProcesses: process.join() # sleep for a couple seconds to make sure the interrupts don't get triggered time.sleep(2) # reenable interrupts # self.startInterrupts() self.running = False self.make_drink = True self.menuContext.showMenu() def displayMenuItem(self, menuItem): #Clear display self.draw.rectangle((0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), outline=0, fill=0) self.draw.text((20, 10), menuItem.name, font=self.font, fill=255) self.disp.image(self.image) self.disp.display() def cycleLights(self): t = threading.currentThread() head = 0 # Index of first 'on' pixel tail = -10 # Index of last 'off' pixel color = 0xFF0000 # 'On' color (starts red) while getattr(t, "do_run", True): self.strip.setPixelColor(head, color) # Turn on 'head' pixel self.strip.setPixelColor(tail, 0) # Turn off 'tail' self.strip.show() # Refresh strip time.sleep(1.0 / 50) # Pause 20 milliseconds (~50 fps) head += 1 # Advance head position if (head >= self.numpixels): # Off end of strip? head = 0 # Reset to start color >>= 8 # Red->green->blue->black if (color == 0): color = 0xFF0000 # If black, reset to red tail += 1 # Advance tail position if (tail >= self.numpixels): tail = 0 # Off end? Reset def lightsEndingSequence(self): # make lights green for i in range(0, self.numpixels): self.strip.setPixelColor(i, 0xFF0000) self.strip.show() time.sleep(5) # turn lights off for i in range(0, self.numpixels): self.strip.setPixelColor(i, 0) self.strip.show() def pour(self, pin, waitTime): GPIO.output(pin, GPIO.LOW) time.sleep(waitTime) GPIO.output(pin, GPIO.HIGH) def progressBar(self, waitTime): interval = waitTime / 116.3 for x in range(1, 101): # Clear display self.draw.rectangle((0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), outline=0, fill=0) #self.draw.text((55,20), str(x) + '%', font = self.font, fill=255) self.updateProgressBar(x, y=10) self.disp.image(self.image) self.disp.display() time.sleep(interval) # # self.disp.clear() # # self.disp.display() # self.image = Image.open('happycat_oled_32.ppm').convert('1') # self.disp.image(self.image) # self.disp.display() def makeDrink(self, drink, ingredients): if self.running: return # cancel any button presses while the drink is being made # self.stopInterrupts() print('Making a ' + drink) self.running = True # launch a thread to control lighting lightsThread = threading.Thread(target=self.cycleLights) lightsThread.start() # Make a list for each potential time maxTime = 0 pumpProcesses = [] for ing in ingredients.keys(): for pump in self.pump_configuration.keys(): if ing == self.pump_configuration[pump]["value"]: waitTime = ingredients[ing] * FLOW_RATE if (waitTime > maxTime): maxTime = waitTime pump_p = threading.Thread( target=self.pour, args=(self.pump_configuration[pump]["pin"], waitTime)) pumpProcesses.append(pump_p) disp_process = threading.Thread(target=self.progressBar, args=(maxTime, )) pumpProcesses.append(disp_process) # start the pump threads for process in pumpProcesses: process.start() # wait for threads to finish for process in pumpProcesses: process.join() # stop the light thread lightsThread.do_run = False lightsThread.join() # show the ending sequence lights self.lightsEndingSequence() # reenable interrupts # sleep for a couple seconds to make sure the interrupts don't get triggered time.sleep(2) # self.startInterrupts() self.running = False print('Finished making ' + drink) self.make_drink = True # show the main menu self.menuContext.showMenu() def left_btn(self, ctx): if not self.running: self.menuContext.advance() def right_btn(self, ctx): if not self.running: self.menuContext.select() def rotary_on_change(self, ctx): if not self.running: if GPIO.input(self.dt): self.menuContext.retreat() else: self.menuContext.advance() def get_ingredients_time(self, drink): # Get the ingredients for the specified drink found = False while (found == False): currmen = self.menuContext.currentMenu.getSelection() if (currmen.name == drink): ingredients = currmen.attributes["ingredients"] self.make_drink = False found = True else: self.menuContext.currentMenu.nextSelection() # Get the drink making time maxTime = 0 for ing in ingredients.keys(): for pump in self.pump_configuration.keys(): if ing == self.pump_configuration[pump]["value"]: waitTime = ingredients[ing] * FLOW_RATE if (waitTime > maxTime): maxTime = waitTime # Return making time and ingredients for drink return ingredients, maxTime def updateProgressBar(self, percent, x=15, y=10): height = 10 width = self.screen_width - 2 * x for w in range(0, width): self.draw.point((w + x, y), fill=255) self.draw.point((w + x, y + height), fill=255) for h in range(0, height): self.draw.point((x, h + y), fill=255) self.draw.point((self.screen_width - x, h + y), fill=255) for p in range(0, percent): p_loc = int(p / 100.0 * width) self.draw.point((x + p_loc, h + y), fill=255) self.draw.text((55, 20), str(percent) + '%', font=self.font, fill=255) #self.disp.image(self.image) #self.disp.display() def endprogram(self): global stopprogram stopprogram = True # Goodbye message self.draw.rectangle((0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), outline=0, fill=0) self.draw.text((25, 10), "Goodbye...", font=self.font, fill=255) self.disp.image(self.image) self.disp.display() time.sleep(3) self.draw.rectangle((0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), outline=0, fill=0) self.draw.text((15, 10), "Have a great day!", font=self.font, fill=255) self.disp.image(self.image) self.disp.display() time.sleep(3) self.disp.clear() self.disp.display() def run(self): self.startInterrupts() # main loop try: while True: if stopprogram: return # self.imap_server = imaplib.IMAP4_SSL("imap.gmail.com",993) # self.imap_server.login(USERNAME, PASSWORD) # self.imap_server.select('INBOX') # mail_list = self.check_email() # if mail_list and not self.running: # self.voice_command(mail_list) time.sleep(0.1) except KeyboardInterrupt: GPIO.cleanup() # clean up GPIO on CTRL+C exit sys.exit(0) GPIO.cleanup() # clean up GPIO on normal exit traceback.print_exc()
class Strip(object): def __init__(self): self.strip = Adafruit_DotStar(NUM_LEDS, 10, 11) self.strip.begin() self.stream = None self.time = 0 def set_colour(self, colour, brightness=50): # Turn all leds the same colour self.strip.setBrightness(brightness) for i in range(NUM_LEDS): self.strip.setPixelColor(i, colour) self.strip.show() def set_colour_rgb(self, r, g, b, brightness=50): # Turn all leds the same colour self.strip.setBrightness(brightness) for i in range(NUM_LEDS): self.strip.setPixelColor(i, g, r, b) self.strip.show() def black(self): self.strip.setBrightness(0) self.strip.show() def aqua(self): # Aqua logo, white text self.strip.setBrightness(50) # White r, g, b = 255, 255, 255 for i in range(180): self.strip.setPixelColor(i, g, r, b) # Aqua r, g, b = 64, 191, 180 for i in range(180, NUM_LEDS): self.strip.setPixelColor(i, g, r, b) self.strip.show() def hue(self, starting_hue=0): # Rainbow through hue spectrum self.strip.setBrightness(50) repeat = 2 s = 1 v = 1 for i in range(NUM_LEDS): h = i / NUM_LEDS * repeat + starting_hue r, g, b = hsv_to_rgb(h, s, v) r = int(r * 255) g = int(g * 255) b = int(b * 255) self.strip.setPixelColor(i, b, r, g) self.strip.show() def animate_hue(self): self.time += 0.01 self.hue(self.time) def red_tick(self, time=0): # Full brightness brightness = 100 r = 0.5 + 0.5 * sin(self.time) g = 0 b = 0 r = int(r * 255) g = int(g * 255) b = int(b * 255) self.set_colour_rgb(r, g, b, brightness) def animate_red(self): # Red flashing self.time += 0.05 self.red_tick(self.time) def noop(self): pass def animate_audio_hue(self): if self.stream is None: self.stream = Stream() bass, mid = self.stream.process_chunk() self.music_hue(bass, mid) def music_hue(self, bass, mid): self.strip.setBrightness(50) h = 0.7 - mid * 0.7 # hue from blue (0) to red (1) s = 1 v = 0.5 + bass * 0.5 r, g, b = hsv_to_rgb(h, s, v) r = int(r * 255) g = int(g * 255) b = int(b * 255) self.set_colour_rgb(r, g, b) def animate_audio_vis(self): if self.stream is None: self.stream = Stream() bass, mid = self.stream.process_chunk() self.music_vis(bass, mid) def music_vis(self, bass, mid): self.strip.setBrightness(50) h = 0.7 - mid * 0.7 # hue from blue (0) to red (1) s = 1 v = 1 r, g, b = hsv_to_rgb(h, s, v) r = int(r * 255) g = int(g * 255) b = int(b * 255) x = int(bass * NUM_LEDS) for i in range(x): self.strip.setPixelColor(i, g, r, b) for i in range(x, NUM_LEDS): self.strip.setPixelColor(i, 0, 0, 0) self.strip.show()
def main(argv): global MODE global INPUT global p MODE = sys.argv[1] # debug / pi INPUT = sys.argv[2] # camera / image / video p = ThreadPool(4) # MODE SETUP FOR LEDs or Display if MODE == 'debug': print('Running in Debug mode') cv2.namedWindow('preview') strip = True # If you're running on the PI, you want to setup the LED strip if MODE == 'pi': from dotstar import Adafruit_DotStar strip = Adafruit_DotStar(HEIGHT*WIDTH + OFFSET, DATAPIN, CLOCKPIN) strip.begin() # Lower power consumption, but makes it flicker. strip.setBrightness(LED_GLOBAL_BRIGHTNESS) bitmap = initialize_empty_bitmap() render_bitmap(bitmap, strip) # INPUT SELECTION SETUP # If you're using a USB camera for input # TODO: Allow for arg use for different cameras if INPUT == 'camera': if MODE == 'debug': cv2.namedWindow('cameraPreview', cv2.WINDOW_NORMAL) vc = cv2.VideoCapture(0) if vc.isOpened(): # vc.set(15, -10) vc.set(3,200) # These aren't accurate, but help vc.set(4,100) rval, frame = vc.read() else: rval = False while rval: rval, frame = vc.read() # if MODE == 'debug': # cv2.imshow('cameraPreview', frame) start = time.time() flow(frame, bitmap, strip) key = cv2.waitKey(15) if key == 27: # exit on ESC break end = time.time() print(end - start) # If you're using a static image for debugging if INPUT == 'image': if len(sys.argv) == 4: frame = cv2.imread(sys.argv[3]) else: frame = cv2.imread('bars.jpg') rval = True # while True: # For 1000 frames start = time.time() while True: flow(frame, bitmap, strip) key = cv2.waitKey(15) if key == 27: # exit on ESC break end = time.time() fps = 1000 / (end - start) print('fps:', fps) # If you're using a pre-recorded video for debugging set it here if INPUT == 'video': cv2.namedWindow('videoPreview', cv2.WINDOW_NORMAL) vc = cv2.VideoCapture('WaveCanon2.mp4') if vc.isOpened(): rval, frame = vc.read() else: rval = False while rval: rval, frame = vc.read() frame = shrink(frame) # 1080p video too big coming in cv2.imshow('videoPreview', frame) flow(frame, bitmap, strip) key = cv2.waitKey(15) if key == 27: # exit on ESC break return False
def init_led(args): strip = Adafruit_DotStar(args.numPixels, 12000000) strip.begin() strip.setBrightness(args.brightness) return strip
class Bartender(MenuDelegate): def __init__(self): self.running = False # set the oled screen height self.screen_width = SCREEN_WIDTH self.screen_height = SCREEN_HEIGHT self.btn1Pin = LEFT_BTN_PIN self.btn2Pin = RIGHT_BTN_PIN # configure interrups for buttons GPIO.setup(self.btn1Pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.btn2Pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # configure screen spi_bus = 0 spi_device = 0 #Load the display driver. Attention: 128_64 is the display size. Needed to be changed if different in your setup self.led = disp = Adafruit_SSD1306.SSD1306_128_64( rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000) ) # Change rows & cols values depending on your display dimensions. # Initialize library. self.led.begin() # Clear display. self.led.clear() self.led.display() # Create image buffer. # Make sure to create image with mode '1' for 1-bit color. self.image = Image.new('1', (self.screen_width, self.screen_height)) # Load default font. #self.font = ImageFont.load_default() self.font = ImageFont.truetype(FONTFILE, FONTSIZE) # Create drawing object. self.draw = ImageDraw.Draw(self.image) # load the pump configuration from file self.pump_configuration = Bartender.readPumpConfiguration() for pump in self.pump_configuration.keys(): GPIO.setup(self.pump_configuration[pump]["pin"], GPIO.OUT, initial=GPIO.HIGH) # setup pixels: self.numpixels = NUMBER_NEOPIXELS # Number of LEDs in strip # Here's how to control the strip from any two GPIO pins: datapin = NEOPIXEL_DATA_PIN clockpin = NEOPIXEL_CLOCK_PIN self.strip = Adafruit_DotStar(self.numpixels, datapin, clockpin) #Auskommentiert solange noch kein LED Strip angebracht. #self.strip.begin() # Initialize pins for output self.strip.setBrightness( NEOPIXEL_BRIGHTNESS) # Limit brightness to ~1/4 duty cycle # turn everything off for i in range(0, self.numpixels): self.strip.setPixelColor(i, 0) self.strip.show() print "Done initializing" @staticmethod def readPumpConfiguration(): return json.load(open('pump_config.json')) @staticmethod def writePumpConfiguration(configuration): with open("pump_config.json", "w") as jsonFile: json.dump(configuration, jsonFile) def startInterrupts(self): GPIO.add_event_detect(self.btn1Pin, GPIO.FALLING, callback=self.left_btn, bouncetime=LEFT_PIN_BOUNCE) GPIO.add_event_detect(self.btn2Pin, GPIO.FALLING, callback=self.right_btn, bouncetime=RIGHT_PIN_BOUNCE) def buildMenu(self, drink_list, drink_options): # create a new main menu m = Menu("Main Menu") # add drink options drink_opts = [] for d in drink_list: drink_opts.append( MenuItem('drink', d["name"], {"ingredients": d["ingredients"]})) configuration_menu = Menu("Configure") # add pump configuration options pump_opts = [] for p in sorted(self.pump_configuration.keys()): config = Menu(self.pump_configuration[p]["name"]) # add fluid options for each pump for opt in drink_options: # star the selected option selected = "*" if opt["value"] == self.pump_configuration[p][ "value"] else "" config.addOption( MenuItem('pump_selection', opt["name"], { "key": p, "value": opt["value"], "name": opt["name"] })) # add a back button so the user can return without modifying config.addOption(Back("Back")) config.setParent(configuration_menu) pump_opts.append(config) # add pump menus to the configuration menu configuration_menu.addOptions(pump_opts) # add a back button to the configuration menu configuration_menu.addOption(Back("Back")) # adds an option that cleans all pumps to the configuration menu configuration_menu.addOption(MenuItem('clean', 'Clean')) # adds an option that shuts down the rpi configuration_menu.addOption(MenuItem('shutdown', 'Shutdown')) configuration_menu.setParent(m) m.addOptions(drink_opts) m.addOption(configuration_menu) # create a menu context self.menuContext = MenuContext(m, self) def filterDrinks(self, menu): """ Removes any drinks that can't be handled by the pump configuration """ for i in menu.options: if (i.type == "drink"): i.visible = False ingredients = i.attributes["ingredients"] presentIng = 0 for ing in ingredients.keys(): for p in self.pump_configuration.keys(): if (ing == self.pump_configuration[p]["value"]): presentIng += 1 if (presentIng == len(ingredients.keys())): i.visible = True elif (i.type == "menu"): self.filterDrinks(i) def selectConfigurations(self, menu): """ Adds a selection star to the pump configuration option """ for i in menu.options: if (i.type == "pump_selection"): key = i.attributes["key"] if (self.pump_configuration[key]["value"] == i.attributes["value"]): i.name = "%s %s" % (i.attributes["name"], "*") else: i.name = i.attributes["name"] elif (i.type == "menu"): self.selectConfigurations(i) def prepareForRender(self, menu): self.filterDrinks(menu) self.selectConfigurations(menu) return True def menuItemClicked(self, menuItem): if (menuItem.type == "drink"): self.makeDrink(menuItem.name, menuItem.attributes["ingredients"]) return True elif (menuItem.type == "pump_selection"): self.pump_configuration[menuItem.attributes["key"]][ "value"] = menuItem.attributes["value"] Bartender.writePumpConfiguration(self.pump_configuration) return True elif (menuItem.type == "clean"): self.clean() return True elif (menuItem.type == "shutdown"): self.shutdown() return True return False def clean(self): waitTime = 20 pumpThreads = [] # cancel any button presses while the drink is being made # self.stopInterrupts() self.running = True for pump in self.pump_configuration.keys(): pump_t = threading.Thread( target=self.pour, args=(self.pump_configuration[pump]["pin"], waitTime)) pumpThreads.append(pump_t) # start the pump threads for thread in pumpThreads: thread.start() # start the progress bar self.progressBar(waitTime) # wait for threads to finish for thread in pumpThreads: thread.join() # show the main menu self.menuContext.showMenu() # sleep for a couple seconds to make sure the interrupts don't get triggered time.sleep(2) def shutdown(self): shutdowntext = "Shutdown takes 10 seconds. Bye!" self.led.clear() self.draw.rectangle((0, 0, self.screen_width, self.screen_height), outline=0, fill=0) words_list = WRAPPER.wrap(text=shutdowntext) TextNew = '' for ii in words_list[:-1]: TextNew = TextNew + ii + "\n" TextNew += words_list[-1] self.draw.text((0, 10), str(TextNew), font=self.font, fill=255) self.led.image(self.image) self.led.display() time.sleep(5) #Clean shutdown device subprocess.Popen(['shutdown', '-h', 'now']) def displayMenuItem(self, menuItem): print menuItem.name self.led.clear() self.draw.rectangle((0, 0, self.screen_width, self.screen_height), outline=0, fill=0) words_list = WRAPPER.wrap(text=menuItem.name) MenuItemNew = '' for ii in words_list[:-1]: MenuItemNew = MenuItemNew + ii + "\n" MenuItemNew += words_list[-1] self.draw.text((0, 10), str(MenuItemNew), font=self.font, fill=255) self.led.image(self.image) self.led.display() def cycleLights(self): t = threading.currentThread() head = 0 # Index of first 'on' pixel tail = -10 # Index of last 'off' pixel color = 0xFF0000 # 'On' color (starts red) while getattr(t, "do_run", True): self.strip.setPixelColor(head, color) # Turn on 'head' pixel self.strip.setPixelColor(tail, 0) # Turn off 'tail' self.strip.show() # Refresh strip time.sleep(1.0 / 50) # Pause 20 milliseconds (~50 fps) head += 1 # Advance head position if (head >= self.numpixels): # Off end of strip? head = 0 # Reset to start color >>= 8 # Red->green->blue->black if (color == 0): color = 0xFF0000 # If black, reset to red tail += 1 # Advance tail position if (tail >= self.numpixels): tail = 0 # Off end? Reset def lightsEndingSequence(self): # make lights green for i in range(0, self.numpixels): self.strip.setPixelColor(i, 0xFF0000) self.strip.show() time.sleep(5) # turn lights off for i in range(0, self.numpixels): self.strip.setPixelColor(i, 0) self.strip.show() def pour(self, pin, waitTime): GPIO.output(pin, GPIO.LOW) time.sleep(waitTime) GPIO.output(pin, GPIO.HIGH) def progressBar(self, waitTime): interval = waitTime / 100.0 for x in range(1, 101): self.led.clear() self.draw.rectangle((0, 0, self.screen_width, self.screen_height), outline=0, fill=0) self.updateProgressBar(x, y=35) self.led.image(self.image) self.led.display() time.sleep(interval) def makeDrink(self, drink, ingredients): # cancel any button presses while the drink is being made # self.stopInterrupts() self.running = True # launch a thread to control lighting lightsThread = threading.Thread(target=self.cycleLights) lightsThread.start() # Parse the drink ingredients and spawn threads for pumps maxTime = 0 pumpThreads = [] for ing in ingredients.keys(): for pump in self.pump_configuration.keys(): if ing == self.pump_configuration[pump]["value"]: waitTime = ingredients[ing] * FLOW_RATE if (waitTime > maxTime): maxTime = waitTime pump_t = threading.Thread( target=self.pour, args=(self.pump_configuration[pump]["pin"], waitTime)) pumpThreads.append(pump_t) # start the pump threads for thread in pumpThreads: thread.start() # start the progress bar self.progressBar(maxTime) # wait for threads to finish for thread in pumpThreads: thread.join() # show the main menu self.menuContext.showMenu() # stop the light thread lightsThread.do_run = False lightsThread.join() # show the ending sequence lights self.lightsEndingSequence() # sleep for a couple seconds to make sure the interrupts don't get triggered time.sleep(2) # reenable interrupts # self.startInterrupts() self.running = False def left_btn(self, ctx): print("LEFT_BTN pressed") if not self.running: self.running = True self.menuContext.advance() print("Finished processing button press") self.running = False def right_btn(self, ctx): print("RIGHT_BTN pressed") if not self.running: self.running = True self.menuContext.select() print("Finished processing button press") self.running = 2 print("Starting button timeout") def updateProgressBar(self, percent, x=15, y=15): height = 10 width = self.screen_width - 2 * x for w in range(0, width): self.draw.point((w + x, y), fill=255) self.draw.point((w + x, y + height), fill=255) for h in range(0, height): self.draw.point((x, h + y), fill=255) self.draw.point((self.screen_width - x, h + y), fill=255) for p in range(0, percent): p_loc = int(p / 100.0 * width) self.draw.point((x + p_loc, h + y), fill=255) def run(self): self.startInterrupts() # main loop try: try: while True: letter = raw_input(">") if letter == "l": self.left_btn(False) if letter == "r": self.right_btn(False) except EOFError: while True: time.sleep(0.1) if self.running not in (True, False): self.running -= 0.1 if self.running == 0: self.running = False print("Finished button timeout") except KeyboardInterrupt: GPIO.cleanup() # clean up GPIO on CTRL+C exit GPIO.cleanup() # clean up GPIO on normal exit traceback.print_exc()
strip.show() sleep(pause) NUM_LEDS = 100 DATAPIN = 15 CLOCKPIN = 14 strip = Adafruit_DotStar(NUM_LEDS, DATAPIN, CLOCKPIN) RED = (255, 0, 0) GREEN = (0, 255, 0) OFF = (0, 0, 0) strip.begin() brightness = 255 strip.setBrightness(brightness) go(OFF) print("done") def main(): while True: print("green") go(GREEN, 0.1) print("red") go(RED, 0.1) if __name__ == '__main__': main()
logging.debug('request ' + str(r)) if data['version'] != v: v = data['version'] logging.debug('version ' + str(v)) logging.debug(data) return True, True thread.start_new_thread(getData, (), {'data': data}) return v, r num = 500 s = Adafruit_DotStar(num, 12000000) s.begin() s.setBrightness(255) def mono(h): return h >> 16 def rgb(d): return (d << 16) + (d << 8) + d def twinkle(p): i = mono(s.getPixelColor(p)) if i == 0: if random.random() < 0.03: s.setPixelColor(p, 0xFFFFFF) return True s.setPixelColor(p, 0) return True
import time from dotstar import Adafruit_DotStar WHITE = 0xFFFFFF n_pixels = 72 # Number of LEDs in strip strip = Adafruit_DotStar(n_pixels) # Use SPI (pins 10=MOSI, 11=SCLK) strip.begin() # Initialize pins for output # Open log file. f = open('powerlog.txt', 'w') f.write("Brightness\tVoltage\n") for p in range(n_pixels): strip.setPixelColor(p, WHITE) for b in range(256): #print b # Set the brightness. strip.setBrightness(b) strip.show() # Refresh strip # Prompt user for data entry. answer = raw_input(str(b)+' ') # Log it. f.write(str(b)+"\t"+answer+"\n") f.flush() # Wait a fraction of a second to help ensure that the write completes, # in case the next brightness level crashes the system. time.sleep(0.1) f.close()
#!/usr/bin/python import math import time from dotstar import Adafruit_DotStar num_pixels = 240 # Number of LEDs in strip. strip = Adafruit_DotStar(num_pixels) # Use SPI (pins 10=MOSI, 11=SCLK). strip.begin() # Initialize pins for output. strip.setBrightness(255) # Full brightness. def simple_chaser(strip, step, period=60): for pixel in range(strip.numPixels()): r = 1.0 + 0.5 * math.cos( (pixel - step) / float(period) * 2 * math.pi - 2 * math.pi / 3) g = 1.0 + 0.5 * math.cos( (pixel - step) / float(period) * 2 * math.pi + 2 * math.pi / 3) b = 1.0 + 0.5 * math.cos((pixel - step) / float(period) * 2 * math.pi) color = ((min(255, int(256 * max(r, 0))) << 16) + (min(255, int(256 * max(g, 0))) << 8) + (min(255, int(256 * max(b, 0))))) strip.setPixelColor(pixel, color) class TravelingWave(object): def __init__(self, wavenumber, omega, phi_0, gain, offset): self.wavenumber = wavenumber self.omega = omega
class SnipsMatrix: queue = Queue.Queue() state_hotword = None state_waiting = None state_rotate = None state_time = None state_weather = None timerstop = None timer_hardware = None timer_short_app = None timer = None hotword_status = False custom_anim = False def __init__(self): numpixels = 128 datapin = 10 clockpin = 11 self.strip = Adafruit_DotStar(numpixels, datapin, clockpin, 1000000) self.strip.begin() self.strip.setBrightness(64) SnipsMatrix.state_hotword = AnimationImage('hotword', self.strip) SnipsMatrix.state_time = AnimationTime(self.strip) SnipsMatrix.state_rotate = AnimationRotate(self.strip, 0) SnipsMatrix.state_weather = AnimationWeather(self.strip) SnipsMatrix.custom_anim = SnipsMatrix.load_custom_animation(self.strip) SnipsMatrix.queue.put(snipsMatrixAction.Hotword()) SnipsMatrix.queue.put(snipsMatrixAction.Clear( DisplayPriority.hardware)) t = threading.Thread(target=SnipsMatrix.worker, args=()) t.start() def hotword_detected(self): SnipsMatrix.hotword_status = True SnipsMatrix.queue.put(snipsMatrixAction.Hotword()) def stop(self): print('stop all animation') self.stop_all_timer() SnipsMatrix.queue.put(snipsMatrixAction.Clear( DisplayPriority.hardware)) def exit(self): print('exit snipsmatrix') self.stop_all_timer() SnipsMatrix.queue.put(snipsMatrixAction.Exit()) def stop_hotword(self): print('stop hotword') SnipsMatrix.hotword_status = False SnipsMatrix.queue.put(snipsMatrixAction.Clear(DisplayPriority.hotword)) def save_image(self, name, directory, image): already_exist = True if (image is None): return if not os.path.exists(CONFIG_INI_DIR): os.makedirs(CONFIG_INI_DIR) if not os.path.exists(CONFIG_INI_DIR + directory): os.makedirs(CONFIG_INI_DIR + directory) already_exist = False f_name = "{}{}/{}".format(CONFIG_INI_DIR, directory, name) try: with open(f_name, 'w') as f: f.write(image) except IOError as e: print(e) return if already_exist: del SnipsMatrix.custom_anim[directory] SnipsMatrix.custom_anim[directory] = AnimationImage( CONFIG_INI_DIR + directory, self.strip, True) def show_time(self, duration, value): if duration is None: duration = 70 SnipsMatrix.create_timer_time(duration, value) def show_animation(self, name, duration=15): SnipsMatrix.queue.put(snipsMatrixAction.CustomAnimation(name)) if duration is None: duration = 12 SnipsMatrix.create_short_app_timer(duration) def show_timer(self, duration): if duration is None: return SnipsMatrix.create_timer(duration) def show_rotate(self, vol): if vol is None: return SnipsMatrix.queue.put(snipsMatrixAction.Rotate(vol)) SnipsMatrix.create_hardware_timer(10) def show_weather(self, tmp, weather): SnipsMatrix.queue.put(snipsMatrixAction.Weather(weather, tmp)) SnipsMatrix.create_short_app_timer(20) @staticmethod def load_custom_animation(strip): dirs = glob.glob("{}*/".format(CONFIG_INI_DIR)) names = [(x.split('/')[-2], x) for x in dirs] res = {} for k in names: res[k[0]] = AnimationImage(k[1], strip, True) res['light'] = AnimationImage('light', strip) res['music'] = AnimationImage('music', strip) return res @staticmethod def worker(): item = "" oldItem = "" goback = False flip = False while True: time.sleep(0.01) if (not SnipsMatrix.queue.empty()): oldItem = item goback = False item = SnipsMatrix.queue.get_nowait() SnipsMatrix.queue.task_done() print(item) if isinstance(item, snipsMatrixAction.Timer): if DisplayPriority.can_I_do_it(DisplayPriority.schedule_apps): SnipsMatrix.state_time.show(item, flip) item = "" else: item = oldItem if isinstance(item, snipsMatrixAction.Time): if DisplayPriority.can_I_do_it(DisplayPriority.short_apps): SnipsMatrix.state_time.show(item, flip) item = "" else: item = oldItem elif isinstance(item, snipsMatrixAction.Rotate): if DisplayPriority.can_I_do_it(DisplayPriority.hardware): SnipsMatrix.state_rotate.show(item) item = "" else: item = oldItem elif isinstance(item, snipsMatrixAction.Weather): if DisplayPriority.can_I_do_it(DisplayPriority.short_apps): SnipsMatrix.state_weather.show(item, flip) item = "" else: item = oldItem elif isinstance(item, snipsMatrixAction.Hotword): if DisplayPriority.can_I_do_it(DisplayPriority.hotword): SnipsMatrix.state_hotword.show() else: item = oldItem elif isinstance(item, snipsMatrixAction.Clear): if DisplayPriority.can_I_do_it(item.value): SnipsMatrix.state_hotword.reset(0) item = "" else: item = oldItem elif isinstance(item, snipsMatrixAction.Exit): return elif isinstance(item, snipsMatrixAction.CustomAnimation): if DisplayPriority.can_I_do_it(DisplayPriority.short_apps): SnipsMatrix.showCustomAnimation(item) else: item = oldItem @staticmethod def showCustomAnimation(item): if (item.value in SnipsMatrix.custom_anim): print(item.value) SnipsMatrix.custom_anim[item.value].show() @staticmethod def create_timer(duration, stop_time=None): if stop_time is None: stop_time = int(time.time()) + duration duration = stop_time - int(time.time()) if SnipsMatrix.timer: SnipsMatrix.timer.cancel() del SnipsMatrix.timer SnipsMatrix.timer = None if duration >= 0: SnipsMatrix.queue.put(snipsMatrixAction.Timer(duration)) elif duration >= -2: SnipsMatrix.queue.put(snipsMatrixAction.Timer(0)) else: SnipsMatrix.queue.put( snipsMatrixAction.Clear(DisplayPriority.schedule_apps)) return SnipsMatrix.timer = threading.Timer(1, SnipsMatrix.create_timer, args=[duration, stop_time]) SnipsMatrix.timer.start() @staticmethod def create_hardware_timer(duration): if SnipsMatrix.timer_hardware: SnipsMatrix.timer_hardware.cancel() del SnipsMatrix.timer_hardware SnipsMatrix.timer_hardware = None SnipsMatrix.timer_hardware = threading.Timer( duration, SnipsMatrix.stop_show_hardware) SnipsMatrix.timer_hardware.start() @staticmethod def create_short_app_timer(duration): if SnipsMatrix.timer_short_app: SnipsMatrix.timer_short_app.cancel() del SnipsMatrix.timer_short_app SnipsMatrix.timer_short_app = None SnipsMatrix.timer_short_app = threading.Timer( duration, SnipsMatrix.stop_show_short_app) SnipsMatrix.timer_short_app.start() @staticmethod def create_timer_time(duration, value): if value is None or value <= 0: SnipsMatrix.queue.put(snipsMatrixAction.Time(time.time())) else: SnipsMatrix.queue.put(snipsMatrixAction.Time(value)) if SnipsMatrix.timer_short_app: SnipsMatrix.timer_short_app.cancel() del SnipsMatrix.timer_short_app SnipsMatrix.timer_short_app = None if duration < 0: SnipsMatrix.queue.put( snipsMatrixAction.Clear(DisplayPriority.short_apps)) return SnipsMatrix.timer_short_app = threading.Timer( 1, SnipsMatrix.create_timer_time, args=[duration - 1, value]) SnipsMatrix.timer_short_app.start() @staticmethod def stop_all_timer(): if SnipsMatrix.timerstop: SnipsMatrix.timerstop.cancel() del SnipsMatrix.timerstop SnipsMatrix.timerstop = None if SnipsMatrix.timer: SnipsMatrix.timer.cancel() del SnipsMatrix.timer SnipsMatrix.timer = None if SnipsMatrix.timer_hardware: SnipsMatrix.timer_hardware.cancel() del SnipsMatrix.timer_hardware SnipsMatrix.timer_hardware = None if SnipsMatrix.timer_short_app: SnipsMatrix.timer_short_app.cancel() del SnipsMatrix.timer_short_app SnipsMatrix.timer_short_app = None @staticmethod def stop_show_hardware(): if SnipsMatrix.timer_hardware: SnipsMatrix.timer_hardware.cancel() del SnipsMatrix.timer_hardware SnipsMatrix.timer_hardware = None SnipsMatrix.queue.put(snipsMatrixAction.Clear( DisplayPriority.hardware)) @staticmethod def stop_show_short_app(): if SnipsMatrix.timer_short_app: SnipsMatrix.timer_short_app.cancel() del SnipsMatrix.timer_short_app SnipsMatrix.timer_short_app = None SnipsMatrix.queue.put( snipsMatrixAction.Clear(DisplayPriority.short_apps))
import time from dotstar import Adafruit_DotStar import MySQLdb import colorsys numpixels = 5 # Number of LEDs in strip # Here's how to control the strip from any two GPIO pins: datapin = 23 clockpin = 24 strip = Adafruit_DotStar(numpixels, datapin, clockpin) strip.begin() # Initialize pins for output strip.setBrightness(64) # Limit brightness to ~1/4 duty cycle dhost = "localhost" duser = "******" dpass = "******" database = "home" db = MySQLdb.connect(dhost,duser,dpass,database) def scale(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)
# or 0 bytes of data. The latter is possible because we are in nonblocking # mode, but unlikely because we are doing a lot of other work between calls. # NOTE: No matter what argument is passed to this routine, it seems to # always return 370 samples (740 byes). Stupid. inp.setperiodsize(n_samples) # Initialize LED strip. #n_pixels = 72 # Number of LEDs in strip strip = Adafruit_DotStar(n_pixels) # Use SPI (pins 10=MOSI, 11=SCLK) strip.begin() # Initialize pins for output MAX_BRIGHTNESS = 255 #brightness = 32 # Limit brightness to ~1/8 duty cycle #brightness = 64 # Limit brightness to ~1/4 duty cycle brightness = 128 # Limit brightness to ~1/2 duty cycle #brightness = MAX_BRIGHTNESS strip.setBrightness(brightness) WHITE = 0xFFFFFF # 8-bit GRB # Read ColorMaps from files. n_colors = 256 # length of static color maps colorMaps, colorMapNames = readColorMaps() cm_HoldTime = 25.0 cm_FadeTime = 4.0 # Choose first ColorMaps. cm_old_n = random.randrange(len(colorMaps)) cm_old_map = numpy.array(colorMaps[cm_old_n][2][0]) cm_new_n = random.randrange(len(colorMaps)) cm_new_map = numpy.array(colorMaps[cm_new_n][2][0]) print "cm =", colorMapNames[cm_old_n], "->", colorMapNames[cm_new_n] # Set up timers for transition. cm_fade_start = time.time() + cm_HoldTime