def bootstrap(self, timeout): from wifi import WiFi network = WiFi() from ssd1306 import SSD1306_I2C from machine import Pin, I2C bus = I2C(-1, Pin(4), Pin(5)) display = SSD1306_I2C(128, 32, bus) from views import Views with network.Context(timeout) as c: while 1: ttl = self.ttl(timeout) if not ttl: self._core.show(display, None) self.data_changed = False break self._core.show( display, Views['network']['wait'](c.net.token, timeout, ttl) ) if c.net.connected: self._core.show( display, Views['network']['connected']() ) self.data_changed = self._core.setup_mode() break self._sleep(0.5) del network, WiFi, display, SSD1306_I2C, Views, Pin, I2C, bus collect() return self.data_changed
def __init__(self, ssid): """ 主类初始化 :param ssid: """ self.wifi = WiFi() self.wifi.StartScan(ssid)
def __init__(self, config, verbose=0): self.verbose = verbose # ------------------------------------------------------------------------------------------------------------ # self.exit = False self.config = config # ------------------------------------------------------------------------------------------------------------ # self.sleep_ms = self.SLEEP_MS_DEFAULT # ------------------------------------------------------------------------------------------------------------ # # Initialise required services # ------------------------------------------------------------------------------------------------------------ # if self.config['pinout']['led'] is None: from led import MockLed self.led = MockLed() else: from led import Led self.led = Led(self.config['pinout']['led']['pin'], self.config['pinout']['led']['on_level']) # ------------------------------------------------------------------------------------------------------------ # if self.config['pinout']['button'] is None: from button import MockButton self.button = MockButton() else: from button import Button self.button = Button(self.config['pinout']['button']['pin'], self.config['pinout']['button']['on_level']) # ------------------------------------------------------------------------------------------------------------ # if self.config['pinout']['relay'] is None: from relay import MockRelay self.relay = MockRelay() else: from relay import Relay self.relay = Relay(self.config['pinout']['relay']['pin'], self.config['pinout']['relay']['on_level']) # ------------------------------------------------------------------------------------------------------------ # self.wifi = WiFi(self.config) # , verbose=self.verbose) self.device_id = self.wifi.device_id() self.messaging = Messaging(self.config, self.device_id) # ------------------------------------------------------------------------------------------------------------ # # Application ready feedback --------------------------------------------------------------------------------- # self.led.on(poll=True) sleep(2) self.led.off(poll=True) # ------------------------------------------------------------------------------------------------------------ # if self.wifi.connected(): self.on_wifi_connected(be_verbose=False) # ------------------------------------------------------------------------------------------------------------ # if self.verbose: print('<{} with id {}>'.format(self.config['device']['type'], self.device_id)) print(self.led) print(self.button) print(self.relay) print(self.wifi) print(self.messaging)
class ThingSpeak(object): # Edit these to suit your particular situation api_key = None host = 'api.thingspeak.com' sock = None ssock = None addr = None config = None wifi = None def open_socket(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.ssock = ssl.wrap_socket(self.sock) self.ssock.connect(self.addr) def close_socket(self): for s in [self.sock, self.ssock]: if s: s.close() def __init__(self, config): self.config = config self.wifi = WiFi(self.config) self.wifi.connect_wifi() self.api_key = config['API_KEY'] self.addr = socket.getaddrinfo(self.host, 443)[0][-1] def update(self, data): self.wifi.connect_wifi() self.open_socket() values = '' for k in data.keys(): values = values + "&{}={}".format(k, data[k]) path = '/update?api_key=' + self.api_key + values try: msg = 'GET /' + path + ' HTTP/1.0\r\n\r\n' self.ssock.send(bytes(msg, 'utf8')) print("Sent message") self.close_socket() except Exception as e: print("Hit an error") print(e) self.close_socket() raise
class WiFiServer(Server): def __init__(self, host, port, mdns_desc, mdns_addr): super().__init__(host, port, mdns_desc, mdns_addr) self.device = WiFi("wlan0", "AAU-1x") def start(self): self.device.start() self.server.message_loop.emits(self.device) super().start() def stop(self): self.device.stop() super().stop()
def __init__(self, config, verbose=0): self.verbose = verbose # ------------------------------------------------------------------------------------------------------------ # self.exit = False self.config = config # ------------------------------------------------------------------------------------------------------------ # # Initialise required services if self.config['pinout']['led'] is None: self.led = led.MockLed() else: self.led = led.Led(self.config['pinout']['led']) self.wifi = WiFi(self.config, verbose=self.verbose) self.device_id = self.wifi.device_id() self.messaging = Messaging(self.config, self.device_id) if self.config['pinout']['ultrasound'] is None: self.water_level = MockWaterLevel() else: self.water_level = WaterLevel(self.config, verbose=self.verbose) if self.config['pinout']['flow_meter'] is None: self.flow_rate = MockFlowRate() else: self.flow_rate = FlowRateFallingEdge(self.config, verbose=self.verbose) # ------------------------------------------------------------------------------------------------------------ # if self.verbose: print('<{} with id {}>'.format(self.config['device']['name'], self.device_id)) print(self.led) print(self.wifi) print(self.messaging) print(self.water_level) print(self.flow_rate) # Application ready feedback --------------------------------------------------------------------------------- # self.led.on(poll=True) time.sleep(2) self.led.off(poll=True) # ------------------------------------------------------------------------------------------------------------ # if self.wifi.connected(): self.on_wifi_connected()
def initialization(init_gy521=True, init_ds18=True, init_bat=True, init_wifi=True): """ Initialize GY521 module, battery ADC pin and wifi NOTE: VPP pin must be turned on in order to initialize the GY521 module """ if init_gy521: from gy521 import GY521 # Initialize the GY521 module print('Initializing GY521 module') try: gy521_sensor = GY521(GY521_SDA, GY521_SCL) except Exception as e: print(e) gy521_sensor = None else: gy521_sensor = None if init_ds18: from tempsensor import Ds18Sensors, SingleTempSensor print('Initializing DS18B20 sensor') try: ow = Ds18Sensors(OW_PIN) romcode_string = ow.get_device_list()[0].get('value') ds18_sensor = SingleTempSensor(ow, romcode_string) except Exception as e: print(e) ds18_sensor = None else: ds18_sensor = None if init_bat: from battery import Battery # Initialize the battery power management print('Initializing power management') lipo = Battery(BAT_ADC_PIN) else: lipo = None if init_wifi: from wifi import WiFi # Initialize Wifi print('Initializing WiFi') wlan = WiFi() else: wlan = None return gy521_sensor, ds18_sensor, lipo, wlan
class Main(object): def __init__(self, ssid): """ 主类初始化 :param ssid: """ self.wifi = WiFi() self.wifi.StartScan(ssid) def choose(self, ssid): """ 选择WiFi :param ssid: :return: """ results = self.wifi.GetScanResults() if len(results) > 0: self.wifi.choose_ap(results, ssid) def connect(self, passwords): """ 连接 :param passwords: :return: """ for index, p in enumerate(passwords): s = "<index>{}</index>\t<password>{}</password>\n".format(index, p) write_status(s, "a") self.wifi.Connect(p) status = self.wifi.GetStatus() if status in [self.wifi.const.IFACE_CONNECTED]: loger("[+]" * 10 + "破解成功" + "[+]" * 10 + "\r") loger("密码为: {}\r".format(p)) os.system("pause") break else: continue os.system("echo 很遗憾!未能成功爆破,换个字典再试试吧!")
temp_sensors.get_realtime_temp() # update temperature readings every 2s utime.sleep_ms(2000) # run measure temp function in a new thread logger.debug('Allocating stack for thread task...') _thread.stack_size(7 * 1024) temp_th = _thread.start_new_thread(measure_realtime_temps, ()) logger.debug('Initializing RTC...') rtc = RealTimeClock(tz=8, update_period=86400) # Connect to WiFi (scan AP, and connect with password) logger.debug('Initializing WiFi...') wifi = WiFi(rtc_obj=rtc) wifi.ap_start(settings['apSsid']) # get the AP IP of ESP32 itself, usually it's 192.168.4.1 ap_ip_addr = wifi.get_ap_ip_addr() logger.debug('AP IP address: ' + ap_ip_addr) # get the Station IP of ESP32 in the WLAN which ESP32 connects to if settings['wifi'].get('ssid'): sta_ip_addr = wifi.sta_connect(settings['wifi']['ssid'], settings['wifi']['pass'], verify_ap=True) if sta_ip_addr: logger.debug('STA IP address: ' + sta_ip_addr) # print current local date & time logger.debug('Date: ' + rtc.get_localdate()) logger.debug('Time: ' + rtc.get_localtime())
IBMorgID = 'cnqzlg' # Identifiant de l'instance 'IoT PLatform' sur 6 caractères deviceType = 'PyCom' # Nom du 'Device Type' défini dans le IoT Platform deviceID = 'device-1' # ID du device (4 dernieres caractères du SSID) deviceToken = 'rp0bTVq!-o4@vVlMWs' # Token (mot de passe) défini pour le device dans le Iot Platform #IBMorgID='514y4j' # Identifiant de l'instance 'IoT PLatform' sur 6 caractères #deviceType='PyCom' # Nom du 'Device Type' défini dans le IoT Platform #deviceID='sdbd' # ID du device (4 dernieres caractères du SSID) #deviceToken='gVVxAcc!tzALKKGHjn' py = Pysense() si = SI7006A20(py) print("wifi before") wifi = WiFi() #print (WiFi.connectwifi('d-01','123456789')) #print (WiFi.connectwifi('E-01','11111111')) #print (WiFi.connectwifi('Gustavo','LMDTBM74')) print(WiFi.connectwifi('floki_io', 'F10kiN37w0rk!')) print("wifi done") client = MQTTClient("d:" + IBMorgID + ":" + deviceType + ":" + deviceID, IBMorgID + ".messaging.internetofthings.ibmcloud.com", user="******", password=deviceToken, port=1883) # Syntaxe pour envoyer un paquet MQTT à IBM Cloud try: client.connect()
def init_wifi(): from wifi import WiFi # Initialize Wifi print('Initializing WiFi') wlan = WiFi() return wlan
class RunLoop: def __init__(self, config, verbose=0): self.verbose = verbose # ------------------------------------------------------------------------------------------------------------ # self.exit = False self.config = config # ------------------------------------------------------------------------------------------------------------ # # Initialise required services if self.config['pinout']['led'] is None: self.led = led.MockLed() else: self.led = led.Led(self.config['pinout']['led']) self.wifi = WiFi(self.config, verbose=self.verbose) self.device_id = self.wifi.device_id() self.messaging = Messaging(self.config, self.device_id) if self.config['pinout']['ultrasound'] is None: self.water_level = MockWaterLevel() else: self.water_level = WaterLevel(self.config, verbose=self.verbose) if self.config['pinout']['flow_meter'] is None: self.flow_rate = MockFlowRate() else: self.flow_rate = FlowRateFallingEdge(self.config, verbose=self.verbose) # ------------------------------------------------------------------------------------------------------------ # if self.verbose: print('<{} with id {}>'.format(self.config['device']['name'], self.device_id)) print(self.led) print(self.wifi) print(self.messaging) print(self.water_level) print(self.flow_rate) # Application ready feedback --------------------------------------------------------------------------------- # self.led.on(poll=True) time.sleep(2) self.led.off(poll=True) # ------------------------------------------------------------------------------------------------------------ # if self.wifi.connected(): self.on_wifi_connected() # ------------------------------------------------------------------------------------------------------------ # def on_wifi_connected(self): self.led.toggle(500) if not self.messaging.connected(): self.messaging.connect() def run(self): if self.verbose: print('Run loop started') while not self.exit: # ======================================================================================================== # self.led.poll() # -------------------------------------------------------------------------------------------------------- # if self.wifi.connected(): if not self.water_level.calibrated(): self.water_level.calibrate() elif self.water_level.read(): self.messaging.publish(self.water_level.level()) if not self.flow_rate.calibrated(): self.flow_rate.calibrate() elif self.flow_rate.read(): self.messaging.publish(self.flow_rate.rate()) elif self.wifi.connecting(): self.led.toggle(250) elif not self.wifi.connected(): self.wifi.connect() if self.wifi.connected(): self.on_wifi_connected() # ======================================================================================================== # if self.flow_rate.reading(): time.sleep_ms(1) else: time.sleep_ms(20) # Reduce the tightness of the run loop # ======================================================================================================== # if self.verbose: print('Run loop exited') def close(self): self.exit = True if self.led: self.led.close() if self.water_level: self.water_level.close() if self.flow_rate: self.flow_rate.close() if self.messaging: self.messaging.disconnect() # if self.wifi: # self.wifi.disconnect() # Don't do this, you will loose connection to the REPL if self.verbose: print('Run loop closed')
def __init__(self, host, port, mdns_desc, mdns_addr): super().__init__(host, port, mdns_desc, mdns_addr) self.device = WiFi("wlan0", "AAU-1x")
from clock import Clock from utils import log, start_time from wifi import WiFi from ota import OTA from os import listdir from machine import reset try: WiFi() Clock() OTA() if 'main' in listdir(): from main.init import start try: start() except Exception as e: log("APP: {}".format(e)) reset() else: log("BOOT: main application not found") except Exception as e: log("BOOT: {}".format(e)) reset()
# ---------------------------------------------------------------------------- help functions def blink(number=3, duration=250): print('[i] running function: blink({0})'.format(number)) led = machine.Pin(2, machine.Pin.OUT, value=1) for i in range(2 * number): led.value(not led.value()) sleep_ms(duration) # ----------------------------------------------------------------------------- main function print('[i] main function') rtc = machine.RTC() rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) print('[i] setting up wifi connection') wifi = WiFi(WIFI_SSID, WIFI_PW) if not wifi.isconnected(): try: wifi.connect() except Exception: print('[-] wifi connection timeout, entering deep sleep') rtc.alarm(rtc.ALARM0, PUBLISH_DELAY) machine.deepsleep() print('[i] connected to {0} wifi'.format(WIFI_SSID)) blink(3) print('[i] setting up mqtt client') mqtt = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER) mqtt.connect() sensor = SHT30()
class RunLoop: SLEEP_MS_DEFAULT = 20 LED_TOGGLE_DEFAULT = 500 def __init__(self, config, verbose=0): self.verbose = verbose # ------------------------------------------------------------------------------------------------------------ # self.exit = False self.config = config # ------------------------------------------------------------------------------------------------------------ # self.sleep_ms = self.SLEEP_MS_DEFAULT # ------------------------------------------------------------------------------------------------------------ # # Initialise required services # ------------------------------------------------------------------------------------------------------------ # if self.config['pinout']['led'] is None: from led import MockLed self.led = MockLed() else: from led import Led self.led = Led(self.config['pinout']['led']['pin'], self.config['pinout']['led']['on_level']) # ------------------------------------------------------------------------------------------------------------ # if self.config['pinout']['button'] is None: from button import MockButton self.button = MockButton() else: from button import Button self.button = Button(self.config['pinout']['button']['pin'], self.config['pinout']['button']['on_level']) # ------------------------------------------------------------------------------------------------------------ # if self.config['pinout']['relay'] is None: from relay import MockRelay self.relay = MockRelay() else: from relay import Relay self.relay = Relay(self.config['pinout']['relay']['pin'], self.config['pinout']['relay']['on_level']) # ------------------------------------------------------------------------------------------------------------ # self.wifi = WiFi(self.config) # , verbose=self.verbose) self.device_id = self.wifi.device_id() self.messaging = Messaging(self.config, self.device_id) # ------------------------------------------------------------------------------------------------------------ # # Application ready feedback --------------------------------------------------------------------------------- # self.led.on(poll=True) sleep(2) self.led.off(poll=True) # ------------------------------------------------------------------------------------------------------------ # if self.wifi.connected(): self.on_wifi_connected(be_verbose=False) # ------------------------------------------------------------------------------------------------------------ # if self.verbose: print('<{} with id {}>'.format(self.config['device']['type'], self.device_id)) print(self.led) print(self.button) print(self.relay) print(self.wifi) print(self.messaging) def on_wifi_connected(self, be_verbose=True): if be_verbose and self.verbose: print(self.wifi) self.led.toggle(self.LED_TOGGLE_DEFAULT) if not self.messaging.connected(): self.messaging.connect() def run(self): if self.verbose: print('Run loop ' 'started') while not self.exit: # ======================================================================================================== # self.led.poll() self.button.poll() # -------------------------------------------------------------------------------------------------------- # if self.relay.state( ) == self.relay.STATE_OFF and self.button.pressed( ) == self.button.SHORT_PRESS: if self.verbose: print('<Button: SHORT_PRESS ' '0' '>') self.messaging.publish({ 'state': '<Button: SHORT_PRESS ' 'relay state: ' 'on' '>' }) self.relay.on() self.button.clear() elif self.relay.state( ) == self.relay.STATE_ON and self.button.pressed( ) > self.button.NOT_PRESSED: if self.verbose: print('<Button: SHORT_PRESS ' '1' '>') self.messaging.publish({ 'state': '<Button: SHORT_PRESS ' 'relay state: ' 'off' '>' }) self.relay.off() self.button.clear() elif self.led.enabled() is True and self.button.pressed( ) == self.button.LONG_PRESS: if self.verbose: print('<Button: LONG_PRESS ' '0' '>') self.messaging.publish({ 'state': '<Button: LONG_PRESS ' 'led enabled: ' 'off' '>' }) self.led.enable(False) self.led.off() self.button.clear() elif self.led.enabled() is False and self.button.pressed( ) > self.button.NOT_PRESSED: if self.verbose: print('<Button: LONG_PRESS ' '2' '>') self.messaging.publish( {'state': '<Button: LONG_PRESS ' 'led enabled: ' 'on' '>'}) self.led.enable(True) self.led.toggle(self.LED_TOGGLE_DEFAULT) self.button.clear() # -------------------------------------------------------------------------------------------------------- # if self.wifi.connected(): if self.messaging.connected() is False: self.on_wifi_connected() if self.messaging.poll(): if 'action' in self.messaging.msg: if self.messaging.msg['action'] == 'on': if self.verbose: print('<Relay: ' 'on' '>') self.relay.on() elif self.messaging.msg['action'] == 'off': if self.verbose: print('<Relay: ' 'off' '>') self.relay.off() elif self.messaging.msg['action'] == 'exit': if self.verbose: print('<Application: ' 'exit' '>') self.exit = True self.messaging.completed() elif self.wifi.connected() is False: if self.wifi.connecting() is False: self.led.toggle(250) self.led.on(poll=True, save_state=True) if self.wifi.connect() is True: self.led.off(poll=True, restore_state=True) # ======================================================================================================== # sleep_ms(self.sleep_ms) # Reduce the tightness of the run loop # ======================================================================================================== # if self.verbose: print('Run loop ' 'exited') def close(self): self.exit = True if self.led: self.led.close() if self.button: self.button.close() if self.relay: self.relay.close() if self.messaging: self.messaging.disconnect() # if self.wifi: # self.wifi.disconnect() # Don't do this, you will loose connection to the REPL if self.verbose: print('Run loop ' 'closed')
from mqtt import MQTTClient import time IBMorgID = '5rg1a4' # Identifiant de l'instance 'IoT PLatform' sur 6 caractères deviceType = 'pycom' # Nom du 'Device Type' défini dans le IoT Platform deviceID = '1181' # ID du device (4 dernieres caractères du SSID) deviceToken = 'Ct-g!TpOwL86V)(a*X' # Token (mot de passe) défini pour le device dans le Iot Platform wifiSSID = "Redmi" # ID du WiFi wifiPSW = "inprogress" # Mot de Passe du WiFi py = Pysense() # Instance de l'objet py de la class Pysense si = SI7006A20( py) # Instance de l'objet si de la class SI7006A20 ayant pour parametre py wifi = WiFi() # Initialisation de l'objet wifi de la class WiFi acc = LIS2HH12( ) # Initialisation de l'objet acc de la class LIS2HH12 ayant pour but de récupérer les données de la carte # print("Temperature: " + str(si.temperature())+ " deg C and Relative Humidity: " + str(si.humidity()) + " %RH") # print("Dew point: "+ str(si.dew_point()) + " deg C") print("Connecting wifi") print(WiFi.connectwifi( wifiSSID, wifiPSW)) # Connection WiFi, affiche quelque chose s'il y a une erreur # Syntaxe pour envoyer un paquet MQTT à IBM Cloud client = MQTTClient("d:" + IBMorgID + ":" + deviceType + ":" + deviceID,
from config import * from wifi import WiFi from machine import Pin from utime import sleep_ms led = Pin(2, Pin.OUT, value=1) wifi = WiFi(WIFI_SSID, WIFI_PW) connected = wifi.isconnected() print('[i] WiFi "{0}" connected: {1}'.format(WIFI_SSID, connected)) if connected: print('[i] Disconnecting WiFi.') wifi.disconnect() try: ip = wifi.connect() print('[i] WiFi "{0}" connected. IP: {1}'.format(WIFI_SSID, ip)) for i in range(6): led.value(not led.value()) sleep_ms(250) except Exception as e: print(e)
def __init__(self, config): self.config = config self.wifi = WiFi(self.config) self.wifi.connect_wifi() self.api_key = config['API_KEY'] self.addr = socket.getaddrinfo(self.host, 443)[0][-1]