예제 #1
0
 def start_webrepl(self, force=False):
     if self.wlan.isconnected():
         if force or self.webrepl_cfg['enable']:
             # noinspection PyUnresolvedReferences
             esp.sleep_type(esp.SLEEP_NONE)
             import webrepl
             # noinspection PyUnresolvedReferences
             webrepl.start(password=self.webrepl_cfg['password'])
예제 #2
0
 def __init__(self, config):
     super().__init__(config)
     self._isconnected = False  # Current connection state
     keepalive = 1000 * self._keepalive  # ms
     self._ping_interval = keepalive // 4 if keepalive else 20000
     p_i = config['ping_interval'] * 1000  # Can specify shorter e.g. for subscribe-only
     if p_i and p_i < self._ping_interval:
         self._ping_interval = p_i
     self._in_connect = False
     self._has_connected = False  # Define 'Clean Session' value to use.
     import esp
     esp.sleep_type(0)  # Improve connection integrity at cost of power consumption.
예제 #3
0
async def main():
    global mqtt_client

    # Wi-Fi connection
    try:
        await uasyncio.wait_for(wifi_connect(WIFI_AP_SSID, WIFI_AP_PSW), 20)
        esp.sleep_type(2)
    except uasyncio.TimeoutError:
        print("wifi connected timeout!")
    # MQTT connection
    try:
        await uasyncio.wait_for(mqtt_connect(), 20)
    except uasyncio.TimeoutError:
        print("mqtt connected timeout!")

    await uasyncio.gather(light_loop())
예제 #4
0
    def runtime_setup(self):
        self.ensure_adc_mode()

        self.lowpower_phase = machine.reset_cause() in (
            machine.DEEPSLEEP_RESET, 2)
        print('Reset cause', machine.reset_cause())
        print('Booted in {} phase'.format(
            'lowpower' if self.lowpower_phase else 'normal'))

        if not self.lowpower_phase:
            self.get_requests()

        self.load_config()
        self.load_state(restore=True)

        esp.sleep_type(esp.SLEEP_LIGHT)
        network.WLAN(network.AP_IF).active(False)  # Disable AP

        self.setup()
예제 #5
0
파일: WLan.py 프로젝트: VladVons/mpy-vRelay
    async def Connect(self, aESSID: str, aPassw: str, aAddr: tuple = None):
        Log.Print(1, 'i', 'Connect() %s, %s, %s' % (aESSID, aPassw, aAddr))

        # Improve connection integrity at cost of power consumption
        if (platform == 'esp8266'):
            from esp import sleep_type
            sleep_type(0)

        R = WLAN(STA_IF)
        R.active(False)
        await sleep(1)
        R.active(True)

        if (aAddr):
            R.ifconfig(aAddr)

        R.connect(aESSID, aPassw)
        await self._WaitForReady(R.isconnected)

        Log.Print(1, 'i', 'Net', R.ifconfig())
        return R
예제 #6
0
 def __init__(self,
              client_id=None,
              server=None,
              port=0,
              user='',
              password='',
              keepalive=60,
              ping_interval=0,
              ssl=False,
              ssl_params={},
              response_time=10,
              clean_init=True,
              clean=True,
              max_repubs=4,
              will=None,
              subs_cb=lambda *_: None,
              wifi_coro=None,
              connect_coro=None,
              ssid=None,
              wifi_pw=None):
     client_id = client_id or hexlify(unique_id())
     wifi_coro = wifi_coro or eliza
     connect_coro = connect_coro or eliza
     super().__init__(client_id, server, port, user, password, keepalive,
                      ping_interval, ssl, ssl_params, response_time,
                      clean_init, clean, max_repubs, will, subs_cb,
                      wifi_coro, connect_coro, ssid, wifi_pw)
     self._isconnected = False  # Current connection state
     keepalive = 1000 * self._keepalive  # ms
     self._ping_interval = keepalive // 4 if keepalive else 20000
     p_i = self.ping_interval * 1000  # Can specify shorter e.g. for subscribe-only
     if p_i and p_i < self._ping_interval:
         self._ping_interval = p_i
     self._in_connect = False
     self._has_connected = False  # Define 'Clean Session' value to use.
     if ESP8266:
         import esp
         esp.sleep_type(
             0
         )  # Improve connection integrity at cost of power consumption.
