def prepare(self): """ Prepare environment. """ # Prepare GPIO. GPIO.setmode(GPIO.BCM) for pin in self.pins: if self.pins[pin][1] == 'out': GPIO.setup(self.pins[pin][0], GPIO.OUT) GPIO.output(self.pins[pin][0], GPIO.HIGH) elif self.pins[pin][1] == 'in': GPIO.setup(self.pins[pin][0], GPIO.IN) # Initialize modules. self.oled = Display(port=self.oled_port, address=self.oled_i2c_address) self.oled.images_path = self.images_path self.menu = Menu(rr=self) self.beeper = Beeper(gpio=GPIO, speaker_pin=self.pins['Beeper'][0]) self.beeper.mute = not self.sounds_is_on self.leds = Leds(gpio=GPIO, pins=self.pins) self.usrinfo = UsrInfo(display=self.oled, leds=self.leds) self.sysinfo = SysInfo(display=self.oled, leds=self.leds) # Set interrupts for buttons. for pin in self.pins: if 'BTN_' in pin: GPIO.add_event_detect(self.pins[pin][0], GPIO.FALLING, callback=self.button_pressed, bouncetime=100)
def init(): gc.enable() Status.init() if not Config.init(): Config.factoryReset() Config.init() Wifi.init() Leds.init() Sensors.init() Relays.init() if Config.getParam("time", "ntp"): i = 1 try: while i < 5 and not ntpclient.settime(Config.getParam("time", "ntp"), Config.getParam("time", "offset")): Status.log("Getting time from NTP... (%s)" % i) i += 1 rtc = machine.RTC() t = rtc.datetime() except Exception: t = utime.localtime(0) else: t = utime.localtime(0) Status.log('Date: {:04d}.{:02d}.{:02d} {:02d}:{:02d}:{:02d}'.format(t[0], t[1], t[2], t[4], t[5], t[6])) # Init timer tim = machine.Timer(0) tim.init(period=50, mode=machine.Timer.PERIODIC, callback=tick50mS())
def mainloop(): Leds.tick50mS() if Status.inMeasure == "scan": Sensors.scan() Status.inMeasure = "idle" elif Status.inMeasure == "start": Sensors.startMeassure() Status.inMeasure = "idle" elif Status.inMeasure == "read": Sensors.readTemp() Status.inMeasure = "idle"
def main(): logger.info('Initialize') data_sink = Observable() builder = Builder(config) builder.bind(data_sink) leds = Leds() while True: try: prices = [entry[1:] for entry in get_dummy_data() ] if config.dummy_data else fetch_prices() data_sink.update_observers(prices) leds.off() time.sleep(config.refresh_interval) except Exception as e: logger.error(str(e)) leds.on() time.sleep(10) except KeyboardInterrupt: logger.info('Exit') data_sink.close() exit()
def __init__(self): print(" [*] Application starting") self.status = 'valid' self.config = Config() self.status = self.config.status self.rabbit_client = RabbitMQ_Client(self.config.rabbitmq, self.config.mac, self.config.amqp_encryption_key) self.rabbit_server = RabbitMQ_Server(self.dispatch, self.config.rabbitmq, self.config.mac, self.config.amqp_encryption_key) self.usb_devices = UsbDevices(self.dispatch) self.leds = Leds() self.gpios = Gpios(self.dispatch) self.displays = Displays(self.dispatch) self.rfids = Rfid(self.dispatch) self.lwm2m = Lwm2m(self.config) self.state = State(self.dispatch) self.monitor = Monitor(self.dispatch, self.config)
def __init__(self, config_file, mock_gpio=False): super().__init__() if not mock_gpio: GPIO.setwarnings(False) if GPIO.getmode() != GPIO.BOARD: GPIO.setmode(GPIO.BOARD) Electrical.setup_gpio() Eink.EPD = EPD() self.eink = Eink(reactor) self.config = self._parse_config(config_file) self._setup_logging(self.config) self.app_state = AppState(self.config) self.leds = Leds() self.machine = Machine(reactor, self.app_state, self.eink, self.leds) self.network_health = NetworkHealth(reactor, self.machine) self.invoicer = Invoicer(reactor, self.app_state, self.machine) self.electical = Electrical(reactor, self.machine)
class Device: #Sensors sensors = 0 #Remote NRF24 = 0 #Remoto devicesRemote = [] #Dispositivos remotos #Rele rele = 0 #Rele camera = 0 #Status connectionStatus = 0 #0 offline, 1 online, 2 portNotOpen alarmMode = 0 #0 No, 1 Yes #Leds leds = 0 #Sounds sounds = 0 #Port and IPs port = 0 publicIp = 0 privateIp = 0 #Code security currentCode = str(randint(10000,99999999)) previousCode = currentCode numberOfPetitions = 0 #Type Device typeDevice = 0 ################################################################################################################################################# ################################################################################################################################################# ##################################################### SECTION DOMOTICS SERVER ######################################################### ################################################################################################################################################# ################################################################################################################################################# def __init__(self): print "Arranca Domotics" #Configuramos el los pines GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(deviceConfig.pinResetButton, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(deviceConfig.pinIRSensor, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) self.leds = Leds() #Cuando se encienda el dispositivo se encenderan todos los leds self.leds.setLedsOn() self.sounds = Sounds() #Configuracion del evento para el reset GPIO.add_event_detect(deviceConfig.pinResetButton, GPIO.FALLING, callback=self.buttonResetCallback, bouncetime=500) time.sleep(1) #Una vez pasa 1 segundo se mantiene encendida solo la luz de error hasta que consiga conectarse a internet y montar el servidor self.leds.setLedsError() print "Solicitamos codigo se seguridad" self.updateSecurityCode() print "¡¡¡Tenemos codigo!!!" self.updateVersionDevice(deviceConfig.deviceId) self.updateSoftware() self.port = int(self.getPort()) #obtenemos el puerto print self.port self.privateIp = self.getPrivateIp() #Obtenemos la ip privada print self.privateIp class RequestHandler(pyjsonrpc.HttpRequestHandler): # Register public JSON-RPC methods methods = { "switchGetValue": self.switchGetValue, "switchSetValue": self.switchSetValue, "sensorGetValues": self.sensorGetValues, "cameraGetPhoto": self.cameraGetPhoto, "cameraGetPhotoForMail": self.cameraGetPhotoForMail, "installRemoteDevice": self.installRemoteDevice, "setDeviceAlarmMode": self.setDeviceAlarmMode, "quitDeviceAlarmMode": self.quitDeviceAlarmMode } # Threading HTTP-Server http_server = pyjsonrpc.ThreadingHttpServer( server_address = (self.privateIp, self.port), RequestHandlerClass = RequestHandler ) print "Creado servidor" # Start the scheduler sched = Scheduler() sched.start() # Schedule sendStatus every 1 minutes sched.add_interval_job(self.sendStatus, minutes=1) # Schedule updateSecurityCode every 1 hours sched.add_interval_job(self.updateSecurityCode, hours=1) # Schedule updateSoftware every 24 hours sched.add_interval_job(self.updateSoftware, hours=24) #Obtenemos del servidor el tipo de dispositivo que es y inicializamos self.typeDevice = int(self.getTypeDevice()) print self.typeDevice #Remote Device if self.typeDevice == 0: self.NRF24 = Remote() sched.add_interval_job(self.newReadingSensors, hours=1) #Rele device elif self.typeDevice == 1: self.rele = Rele() #Camera device elif self.typeDevice == 2: self.camera = Camera() #Sensors device elif self.typeDevice == 4: self.sensors = Sensors() sched.add_interval_job(self.newReadingSensors, hours=1) print "Actualizamos estado dispositivo" ## Actualizamos el estado del dispositivo self.sendStatus() #Temporizador para guadar datos de sensores if self.typeDevice == 0 or self.typeDevice == 4: self.newReadingSensors() #Configuracion del evento para el detector de presencia GPIO.add_event_detect(deviceConfig.pinIRSensor, GPIO.RISING, callback=self.IRSensorDetectCallback, bouncetime=10000) print "Listo para arracar el servidor" self.sounds.start() #print myconfig.urlDb print "Starting HTTP server ..." print "URL: http://%s:%d" % (self.privateIp, self.port) try: http_server.serve_forever() except KeyboardInterrupt: http_server.shutdown() self.leds.setLedsError() except: self.leds.setLedsError() time.sleep(10) os.system('sudo reboot') print "Stopping HTTP server ..." ################################################################################################################################################# ################################################################################################################################################# ##################################################### SECTION INSTALL DEVICE ######################################################### ################################################################################################################################################# ################################################################################################################################################# def buttonResetCallback(self, channel): print "Reset" time.sleep(1) if GPIO.input(channel) == GPIO.LOW: buttonAlwaysPressed = 1 for i in range(10): if GPIO.input(channel) == GPIO.LOW: self.leds.setLedsOn() time.sleep(0.2) self.sounds.on() time.sleep(0.1) self.sounds.off() time.sleep(0.2) self.leds.setLedsOff() time.sleep(0.5) else: buttonAlwaysPressed = 0 if GPIO.input(channel) == GPIO.LOW and buttonAlwaysPressed == 1: self.leds.setLedsAdhoc() os.system('sudo cp /home/pi/Domotics/Default/bootInstall.py /home/pi/Domotics/bootConfig.py') os.system('sudo cp /home/pi/Domotics/Default/network/adhoc/dhcpd.conf /etc/dhcp/dhcpd.conf') os.system('sudo cp /home/pi/Domotics/Default/network/adhoc/wpa_supplicant.conf /etc/wpa_supplicant/wpa_supplicant.conf') #Eliminamos fichero de configuracion os.system('sudo rm /etc/network/interfaces') nameWIFI = "Domotics%d" % (randint(1000,9999)) #Creamos el fichero de configuración en base a la plantilla y rellenamos el nombre de la red adhoc with open("/etc/network/interfaces", "wt") as fout: with open("/home/pi/Domotics/Default/network/adhoc/interfaces", "rt") as fin: for line in fin: fout.write(line.replace('<NAME>', nameWIFI)) self.sounds.reset() time.sleep(2) os.system('sudo reboot') else: self.leds.updateLeds(self.connectionStatus, self.alarmMode) def installRemoteDevice(self, idDevice, pipeSend, pipeRecv, code): if (self.currentCode == code or self.previousCode == code) and self.numberOfPetitions < deviceConfig.maxNumberOfPetitions: #Eliminamos el software anterior os.system('sudo rm /home/pi/Domotics/Arduino/src/domotics.ino') #Configuramos el nuevo software con el valor del pipeSend y el pipeRecv with open("/home/pi/Domotics/Arduino/src/domotics.ino", "wt") as fout: with open("/home/pi/Domotics/Default/domoticsAux.ino", "rt") as fin: for line in fin: fout.write(line.replace('<PIPE_SEND>', pipeSend).replace('<PIPE_RECV>', pipeRecv)) #Cambiamos la ruta en la que esta el Software Arduino os.chdir('/home/pi/Domotics/Arduino') #Limpiamos el proyecto #os.system('sudo ino clean') #Compilamos os.system('sudo ino build -m leonardo') #Subimos el binario al ardino os.system('sudo ino upload -m leonardo') self.updateVersionDevice(idDevice) self.sendStatus() return 1 else: self.numberOfPetitions += 1 return -1 ################################################################################################################################################# ################################################################################################################################################# ##################################################### SECTION SECURITY CODE ######################################################### ################################################################################################################################################# ################################################################################################################################################# def updateSecurityCode(self): self.previousCode = self.currentCode self.currentCode = str(randint(10000,99999999)) rpc_client = pyjsonrpc.HttpClient(url = deviceConfig.url) result = rpc_client("updateSecurityCode", deviceConfig.deviceId, self.currentCode, self.previousCode) while result == 0: time.sleep(5) result = rpc_client("updateSecurityCode", deviceConfig.deviceId, self.currentCode, self.previousCode) print "Intentamos enviar el codigo de seguridad" return result ################################################################################################################################################# ################################################################################################################################################# ################################################ SECTION GET DEVICE IP & PORT ####################################################### ################################################################################################################################################# ################################################################################################################################################# # private IP def getPrivateIp(self): success = False privateIp = 0 while success == False: try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.connect_ex(('<broadcast>', 0)) privateIp = s.getsockname()[0] success = True except: success = False self.connectionStatus = 0 self.leds.setLedsError() time.sleep(1) return privateIp # public IP def getPublicIp(self): success = False publicIp = 0 while success == False: try: publicIp = json.load(urllib2.urlopen('http://httpbin.org/ip'))['origin'] success = True except: self.connectionStatus = 0 self.leds.setLedsError() time.sleep(1) try: publicIp = json.load(urllib2.urlopen('http://jsonip.com'))['ip'] success = True except: self.connectionStatus = 0 self.leds.setLedsError() time.sleep(1) try: publicIp = json.load(urllib2.urlopen('https://api.ipify.org/?format=json'))['ip'] success = True except: success = False self.connectionStatus = 0 self.leds.setLedsError() time.sleep(1) return publicIp # Port def getPort(self): success = False port = 0 while success == False: try: rpc_client = pyjsonrpc.HttpClient(url = deviceConfig.url) port = rpc_client("getPort", deviceConfig.deviceId, self.currentCode)['port'] success = True except: success = False self.connectionStatus = 0 self.leds.setLedsError() time.sleep(1) return port def checkPortConnection(self, port, publicIp): # Setup socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(1) connectionStatus = 2 try: sock.connect((publicIp, port)) except Exception,e: rpc_client = pyjsonrpc.HttpClient(url = deviceConfig.url) result = rpc_client("checkPort", publicIp, port) if result: #print "Port is open" connectionStatus = 1 else: #print "Port is not open" connectionStatus = 2 else:
from flask import Flask app = Flask(__name__) app.debug = True from leds import Leds from tempsensor import TemperatureSensor from flask import render_template tep = TemperatureSensor() led1 = Leds() led2 = Leds() @app.route('/') def read_temp(): temp_c = tep.WarningTemperature() if temp_c < 22: message = 'froid' led1.led_on('2') led2.led_of('1') elif 22 <= temp_c < 23: message = 'bon' led2.led_of('1') led2.led_of('2') else: message = 'chaud' led1.led_on('1') led2.led_of('2') return render_template('temperature.html', message=message, temp_c=temp_c)
#!/usr/bin/env python3 import time import board import pickle import random from audio import RidderAudio from sensor import Distance from leds import Leds, RGB, WavAnimation, FadeAnimation ## Config from config import * ## Start Script LEDs = Leds(pin=board.D18, num_leds=NumLEDs) sensor = Distance(SensorType) audio = RidderAudio(AudioDir) start = time.time() detect = 0 dice = 0 audioLength = 0 wavAnimation = None def loadAnimation(wav, audioLength): picklefile = wav.replace('.wav', '.pkl') with open(picklefile, 'rb') as f:
class RRouter(object): """ Router controller program. """ def __init__(self): self.pins = {} self.sounds_is_on = True self.animations_is_on = True self.animation_sets = [] self.idle_time_to_sleep = 8 self.oled_port = 1 self.oled_i2c_address = 0x0 self.images_path = '' self.sleeping = True self.last_key_press_time = 0 self.wake_up_last_time = 0 self.wake_up_timeout = 20 self.inet_check_last_time = 0 self.inet_check_timeout = 40 self.inet_check_sound_notified = False self.oled = None self.menu = None self.beeper = None self.usrinfo = None self.sysinfo = None def prepare(self): """ Prepare environment. """ # Prepare GPIO. GPIO.setmode(GPIO.BCM) for pin in self.pins: if self.pins[pin][1] == 'out': GPIO.setup(self.pins[pin][0], GPIO.OUT) GPIO.output(self.pins[pin][0], GPIO.HIGH) elif self.pins[pin][1] == 'in': GPIO.setup(self.pins[pin][0], GPIO.IN) # Initialize modules. self.oled = Display(port=self.oled_port, address=self.oled_i2c_address) self.oled.images_path = self.images_path self.menu = Menu(rr=self) self.beeper = Beeper(gpio=GPIO, speaker_pin=self.pins['Beeper'][0]) self.beeper.mute = not self.sounds_is_on self.leds = Leds(gpio=GPIO, pins=self.pins) self.usrinfo = UsrInfo(display=self.oled, leds=self.leds) self.sysinfo = SysInfo(display=self.oled, leds=self.leds) # Set interrupts for buttons. for pin in self.pins: if 'BTN_' in pin: GPIO.add_event_detect(self.pins[pin][0], GPIO.FALLING, callback=self.button_pressed, bouncetime=100) def button_pressed(self, channel=0): """ Buttons actions. """ # Get button name by it's channel. btn_name = '' for pin in self.pins: if self.pins[pin][0] == channel: btn_name = pin break if not btn_name: return False # Blink LED. self.leds.blink('B') # Play sound on button press. if btn_name in ['BTN_1', 'BTN_4', 'BTN_5']: self.beeper.play('alien-signal', length=1) else: self.beeper.play('click') # Actions for buttons. if btn_name == 'BTN_1': if self.sleeping: self.menu.show() else: # Menu items actions. if self.menu.selected_item == 1: self.usrinfo.show() elif self.menu.selected_item == 2: self.sysinfo.show() elif self.menu.selected_item == 3: if self.beeper.mute: self.beeper.mute = False self.show_image_center('sound-on.png') else: self.beeper.mute = True self.show_image_center('sound-off.png') elif self.menu.selected_item == 4: if self.animations_is_on: self.animations_is_on = False self.show_image_center('animation-off.png') else: self.animations_is_on = True self.show_image_center('animation-on.png') elif self.menu.selected_item == 5: self.power_off() elif btn_name == 'BTN_2': self.menu.select_prev() elif btn_name == 'BTN_3': self.menu.select_next() elif btn_name == 'BTN_4': self.sysinfo.show() elif btn_name == 'BTN_5': self.usrinfo.show() # Deactivate sleeping mode. self.sleeping = False self.last_key_press_time = time() def power_off(self): """ Powering OFF. """ # Show message + simple countdown. self.leds.set_one('R', 1) self.oled.clean() self.oled.font_set('NotoMono', 17) self.oled.add_text('Powering OFF', x=0, y=21) self.oled.show() for i in range(0, 8): x = i * 5 self.oled.add_text('.', x=x, y=40) self.oled.show() # Shutdown. call('poweroff', shell=True) def show_animation(self, set_name='', repeat=1): """ Showing animation from PNG files. """ set_prefix = 'anim_' + set_name files = [] for f in os.listdir(self.images_path): if set_prefix in f \ and os.path.isfile(os.path.join(self.images_path, f)): files.append(f) files.sort() for i in range(0, repeat): for img_file in files: self.show_image_center(img_file) def show_image_center(self, img_file=''): """ Show image in center of the screen. """ self.oled.clean() self.oled.add_image_center(img_file) self.oled.show() def start(self): """ Main function for daemon. """ # Main cycle. self.leds.set_all(1) self.show_animation('deb', repeat=2) self.leds.set_all(0) try: while True: # Sleeping mode guard. if self.last_key_press_time + self.idle_time_to_sleep < time(): self.sleeping = True self.menu.selected_item = 0 self.oled.clean() self.oled.show() # Wake UP + animations. if self.sleeping\ and self.wake_up_last_time + self.wake_up_timeout < time() \ and self.animations_is_on: if self.wake_up_last_time: self.show_animation(choice(self.animation_sets)) self.wake_up_last_time = time() # Internet connection checker. if self.sleeping\ and self.inet_check_last_time + \ self.inet_check_timeout < time(): if not self.sysinfo.check_host_port('8.8.8.8', 53): self.leds.set_one('R', 1) self.show_image_center('no-internet.png') if not self.inet_check_sound_notified: self.beeper.play('error') self.inet_check_sound_notified = True else: self.leds.set_one('R', 0) self.inet_check_sound_notified = False self.inet_check_last_time = time() sleep(1) except KeyboardInterrupt: pass print('OK') GPIO.cleanup()
def __init__(self, sys_clk_freq, **kwargs): platform = Platform() kwargs["cpu_type"] = None kwargs["with_uart"] = False kwargs["with_timer"] = False #kwargs["with_ctrl"] = False # Force the SRAM size to 0, because we add our own SRAM with SPRAM kwargs["integrated_sram_size"] = 0 kwargs["integrated_rom_size"] = 0 kwargs["csr_data_width"] = 32 clock_ext = [ ("clk16", 0, Pins("20"), IOStandard("LVCMOS33")) ] platform.add_extension(clock_ext) SoCCore.__init__(self, platform, sys_clk_freq, **kwargs) self.submodules.crg = _CRG(platform, sys_clk_freq) reset_btn = platform.request("user_btn_n") self.comb += self.crg.reset.eq(~reset_btn) led = platform.request("user_led_n") led2 = platform.request("user_led_n") spi_ext = [ ("spi_slave", 0, Subsignal("cs_n", Pins("16"), IOStandard("LVCMOS33")), Subsignal("clk", Pins("15"), IOStandard("LVCMOS33")), Subsignal("mosi", Pins("17"), IOStandard("LVCMOS33")), Subsignal("miso", Pins("14"), IOStandard("LVCMOS33")), ), ] platform.add_extension(spi_ext) spi_pads = platform.request("spi_slave") self.submodules.bridge = bridge = SPIBridge(spi_pads) self.bus.add_master(name="bridge", master=self.bridge.wishbone) # UP5K has single port RAM, which is a dedicated 128 kilobyte block. # Use this as CPU RAM. # spram_size = 128 * 1024 # self.submodules.spram = Up5kSPRAM(size=spram_size) # self.register_mem("sram", self.mem_map["sram"], self.spram.bus, spram_size) # The litex SPI module supports memory-mapped reads, as well as a bit-banged mode # for doing writes. # spiflash_size = 16 * 1024 * 1024 # self.submodules.spiflash = SpiFlash(platform.request("spiflash4x"), dummy=6, endianness="little") # self.register_mem("spiflash", self.mem_map["spiflash"], self.spiflash.bus, size=spiflash_size) # self.add_csr("spiflash") # Add ROM linker region #self.add_memory_region("rom", self.mem_map["spiflash"] + flash_offset, spiflash_size - flash_offset, type="cached+linker") platform.add_extension(break_off_pmod) self.submodules.leds = Leds(Cat( #platform.request("user_ledr_n"), #platform.request("user_ledg_n"), platform.request("user_ledr"), platform.request("user_ledg", 0), platform.request("user_ledg", 1), platform.request("user_ledg", 2), platform.request("user_ledg", 3)), led_polarity=0x00, led_name=[ #["ledr", "The Red LED on the main iCEBreaker board."], #["ledg", "The Green LED on the main iCEBreaker board."], ["hledr1", "The center Red LED #1 on the iCEBreaker head."], ["hledg2", "Green LED #2 on the iCEBreaker head."], ["hledg3", "Green LED #3 on the iCEBreaker head."], ["hledg4", "Green LED #4 on the iCEBreaker head."], ["hledg5", "Green LED #5 on the iCEBreaker head."]]) self.add_csr("leds") assert hasattr(self.platform.toolchain, "build_template") if self.platform.toolchain.build_template[0].startswith("yosys "): self.platform.toolchain.build_template[0] =\ self.platform.toolchain.build_template[0].replace("yosys ", "yosys -q ")
@brief <вставьте сюда краткое описание модуля> ''' import time from uart import Uart from sdcard import Sdcard from leds import Leds if __name__ == "__main__": uart1 = Uart() card = Sdcard(uart1) leds1 = Leds(uart1) # leds1.test() time.sleep(1) print(''' Step 1 Set DI and CS high and apply 74 or more clock pulses to SCLK. Without this step under certain circumstances SD-card will not work. For instance, when multiple SPI devices are sharing the same bus (i.e. MISO, MOSI, CS).''') card.preInit() print() print('Переводим сигнал NCS у SD-карты в состояние лог.0') card.select() print()
import RPi.GPIO as GPIO import time from leds import Leds leds = Leds() class Mouvement(): broche = 17 GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(broche, GPIO.IN) # Pinout leds GPIO.setup(18, GPIO.OUT) GPIO.setup(24, GPIO.OUT) def detectMove(self, socketIo): previousstate = 0 while True: # Lecture du capteur currentstate = GPIO.input(self.broche,) # Si le capteur est déclenché if currentstate == 1 and previousstate == 0: socketIo.emit('MoveOn', 'mouvement détecté', Broadcast=True) leds.led_on('1') # En enregistrer l'état previousstate = 1 # Si le capteur est stabilisé elif currentstate == 0 and previousstate == 1: socketIo.emit('MoveOff', 'aucun mouvement', Broadcast=True)
def main(): Status.log('Runnning HTTP server') s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 80)) s.settimeout(1) s.listen(5) while True: Status.log(inHttpRequest=" ") try: conn, addr = s.accept() HTTP.init(conn, addr) except: mainloop() continue Status.log('Got a connection from %s' % (str(addr)), inHttpRequest="o") if not HTTP.Valid: HTTP.error(400, "Bad request") continue if Status.flags["inFactoryreset"] == "!" and HTTP.checkRequest('/'): if HTTP.checkRequest('/setup'): HTTP.redirect("/setup") if HTTP.checkRequest('/'): HTTP.home() if HTTP.checkRequest('/setup'): HTTP.setup() elif HTTP.checkRequest('/setup', method='POST'): Status.log("Setup POST page") try: cfg = HTTP.getRequestVar("cfg") json = HTTP.urlDecode(cfg) json = ujson.loads(json) Config.load(json) Config.write() HTTP.OK("Setup OK") machine.reset() except ValueError: HTTP.error(400, "Bad JSON") elif HTTP.checkRequest('/flowui', method='GET'): Status.log("Reverting to flowUI") try: s = os.remove("boot.py") HTTP.OK("Reverted to FlowUI.") machine.reset() except ValueError: HTTP.error(400, "Cannot remove boot.py") elif HTTP.checkRequest('/factory-defaults', method='GET'): Status.log("Reverting to factory Defaults") try: s = os.remove("_settings.py") HTTP.OK("Factory defaults done.") machine.reset() except ValueError: HTTP.error(400, "Cannot remove _settings.py") elif HTTP.checkRequest('/push-file', method='POST'): file = HTTP.getRequestVar("file") if file: HTTP.begin(200, ctype="text/plain", html=False) HTTP.send(file) HTTP.end(html=False) continue if data: Status.log("Writing file %s" % file) s = open(file, "w") s.write(data) HTTP.OK("File written OK", msg=data) continue HTTP.error(400, "Bad request") # /led/set/<stripe>/<led>/<color> # /led/set/0/1/ffffff elif HTTP.checkRequest('/led/set'): stripe = HTTP.getRequestVar("stripe") led = HTTP.getRequestVar("led") color = HTTP.getRequestVar("color") if color and Leds.setColor(stripe, led, Leds.fromHtml(color)): HTTP.OK() else: HTTP.error(400, "Error in request") else: HTTP.error(404, "Not found")
def __init__(self): print "Arranca Domotics" #Configuramos el los pines GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(deviceConfig.pinResetButton, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(deviceConfig.pinIRSensor, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) self.leds = Leds() #Cuando se encienda el dispositivo se encenderan todos los leds self.leds.setLedsOn() self.sounds = Sounds() #Configuracion del evento para el reset GPIO.add_event_detect(deviceConfig.pinResetButton, GPIO.FALLING, callback=self.buttonResetCallback, bouncetime=500) time.sleep(1) #Una vez pasa 1 segundo se mantiene encendida solo la luz de error hasta que consiga conectarse a internet y montar el servidor self.leds.setLedsError() print "Solicitamos codigo se seguridad" self.updateSecurityCode() print "¡¡¡Tenemos codigo!!!" self.updateVersionDevice(deviceConfig.deviceId) self.updateSoftware() self.port = int(self.getPort()) #obtenemos el puerto print self.port self.privateIp = self.getPrivateIp() #Obtenemos la ip privada print self.privateIp class RequestHandler(pyjsonrpc.HttpRequestHandler): # Register public JSON-RPC methods methods = { "switchGetValue": self.switchGetValue, "switchSetValue": self.switchSetValue, "sensorGetValues": self.sensorGetValues, "cameraGetPhoto": self.cameraGetPhoto, "cameraGetPhotoForMail": self.cameraGetPhotoForMail, "installRemoteDevice": self.installRemoteDevice, "setDeviceAlarmMode": self.setDeviceAlarmMode, "quitDeviceAlarmMode": self.quitDeviceAlarmMode } # Threading HTTP-Server http_server = pyjsonrpc.ThreadingHttpServer( server_address = (self.privateIp, self.port), RequestHandlerClass = RequestHandler ) print "Creado servidor" # Start the scheduler sched = Scheduler() sched.start() # Schedule sendStatus every 1 minutes sched.add_interval_job(self.sendStatus, minutes=1) # Schedule updateSecurityCode every 1 hours sched.add_interval_job(self.updateSecurityCode, hours=1) # Schedule updateSoftware every 24 hours sched.add_interval_job(self.updateSoftware, hours=24) #Obtenemos del servidor el tipo de dispositivo que es y inicializamos self.typeDevice = int(self.getTypeDevice()) print self.typeDevice #Remote Device if self.typeDevice == 0: self.NRF24 = Remote() sched.add_interval_job(self.newReadingSensors, hours=1) #Rele device elif self.typeDevice == 1: self.rele = Rele() #Camera device elif self.typeDevice == 2: self.camera = Camera() #Sensors device elif self.typeDevice == 4: self.sensors = Sensors() sched.add_interval_job(self.newReadingSensors, hours=1) print "Actualizamos estado dispositivo" ## Actualizamos el estado del dispositivo self.sendStatus() #Temporizador para guadar datos de sensores if self.typeDevice == 0 or self.typeDevice == 4: self.newReadingSensors() #Configuracion del evento para el detector de presencia GPIO.add_event_detect(deviceConfig.pinIRSensor, GPIO.RISING, callback=self.IRSensorDetectCallback, bouncetime=10000) print "Listo para arracar el servidor" self.sounds.start() #print myconfig.urlDb print "Starting HTTP server ..." print "URL: http://%s:%d" % (self.privateIp, self.port) try: http_server.serve_forever() except KeyboardInterrupt: http_server.shutdown() self.leds.setLedsError() except: self.leds.setLedsError() time.sleep(10) os.system('sudo reboot') print "Stopping HTTP server ..."
class Application: def __init__(self): print(" [*] Application starting") self.status = 'valid' self.config = Config() self.status = self.config.status self.rabbit_client = RabbitMQ_Client(self.config.rabbitmq, self.config.mac, self.config.amqp_encryption_key) self.rabbit_server = RabbitMQ_Server(self.dispatch, self.config.rabbitmq, self.config.mac, self.config.amqp_encryption_key) self.usb_devices = UsbDevices(self.dispatch) self.leds = Leds() self.gpios = Gpios(self.dispatch) self.displays = Displays(self.dispatch) self.rfids = Rfid(self.dispatch) self.lwm2m = Lwm2m(self.config) self.state = State(self.dispatch) self.monitor = Monitor(self.dispatch, self.config) def run(self): print(" [*] Application running") #Application main loop while 1: sleep(0.1) def inferDirection(self, message): if message["type"] == "led": return Direction.ToLeds elif message["type"] == "gpio": return Direction.ToGpios elif message["type"] == "display": return Direction.ToDisplays else: print(" [x] Couln't infer direction!") return Direction.Unknown def validateMessage(self, message): if type(message) is not dict: print(" [x] Invalid message. Message is not a dict: " + str(message)) return 1 if "type" not in message: print(" [x] Invalid message. Message has no type: " + str(message)) return 2 return 0 def dispatch(self, message, direction, save=True): if self.validateMessage(message) != 0: print(" [x] Dropping invalid message") return if direction == Direction.InferDirection: direction = self.inferDirection(message) if direction == Direction.ToDojot: self.rabbit_client.publish(json.dumps(message)) elif direction == Direction.ToLeds: self.leds.process_message(message) if save: self.state.saveState(message) elif direction == Direction.ToGpios: self.gpios.process_message(message) if save: self.state.saveState(message) elif direction == Direction.ToDisplays: self.displays.process_message(message) if save: self.state.saveState(message) else: print( " [x] Invalid message or destination. No information to route it!" )
from audio import RidderAudio import time import board from sensor import Distance from leds import Leds print('start') sensor = Distance('vl61') leds = Leds(pin=board.D18, num_leds=4) leds.red() audio = RidderAudio('../audio/') audio.play_random_dankjewel() print('got distance:', sensor.get()) time.sleep(8) audio.play_random_papierhier() time.sleep(8)
"8": (65, 2), } # capabilities of the hardware CAPABILITIES = { "channels": 8, "charge": False, "discharge": True, "configurableChargeCurrent": False, "configurableDischargeCurrent": False, "configurableChargeVoltage": False, "configurableDischargeVoltage": True, } # try: status_leds = Leds(number=CAPABILITIES["channels"]) channels = list() current_sensors = CurrentSensors(current_sensor_configuration) wlan = network.WLAN(network.STA_IF) wlan.active(True) if not wlan.isconnected(): log.info("Connecting to WiFi...") wlan.connect("Bill Wi The Science Fi", "225261007622") # wlan.connect("HSBNEWiFi", "HSBNEPortHack") while not wlan.isconnected(): time.sleep(0.25) status_leds.set_channel(4, OFF) status_leds.set_channel(5, BLUE)
from leds import Leds myled = Leds() myled.run(247, 29)