class PhoneControls: def __init__(self, callbPush, callbHang, ledPins=(17, 27, 22), buzzerPin=13, pttPin=18, canPin=19): # define properties self.led = RGBLED(ledPins[0], ledPins[1], ledPins[2]) self.buzzer = Buzzer(buzzerPin, active_high=True) self.pttButton = Device.pin_factory.pin(pttPin) self.canButton: Pin = Device.pin_factory.pin(canPin) # configure hardware self.__configPinHandler__(self.pttButton, self.__pttCallback__) self.__configPinHandler__(self.canButton, self.__canCallback__) self.cbCan = callbHang self.cbPtt = callbPush def __configPinHandler__(self, button: Pin, cb): button.edges = "both" button.input_with_pull("up") button.bounce = .250 button.when_changed = cb def __canCallback__(self, ticks, state): sleep(0.2) state = self.canButton.state log.debug("Can button state=%d", state) if state == 0: self.cbCan(CanState.HUNGUP) else: self.cbCan(CanState.LIFTED) def __pttCallback__(self, ticks, state): sleep(0.2) state = self.pttButton.state log.debug("PTT button state=%d", state) if state == 1: self.cbPtt(PttState.RELEASED) else: self.cbPtt(PttState.PRESSED) def ledOff(self): self.led.off() def ledOn(self, rgb=(1, 1, 1)): self.led.value = rgb def startBlinking(self, rgb=(1, 1, 1), off_time=0.5, on_time=0.5): self.led.blink(on_time=on_time, off_time=off_time, on_color=rgb, background=True) def beep(self): self.buzzer.beep(on_time=1, off_time=0.25, background=True) def stopBeep(self): self.buzzer.off()
class Stop: ''' Create a object to store a stop with relation to its rgb pin mappings''' def __init__(self, name, arrival_time, red, green, blue): self.name = name self.arrival_time = arrival_time self.light = RGBLED(red, green, blue) self.colors = { 'red': (1, 0, 0), 'blue': (0, 0, 1), 'green': (0, 1, 0), 'yellow': (1, 1, 0), } def pulse(self, color): self.light.pulse(fade_in_time=.7, fade_out_time=.3, on_color=color, off_color=(0, 0, 0), background=True) return def color_decider(self): ''' Set light to be color/pulse depending on how long until the muni is coming''' self.light.on() if self.arrival_time in (0, 1, 2): self.pulse(self.colors['red']) elif self.arrival_time in (3, 4): self.pulse(self.colors['green']) elif self.arrival_time in (5, 6, 7, 8): self.light.color = self.colors['green'] elif self.arrival_time in (9, 10, 11, 12, 13, 14, 15): self.light.color = self.colors['yellow'] elif self.arrival_time > 15: self.light.color = self.colors['blue'] else: raise Exception( 'Unexpected else in color decider on arrival_time value: {}'. format(self.arriva_time)) return def cycle_colors(self): ''' Cycling colors indicates to users that the lights are updating ''' self.light.on() self.light.color = self.colors['red'] time.sleep(.5) self.light.color = self.colors['green'] time.sleep(.5) self.light.color = self.colors['blue'] time.sleep(.5) self.light.color = self.colors['yellow'] time.sleep(.5) self.light.off()
def notify_led(): """ blink LED indefinitely """ led = RGBLED(red=17, green=27, blue=22) while True: led.color = (1, 0, 1) time.sleep(1) led.off() time.sleep(1) led.color = (1, 1, 0) time.sleep(1)
def handle_lighting(): """Handles the lighting state management.""" status_led = RGBLED(13, 19, 26) steps = 100 current_step = 0 while not QUIT_EVENT.is_set(): if GPS_STATUS in GPSStatus.locked_states(): set_rgb_colour(status_led, Colour.GREEN) sleep(1) else: current_step = (current_step + 1) % steps cycle_rgb_led(status_led, current_step, steps) sleep(1 / steps) status_led.off() status_led.close()
class PiPadLED: # initialize def __init__(self): # set PINs on BOARD log.debug("Initializing LEDs...") log.debug("> RED pin: " + str(_conf['red_pin'])) log.debug("> GREEN pin: " + str(_conf['green_pin'])) log.debug("> BLUE pin: " + str(_conf['blue_pin'])) self.rgbled = RGBLED(_conf['red_pin'], _conf['green_pin'], _conf['blue_pin']) log.debug("...init done!") # off def off(self): log.debug("Set to off") self.rgbled.off() # on def on(self): log.debug("Set to on") self.color() # set color def color(self, color="white", time=0): log.debug("Set to " + color + " color for " + str(time) + "s") self.rgbled.color = Color(color) if not time == 0: sleep(time) self.rgbled.off() # terminate def terminate(self): log.debug("LEDs termination...") self.rgbled.close()
class RGB: def __init__(self): self.led = RGBLED(red=23, green=24, blue=25) self.led.off() def green(self): self.led.color = (0, 1, 0) def red(self): self.led.color = (1, 0, 0) def blue(self): self.led.color = (0, 0, 1) def off(self): self.led.color = (0, 0, 0) def blink(self, color, times, break_seconds): for i in range(times): if color == "green": self.green() sleep(break_seconds) self.off() sleep(break_seconds) if color == "red": self.red() sleep(break_seconds) self.off() sleep(break_seconds) if color == "blue": self.blue() sleep(break_seconds) self.off() sleep(break_seconds)
from gpiozero import RGBLED from time import sleep mainled = RGBLED(2,3,4) mainled.off() mainled.red = 1 sleep(1) mainled.off() mainled.blue = 1 sleep(1) mainled.off() mainled.green = 1 sleep(1) mainled.off()
rangefind = DistanceSensor(24, 18) # Test the LEDs # turn on the RGB LED rgbLED.color = (1, 0, 0) # red time.sleep(1) rgbLED.color = (0, 1, 0) # green time.sleep(1) rgbLED.color = (0, 0, 1) # blue time.sleep(1) rgbLED.color = (1, 1, 1) # bright white time.sleep(1) rgbLED.color = (.01, .01, .01) # dim white time.sleep(1) rgbLED.off() # turn on LED singleLED.value = .01 # dim time.sleep(1) singleLED.value = 1 # bright time.sleep(1) singleLED.off() # test the Rangefinder for thisloop in range(0, 5): print(thisloop, ' - Distance to nearest object is', rangefind.distance, 'm') time.sleep(1) # control the LEDs with the rangefinder
# and choose your own keyword/hashtag (line 56) import time, sys from textblob import TextBlob from gpiozero import RGBLED from twython import TwythonStreamer # Add Python Developer App tokens and secret keys APP_KEY ='ENTER APP KEY HERE' # <- CHANGE APP_SECRET = 'ENTER APP SECRET HERE' # <- CHANGE OAUTH_TOKEN = 'ENTER OAUTH_TOKEN HERE' # <- CHANGE OAUTH_TOKEN_SECRET = 'ENTER OAUTH_TOKEN_SECRET HERE' # <- CHANGE # Set our RGB LED pins status_led = RGBLED(14,15,18, active_high=True) # Set active_high to False for common anode RGB LED status_led.off() totals = {'pos':0,'neg':0,'neu':0} colours = {'pos':(0,1,0),'neg':(1,0,0),'neu':(0,0,1)} class MyStreamer(TwythonStreamer): def on_success(self,data): # When we get valid data if 'text' in data: # If the tweet has a text field tweet = data['text'].encode('utf-8') #print(tweet) # uncomment to display each tweet tweet_pro = TextBlob(data['text']) # calculate sentiment # adjust value below to tune sentiment sensitivity if tweet_pro.sentiment.polarity > 0.1: # Positive print('Positive') status_led.blink(on_time=0.4, off_time=0.2, on_color=(0, 1, 0), n=1, background=False) totals['pos']+=1 # adjust value below to tune sentiment sensitivity
class Beacon(object): connectState = ConnectState.Disconnected failConnectCount = 0 configData = None commandsData = None client = None soundDir = os.path.join(launchDir, 'sounds/') rgbLED = None button = None buttonHoldTime = None persistentLedRule = None def __init__(self): logging.info("Beacon service initialized") with open(os.path.join(launchDir, 'beacon.json')) as data_file: self.configData = json.load(data_file) #need to account for no json data loaded if (self.configData.get("gpio")): gpioData = self.configData["gpio"] if gpioData.get("button"): self.button = Button(int(gpioData["button"])) self.button.when_released = self.buttonReleased self.button.when_held = self.buttonHeld else: logging.error( "config json gpio object missing required button id") if gpioData.get("red_led") and gpioData.get( "green_led") and gpioData.get("blue_led"): self.rgbLED = RGBLED(int(gpioData["red_led"]), int(gpioData["green_led"]), int(gpioData["blue_led"]), False, (0, 0, 0), True) else: logging.error( "config json gpio object missing required redled, greenled, and blueled ids" ) else: logging.error("config json missing require gpio object") if self.configData.get("directories"): dirObj = self.configData["directories"] if dirObj.get("sound"): soundDir = dirObj["sound"] if self.configData.get("commands"): self.commandsData = self.configData["commands"] self.ledDisplay(LedDisplayRule(0, 1, 0, 1, 1)) sleep(1) self.client = MQTTClient(self.configData["credentials"]["username"], self.configData["credentials"]["key"]) self.client.on_connect = self.connected self.client.on_disconnect = self.disconnected self.client.on_message = self.message while True: if self.connectState == ConnectState.Disconnected: self.connect() elif self.connectState == ConnectState.PendingReconnect: self.reconnect() try: self.client.loop() except RuntimeError: logging.exception("runtime error caught from mqtt client loop") self.reconnect() def buttonHeld(self): self.buttonHoldTime = time.time() def buttonReleased(self): if self.buttonHoldTime is not None: heldTime = time.time() - self.buttonHoldTime + 1 self.buttonHoldTime = None print heldTime if heldTime > 5: self.ledDisplay(LedDisplayRule(1, 0, 0, 3, .5)) sleep(2) self.stopLED() os.system('sudo shutdown -r now') else: self.stopLED() self.persistentLedRule = None print self.commandsData if mixer.get_init() and mixer.music.get_busy(): mixer.music.stop() mixer.quit() elif self.commandsData is not None: self.client.publish(self.configData["feeds"]["outbound"], self.commandsData[0]) def message(self, client, feed_id, payload): msgStr = 'Feed {0} received new value: {1}'.format(feed_id, payload) log_data = "" with open(logFilePath, 'r') as myfile: log_data = myfile.read().replace('\n', '') if log_data.find(msgStr) == -1 or testing: logging.info(msgStr) messageData = None try: messageData = json.loads(payload) except: pass sound = None volume = 1 redVal = 0 greenVal = 1 blueVal = 0 blinkCount = 1 blinkRate = 1 persistent = False pulse = False if self.configData.get("sounds"): sound = self.configData["sounds"]["default"] if messageData is not None: if messageData.get("sound"): sound = self.configData["sounds"][messageData["sound"]] if messageData.get("persistent") and str( messageData["persistent"]).lower() == "true": persistent = True if messageData.get("volume") is not None: volume = float(messageData.get("volume")) if messageData.get("blinkCount") is not None: blinkCount = int(messageData.get("blinkCount")) if messageData.get("blinkRate") is not None: blinkRate = float(messageData.get("blinkRate")) if messageData.get("pulse") is not None and str( messageData["pulse"]).lower() == "true": pulse = True if messageData.get("color") is not None: try: colorArr = str(messageData.get("color")).split("/") redVal = float(colorArr[0]) greenVal = float(colorArr[1]) blueVal = float(colorArr[2]) except: pass if sound is not None: mixer.init() mixer.music.set_volume(volume) mixer.music.load(self.soundDir + sound) mixer.music.play() self.ledDisplay( LedDisplayRule(redVal, greenVal, blueVal, blinkCount, blinkRate, pulse, persistent)) def stopLED(self): self.rgbLED._stop_blink() self.rgbLED.off() def ledDisplay(self, rule): self.stopLED() blinkCount = rule.blinkCount if (rule.persistent): blinkCount = None self.persistentLedRule = rule if (rule.pulse): self.rgbLED.pulse(fade_in_time=rule.blinkRate, fade_out_time=rule.blinkRate, on_color=(rule.r, rule.g, rule.b), off_color=(0, 0, 0), n=blinkCount, background=True) else: self.rgbLED.blink(on_time=rule.blinkRate, off_time=rule.blinkRate, fade_in_time=0, fade_out_time=0, on_color=(rule.r, rule.g, rule.b), off_color=(0, 0, 0), n=blinkCount, background=True) def connected(self, client): logging.info("Connected to Adafruit IO") self.connectState = ConnectState.Connected self.failConnectCount = 0 self.client.subscribe(self.configData["feeds"]["inbound"]) def disconnected(self, client): logging.info('Disconnected from AdafruitIO') self.connectState = ConnectState.Disconnected self.reconnect() def connect(self): logging.info("init connect to Adafruit IO") self.connectState = ConnectState.Connecting try: self.client.connect() except Exception as e: logging.exception("Exception from Adafruit client connect") self.reconnect() def reconnect(self): self.failConnectCount += 1 logging.info('pending Adafruit IO reconnect - failcount=' + str(self.failConnectCount)) self.connectState = ConnectState.Connecting sleep(10) self.connect()
from glob import glob from time import sleep sensor = MPR121.begin() sensor.set_touch_threshold(40) sensor.set_release_threshold(20) led = RGBLED(6, 5, 26, active_high=False) num_electrodes = 12 # Convertion des fichier MP3 en WAV led.blue = 1 subprocess.call("picap-samples-to-wav soundtable", shell=True) #soundtable = nom du dossier led.off() # init pygame.mixer.pre_init(frequency=44100, channels=64, buffer=1024) pygame.init() sounds = [Sound(path) for path in glob("soundtable/.wavs/*.wav") ] #soundtable = nom du dossier def play_sounds_when_touched(): if sensor.touch_status_changed(): #verifie si une electrode a ete touchee sensor.update_touch_data() is_any_touch_registered = False
GREEN_PIN = 20 #URLs for data ROOT_URL = 'http://54.147.192.125' if "-local" in sys.argv: ROOT_URL = 'http://localhost:5000' FALSE_ROOM_URL = "/roomdata?r={}&f=0".format(ROOM_NUM) TRUE_ROOM_URL = "/roomdata?r={}&f=1".format(ROOM_NUM) FALSE_JAM_URL = "/jamdata?r={}&j=0".format(ROOM_NUM) TRUE_JAM_URL = "/jamdata?r={}&j=1".format(ROOM_NUM) # Sensor and output setup pir_sensor = Button(PIR_PIN, True) #distance_sensor = DistanceSensor(echo=DISTANCE_ECHO_PIN, trigger=DISTANCE_TRIGGER_PIN, max_distance=3) rgb_led = RGBLED(RED_PIN, BLUE_PIN, GREEN_PIN) rgb_led.off() jam_led = LED(JAM_LED_PIN) jam_led.off() jam_button = Button(JAM_BUTTON_PIN, True) # Waits for network connection and valid http requests from the ROOT_URL def network_wait(): print("network error!") while True: # Check if pinging google works ping_result = requests.get("http://google.com") # If it worked, test http request if ping_result.status_code < 300: # Try the request, and if it works and has a good status code, exit the function try:
from gpiozero import RGBLED from time import sleep colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 0), (1, 0, 1), (1, 1, 1)] if __name__ == "__main__": rgbled = RGBLED(17, 27, 22) while True: for color in colors: rgbled.color = color sleep(0.1) rgbled.off() sleep(0.1)
btnRed = Button(19) btnBlue = Button(26) #btnRed.is_pressed RGB = RGBLED(22, 27, 17) i = .01 j = 0.1 try: while (1): '''if btnRed.is_pressed and i!=0 : i = 0 RGB.color = (1,0,0) time.sleep(j)''' '''time.sleep(i) RGB.color = (0,1,0) time.sleep(i) RGB.color = (0,0,1) time.sleep(i)''' '''elif btnRed.is_pressed and i==0: RGB.off() i = 1 time.sleep(j)''' RGB.color = (1, 0, 0) #time.sleep(j) time.sleep(i) RGB.color = (0, 1, 0) time.sleep(i) RGB.color = (0, 0, 1) time.sleep(i) except KeyboardInterrupt: RGB.off()
class ILedStrip(object): """ Interface to GPIOZERO RGBLED Adds support for Hex and Generic words such as: "none", "red", "green", "blue", "purple", "yellow" "aqua", "orange", "magenta", "white" """ def __init__(self, red, green, blue): """ sets up the Interface Args: red (int): GPIO Pin green (int): GPIO pin blue (int): GPIO Pin """ self._led_strip = RGBLED(red, green, blue) self._cur_color = "#0000FF" self._prev_color = "#0000FF" self._is_pulse = False self._defined_colors = { "none": "#000000", "red": "#FF0000", "green": "#00FF00", "blue": "#0000FF", "purple": "#FF00FF", "yellow": "#FFFF00", "aqua": "#00FFFF", "orange": "#FF1000", "magenta": "#FF0080", "white": "#FFFFFF" } # Setter def set_on(self): """ Turns RGB on sets to the defined color """ self._is_pulse = False self._led_strip.color = self._cvt_hex(self._cur_color) # Setter def set_off(self): """ Turns RGB off """ self._is_pulse = False self._led_strip.off() # Setter def set_color_hex(self, color="#000000"): """ Sets the color to hex or sets it to none if not valid hex """ if self._is_valid_hex(color): self._led_strip.color = self._cvt_hex(color) self._prev_color = self._cur_color self._is_pulse = False self._cur_color = color # Setter def set_color_word(self, color="none"): """ Set color to current word or sets it to none if it is not supported """ self._led_strip.color = self._color_map(color) self._prev_color = self._cur_color self._is_pulse = False self._cur_color = self._color_map(color, return_tuple=False) # Getter def get_status(self): """ returns if the led_strip is lit """ if self._is_pulse: return True return self._led_strip.is_lit def get_pulse_status(self): """ returns true if currently pulsing """ return self._is_pulse def get_prev_color(self): """ returns previous color """ return self._color_map(self._prev_color, return_tuple=False) # Getter def get_defined_colors(self): """ returns what colors are supported and which color it is currently set to """ defined_colors = {} for color in self._defined_colors: hex_color = self._color_map(color, return_tuple=False) if hex_color == self._cur_color: defined_colors[color] = True else: defined_colors[color] = False return defined_colors def toggle(self): """ Toggles between off and on """ if not self.led_strip.is_lit: self.set_on() else: self.set_off() def pulse(self, fade_in_time=5, fade_out_time=5, off_color=(0, 0, 0)): on_color = self._cvt_hex(self._cur_color) self._is_pulse = True self._led_strip.pulse(fade_in_time=fade_in_time, fade_out_time=fade_out_time, on_color=on_color, off_color=off_color) def blue2red(self): self._led_strip.pulse(fade_in_time=10, fade_out_time=10, on_color=(1, 0, 0), off_color=(0, 0, 1)) def _cvt_hex(self, colorInHex): """ TODO: make this more reslient """ try: red = float(int(colorInHex[1:3], 16)) / 255 green = float(int(colorInHex[3:5], 16)) / 255 blue = float(int(colorInHex[5:], 16)) / 255 return (red, green, blue) except: return self._cvt_hex(self._cur_color) LOGGER.debug("Exception in cvtHex") def _color_map(self, color, return_tuple=True): if return_tuple: return self._cvt_hex(self._defined_colors.get(color, "#000000")) else: return self._defined_colors.get(color, "#000000") def _is_valid_hex(self, colorInHex): _rgbstring = re.compile(r'#[a-fA-F0-9]{6}$') return bool(_rgbstring.match(colorInHex))
apply = Button(21) kill = Button(20) print("PROGRAM ACTIVE") red.off() green.off() blue.off() selectionLED.color = (0, 0, 0) while kill.is_pressed == False: #TODO: add in support for lightRelays1 selectionLED.pulse(1, 1, (0, 0, 1)) #blue blue.on() apply.wait_for_press() selectionLED.off() blue.off() apply.wait_for_release() selectionLED.pulse(1, 1, (0, 1, 0)) #green green.on() apply.wait_for_press() selectionLED.off() green.off() apply.wait_for_release() selectionLED.pulse(1, 1, (0, 1, 1)) #teal green.on() blue.on() apply.wait_for_press() selectionLED.off()
import forecastio import datetime from gpiozero import RGBLED, Button from time import sleep from signal import pause from math import pow # https://developer.forecast.io/docs/v2#forecast_call led = RGBLED(red=4, green=26, blue=19) #led2 = RGBLED(red=13, green=6, blue=5) button = Button(18) button2 = Button(23) led.off() api_key = "9c09fe99666a61bbd85aa2743387cd31" lat = 47.3769 lng = 8.5417 def nextHours(hours): if led.is_lit: led.off() led2.off() return # till the forecast is loaded led.color = (0.2,0.2,0.2) led2.color = (0.2,0.2,0.2)
from gpiozero import RGBLED from time import sleep l = RGBLED(2, 3, 4) try: print("off") l.red = 1 l.blue = 1 l.green = 1 sleep(1) finally: l.off()
print('received %s bytes from %s' % (len(data), address)) print(data) if data: print("data recvd") sent = sock.sendto(data, address) print('sent %s bytes back to %s' % (sent, address)) packet_received_time = int(time.time()) if data == b"servo;\n": swipe() print("Servod") else: #indicator.fadeIn() sol.trigger() print("solenoid triggered") print(indicator_state) if indicator_state == False and int( time.time()) - packet_received_time > 0.5: indicator_state = True time.sleep(0.1) indicator_state = False if indicator_state: indicator.on() else: indicator.off()
class LED: def __init__(self, red, green, blue, verbose=False): self.led = RGBLED(red, green, blue) self.bright = 1 self.thread = Thread() self.stop_thread = False self.verbose = verbose if AUTODIM: t = Thread(target=self.autoDimming, daemon=True) t.start() self.changeLights(LightChanges.instant, DEFAULT_COLOR) self.dprint('lights init') def handle(self, payload): #kill old thread self.killThread() #handle brightness if payload in LED_bright_terms: self.dprint('brightness to {}'.format(payload)) self.bright = LED_bright_terms[payload] self.changeLights(self.change_type, self.color) return True change_type = LightChanges.transition #handle toggle/on/off/stop if payload == 'toggle': self.dprint('toggle') if self.led.is_lit: self.led.off() else: self.changeLights(change_type, self.color) return True if payload == 'off': self.dprint('off') self.led.off() return True if payload == 'on': self.dprint('on') self.changeLights(change_type, self.color) return True if payload == 'stop': self.dprint('stop') self.led.color = self.led.color return True color = payload if 'pulse' in payload: color = payload.replace('pulse', '').replace(' ', '') if color == '': color = self.color change_type = LightChanges.pulse elif 'rain' in payload: color = 'black' change_type = LightChanges.rainbow #handle color self.thread = Thread(target=self.changeLights, args=(change_type, color), daemon=True) self.thread.start() return True def changeLights(self, type, colortext='black'): try: color = Color(colortext) except ValueError: self.dprint('error while trying to parse {}'.format(colortext)) return False self.dprint('change type {} to {}{}{}'.format(type, color, color.rgb, Color('white'))) self.change_type = type switcher = { LightChanges.instant: self.setColor, LightChanges.transition: self.chgTrans, LightChanges.pulse: self.chgPulse, LightChanges.rainbow: self.chgRain } switcher.get(type, lambda x: self.dprint('invalid input'))(color) return True def setColor(self, color, ignore_bright=False): self.color = color self.led.color = self.applyBright( color) if ignore_bright is False else color self.dprint('set color to {}{}{}'.format(color, color.rgb, Color('white'))) def applyBright(self, color): if self.bright == 1: return color else: return Color(tuple(self.bright * x for x in color)) def chgTrans(self, new_color, ignore_bright=False, duration=TRANSITION_DURATION): N = REFRESH_RATE * duration #total color difference diff = [] for n, c in zip(new_color, self.led.color): diff.append(n - c) self.color = self.led.color #color change per update step = tuple(x / N for x in diff) for _ in range(N - 1): step_color = [] for c, s in zip(self.color, step): step_color.append(c + s) self.setColor(Color(tuple(step_color)), ignore_bright) sleep(1 / REFRESH_RATE) self.setColor(new_color, ignore_bright) def chgPulse(self, color): self.dprint('pulsing on {}{}{}'.format(color, color.rgb, Color('white'))) color = self.applyBright(color) self.led.pulse(fade_in_time=FADE_DURATION, fade_out_time=FADE_DURATION, on_color=color) def chgRain(self, _): self.dprint('running rainbow') freq1, freq2, freq3 = .03, .03, .03 ph1, ph2, ph3 = 0, 2, 4 center, width = 128, 127 #center, width = 230, 25 #for pastels length = 200 while self.stop_thread is not True: for i in range(length): if self.stop_thread is True: break red = sin(freq1 * i + ph1) * width + center green = sin(freq2 * i + ph2) * width + center blue = sin(freq3 * i + ph3) * width + center self.setColor(Color(red, green, blue)) sleep((1 / REFRESH_RATE) * 2) def autoDimming(self): last_dimmed_day = 0 last_undimmed_day = 0 while True: dt = datetime.now() if (last_dimmed_day != dt.day) and (DIM_START_HOUR <= dt.hour < DIM_END_HOUR) and self.bright != 0.25: self.dprint('auto-dimming') last_dimmed_day = dt.day self.bright = 0.25 elif (last_undimmed_day != dt.day) and ( dt.hour < DIM_START_HOUR or dt.hour >= DIM_END_HOUR) and self.bright != 1: self.dprint('auto-undimming') last_undimmed_day = dt.day self.bright = 1 else: sleep(60) continue if self.led.is_lit: self.killThread() if self.change_type == LightChanges.transition: self.chgTrans(applyBright(self.color), ignore_bright=True, duration=3) else: self.changeLights(self.change_type, self.color) sleep(60) def killThread(self): if self.thread.is_alive() is not True: return self.dprint('stop thread') self.stop_thread = True self.thread.join() self.stop_thread = False def dprint(self, text): if self.verbose: print(text)
class FabmanBridge(object): def __init__(self, config=None, config_file="fabman.json" ): # if no config is given read config from "fabman.json" #try: # default values self.config = { "api_url_base": "https://fabman.io/api/v1/", "heartbeat_interval": 30, "left_button": 24, "reader_type": "MFRC522", "led_r": 17, "led_g": 27, "led_b": 22, "display": "SSD1306_128_32", "relay": 26, "buzzer": 18 } if (config is None): self.config_file = config_file self.load_config(self.config_file) else: self.config_file = None pprint.pprint(config) self.config.update(config) if ("api_token" in self.config): self.api_header = { 'Content-Type': 'application/json', 'Authorization': 'Bearer {0}'.format(self.config['bridge_api_token']) } else: logging.warning( 'Not api-token defined: Cannot access Fabman via Bridge API') self.session_id = None self.next_heartbeat_call = time.time() self.rgbled = RGBLED(self.config["led_r"], self.config["led_g"], self.config["led_b"]) self.buzzer = Buzzer(self.config["buzzer"]) self.relay = Relay(self.config["relay"], 0) GPIO.setwarnings(False) if (self.config["reader_type"] == "MFRC522"): #self.reader = SimpleMFRC522() #self.reader = SimpleMFRC522() self.reader = MFRC522.MFRC522(dev=1) self.chip_type = "nfca" elif (self.config["reader_type"] == "Gwiot7941E"): #print ("setze reader") self.reader = Gwiot7941E() self.chip_type = "em4102" if (self.config["heartbeat_interval"] > 0): self._start_heartbeat_thread() ''' if ("stop_button" in self.config and not(self.config["stop_button"] is None)): GPIO.setmode(GPIO.BCM) #GPIO.setmode(GPIO.BOARD) GPIO.setup(self.config["stop_button"], GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(self.config["stop_button"], GPIO.FALLING, callback=self._callback_stop_button, bouncetime=300) ''' if ("left_button" in self.config and not (self.config["left_button"] is None)): GPIO.setmode(GPIO.BCM) #GPIO.setmode(GPIO.BOARD) GPIO.setup(self.config["left_button"], GPIO.IN, pull_up_down=GPIO.PUD_UP) if ("right_button" in self.config and not (self.config["right_button"] is None)): GPIO.setmode(GPIO.BCM) #GPIO.setmode(GPIO.BOARD) GPIO.setup(self.config["right_button"], GPIO.IN, pull_up_down=GPIO.PUD_UP) #if ("left_button_pin" in self.config and not(self.config["left_button_pin"] is None)): # self.left_button = Button(self.config["left_button_pin"], pull_up=True, bounce_time=0.3) #if ("right_button_pin" in self.config and not(self.config["right_button_pin"] is None)): # self.right_button = Button(pin=self.config["right_button_pin"], pull_up=True, bounce_time=0.3) if (self.config["display"] == "sh1106"): # 1,3" I2C OLED Display self.device = get_device(("--display", self.config["display"])) self.screen_message = "" #except Exception as e: # logging.error('Function FabmanBridge.__init__ raised exception (' + str(e) + ')') def save_config(self, filename="fabman.json"): try: with open(filename, 'w') as fp: json.dump(self.config, fp, sort_keys=True, indent=4) return True except Exception as e: logging.error( 'Function FabmanBridge.save_config raised exception (' + str(e) + ')') return False def load_config(self, filename="fabman.json"): try: with open(filename, 'r') as fp: file_config = json.load(fp) self.config.update(file_config) return self.config except Exception as e: logging.error( 'Function FabmanBridge.load_config raised exception (' + str(e) + ')') return False def access(self, user_id): # user_id can be email address or rfid key try: if (user_id): if ("@" in str(user_id)): # authenticate with email address data = {'emailAddress': user_id, 'configVersion': 0} else: # authenticate with rfid key data = { "keys": [{ "type": self.chip_type, "token": user_id }], "configVersion": 0 } api_url = '{0}bridge/access'.format( self.config["api_url_base"]) response = requests.post(api_url, headers=self.api_header, json=data) if (response.status_code == 200 and json.loads( response.content.decode('utf-8'))['type'] == "allowed"): logging.info('Bridge started successfully.') #self.display_text("Access granted\n\n\n<-STOP") self.rgbled.color = Color('green') self.session_id = json.loads( response.content.decode('utf-8'))["sessionId"] return True else: logging.warning('Bridge could not be started (user_id: ' + str(user_id) + ')') pprint.pprint(json.loads(response.content.decode('utf-8'))) #self.display_error("Access\ndenied") #self.display_text("Access denied") #self.display_text("Access denied",3) return False else: logging.warning("No user_id set for /bridge/access") except Exception as e: logging.error('Function FabmanBridge.access raised exception (' + str(e) + ')') return False def stop(self, metadata=None, charge=None): try: api_url = '{0}bridge/stop'.format(self.config["api_url_base"]) data = { "stopType": "normal", "currentSession": { "id": self.session_id } } if (metadata is not None): data['currentSession'].update({'metadata': metadata}) if (charge is not None): print("UPDATE CHARGE DURING BRIDGE STOP:") data['currentSession'].update({'charge': charge}) pprint.pprint(data['currentSession']) ''' if (metadata is None): # do not set metadata if no data available #data = { "stopType": "normal", "currentSession": { "id": sessionId, "idleDurationSeconds": idleTime } } data = { "stopType": "normal", "currentSession": { "id": self.session_id } } else: # set metadata, if available try: data = { "stopType": "normal", "currentSession": { "id": sessionId, "idleDurationSeconds": idleTime, "metadata": metadata, "charge": create_charge(get_metadata()) } } except: # no charge data available data = { "stopType": "normal", "currentSession": { "id": sessionId, "idleDurationSeconds": idleTime, "metadata": metadata } } data = { "stopType": "normal", "currentSession": { "id": sessionId, "idleDurationSeconds": idleTime, "metadata": metadata, "charge": create_charge(get_metadata()) } } ''' response = requests.post(api_url, headers=self.api_header, json=data) if response.status_code == 200 or response.status_code == 204: #self.user_id = None self.session_id = None logging.info('Bridge stopped successfully.') #self.rgbled.off("g") self.rgbled.off() return True else: logging.error('Bridge could not be stopped (status code ' + str(response.status_code) + ')') pprint.pprint(data) self.display_error() return False except Exception as e: logging.error('Function FabmanBridge.stop raised exception (' + str(e) + ')') return False def read_key(self): try: if (self.config["reader_type"] == "MFRC522"): #return str(hex(self.reader.read_id()))[2:10] continue_reading = True while continue_reading: # Scan for cards (status, TagType) = self.reader.MFRC522_Request( self.reader.PICC_REQIDL) # If a card is found if status == self.reader.MI_OK: logging.debug("Card detected") continue_reading = False # Get the UID of the card (status, uid) = self.reader.MFRC522_SelectTagSN() # If we have the UID, continue if status == self.reader.MI_OK: uid_string = "" for i in uid: uid_string += format(i, '02X') logging.debug("Card uid: " + uid_string) return uid_string else: logging.debug("Card authentication error") elif (self.config["reader_type"] == "Gwiot7941E"): uid_string = self.reader.read() return uid_string else: logging.error("Undefined reader type") return False except Exception as e: logging.error('Function FabmanBridge.read_key raised exception (' + str(e) + ')') return False def is_on(self): try: if (self.session_id is None): return False else: return True except Exception as e: logging.error('Function FabmanBridge.is_on raised exception (' + str(e) + ')') return False def is_off(self): try: return not (self.is_on()) except Exception as e: logging.error('Function FabmanBridge.is_off raised exception (' + str(e) + ')') return False def display_error(self, message=None): try: #self.rgbled.on("r",0.1) #self.rgbled.off("r",0.1) #self.rgbled.on("r",0.1) #self.rgbled.off("r",0.1) #self.rgbled.on("r",0.1) #self.rgbled.off("r") self.rgbled.blink(0.1, 0.1, 0, 0, Color('red'), Color('black'), 3, True) if (message is not None): logging.error(message) self.display_text(message, 3) print(message) return True except Exception as e: logging.error( 'Function FabmanBridge.display_error raised exception (' + str(e) + ')') return False def display_warning(self, message=None): try: #self.rgbled.on("b",0.1) #self.rgbled.off("b",0.1) #self.rgbled.on("b",0.1) #self.rgbled.off("b",0.1) #self.rgbled.on("b",0.1) #self.rgbled.off("b") self.rgbled.blink(0.1, 0.1, 0, 0, Color('yellow'), Color('black'), 3, True) if (message is not None): logging.warning(message) self.display_text(message, 3) print(message) return True except Exception as e: logging.error( 'Function FabmanBridge.display_warning raised exception (' + str(e) + ')') return False def display_text(self, text="", duration=None): # duration None = forever try: if ( duration is None ): # new text remains "forever" - no old text to recover afterwards self.screen_message = text #print("************interval*****" + str(self.config["display"].startswith('SSD1306'))) if (self.config["display"] == "sh1106"): # 1,3" I2C OLED Display def display_line(draw, text, font_size=15, y=0, x=0, font='C&C Red Alert [INET].ttf'): # use custom font font_path = os.path.abspath( os.path.join(os.path.dirname(__file__), 'fonts', font)) #font2 = ImageFont.truetype(font_path, 12) #print (font_path) font = ImageFont.truetype(font_path, font_size) #with canvas(device) as draw: draw.text((x, y), str(text), font=font, fill="white") if (type(text).__name__ == "str"): default_size = 15 #print(type(text).__name__) line_array = text.splitlines() lines = [] #pprint.pprint(line_array) for i in range(len(line_array)): #print (line_array[i]) lines.insert(i, { "text": line_array[i], "size": default_size }) #pprint.pprint(lines) #self.device = get_device(("--display", self.config["display"])) with canvas(self.device) as draw: y = 0 for line in lines: #print(line['text']) display_line(draw, line['text'], line['size'], y) y += (line['text'].count("\n") + 1) * line['size'] if (duration is not None): time.sleep(duration) with canvas(self.device) as draw: y = 0 for line in lines: #print(line['text']) display_line(draw=draw, text=self.screen_message, y=y) y += (line['text'].count("\n") + 1) * line['size'] elif (self.config["display"].startswith('SSD1306')): # Raspberry Pi pin configuration: RST = None # on the PiOLED this pin isnt used if (self.config["display"] == "SSD1306_128_32"): # 128x32 display with hardware I2C: disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST) elif (self.config["display"] == "SSD1306_128_64"): # 128x64 display with hardware I2C: disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST) # Note you can change the I2C address by passing an i2c_address parameter like: # disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3C) # Alternatively you can specify an explicit I2C bus number, for example # with the 128x32 display you would use: # disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, i2c_bus=2) # 128x32 display with hardware SPI: # disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000)) # 128x64 display with hardware SPI: # disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000)) # Alternatively you can specify a software SPI implementation by providing # digital GPIO pin numbers for all the required display pins. For example # on a Raspberry Pi with the 128x32 display you might use: # disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, dc=DC, sclk=18, din=25, cs=22) # Initialize library. disp.begin() # Clear display. disp.clear() disp.display() # Create blank image for drawing. # Make sure to create image with mode '1' for 1-bit color. width = disp.width height = disp.height image = Image.new('1', (width, height)) # Get drawing object to draw on image. draw = ImageDraw.Draw(image) # Draw a black filled box to clear the image. draw.rectangle((0, 0, width, height), outline=0, fill=0) # Load default font. font = ImageFont.load_default() # Alternatively load a TTF font. Make sure the .ttf font file is in the same directory as the python script! # Some other nice fonts to try: http://www.dafont.com/bitmap.php # font = ImageFont.truetype('Minecraftia.ttf', 8) # Draw a black filled box to clear the image. draw.rectangle((0, 0, width, height), outline=0, fill=0) # Draw some shapes. # First define some constants to allow easy resizing of shapes. x = 0 padding = -2 top = padding bottom = height - padding linespacing = 8 # Write four lines of text lines = text.split("\n") if (len(lines) >= 1): draw.text((x, top + 0 * linespacing), lines[0], font=font, fill=255) if (len(lines) >= 2): draw.text((x, top + 1 * linespacing), lines[1], font=font, fill=255) if (len(lines) >= 3): draw.text((x, top + 2 * linespacing), lines[2], font=font, fill=255) if (len(lines) >= 4): draw.text((x, top + 3 * linespacing), lines[3], font=font, fill=255) # Display image. disp.image(image) disp.display() if (duration is not None): time.sleep(duration) # clear display disp.clear() disp.display() # recover previous screen message lines = self.screen_message.split("\n") if (len(lines) >= 1): draw.text((x, top + 0 * linespacing), lines[0], font=font, fill=255) if (len(lines) >= 2): draw.text((x, top + 1 * linespacing), lines[1], font=font, fill=255) if (len(lines) >= 3): draw.text((x, top + 2 * linespacing), lines[2], font=font, fill=255) if (len(lines) >= 4): draw.text((x, top + 3 * linespacing), lines[3], font=font, fill=255) else: logging.warning('Unsupported display type: ' + str(self.config["display"])) return True except Exception as e: logging.error( 'Function FabmanBridge.display_text raised exception (' + str(e) + ')') return False def _start_heartbeat_thread(self): try: #print datetime.datetime.now() api_url = '{0}bridge/heartbeat'.format(self.config["api_url_base"]) data = {'configVersion': 0} response = requests.post(api_url, headers=self.api_header, json=data) if response.status_code == 200: response = json.loads(response.content.decode('utf-8')) logging.debug("Heartbeat sent") else: logging.warning("Heartbeat failed") self.next_heartbeat_call += self.config["heartbeat_interval"] heartbeat_thread = threading.Timer( self.next_heartbeat_call - time.time(), self._start_heartbeat_thread) heartbeat_thread.daemon = True heartbeat_thread.start() except Exception as e: logging.error( 'Function FabmanBridge._start_heartbeat_thread raised exception (' + str(e) + ')') return False ''' def _callback_stop_button(self, channel): try: #print("self.config[stop_button] = " + str(self.config["stop_button"])) #print("channel = " + str(channel)) if (self.config["stop_button"] == channel and self.is_on()): logging.debug("Switching off ...") self.stop() #else: # print "stop button (gpio" + str(channel) + ") pressed." # print "stop_button: " + str(self.config["stop_button"]) # print "channel (muss gleich sein wie stop_button): " + str(channel) # print "is_on (muss True sein): " +str(self.is_on()) # print "stop() wurde nicht aufgerufen" # self.display_warning() except Exception as e: logging.error('Function FabmanBridge._callback_stop_button raised exception (' + str(e) + ')') return False ''' ''' def run(self): try: logging.info("Bridge started.") while (True): if (self.is_off()): logging.debug("Ready to read nfc key ...") self.display_text("Show card to start") key = self.read_key() if (key != False and key is not None): self.access(key) except Exception as e: logging.error('Function FabmanBridge.run raised exception (' + str(e) + ')') return False ''' def send_email(self, subject, text, email_to=None): try: # default values from fabman.json if (email_to is None): email_to = self.config["email_operator"] server = smtplib.SMTP(self.config["email_smtp"], self.config["email_port"]) server.ehlo() server.starttls() server.login(self.config["email_sender"], self.config["email_password"]) msg = MIMEMultipart('alternative') msg.set_charset('utf8') msg['FROM'] = self.config["email_sender"] msg['Subject'] = Header(subject.encode('utf-8'), 'UTF-8').encode() msg['To'] = email_to _attach = MIMEText(text.encode('utf-8'), 'html', 'UTF-8') msg.attach(_attach) server.sendmail(self.config["email_sender"], [email_to], msg.as_string()) logging.info('Email "' + subject + '" sent to ' + email_to) #logging.debug(text) server.quit() except Exception as e: logging.error('Sending email "' + subject + '" to ' + email_to + 'FAILED: ' + text) logging.error( 'Function FabmanBridge.send_email raised exception (' + str(e) + ')') server.quit() return False
led19 = LED(19) led6 = LED(6) led22 = LED(22) led25 = LED(25) led = RGBLED(red=21, green=18, blue=12) led2 = RGBLED(red=27, green=5, blue=26) while True: if button.is_pressed: print("Button is pressed") led4.on() led17.on() led23.on() led19.on() led6.on() led22.on() led.color = (0, 1, 0) # white led2.color = (0, 1, 0) # white led25.on() else: print("Button is not pressed") led4.off() led17.off() led23.off() led19.off() led6.off() led22.off() led.off() led2.off() led25.off() sleep(0.2)