예제 #7
0
def main():

    while True:
        gotTime, curr_tm = getDateTime()  # get time

        # check if lighting is needed - if needed, turn on the light
        if gotTime and time_in_range(START_TIME, END_TIME, curr_tm[4]):
            print("Light should be ON -> Turning ON ")
            lightOn()
            print("Now waiting to load new file for 30 seconds ")
            utime.sleep(30)
            print("Now going to light sleep for: ", SLEEP_INTERVAL, " seconds")
            esp.sleep_type(esp.SLEEP_LIGHT)
            utime.sleep(SLEEP_INTERVAL)
        else:
            print("Light should be OFF -> Turning OFF ")
            lightOff()

            # safety sleep to allow multitasking between ESP core and WiFI
            print("5 seconds sleep before DEEP SLEEP")
            utime.sleep(5)
            sleepStart()  # put the device to sleep
예제 #8
0
    def connect(self):
        """ activates the wlan and polls to see if connected
            returns a tuple:
              - a boolean to indicate successful connection or not
              - a msg to display if connection failed
        """
        import esp, network
        from utime import sleep_ms

        if "sleep_type" in dir(esp):
            esp.sleep_type(esp.SLEEP_NONE)  # don't shut off wifi when sleeping
        wlan = network.WLAN(network.STA_IF)
        wlan.active(True)
        connected = False
        for _ in range(20):
            connected = wlan.isconnected()
            if connected:
                return True, None
            else:
                sleep_ms(333)
        if not connected:
            from setwifi import setwifi as setwifi
            setwifi()
            return False, "Warning: unable to connect to WiFi; setWiFi run to get new credentials"
예제 #9
0
    def __init__(self):
        """Init the weather station."""

        # We do not want to sleep, wall socket powered...
        esp.sleep_type(esp.SLEEP_NONE)
        # SLEEP_MODEM is also an option, but prevent it from re-loading data...

        self.display = Display()
        # Neopixel
        self.np = neopixel.NeoPixel(Pin(PINNEOPIXEL), 1)

        self.self_info()
        self.net = Network()
        self.dht = dht.DHT22(machine.Pin(PINDHT))

        # MQTT
        self.CLIENT_ID = b"esp8266_"+ubinascii.hexlify(machine.unique_id())
        self.mclient = MQTTClient(self.CLIENT_ID, secrets.BROKER)
        self.mclient.connect()

        self.door = machine.Pin(PINDOOR, machine.Pin.IN, machine.Pin.PULL_UP)

        self.net.getForecast()

        # Initial display
        self.updateDisplay()

        # Timer to periodically update display
        self.tim = machine.Timer(1)
        self.tim.init(period=60000, mode=machine.Timer.PERIODIC,
                      callback=lambda t: self.updateDisplay())

        # Forecast update
        self.tim = machine.Timer(2)
        self.tim.init(period=60000*3, mode=machine.Timer.PERIODIC,
                      callback=lambda t: self.net.getForecast())
예제 #10
0
파일: oled.py 프로젝트: aid402/uPy-ESP-01
def sub_cb(topic, msg):
    msg = json.loads(msg)
    for c in msg['cmd']:
        if c[0] == 'fill': oled.fill(c[1])
        elif c[0] == 'pixel': oled.pixel(c[1], c[2], c[3])
        elif c[0] == 'text': oled.text(c[1], c[2], c[3], c[4])
        elif c[0] == 'rect': oled.rect(c[1], c[2], c[3], c[4], c[5])
        elif c[0] == 'fill_rect': oled.fill_rect(c[1], c[2], c[3], c[4], c[5])
        elif c[0] == 'line': oled.line(c[1], c[2], c[3], c[4], c[5])
        elif c[0] == 'vline': oled.vline(c[1], c[2], c[3], c[4])
        elif c[0] == 'hline': oled.hline(c[1], c[2], c[3], c[4])
        elif c[0] == 'scroll': oled.scroll(c[1], c[2])
        elif c[0] == 'blit': oled.blit(c[1], c[2], c[3], c[4])
        elif c[0] == 'show': oled.show()
        elif c[0] == 'poweron': oled.poweron()
        elif c[0] == 'poweroff': oled.poweroff()
        elif c[0] == 'collect': gc.collect()
        elif c[0] == 'reset': machine.reset()
        elif c[0] == 'sleep':
            if c[1] == 'none': esp.sleep_type(esp.SLEEP_NONE)
            elif c[1] == 'light': esp.sleep_type(esp.SLEEP_LIGHT)
            sleep(c[2])
    msg = json.dumps({'ID': CONFIG['CLIENT_ID'], 'mem_free': gc.mem_free()})
    client.publish(Topic1, msg)
