def main(): if os.environ.get('MOCK', default='0') == '1': status_handler = LogStatusHandler() readers = [ MockWaterMeterDeviceReader('TestMeter1'), MockWaterMeterDeviceReader('TestMeter2'), ] else: pi = pigpio.pi() status_handler = LedStatusHandler(green_led=LED(pi, GREEN_LED_PIN), red_led=LED(pi, RED_LED_PIN)) readers = [ WaterMeterDeviceReader('JimenezWaterMeter', pi, JIMENEZ_SENSOR_PIN), WaterMeterDeviceReader('PahuckiWaterMeter', pi, PAHUCKI_SENSOR_PIN) ] metering = None try: logger.info('Starting metering...') metering = Metering(readers, socket.gethostname(), status_handler, 15, True) status_handler.ok() metering.run() except Exception: logger.critical('Exiting due to unexpected error %s' % traceback.format_exc()) status_handler.not_ok() except KeyboardInterrupt: logger.info('Exiting at user request...') status_handler.not_ok() logger.info('Stopping metering...') metering.stop() logger.info('Done.')
def importAni(): global leds global frame_number with open('animation8x4.py') as ll: line_count = sum(1 for _ in ll) ll.close() #animation = {} frame_number = 1 file = open('animation8x4.py') for r in range(4): file.readline() for frame in range(line_count-9): buff = file.readline() load_frame = buff.split('], [') #print(load_frame) counter = 1 uh_leds =[] for f in load_frame: if counter == 1: f = f[3:] elif counter == 64: f = f[:-5] elif counter%8 == 0 and counter != 64: f = f[:-1] elif (counter-1)%8 == 0: f = f[1:] y = int((counter-1)/8) x = int((counter-1)%8) #print(counter,x,y) led = LED(radius=20,pos=(x, y)) #print(' x= ' + str(led.pos_x) + ' y= ' + str(led.pos_y)) #print(f) if f == '0, 0, 0': led.lit = False else: led.lit = True f_colours = f.split(',') #print(f_colours) led.color = [int(f_colours[0]),int(f_colours[1]),int(f_colours[2])] uh_leds.append(led) counter+=1 leds = [] for pp in range(32): leds.append(uh_leds[pp]) animation[frame_number] = copy.deepcopy(leds) frame_number+=1 counter+=1 file.close()
def setup(): global Network, lora global sleep_time, STOP, myId global dust, meteo, thisGPS, useGPS display("MySense V %s" % __version__[:6], (0,0), clear=True) display("s/n " + myID) display("PM : " + Dust[dust]) display("meteo: " + Meteo[meteo]) if useGPS: display('G:%.4f/%.4f' % (thisGPS[LAT],thisGPS[LON])) sleep(15) if Network == 'TTN': # Connect to LoRaWAN display("Try LoRaWan", (0,0), clear=True) display("LoRa App EUI:") display(str(app_eui)) lora = LORA() if lora.connect(dev_eui,app_eui,app_key, ports=2, callback=CallBack): display("Joined LoRaWan") SendInfo() else: display("NOT joined LoRa!") lora = None Network = 'None' sleep(10) if Network == 'None': display("No network!", (0,0), clear=True) LED.blink(10,0.3,0xff00ff,True) # raise OSError("No connectivity") display("Setup done")
def ProgressBar(x,y,width,height,secs,blink=0,slp=1): global oled, LED, STOP if not oled: return rectangle(x,y,width,height) if (height > 4) and (width > 4): rectangle(x+1,y+1,width-2,height-2,0) x += 2; width -= 4; y += 2; height -= 4 elif width > 4: rectangle(x+1,y,width-2,height,0) x += 2; width -= 4; else: rectangle(x,y,width,height,0) step = width/(secs/slp); xe = x+width; myslp = slp if blink: myslp -= (0.1+0.1) for sec in range(int(secs/slp+0.5)): if STOP: return False if blink: LED.blink(1,0.1,blink,False) sleep(myslp) if x > xe: continue rectangle(x,y,step,height) oled.show() x += step return True
def exportAni(): global saved FILE = open("animation8x8.py", "wb") FILE.write("from astro_pi import AstroPi\n") FILE.write("import time\n") FILE.write("ap=AstroPi()\n") FILE.write("FRAMES = [\n") global leds global frame_number animation[frame_number] = copy.deepcopy(leds) # print 'length of ani is ' + str(len(animation)) for playframe in range(1, (len(animation) + 1)): # print(playframe) leds = [] for x in range(0, 8): for y in range(0, 8): led = LED(pos=(x, y)) leds.append(led) for saved_led in animation[playframe]: if saved_led.lit: for led in leds: if led.pos == saved_led.pos: led.color = saved_led.color led.lit = True grid, png_grid = buildGrid() FILE.write(str(grid)) FILE.write(",\n") FILE.write("]\n") FILE.write("for x in FRAMES:\n") FILE.write("\t ap.set_pixels(x)\n") FILE.write("\t time.sleep(" + str(1.0 / fps) + ")\n") FILE.close() saved = True
def send(self, data, port=2): """ Send data over the network. """ if (port < 2) or (port > len(self.s)): raise ValueError('Unknown LoRa port') if not self.s[port]: raise OSError('No socket') rts = True try: self.s[port].send(data) LED.blink(2, 0.1, 0x0000ff) # print("Sending data") # print(data) except OSError as e: if e.errno == 11: print("Caught exception while sending") print("errno: ", e.errno) rts = False LED.off() data = self.s[port].recv(64) # print("Received data:", data) if self.callback and data: self.callback(port, data) return rts
def exportAni(): global saved FILE=open('animation8x8.py','w') FILE.write('from sense_hat import SenseHat\n') FILE.write('import time\n') FILE.write('sh=SenseHat()\n') FILE.write('FRAMES = [\n') global leds global frame_number animation[frame_number] = copy.deepcopy(leds) #print 'length of ani is ' + str(len(animation)) for playframe in range(1,(len(animation)+1)): #print(playframe) leds =[] for x in range(0, 8): for y in range(0, 8): led = LED(radius=20,pos=(x, y)) leds.append(led) for saved_led in animation[playframe]: if saved_led.lit: for led in leds: if led.pos == saved_led.pos: led.color = saved_led.color led.lit = True grid, png_grid = buildGrid() FILE.write(str(grid)) FILE.write(',\n') FILE.write(']\n') FILE.write('for x in FRAMES:\n') FILE.write('\t sh.set_pixels(x)\n') FILE.write('\t time.sleep('+ str(1.0/fps) + ')\n') FILE.close() saved = True
def handle(self): req_raw = self.request.recv(1024) self.logger.debug("Recv from:{0}, data:{1}".format( self.client_address, req_raw)) try: req = json.loads(req_raw) except Exception: self.logger.exception( "Failed to parse request: {0}".format(req_raw)) socket.sendto(json.dumps({ "code": -1, "data": "Error" }), self.client_address) return if req['cmd'] == 'led-control': data = req['data'] led = LED(LED_NAMES.get(data['led-name'].upper())) if data['op'].lower() == 'blink': if led.blink(count=data.get('count', 1), delay=data.get('delay', 0.5)): self.request.sendall(json.dumps({"code": 0, "data": "OK"})) else: self.request.sendall( json.dumps({ "code": 1, "data": "FAIL" })) elif req['cmd'] == 'quit': tcp_stop_event.set() self.request.sendall(json.dumps({"code": 1, "data": "OK"})) self.logger.debug("Request handled.")
def exportAni(): global saved FILE=open('animation8x8.py','w') FILE.write('from sense_emu import SenseHat\n') FILE.write('import time\n') FILE.write('sh=SenseHat()\n') FILE.write('FRAMES = [\n') global leds global frame_number animation[frame_number] = copy.deepcopy(leds) #print 'length of ani is ' + str(len(animation)) for playframe in range(1,(len(animation)+1)): #print(playframe) leds =[] for x in range(0, 8): for y in range(0, 8): led = LED(radius=20,pos=(x, y)) leds.append(led) for saved_led in animation[playframe]: if saved_led.lit: for led in leds: if led.pos == saved_led.pos: led.color = saved_led.color led.lit = True grid, png_grid = buildGrid() FILE.write(str(grid)) FILE.write(',\n') FILE.write(']\n') FILE.write('for x in FRAMES:\n') FILE.write('\t sh.set_pixels(x)\n') FILE.write('\t time.sleep('+ str(1.0/fps) + ')\n') FILE.close() saved = True
def __init__(self, pin_config): self.data = Data() self.led = LED() self.temp_hum = Temp_Hum() self.led_color = (0, 0, 0) self.pump = GPIOOut(pin_config.pump_pin) self.valve_active = GPIOOut(pin_config.valve_pin) self.water_level = GPIOIn(pin_config.water_level_pin) self.fan = GPIOOut(pin_config.fan_pin)
def importAni(): global leds global frame_number with open('animation8x8.py') as ll: line_count = sum(1 for _ in ll) ll.close() #animation = {} frame_number = 1 file = open('animation8x8.py') for r in range(3): file.readline() for frame in range(line_count - 8): buff = file.readline() load_frame = buff.split('], [') #print load_frame counter = 1 leds = [] for f in load_frame: if counter == 1: f = f[3:] elif counter == 64: f = f[:-5] elif counter % 8 == 0 and counter != 64: f = f[:-1] elif (counter - 1) % 8 == 0: f = f[1:] y = int((counter - 1) / 8) x = int((counter - 1) % 8) #print(counter,x,y) #print(str(counter) + ' ' + f + ' x= ' + str(x) + ' y= ' + str(y)) led = LED(radius=20, pos=(x, y)) if f == '0, 0, 0': led.lit = False else: led.lit = True f_colours = f.split(',') #print(f_colours) led.color = [ int(f_colours[0]), int(f_colours[1]), int(f_colours[2]) ] leds.append(led) counter += 1 animation[frame_number] = copy.deepcopy(leds) frame_number += 1 counter += 1 file.close()
def connect(self, dev_eui, app_eui, app_key, ports=1, callback=None): """ Connect device to LoRa. Set the socket and lora instances. """ dev_eui = unhexlify(dev_eui) app_eui = unhexlify(app_eui) app_key = unhexlify(app_key) self.callback = callback # call back routine on LoRa reply callback(port,response) # Disable blue blinking and turn LED off LED.heartbeat(False) LED.off() # Initialize LoRa in LORAWAN mode self.lora = LoRa(mode=LoRa.LORAWAN) # Join a network using OTAA (Over the Air Activation) self.lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0) # Wait until the module has joined the network count = 0 while not self.lora.has_joined(): LED.blink(1, 2.5, 0xff0000) if count > 20: return False print("Trying to join: ", count) count += 1 # Create a LoRa socket LED.blink(2, 0.1, 0x009900) self.s = [] self.s.append(socket.socket(socket.AF_LORA, socket.SOCK_RAW)) # Set the LoRaWAN data rate self.s[0].setsockopt(socket.SOL_LORA, socket.SO_DR, 5) # Make the socket non-blocking self.s[0].setblocking(False) print("Success after %d tries" % count) # print("Create LoRaWAN socket") # Create a raw LoRa socket # default port 2 self.s.append(None) for nr in range(ports): print("Setting up port %d" % (nr + 2)) self.s.append(socket.socket(socket.AF_LORA, socket.SOCK_RAW)) self.s[nr + 2].setblocking(False) if nr: self.s[nr + 2].bind(nr + 2) LED.off() return True
def __init__(self): from machine import Pin from machine import SoftI2C as I2C i2 = I2C(scl=Pin(22), sda=Pin(21), freq=400000) AXP192PLUS.__init__(self, i2) LED.__init__(self) ST7789PLUS.__init__(self) BUTTON.__init__(self) RTCPLUS.__init__(self, i2) SOUND.__init__(self) self.wlan = WIFI('', '')
def main(): #Create unix pipe main_pipe, fingerpint_pipe = Pipe() LCD_IN, LCD_OUT = Pipe() # Initializes LCD and LED LCD.init() LED.init() # Create an object of the class Parser and Poller parser = Parser() poller = Poller(parser, fingerpint_pipe, 1) # Create child process pid = os.fork() # Parent process if pid: try: # start the individual threads for LCD, NFC and poller lcd_thread = threading.Thread(target=LCD.new_start, args=(LCD_IN,)) lcd_thread.daeomon = True lcd_thread.start() nfc_thread = threading.Thread(target=nfcread.readNFC, args=(parser, fingerpint_pipe, LCD_OUT,)) nfc_thread.daeomon = True nfc_thread.start() poll_thread = threading.Thread(target=poller.startPolling) poll_thread.daeomon = True poll_thread.start() except: print "Error: unable to start thread" try: # Poll fingerprint pipe while 1: if fingerpint_pipe.poll(1): parser.course_id = fingerpint_pipe.recv() # Kill the threads and clears the LCD screen except KeyboardInterrupt: LCD.clear() os.kill(pid, signal.SIGKILL) os.kill(os.getpid(), signal.SIGKILL) sys.exit() else: # Start fingerprint on child procces try: fingerprint = Fingerprint() fingerprint.start(parser, main_pipe, LCD_OUT) # Clear the screen except KeyboardInterrupt: LCD.clear() sys.exit()
def importAni(): global leds global frame_number with open('animation8x8.py') as ll: line_count = sum(1 for _ in ll) ll.close() # start of actual good code #animation = {} frame_number = 1 file = open('animation8x8.py') for r in range(line_count): buff = file.readline() if (buff[:2] == '[['): load_frame = buff.split('], [') counter = 1 leds =[] for f in load_frame: if counter == 1: f = f[2:] elif counter == 64: f = f[:-4] y = int((counter-1)/8) x = int((counter-1)%8) #print(str(counter) + ' ' + f + ' x= ' + str(x) + ' y= ' + str(y)) led = LED(radius=20,pos=(x, y)) if f == '0, 0, 0': led.lit = False else: led.lit = True f_colours = f.split(',') #print(f_colours) led.color = [int(f_colours[0]),int(f_colours[1]),int(f_colours[2])] leds.append(led) counter+=1 animation[frame_number] = copy.deepcopy(leds) frame_number+=1 counter+=1 ##### end of actual good code file.close()
def heating(temperature, thermostat_temp): # red = [255, 0, 0] # black = [0, 0, 0] pin = 16 led = LED(rpi, pin) if thermostat_temp <= temperature: # sense.led_2(black) led.turn_off() return "OFF" else: # sense.led_2(red) led.turn_on() return "ON"
def pollPendingPracticals(self): if self.parser.course_id == None: # Try to get pending practicals pending_practical = self.parser.query_pending_practicals( self.pi_id) if pending_practical.error != None: print("There was an error:" + pending_practical.error) elif pending_practical.pending: print("Practical for course: " + pending_practical.course_id + " started") LED.asyncGreen() # Inform fingerprint about practical self.fingerprint_pipe.send(pending_practical.course_id) # Wait 10 seconds time.sleep(10)
def __init__(self, rows, columns, serial_type=1, led_pin=18): ## # serial_type 信号线连接方式, 1表示弓字形连线,2表示Z字形连线 ## self.rows = rows self.columns = columns self.led_numbers = rows * columns self._mod = 1 self.leds = [] for i in range(self.led_numbers): self.leds.append(LED(i)) self.led_index = [[0 for i in range(self.columns)] for i in range(self.rows)] if (serial_type == 1): for i in range(0, rows, 2): for j in range(0, self.columns): self.led_index[i][j] = i * self.columns + j for i in range(1, rows, 2): for j in range(0, self.columns): self.led_index[i][j] = (i + 1) * self.columns - (j + 1) elif (serial_type == 2): for i in range(0, rows): for j in range(0, columns): self.led_index[i][j] = i * self.columns + j self.strip = PixelStrip(self.led_numbers, led_pin) self.strip.begin() self.strip.setBrightness(255)
def main(): gpio_classes = [ ] # Add any GPIO class we use, so we can clean up at the end try: buzzerController = Buzzer() ledController = LED() gpio_classes.append(buzzerController) gpio_classes.append(ledController) sensor = UltraSonic() socket = ServerSocket() socket.setLightsUpdated(ledController.setState) sensor.setHandDetectedCallback(lambda: (buzzerController.playSound( ) or True) and socket.sendFlameState(True)) sensor.setHandRemovedCallback(lambda: socket.sendFlameState(False)) sensor.start() while True: time.sleep(1) except KeyboardInterrupt: print("Program stopped...") for g in gpio_classes: g.cleanup()
def importAni(): global leds global frame_number with open('animation8x8.py') as ll: line_count = sum(1 for _ in ll) ll.close() #animation = {} frame_number = 1 file = open('animation8x8.py') for r in range(4): file.readline() for frame in range(line_count-8): buff = file.readline() load_frame = buff.split('], [') counter = 1 leds =[] for f in load_frame: if counter == 1: f = f[2:] elif counter == 64: f = f[:-4] y = int((counter-1)/8) x = int((counter-1)%8) #print(str(counter) + ' ' + f + ' x= ' + str(x) + ' y= ' + str(y)) led = LED(radius=20,pos=(x, y)) if f == '0, 0, 0': led.lit = False else: led.lit = True f_colours = f.split(',') #print(f_colours) led.color = [int(f_colours[0]),int(f_colours[1]),int(f_colours[2])] leds.append(led) counter+=1 animation[frame_number] = copy.deepcopy(leds) frame_number+=1 counter+=1 file.close()
def initLEDs(config): """ Given a LockingConfigParser configuration instance, create a dictionary of GPIOLED instances to control the various LEDs. """ # Create the GPIOLED instances leds = {} for color in ('red', 'yellow', 'green'): try: pin = config.get('LED', '%spin' % color) leds[color] = LED(pin) except NoSectionError: leds[color] = LED(-1) # Done return leds
def __init__(self): self._show_timeout = 0 self._first_update = True self._led = LED(Pins.RED, Pins.GREEN, Pins.BLUE) self._led.blink((1, 0, 0)) self._simple = Geoclue.Simple.new('geoclue-where-am-i', # Let's cheat Geoclue.AccuracyLevel.EXACT, None, self._on_simple_ready)
def start(self): led = LED() s = socket.socket() ai = socket.getaddrinfo("0.0.0.0", 8080) print("Bind address info:", ai) addr = ai[0][-1] s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(5) print("Listening, connect your browser to http://<this_host>:8080/") counter = 0 while True: res = s.accept() client_s = res[0] client_addr = res[1] print("Client address:", client_addr) print("Client socket:", client_s) req = client_s.recv(4096) arr = req.decode().split('\n') dic = {} for line in arr: if line.startswith('GET /?'): print(line) queryString = line.split(' ')[1][2:] print('queryString=', queryString) params = queryString.split('&') for param in params: p = param.split('=') print(p) dic[p[0]] = int(p[1]) led.set(dic) print(dic) client_s.send(CONTENT % counter) client_s.close() counter += 1 print()
class DataBoard: temperature = dict() defaultWait = 5 def __init__(self): self.weatherDataObj = WeatherData() self.palletObj = Pallet() self.fbNotificationObj = fbNotification() self.fb_led = LED(22) def show_temperature(self, temperature = None): self.weatherDataObj.get_weather() if temperature is not None: print "\n Temperature : %f" % temperature else: print "\n Temperature : %f" % self.weatherDataObj.weather['temperature'] self.__temperature_gradient(temperature) self.palletObj.color( self.temperature['led']['r'], self.temperature['led']['g'], self.temperature['led']['b']) time.sleep( self.defaultWait ) def __temperature_gradient(self, temperature=None): leds = dict() if temperature is None: leds['r'] = self.__calculate_temperature_gradient( self.weatherDataObj.weather['temperature'] ) else: leds['r'] = temperature leds['b'] = 255 - leds['r'] leds['g'] = 0 self.temperature['led'] = leds def __calculate_temperature_gradient(self, temperature): return round( (255 * temperature )/ 90 ) def fb_notification(self): fb_notifications = self.fbNotificationObj.notifications(True) if len( fb_notifications ) : self.fb_led.pulse()
def add_reactor(self, button, led): # Setup the button GPIO.setup(button, GPIO.IN) button_obj = TactileSwitch(button) # Setup the LED GPIO.setup(led, GPIO.OUT) led_obj = LED(led) self.reactors.append((button_obj, led_obj))
def __init__(self, token, duration, interval, retrytime, last_uploaded_file): self.token = token self.duration = duration self.interval = interval self.retrytime = retrytime self.last_uploaded_file = last_uploaded_file self.led = LED(red=13, green=19, blue=26, initial_color='white') self._q = Queue() self.default_blink_interval = (5, 300) self.fast_blinking = (0.5, 500)
def __init__(self, start, angle, nleds, spacing, task_period): self.start = start self.xstep = spacing * cos(radians(angle)) # Invert Y because processing's coordinate system is backwards self.ystep = -(spacing * sin(radians(angle))) self.leds = [LED(5)] * nleds self.end = Point(self.start.x + (self.xstep * nleds), self.start.y + (self.ystep * nleds)) self.next = None self.colours = deque([color(0)] * nleds) self.task = Task(task_period)
def _ConfigureBoard(self): """Initializes the board.""" Log('Configuring board') if self.status_led_pin: self._status_led = LED(self.status_led_pin) self._shutter_btn = machine.Pin(self.shutter_pin, machine.Pin.IN) self._shutter_btn.irq(trigger=machine.Pin.IRQ_FALLING, handler=self._ShutterCallback) if self.next_mode_pin: self._next_mode_btn = machine.Pin(self.next_mode_pin, machine.Pin.IN) self._next_mode_btn.irq(trigger=machine.Pin.IRQ_FALLING, handler=self._ModeWheelCallback) if self.prev_mode_pin: self._prev_mode_btn = machine.Pin(self.prev_mode_pin, machine.Pin.IN) self._prev_mode_btn.irq(trigger=machine.Pin.IRQ_FALLING, handler=self._ModeWheelCallback)
def send(self, data): """ Send data over the network. """ try: self.s.send(data) LED.blink(2, 0.1, 0x00ff00) print("Sending data:") print(data) except OSError as e: if e.errno == 11: print("Caught exception while sending") print("errno: ", e.errno) LED.off() data = self.s.recv(64) print("Received data:", data) return data
def play(): global leds global frame_number animation[frame_number] = copy.deepcopy(leds) #print 'length of ani is ' + str(len(animation)) for playframe in range(1,(len(animation)+1)): #print(playframe) leds =[] for x in range(0, 8): for y in range(0, 8): led = LED(radius=20,pos=(x, y)) leds.append(led) for saved_led in animation[playframe]: if saved_led.lit: for led in leds: if led.pos == saved_led.pos: led.color = saved_led.color led.lit = True piLoad() time.sleep(1.0/fps)
def play(): global leds global frame_number animation[frame_number] = copy.deepcopy(leds) #print 'length of ani is ' + str(len(animation)) for playframe in range(1,(len(animation)+1)): #print(playframe) leds =[] for x in range(0, 8): for y in range(0, 8): led = LED(pos=(x, y)) leds.append(led) for saved_led in animation[playframe]: if saved_led.lit: for led in leds: if led.pos == saved_led.pos: led.color = saved_led.color led.lit = True piLoad() time.sleep(1.0/fps)
def main(): ''' Test LED Blink Red Solid Red Blink Green Solid Green Test Trigger Push trigger Hold trigger Test Send fake IR code Listen for callback ''' led = LED() print("Testing LEDs.\n") eventOne = threading.Event() threadOne = threading.Thread(name='ledOnRed', target=setLED, args=(eventOne, 'red', led, 1)) threadOne.start() answer = input("Is the Red LED on? y/n: ") eventOne.set() if not answer.lower() == 'y': return False eventTwo = threading.Event() threadTwo = threading.Thread(name='ledBlinkRed', target=toggleLED, args=(eventTwo, 'red', led, 1)) threadTwo.start() answer = input("Is the Red LED blinking? y/n: ") # Get user input. eventTwo.set() if not answer.lower() == 'y': return False eventThree = threading.Event() threadThree = threading.Thread(name='ledOnGreen', target=setLED, args=(eventThree, 'green', led, 1)) threadThree.start() answer = input("Is the Green LED on? y/n: ") eventThree.set() if not answer.lower() == 'y': return False eventFour = threading.Event() threadFour = threading.Thread(name='ledBlinkGreen', target=toggleLED, args=(eventFour, 'green', led, 1)) threadFour.start() answer = input("Is the Green LED blinking? y/n: ") # Get user input. eventFour.set() if not answer.lower() == 'y': return False trigger = Trigger() print("Push and hold the trigger for 10 events.") i = 0 while i < 10: if GPIO.input(trigger.TRIGGER) == GPIO.HIGH: time.sleep(0.1) print(("{}: Trigger detected.").format(datetime.datetime.now())) i += 1 time.sleep(1) print("LaserPi programmed remote codes:") call(["irsend", "LIST", "laserpi", ""]) return True
def __init__(self, local_led=None): self.valid_coins = { NICKEL: .05, DIME: 0.1, QUARTER: 0.25, DOLLAR: 1.00 } self.coins = [] self.products = {APPLE: 0.65, ORANGE: 0.75, BANANA: 1.0} self.green_light = local_led if not self.green_light: self.green_light = LED(LED.GREEN_LIGHT)
def runMe(): global lora, sleep_time, oled global useDust setup() # Setup network & sensors while True: toSleep = time() dData = DoDust() mData = DoMeteo() # Send packet if lora != None: if lora.send(DoPack(dData,mData,LocUpdate())): LED.off() else: display(" LoRa send ERROR") LED.blink(5,0.2,0x9c5c00,False) toSleep = sleep_time - (time() - toSleep) if useDust: if toSleep > 30: toSleep -= 15 useDust.Standby() # switch off laser and fan elif toSleep < 15: toSleep = 15 if not ProgressBar(0,63,128,2,toSleep,0xebcf5b,10): display('stopped SENSING', (0,0), clear=True) LED.blink(5,0.3,0xff0000,True) if STOP: sleep(60) oled.poweroff() # and put ESP in deep sleep: machine.deepsleep() return False
def start_animation(): global animation_process global saved FILE=open('/home/pi/RPi_8x8GridDraw/animation8x8.py','wb') FILE.write('from sense_hat import AstroPi\n') FILE.write('import time\n') FILE.write('ap=AstroPi()\n') FILE.write('FRAMES = [\n') global leds global frame_number animation[frame_number] = copy.deepcopy(leds) #print 'length of ani is ' + str(len(animation)) for playframe in range(1,(len(animation)+1)): #print(playframe) leds =[] for x in range(0, 8): for y in range(0, 8): led = LED(pos=(x, y)) leds.append(led) for saved_led in animation[playframe]: if saved_led.lit: for led in leds: if led.pos == saved_led.pos: led.color = saved_led.color led.lit = True grid, png_grid = buildGrid() FILE.write(str(grid)) FILE.write(',\n') FILE.write(']\n') FILE.write('while True:\n') FILE.write('\tfor x in FRAMES:\n') FILE.write('\t\tap.set_pixels(x)\n') FILE.write('\t\ttime.sleep('+ str(1.0/fps) + ')\n') FILE.close() saved = True if animation_process is not None: animation_process.terminate() animation_process = subprocess.Popen(["python", "/home/pi/RPi_8x8GridDraw/animation8x8.py"])
def main(): global g_event, g_led cwd = os.path.abspath(os.path.dirname(__file__)) logging.basicConfig(filename=cwd+'/log.log',level=logging.DEBUG,format='%(asctime)s %(filename)s[line:%(lineno)d] %(message)s',datefmt='%Y-%m-%d %H:%M:%S') # 初始化 event g_event = threading.Event() # 初始化 gpio GPIO.setwarnings(True) # Ignore warning for now GPIO.setmode(GPIO.BOARD) # Use physical pin numbering # 初始化 LED g_led = LED() g_led.set_value(15) regist_button() b_reboot = False try: # 等待事件触发 g_event.wait() b_reboot = True except KeyboardInterrupt as e: logging.warning("KeyboardInterrupted") pass # 清理GPIO logging.debug("gpio cleaning") GPIO.cleanup() # Clean up logging.debug("gpio cleaned") if b_reboot: logging.debug("shutting down") os.system('shutdown -r 0')
def nextFrame(): global frame_number global leds #print(frame_number) animation[frame_number] = copy.deepcopy(leds) #clearGrid() frame_number+=1 if frame_number in animation: leds =[] for x in range(0, 8): for y in range(0, 8): led = LED(radius=20,pos=(x, y)) leds.append(led) load_leds_to_animation()
def run(self): led = LED() sensor_reader = SensorReader(self.device_port, self.baudrate) sensor_reader.start_reading() # database = Database(self.db_file) light_controller = Controller(sensor_reader, led) try: log.startLogging(sys.stdout) factory = WebSocketServerFactory() factory.protocol = RPiServerProtocol factory.protocol.controller = light_controller light_controller._init_read_thread() broadcast_task = task.LoopingCall(self.broadcast, factory) broadcast_task.start(self.broadcast_frequency) reactor.listenTCP(self.port, factory) reactor.run() except CannotListenError: print "Another server already opened at port: ", self.port finally: sensor_reader.close() light_controller.stop() # database.close_connection() led.stop()
def prevFrame(): global frame_number global leds #print(frame_number) animation[frame_number] = copy.deepcopy(leds) clearGrid() if frame_number != 1: frame_number-=1 if frame_number in animation: leds =[] for x in range(0, 8): for y in range(0, 8): led = LED(pos=(x, y)) leds.append(led) load_leds_to_animation()
def connect(self, dev_eui, app_eui, app_key): """ Connect device to LoRa. Set the socket and lora instances. """ dev_eui = unhexlify(dev_eui) app_eui = unhexlify(app_eui) app_key = unhexlify(app_key) # Disable blue blinking and turn LED off LED.heartbeat(False) LED.off() # Initialize LoRa in LORAWAN mode self.lora = LoRa(mode=LoRa.LORAWAN) # Join a network using OTAA (Over the Air Activation) self.lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0) # Wait until the module has joined the network count = 0 while not self.lora.has_joined(): LED.blink(1, 2.5, 0xff0000) # print("Trying to join: " , count) count = count + 1 # Create a LoRa socket LED.blink(2, 0.1) self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # Set the LoRaWAN data rate self.s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) # Make the socket non-blocking self.s.setblocking(False) # print ("Joined! ", count) # print("Create LoRaWAN socket") # Create a raw LoRa socket self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self.s.setblocking(False)
def main(): action = request.values['action'] led = LED(17) if action == 'on': led.on() if action == 'off': led.off() return 'success'
from led import LED led = LED(27) while(True): led.wait(1) led.turnOn() led.wait(1) led.turnOff()
class PyBlaster: """Daemon for PiBlaster project""" def __init__(self): """Whole project is run from this constructor """ # +++++++++++++++ Init +++++++++++++++ # self.keep_run = 0 # used in run for daemon loop, reset by SIGTERM self.log = Log(self) self.settings = Settings(self) self.led = LED(self) self.dbhandle = DBHandle(self) self.mixer = AlsaMixer(self) self.usb = UsbManager(self) self.rfcomm = RFCommServer(self) self.cmd = EvalCmd(self) self.listmngr = PlayListManager(self) self.play = Play(self) self.lirc = LircThread(self) self.buttons = Buttons(self) self.keep_run = 1 self.ret_code = 0 # return code to command line (10 = shutdown) self.led.reset_leds() # invoke arg parser and parse config or create new config if not found self.settings.parse() # check if we can load database, create otherwise self.dbhandle.dbconnect() # restore alsa mixer settings self.mixer.restore_mixer() # load connected usb before bluetooth self.usb.check_new_usb() # initialize sound mixer self.play.init_mixer() # load latest playlist from database self.listmngr.load_active_playlist() # open cmd fifo to read commands self.cmd.open_fifo() # fire up bluetooth service self.rfcomm.start_server_thread() # start lirc thread self.lirc.start() # fire up one thread per each button self.buttons.start() # +++++++++++++++ Daemoninze +++++++++++++++ # self.check_pidfile() self.daemonize() self.create_pidfile() self.led.show_init_done() # +++++++++++++++ Daemon loop +++++++++++++++ # self.run() # +++++++++++++++ Finalize +++++++++++++++ # self.listmngr.save_active() self.led.cleanup() self.delete_pidfile() def run(self): """Daemon loop""" # Expensive operations like new usb drive check # should not be run every loop run. poll_count = 0 # -e flag is set, run only init and exit directly. self.keep_run = 0 if self.settings.exitafterinit else 1 reset_poll_count = self.settings.keep_alive_count * 30 * 4 # # # # # # DAEMON LOOP ENTRY # # # # # # while self.keep_run: poll_count += 1 # Check cmd fifo for new commands. if poll_count % 10 == 0: # each 300 ms is enough self.cmd.read_fifo() # Check button events if self.buttons.has_button_events(): self.buttons.read_buttons() # Check bluetooth channel for new messages/connections. self.rfcomm.check_incomming_commands() # Check if lirc thread has command in queue if self.lirc.queue_not_empty(): ircmd = self.lirc.read_command() if ircmd is not None: self.cmd.evalcmd(ircmd, "lirc") # Check if song has ended if poll_count % 4 == 0: # every 120 ms self.play.check_pygame_events() time.sleep(self.settings.polltime / 1000.) # 30ms default in # config if poll_count % self.settings.keep_alive_count == 0: self.led.set_led_green(1) if (poll_count - self.settings.flash_count) % \ self.settings.keep_alive_count == 0: self.led.set_led_green(0) # Check for new USB drives. if poll_count % 30 == 0: # If new usb device found, new usbdev instance will be created, # including dir and mp3 entries. # If usb device got lost, all its entries will be removed. # To check every ~900ms is enough self.usb.check_new_usb() # Multiple of all poll counts reached: # may reset poll count at reset_poll_count. if poll_count >= reset_poll_count: poll_count = 0 # end daemon loop # # # # # # # DAEMON LOOP EXIT # # # # # # # join remaining threads self.mixer.save_mixer() self.lirc.join() self.buttons.join() self.rfcomm.join() self.log.write(log.MESSAGE, "---- closed regularly ----") # end run() # def daemonize(self): """Fork process and disable print in log object""" signal.signal(signal.SIGTERM, self.term_handler) signal.signal(signal.SIGINT, self.term_handler) if not self.settings.daemonize: self.log.init_log() return self.log.write(log.DEBUG1, "daemonizing") try: pid = os.fork() except OSError: self.log.write(log.EMERGENCY, "Failed to fork daemon") raise if pid == 0: os.setsid() try: pid = os.fork() except OSError: self.log.write(log.EMERGENCY, "Failed to fork daemon") raise if pid == 0: os.chdir("/tmp") os.umask(0) else: os._exit(0) else: os._exit(0) self.settings.is_daemonized = True self.log.init_log() self.log.write(log.MESSAGE, "daemonized.") # end daemonize() # def term_handler(self, *args): """ Signal handler to stop daemon loop""" self.keep_run = 0 def check_pidfile(self): """Check if daemon already running, throw if pid file found""" if os.path.exists(self.settings.pidfile): self.log.write(log.EMERGENCY, "Found pid file for pyblaster, " "another process running?") raise Exception("pid file found") def create_pidfile(self): """Write getpid() to file after daemonize()""" try: fpid = open(self.settings.pidfile, "w") except IOError: self.log.write(log.EMERGENCY, "failed to create pidfile %s" % self.settings.pidfile) raise fpid.write("%s\n" % os.getpid()) def delete_pidfile(self): """Try to remove pid file after daemon should exit""" if os.path.exists(self.settings.pidfile): try: os.remove(self.settings.pidfile) except OSError: self.log.write(log.EMERGENCY, "failed to remove pidfile %s" % self.settings.pidfile) raise def kill_other_pyblaster(self): """Check if pid found in pid file and try to kill this (old) process""" if not os.path.exists(self.settings.pidfile): return try: f = open(self.settings.pidfile, "r") except IOError: self.log.write(log.EMERGENCY, "failed to read pidfile %s" % self.settings.pidfile) raise pid = int(f.readline().strip()) print("Trying to kill old process with pid %s..." % pid) try: os.kill(pid, signal.SIGTERM) except OSError: self.log.write(log.EMERGENCY, "failed to kill process with pid %s" % pid) raise exit(0)
class LEDWeather: def __init__(self): self._show_timeout = 0 self._first_update = True self._led = LED(Pins.RED, Pins.GREEN, Pins.BLUE) self._led.blink((1, 0, 0)) self._simple = Geoclue.Simple.new('geoclue-where-am-i', # Let's cheat Geoclue.AccuracyLevel.EXACT, None, self._on_simple_ready) def close(self): self._unshedule_weather_show() self._led.close() def _on_simple_ready(self, simple, data): location = simple.get_location() self._on_location_updated(location) def _on_location_updated(self, location): latitude = location.get_property('latitude') longitude = location.get_property('longitude') world = GWeather.Location.get_world() city = world.find_nearest_city(latitude, longitude) self.info = GWeather.Info.new(city, GWeather.ForecastType.LIST) self.info.set_enabled_providers(GWeather.Provider.METAR | GWeather.Provider.YR_NO) self.info.connect('updated', self._on_weather_updated, None) self._update_timeout = GLib.timeout_add_seconds(3600, self._on_weather_update_timeout) def _on_weather_update_timeout(self): self._unshedule_weather_show() self._led.blink((1, 0, 0)) self.info.update() return True def _on_weather_updated(self, info, data): self._unshedule_weather_show() self._index = 0 if self._first_update: self._show_weather() self._first_update = False else: self._show_timeout = GLib.timeout_add_seconds(5, self._on_show_weather_timeout) def _on_show_weather_timeout(self): self._show_timeout = 0 forecast_time = self._get_current_forecast_time() n_blinks = round((forecast_time - time.time()) / 12 / 3600) if n_blinks > 0: self._led.blink((0, 1, 0), n_blinks, self._show_weather) else: self._show_weather() return False def _show_weather(self): forecasts = self.info.get_forecast_list() current_time = self._get_current_forecast_time() if self._index >= len(forecasts) or current_time >= time.time() + 3600 * 72: self._index = 0 self._led.show_weather(None) self._show_timeout = GLib.timeout_add_seconds(5, self._on_show_weather_timeout) return False current_time = self._get_current_forecast_time() str = time.strftime("%c", time.gmtime(current_time)) print("Weather at %s" % str) if self._index == 0: self._led.show_weather(self.info) else: self._led.show_weather(forecasts[self._index]) self._set_next_index() self._show_timeout = GLib.timeout_add_seconds(5, self._on_show_weather_timeout) return False def _set_next_index(self): forecasts = self.info.get_forecast_list() current_time = self._get_current_forecast_time() index = self._index next_index = -1 while index < len(forecasts): [ret, timestamp] = forecasts[index].get_value_update() if ret and timestamp >= current_time + 3600 * 12: next_index = index break else: index = index + 1 if next_index == -1: self._index = 0 else: self._index = next_index def _get_current_forecast_time(self): if self._index == 0: return time.time() forecasts = self.info.get_forecast_list() [ret, timestamp] = forecasts[self._index].get_value_update() if not ret: # Shouldn't be happening but let's be prepared return time.time() return timestamp def _unshedule_weather_show(self): if self._show_timeout == 0: return GLib.source_remove(self._show_timeout) self._show_timeout = 0
def __init__(self): self.weatherDataObj = WeatherData() self.palletObj = Pallet() self.fbNotificationObj = fbNotification() self.fb_led = LED(22)
pass # testing purposes if __name__ == "__main__": # rpi sr = SensorReader('/dev/ttyUSB0', 115200) # red/4 # sr = SensorReader('/dev/tty.usbserial-MFU7XGR7', 115200) # blue/7 # sr = SensorReader('/dev/tty.usbserial-MFUD5O75', 115200) # sr.start_reading() led = LED() out_file = open(time.strftime('%Y%m%d-%H%M%S') + ".csv", "w") database = Database("../rpi.db") controller = Controller(sr, led, file=out_file) try: if len(sys.argv) >= 2: for arg in sys.argv: if arg == "single_loop": print "single loop option selected" controller.single_loop() elif arg == "single": print "measure on single thread selected" controller.single_measure(100) elif arg == "stairs": print "measure on single thread selected" controller.stairs_loop()
import time from led import Color, LED import xbee_leds if __name__ == '__main__': xbees = xbee_leds.get_xbee_list(True) if not xbees: raise Exception('No XBees found on network') eui = xbees[0] #initialize ZigBee driver xbee_leds.initialize() while True: for c in (Color(red=0xF), Color(blue=0xF), Color(green=0xf), Color(0xf, 0xf, 0xf)): for i in xrange(50): bulb = LED(i, c) time.sleep(.25) xbee_leds.send_leds(bulb.export(), eui) # make sure we don't try to send too fast while xbee_leds.queue_size(eui) > 3: time.sleep(0.01)
parser.add_argument("-b", "--min_distance", help="sensor min distance measured in centimeters", type=float, default=2) parser.add_argument("-g", "--log_level", help="log level", type=int, default=logging.INFO) args = parser.parse_args() # logging setup logger = set_logger(level=args.log_level) # initialize distance sensor GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(args.trigger_pin, GPIO.OUT) GPIO.setup(args.echo_pin, GPIO.IN) recent = [] led = LED('led1', 13) led.start() range = args.max_distance - args.min_distance while True: try: sample = [] for reading in range(args.sample_size): GPIO.output(args.trigger_pin, GPIO.LOW) time.sleep(args.sensor_settle) GPIO.output(args.trigger_pin, True) time.sleep(0.00001) GPIO.output(args.trigger_pin, False) while GPIO.input(args.echo_pin) == 0: sonar_signal_off = time.time() while GPIO.input(args.echo_pin) == 1:
def __init__(self): """Whole project is run from this constructor """ # +++++++++++++++ Init +++++++++++++++ # self.keep_run = 0 # used in run for daemon loop, reset by SIGTERM self.log = Log(self) self.settings = Settings(self) self.led = LED(self) self.dbhandle = DBHandle(self) self.mixer = AlsaMixer(self) self.usb = UsbManager(self) self.rfcomm = RFCommServer(self) self.cmd = EvalCmd(self) self.listmngr = PlayListManager(self) self.play = Play(self) self.lirc = LircThread(self) self.buttons = Buttons(self) self.keep_run = 1 self.ret_code = 0 # return code to command line (10 = shutdown) self.led.reset_leds() # invoke arg parser and parse config or create new config if not found self.settings.parse() # check if we can load database, create otherwise self.dbhandle.dbconnect() # restore alsa mixer settings self.mixer.restore_mixer() # load connected usb before bluetooth self.usb.check_new_usb() # initialize sound mixer self.play.init_mixer() # load latest playlist from database self.listmngr.load_active_playlist() # open cmd fifo to read commands self.cmd.open_fifo() # fire up bluetooth service self.rfcomm.start_server_thread() # start lirc thread self.lirc.start() # fire up one thread per each button self.buttons.start() # +++++++++++++++ Daemoninze +++++++++++++++ # self.check_pidfile() self.daemonize() self.create_pidfile() self.led.show_init_done() # +++++++++++++++ Daemon loop +++++++++++++++ # self.run() # +++++++++++++++ Finalize +++++++++++++++ # self.listmngr.save_active() self.led.cleanup() self.delete_pidfile()
def led_on_demo(): pin_number = 18 # edit pin number led = LED(rpi, pin_number) led.turn_on() sleep(2) led.turn_off()
class ListenIn(object): def __init__(self, token, duration, interval, retrytime, last_uploaded_file): self.token = token self.duration = duration self.interval = interval self.retrytime = retrytime self.last_uploaded_file = last_uploaded_file self.led = LED(red=13, green=19, blue=26, initial_color='white') self._q = Queue() self.default_blink_interval = (5, 300) self.fast_blinking = (0.5, 500) def start_blinker(self): self._blinker_stop = Event() self._blinker_thread = Thread(target=self.blink_periodically) self._blinker_thread.start() def stop_blinker(self): self._blinker_stop.set() self._blinker_thread.join() def blink_periodically(self): last_blink_time = time.time() interval, duration = self.default_blink_interval while True: if self._blinker_stop.isSet(): break try: interval, duration = self._q.get_nowait() except Empty: pass if time.time() - last_blink_time > interval: self.led.blink(duration=duration) last_blink_time = time.time() time.sleep(0.1) def write_last_uploaded_ts(self): try: tmp_file = self.last_uploaded_file + '.tmp' open(tmp_file, 'w').write(str(int(time.time()))) os.rename(tmp_file, self.last_uploaded_file) except Exception: pass def listen(self): self.start_blinker() while True: try: logging.info('waiting for audio signal') self.led.set('purple') r = self.record_sample() next(r) logging.info('recording') self.led.set('red') sample = next(r) logging.info('uploading') self.led.set('blue') t0 = time.time() self.upload_sample(sample) except Exception as e: logging.error('%s: %s', e.__class__.__name__, e) self.led.set('orange') self._q.put(self.fast_blinking) time.sleep(self.retrytime) self._q.put(self.default_blink_interval) else: self.write_last_uploaded_ts() logging.info('sample recorded and uploaded, sleeping for %d seconds', self.interval) self.led.set('green') sleep_time = self.interval - (time.time() - t0) if sleep_time >= 0: time.sleep(sleep_time) def record_sample(self): output_file = '/tmp/output.mp3' processed_file = '/tmp/processed.mp3' downsampled_output_file = '/tmp/downsampled.1c.8k.flac' for f in output_file, downsampled_output_file: if os.path.exists(f): os.unlink(f) rec_cmd = 'rec --no-show-progress -t mp3 -C 0 {} highpass 60 silence 1 0.1 -35d 1 2.0 -35d trim 0 {}'.format( output_file, self.duration, ) rec_process = subprocess.Popen(rec_cmd.split()) while True: rc = rec_process.poll() if rc is not None: break try: if os.path.getsize(output_file) > 0: break except OSError: pass time.sleep(0.1) if rc is None: yield rc = rec_process.wait() if rc != 0: raise RuntimeError('failed to record: return code = {}'.format(rc)) normalize_cmd = 'sox --norm {} {}'.format(output_file, processed_file) subprocess.check_call(normalize_cmd.split()) downsample_cmd = 'sox {} -r 8000 -b 16 -c 1 {}'.format(processed_file, downsampled_output_file) subprocess.check_call(downsample_cmd.split()) w = Wave(downsampled_output_file) if w.length < self.duration: raise RuntimeError('sample duration too short ({}<{})'.format(w.length, self.duration)) if w.is_silence: raise RuntimeError('sample is silent') if w.is_noise: raise RuntimeError('sample is 50hz hum') yield open(processed_file).read() def assert_sample_is_valid(self, sample_file): pass def upload_sample(self, sample): url = 'http://api.listenin.io/upload?token={}'.format(self.token) requests.post(url, data=sample, timeout=60).raise_for_status() def cleanup(self): self.stop_blinker()