예제 #11
0
    def __init__(self,
                 my_id,
                 server,
                 port=8123,
                 ssid='',
                 pw='',
                 timeout=2000,
                 conn_cb=None,
                 conn_cb_args=None,
                 verbose=False,
                 led=None,
                 wdog=False):
        self._my_id = '{}{}'.format(my_id, '\n')  # Ensure >= 1 newline
        self._server = server
        self._ssid = ssid
        self._pw = pw
        self._port = port
        self._to = timeout  # Client and server timeout
        self._tim_ka = timeout // 4  # Keepalive interval
        self._concb = conn_cb
        self._concbargs = () if conn_cb_args is None else conn_cb_args
        self._verbose = verbose
        self._led = led

        if wdog:
            if platform == 'pyboard':
                self._wdt = machine.WDT(0, 20000)

                def wdt():
                    def inner(feed=0):  # Ignore control values
                        if not feed:
                            self._wdt.feed()

                    return inner

                self._feed = wdt()
            else:

                def wdt(secs=0):
                    timer = machine.Timer(-1)
                    timer.init(period=1000,
                               mode=machine.Timer.PERIODIC,
                               callback=lambda t: self._feed())
                    cnt = secs
                    run = False  # Disable until 1st feed

                    def inner(feed=WDT_CB):
                        nonlocal cnt, run, timer
                        if feed == 0:  # Fixed timeout
                            cnt = secs
                            run = True
                        elif feed < 0:  # WDT control/callback
                            if feed == WDT_CANCEL:
                                timer.deinit()  # Permanent cancellation
                            elif feed == WDT_CB and run:  # Timer callback and is running.
                                cnt -= 1
                                if cnt <= 0:
                                    machine.reset()

                    return inner

                self._feed = wdt(20)
        else:
            self._feed = lambda x: None

        self._sta_if = network.WLAN(network.STA_IF)
        ap = network.WLAN(network.AP_IF)  # create access-point interface
        ap.active(False)  # deactivate the interface
        self._sta_if.active(True)
        gc.collect()
        if platform == 'esp8266':
            import esp
            # Improve connection integrity at cost of power consumption.
            esp.sleep_type(esp.SLEEP_NONE)

        self._evfail = asyncio.Event()  # Set by any comms failure
        self._evok = asyncio.Event()  # Set by 1st successful read
        self._s_lock = asyncio.Lock()  # For internal send conflict.
        self._w_lock = asyncio.Lock()  # For .write rate limit
        self._last_wr = utime.ticks_ms()
        self._lineq = Queue(20)  # 20 entries
        self.connects = 0  # Connect count for test purposes/app access
        self._sock = None
        self._acks_pend = ASetByte()  # ACKs which are expected to be received
        gc.collect()
        asyncio.create_task(self._run())
# upip packages - see README.md
# upip.install('micropython-umqtt.simple')
# upip.install('micropython-umqtt.robust')

ap_if = network.WLAN(
    network.AP_IF)  # turn off the access point which is on by default
ap_if.active(False)

cfg = config.Config('config.json')

if cfg.isEsp8266:
    BuiltinLedPin = 2
    i2c = I2C(scl=Pin(5), sda=Pin(4))
    adc = ADC(0)  # create ADC object on ADC pin
    mqttId = str(esp.flash_id())
    esp.sleep_type(esp.SLEEP_LIGHT)
else:
    BuiltinLedPin = 5
    i2c = I2C(scl=Pin(22), sda=Pin(21))
    adc = None
    import urandom as random
    mqttId = str(random.randint(100, 100000))

builtinLed = Pin(BuiltinLedPin, Pin.OUT)

mySensor = cfg.sensor.Sensor(i2c)

client = MQTTClient(mqttId, cfg.mqttBroker)
sta_if.connect(cfg.wifiSsid, cfg.wifiPwd)

display = None
예제 #13
0
import esp
esp.sleep_type(esp.SLEEP_LIGHT)
예제 #14
0
 def connect(self):
     esp.sleep_type(esp.SLEEP_NONE)
     esp.wifi_mode(esp.STA_MODE)
     network.connect("MosEisleySpaceport", "supersonic")
def main():
    global dht_sensor
    global dht_tim
    global v_tim

    try:
        i2c = I2C(scl=Pin(PIN_I2C_SCL), sda=Pin(PIN_I2C_SDA))
        init_display(i2c)
    except OSError as e:
        print("Can not initialize display!", repr(e))
        time.sleep(10)
        machine.reset()
        return

    from display import instance as display
    display.render(sys_status_view)

    while 1:
        try:
            dht_sensor = MultiSensor(pin=PIN_DHT, i2c=i2c)
            dht_sensor.sample()  # test sensor
            sys_status.set_sensor(True)
            display.render(sys_status_view)
            break
        except OSError as e:
            print("Sensor failure", repr(e))
            time.sleep(3)

    hass_api = hass.API(HASS_BASE_URL, api_password=HASS_PASSWORD)
    hass_thermo = HassThermostatAPI(hass_api, HASS_THERMOSTAT_ID)

    cur_state = hass_thermo.get_state()
    while cur_state is None:
        print("[HASS] Connecting to the server...")
        time.sleep_ms(500)
        cur_state = hass_thermo.get_state()
    print("[HASS] Connected")
    sys_status.set_hass_api(True)
    display.render(sys_status_view)

    model.init(cur_state)

    mqtt.init(mqtt_msg_dispatch)
    sys_status.set_mqtt(True)
    display.render(sys_status_view)
    time.sleep(1)
    sys_status.boot = False
    display.render(sys_status_view)

    t_sensor_mqtt = mqtt.HassMQTTTemperatureSensor(mapper=lambda x: x.t)
    t_sensor_mqtt.register({})

    h_sensor_mqtt = mqtt.HassMQTTHumiditySensor(mapper=lambda x: x.h)
    h_sensor_mqtt.register({})

    v_sensor_mqtt = mqtt.HassMQTTVoltageSensor()
    v_sensor_mqtt.register({})

    dht_tim = Timer(DHT_TIM_ID)
    sensor_update = dht_updater(t_sensor_mqtt, h_sensor_mqtt, Sensor2Model())
    sensor_update(None)
    dht_tim.init(period=SENSOR_SAMPLE_INTERVAL * 1000,
                 mode=Timer.PERIODIC,
                 callback=sensor_update)

    v_tim = Timer(V_TIM_ID)
    v_update = voltage_updater(v_sensor_mqtt)
    v_update(None)
    v_tim.init(period=30 * 1000, mode=Timer.PERIODIC, callback=v_update)

    controller = Controller(
        hass_thermo_api=hass_thermo,
        thermostat_model=model.instance,
        local_changes=LocalChanges(
            max_temp=float(cur_state['attributes']['max_temp']),
            min_temp=float(cur_state['attributes']['min_temp'])))

    if LIGHT_SLEEP_ENABLED:
        esp.sleep_type(esp.SLEEP_LIGHT)

    lux_sensor = TSL2561(i2c=i2c)
    lux_sensor.active(True)
    time.sleep_ms(500)

    while 1:
        adjust_display_brightness(lux_sensor)
        mqtt.loop()
        controller.loop()
예제 #16
0
print('boot.py')  # noqa isort:skip
import gc
import sys

import esp
import micropython
import utime

for no in range(2, 0, -1):
    print('%i boot.py wait...' % no)
    utime.sleep(1)

esp.osdebug(None)  # turn off vendor O/S debugging messages
esp.sleep_type(esp.SLEEP_NONE)  # Don't go into sleep mode

micropython.alloc_emergency_exception_buf(128)

gc.enable()

# https://forum.micropython.org/viewtopic.php?f=2&t=7345&p=42390#p42390
gc.threshold(8192)

# default is:
#   sys.path=['', '/lib', '/']
# But we would like to be possible to overwrite frozen modues with .mpy on flash drive ;)
sys.path.insert(0, '.')
print('sys.path=%r' % sys.path)

print('boot.py END')
예제 #17
0
파일: main.py 프로젝트: gundami/mpywatch
    else:
        oled.poweroff()
    #weather
    if (page == 1):
        if wlanstatus == 1:
            weather()
        else:
            oled.fill(0)
            oled.text("Network Error", 10, 10)
            oled.show()
    #timer
    elif (page == 3):
        button1()
    #showtime
    elif (page == 2):
        (year, month, mday, hour, minute, second, weekday,
         yearday) = utime.localtime()
        timeshow()
    elif page > 3:
        oled.fill(0)
        oled.text("final page", 10, 20)
        oled.show()
        page = 3
    elif page < 1:
        oled.fill(0)
        oled.text("first page", 10, 20)
        oled.show()
        page = 1
    esp.sleep_type(esp.SLEEP_MODEM)
    utime.sleep(1)
예제 #18
0
from machine import freq, Pin, ADC, reset
from esp import sleep_type, SLEEP_NONE
import webrepl

print(
    "\n\nJust Do It Yourself World Company Incorporated (c) from 2020 to eternity and beyond...\n"
)

freq(160000000)
sleep_type(SLEEP_NONE)

webrepl.start()


def rst():
    reset()


def ir_on():
    ir_power = Pin(16, Pin.OUT)
    ir_power.on()


def ir_off():
    ir_power = Pin(16, Pin.OUT)
    ir_power.off()


def ir_read():
    ir_sensor = ADC(0)
    print("> IR sensor read: {}".format(ir_sensor.read()))
예제 #19
0

def wifi_init():
    sta = network.WLAN(network.STA_IF)
    sta.active(True)
    sta.connect("Wilko Wireless", "WilkoN600")
    if not sta.isconnected():
        time.sleep(0.5)


def publish(t, h):
    c = MQTTClient('my_sensor', 'iot.eclipse.org')  #change my_sensor!!
    c.connect()
    c.publish('RIFF/phil/temperature', str(t))  # change the topic tree!
    c.publish('RIFF/phil/humidity', str(h))  # change the topic tree!
    c.disconnect()


def wifi_deinit():
    sta = network.WLAN(network.STA_IF)
    sta.active(False)


esp.sleep_type(esp.SLEEP_MODEM)  #all sleep is modem sleep
while True:
    t, h = poll_sensor()
    wifi_init()
    publish(t, h)
    wifi_deinit()
    time.sleep(60)
예제 #20
0
import uasyncio as asyncio
import time
import machine
from pysmartnode.utils.sys_vars import getDeviceID
import network

try:
    s = network.WLAN(network.STA_IF)
    s.config(dhcp_hostname="{}{}".format("ESP8266_", getDeviceID()))
except Exception as e:
    print(e)  # not important enough to do anything about it

if config.WIFI_SLEEP_MODE is not None:
    import esp

    esp.sleep_type(config.WIFI_SLEEP_MODE)

if config.RTC_SYNC_ACTIVE:
    import ntptime

    async def _sync():
        s = 1
        while True:
            print("Synchronize time from NTP server ...")
            try:
                ntptime.settime()
                gc.collect()
                tm = time.localtime()
                hour = tm[3] + config.RTC_TIMEZONE_OFFSET
                day = tm[2]
                if hour > 24:
예제 #21
0
# -*- coding: utf-8 -*-
#Micropython on ESP8266 - Smart Home V0.1 (c)2019 Ursa Robotics 1st EPA.L. of Preveza
import machine, gc, time
print('\n=========== Ursa Robotics - Smart Home (c)2019 ===================')
machine.freq(160000000) #Να τρέχει στα 160MHz
print('[Initial free RAM:', gc.mem_free(), 'bytes]')

import os, network, esp, ustruct, onewire, ds18x20, ubinascii, bme280
from umqtt.simple import MQTTClient

#Αρχεία τα οποία ορίζονται μέσα στο έργο
import definitions as df
import functions as fn

esp.osdebug(None)
esp.sleep_type(0) #esp.sleep_type(esp.SLEEP_NONE)

#Ορισμός timer
timer1 = machine.Timer(-1)
timer2 = machine.Timer(-1)

#Πληροφορίες για το μέγεθος της μνήμης Flash
print('[Program file system total :', os.statvfs("/")[0] * os.statvfs("/")[2], 'bytes]')
print('[Program file system free :', os.statvfs("/")[0] * os.statvfs("/")[3], 'bytes]')

#Δημιουρία αντικειμένων OneWire
ds1 = ds18x20.DS18X20(onewire.OneWire(df.OW1_DATA)) #Εξωτερικό θερμόμετρο
ds2 = ds18x20.DS18X20(onewire.OneWire(df.OW2_DATA)) #Εσωτερικό θερμόμετρο

#Εμφάνισε τα Id των θερμομέτρων
roms_ext = ds1.scan()