Example #1
0
def octopus_init():
    Env.start = ticks_ms()
    print("auto Init: " + str(Env.autoInit))
    #if Env.autoInit:
    printTitle("> auto Init ")
    if io_conf.get('led'):
        printLog("led.blink()")
        print("testing led")
        led.blink()

    if io_conf.get('ws'):
        printLog("ws.test()")
        print("testing ws - RGB led")
        ws.test()

    if io_conf.get('led7'):
        Env.d7 = disp7_init()

    if io_conf.get('oled'):
        Env.o = oled_init()

    if io_conf.get('temp'):
        Env.t = temp_init()

    printLog("ticks_diff(ticks_ms(), Env.start)")
    delta = ticks_diff(ticks_ms(), Env.start)
    print("delta_time: " + str(delta))
Example #2
0
def o_info():
    from os import statvfs
    from gc import mem_free
    printTitle("basic info > ")
    print("This is basic info about system and setup")

    print("> machine.freq: " + str(Env.freq) + " [Hz]")
    printLog("memory")
    print("> ram free: " + str(mem_free()) + " [B]")
    #print("> flash: "+str(os.statvfs("/")))
    ff = int(statvfs("/")[0]) * int(statvfs("/")[3])
    print("> flash free: " + str(int(ff / 1000)) + " [kB]")
    printLog("device")
    try:
        with open('config/device.json', 'r') as f:
            d = f.read()
            f.close()
            print(" > config/device: " + d)
            # device_config = json.loads(d)
    except Exception as e:
        print(
            "Device config 'config/device.json' does not exist, please run setup()"
        )

    printLog("pinout")
    print(pinout)
    printLog("io_conf")
    print(io_conf)
    printInfo()
Example #3
0
 def i2c_expander_init(addr=0):
     printTitle("i2c_expander_init()")
     from components.i2c_expander import Expander8  # from components.i2c_expander import neg, int2bin
     if addr == 0:
         e8 = Expander8()
     else:
         e8 = Expander8(addr)
     return e8
Example #4
0
def o_help():
    from shell import cat
    printOctopus()
    print("Welcome to MicroPython on the ESP32 octopusLAB board")
    print("("+getVer()+")")
    printTitle("basic commands - list, examples", 53)
    cat("util/octopus_help.txt", False)
    printInfo()
Example #5
0
 def disp7_init():
     printTitle("disp7init()")
     from components.display7 import Display7
     print("display test: octopus")
     d7 = Display7(spi, ss)
     d7.write_to_buffer('octopus')
     d7.display()
     return d7
Example #6
0
def ap_init(): #192.168.4.1
    printTitle("AP init > ")
    from utils.wifi_connect import WiFiConnect
    import ubinascii
    w = WiFiConnect()
    w.ap_if.active(True)
    mac = ubinascii.hexlify(w.ap_if.config('mac'),':').decode()
    w.ap_if.config(essid="octopus_ESP32_" + mac)
    print(w.ap_if.ifconfig())
    print("AP Running: " + w.ap_if.config("essid"))
    return w
Example #7
0
        def oled_init(ox=128, oy=64, runTest=True):
            printTitle("oled_init()")

            from components.oled import Oled
            from components.display_segment import threeDigits
            sleep_ms(1000)

            oled = Oled(i2c, 0x3c, ox, oy)
            print("test oled display: OK")
            if runTest:
                oled.test()
                threeDigits(oled, 123)

            return oled
Example #8
0
        def lcd2_init(addr = LCD_ADDR):

            printTitle("lcd2init()")
            LCD_ROWS=2
            LCD_COLS=16
            from lib.esp8266_i2c_lcd import I2cLcd
            lcd = I2cLcd(i2c, addr, LCD_ROWS, LCD_COLS)
            print("display test: octopusLAB")
            happy_face = bytearray([0x00,0x0A,0x00,0x04,0x00,0x11,0x0E,0x00])
            lcd.custom_char(0, happy_face)
            # lcd.move_to(0,1) # col 1 (0) / row 2 (012)
            lcd.clear()
            lcd.putstr("octopusLAB")
            return lcd
Example #9
0
        def disp8_init():
            printTitle("disp8init()")
            from lib.max7219 import Matrix8x8
            d8 = Matrix8x8(spi, ss, 1)  # 1/4

            count = 6
            for i in range(count):
                d8.fill(0)
                d8.text(str(i), 0, 0, 1)
                d8.show()
                print(i)
                sleep_ms(500)
            d8.fill(0)
            d8.show()
            return d8
Example #10
0
def time_init(urlApi ="https://www.octopusengine.org/api/hydrop"):
    from urequests import get
    printTitle("time setup from url")
    urltime=urlApi+"/get-datetime.php"
    print("https://urlApi/"+urltime)
    try:
        response = get(urltime)
        dt_str = (response.text+(",0,0")).split(",")
        print(str(dt_str))
        dt_int = [int(numeric_string) for numeric_string in dt_str]
        rtc.init(dt_int)
        #print(str(rtc.datetime()))
        print("time: " + get_hhmm())
    except Exception as e:
        print("Err. Setup time from URL")
Example #11
0
def w(logD=True, echo=True):
    if echo:
        printInfo()
        printTitle("WiFi connect > ")
    w = w_connect()
    if logD and Env.logDev: logDevice()

    from ubinascii import hexlify
    try:
        Env.MAC = hexlify(w.sta_if.config('mac'),':').decode()
    except:
        Env.MAC = "Err: w.sta_if"
    if echo:
        getFree(True)
    return w
Example #12
0
# octopusLAB simple example
# ESP32board with "BUILT_IN_LED" and OLED display 

import machine
from time import sleep
from utils.octopus import Env, w, time_init, get_hhmm, get_hhmmss
from shell.terminal import printTitle
isOled = False
isDisp7 = True

printTitle("examples/deep_sleep1.py")
from components.led import Led
led = Led(2)


if get_hhmm() == "00:00":
    print("first time setup > ")
    w()
    time_init()

print(get_hhmmss())


def sendValue(val = 0,urlPOST = "http://your_server/add_item_to_database.php"):
    from urequests import post
    header = {}
    header["Content-Type"] = "application/x-www-form-urlencoded"
    deviceID = Env.uID
    place = "octoPy32"
    value =  int(float(Env.ver)*100)
    try:
Example #13
0
# simple basic example - ESP32
# cp("examples/bme280.py") > main.py

from time import sleep
from utils.octopus import i2c_init
from shell.terminal import printTitle
from bme280 import BME280


def bme280_init():
    i2c = i2c_init(1)
    bme = BME280(i2c=i2c)
    return bme


printTitle("examples/bme280.py")
print("this is simple Micropython example | ESP32 & octopusLAB")
print()

bme280 = bme280_init()

while True:
    print(bme280.values)
    sleep(1)
Example #14
0
from time import sleep
from utils.octopus import *
from shell.terminal import printTitle

d7 = disp7_init()

d7.show("Connect")
iface = w_connect()
#iface = lan_connect()

printTitle("remote terminal")
print("this is simple Micropython example | ESP32 & octopusLAB")
print()    

import webrepl
webrepl.start()

print("IP Address: ")
ip = iface.ifconfig()[0]
print(ip)

loop = 0
run = True

while run:
    d7.show("1-{0}.{1}.".format(ip.split('.')[0], ip.split('.')[1]))
    sleep(2)
    d7.show("2-{0}.{1}".format(ip.split('.')[2], ip.split('.')[3]))
    sleep(2)
    loop += 1
    if loop == 3: run = False
Example #15
0
# simple basic example - ESP32 - thermometer
# cp("examples/bme280-therm.py") > main.py

from time import sleep
from utils.octopus import i2c_init, disp7_init
from shell.terminal import printTitle
from bme280 import BME280


def bme280_init():
    i2c = i2c_init(1)
    bme = BME280(i2c=i2c)
    print(bme.values)
    return bme


printTitle("examples/bme280-therm.py")
print("this is simple Micropython example | ESP32 & octopusLAB")
print()

disp7 = disp7_init()
sleep(2)

bme280 = bme280_init()

while True:
    print(bme280.values)
    disp7.show(bme280.values[0])
    sleep(1)
Example #16
0
# get bitcoin

from time import sleep
import urequests, json
from utils.octopus import w
from shell.terminal import printTitle

w()


def bitcoin_usd():

    res = urequests.get("https://api.coinpaprika.com/v1/tickers/btc-bitcoin")
    btcusd = res.json()['quotes']["USD"]["price"]
    return float(btcusd)


printTitle("get_bitcoin.py")
print("this is simple Micropython example | ESP32 & octopusLAB")
print()

while True:
    btc = bitcoin_usd()
    print(btc)
    sleep(10)
Example #17
0
def web_server():
    printTitle("web_server start > ")
    from lib.microWebSrv import MicroWebSrv
    import os, webrepl
    from ubinascii import hexlify
    from utils.wifi_connect import WiFiConnect

    expander = None
    if Env.wscExp8:
        from components.i2c_expander import Expander8
        expander = Expander8()

    wc = WiFiConnect()

    led = None

    if io_conf.get('led') is None:
        led = led_init(None)
    elif io_conf.get('led') == 1:
        print("Led | ", end="")
        led = led_init()
    else:
        print("Led | ", end="")
        led = led_init(io_conf.get('led'))

    led.blink()

    @MicroWebSrv.route('/setup/wifi/networks.json')  # GET
    def _httpHandlerWiFiNetworks(httpClient, httpResponse):
        nets = [[item[0],
                 hexlify(item[1], ":"), item[2], item[3], item[4]]
                for item in wc.sta_if.scan()]
        httpResponse.WriteResponseJSONOk(nets)

    @MicroWebSrv.route('/setup/wifi/savednetworks.json')  # GET
    def _httpHandlerWiFiNetworks(httpClient, httpResponse):
        wc.load_config()
        nets = [k for k, v in wc.config['networks'].items()]
        httpResponse.WriteResponseJSONOk(nets)

    @MicroWebSrv.route('/setup/wifi/network')  # Get acutal network
    def _httpHandlerWiFiCreateNetwork(httpClient, httpResponse):
        content = None
        data = dict()
        sta_ssid = wc.sta_if.config("essid")
        sta_rssi = wc.sta_if.status("rssi") if wc.sta_if.isconnected() else 0
        sta_connected = wc.sta_if.isconnected()
        sta_active = wc.sta_if.active()

        ap_ssid = wc.ap_if.config("essid")
        ap_connected = wc.ap_if.isconnected()
        ap_active = wc.ap_if.active()
        ap_stations = [
            hexlify(sta[0], ":") for sta in wc.ap_if.status("stations")
        ] if wc.ap_if.active() else []

        data["sta_if"] = {
            "active": sta_active,
            "connected": sta_connected,
            "ssid": sta_ssid,
            "rssi": sta_rssi
        }
        data["ap_if"] = {
            "active": ap_active,
            "connected": ap_connected,
            "ssid": ap_ssid,
            "stations": ap_stations
        }
        httpResponse.WriteResponseJSONOk(data)

    @MicroWebSrv.route('/setup/wifi/network', "POST")  # Create new network
    def _httpHandlerWiFiCreateNetwork(httpClient, httpResponse):
        data = httpClient.ReadRequestContentAsJSON()
        responseCode = 500
        content = None

        if len(data) < 1:
            responseCode = 400
            content = "Missing ssid in request"
            httpResponse.WriteResponse(code=400,
                                       headers=None,
                                       contentType="text/plain",
                                       contentCharset="UTF-8",
                                       content=content)
            return

        ssid = data[0]
        psk = data[1] if len(data) > 1 else ""
        wc.add_network(ssid, psk)
        responseCode = 201

        httpResponse.WriteResponse(code=responseCode,
                                   headers=None,
                                   contentType="text/plain",
                                   contentCharset="UTF-8",
                                   content=content)

    @MicroWebSrv.route('/setup/wifi/network', "PUT")  # Update existing network
    def _httpHandlerWiFiUpdateNetwork(httpClient, httpResponse):
        data = httpClient.ReadRequestContentAsJSON()
        responseCode = 500
        content = None

        print(data)
        if len(data) < 1:
            responseCode = 400
            content = "Missing ssid in request"
            httpResponse.WriteResponse(code=400,
                                       headers=None,
                                       contentType="text/plain",
                                       contentCharset="UTF-8",
                                       content=content)
            return

        ssid = data[0]
        psk = data[1] if len(data) > 1 else ""

        print("Updating network {0}".format(data[0]))
        wc.add_network(ssid, psk)
        responseCode = 201
        httpResponse.WriteResponse(code=responseCode,
                                   headers=None,
                                   contentType="text/plain",
                                   contentCharset="UTF-8",
                                   content=content)

    @MicroWebSrv.route('/setup/wifi/network',
                       "DELETE")  # Delete existing network
    def _httpHandlerWiFiDeleteNetwork(httpClient, httpResponse):
        data = httpClient.ReadRequestContentAsJSON()
        responseCode = 500
        content = None

        if len(data) < 1:
            responseCode = 400
            content = "Missing ssid in request"
            httpResponse.WriteResponse(code=400,
                                       headers=None,
                                       contentType="text/plain",
                                       contentCharset="UTF-8",
                                       content=content)
            return

        ssid = data[0]
        wc.remove_network(ssid)
        responseCode = 201
        httpResponse.WriteResponse(code=responseCode,
                                   headers=None,
                                   contentType="text/plain",
                                   contentCharset="UTF-8",
                                   content=content)

    @MicroWebSrv.route('/setup/devices.json')  # GET boards
    def _httpHandlerDevices(httpClient, httpResponse):
        from utils.setup import devices

        httpResponse.WriteResponseJSONOk(devices)

    @MicroWebSrv.route('/esp/control_info.json')  # GET info
    def _httpHandlerInfo(httpClient, httpResponse):

        infoDict = {}
        infoDict["deviceUID"] = Env.uID
        infoDict["deviceMAC"] = Env.MAC
        infoDict["freq"] = Env.freq
        infoDict["freeRAM"] = getFree()
        infoDict["freeFLASH"] = str(
            int(os.statvfs("/")[0]) * int(os.statvfs("/")[3]))
        httpResponse.WriteResponseJSONOk(infoDict)

    @MicroWebSrv.route('/esp/control/led', "POST")  # Set LED
    def _httpHandlerSetDevice(httpClient, httpResponse):
        data = httpClient.ReadRequestContent()
        val = int(data)
        print("control/led call: " + str(val))
        led.value(val)
        if Env.wscWS:
            if val == 2: ws.color(RED)
            if val == 3: ws.color(GREEN)
            if val == 4: ws.color(BLUE)
            if val == 5: ws.color(ORANGE)
            if val == 6: ws.color((128, 0, 128))
            if val == 0: ws.color(BLACK)
        httpResponse.WriteResponseOk(None)

    @MicroWebSrv.route('/esp/control/pwm',
                       "POST")  # PWM - IOT/ Hydroponics LED
    def _httpLedPwmSet(httpClient, httpResponse):
        data = httpClient.ReadRequestContent()
        print("LED PWM Call: " + str(int(data)))

        if FET is None:
            httpResponse.WriteResponse(
                code=500,
                headers=None,
                contentType="text/plain",
                contentCharset="UTF-8",
                content="MFET is not defined, check setup()")
            return
        try:
            value = int(data)
            if value > 390: FET.freq(2000)
            else: FET.freq(300)
            FET.duty(value)
        except Exception as e:
            print("Exception: {0}".format(e))
            raise
        finally:
            httpResponse.WriteResponseOk(None)
        httpResponse.WriteResponse(code=204,
                                   headers=None,
                                   contentType="text/plain",
                                   contentCharset="UTF-8",
                                   content=None)

    @MicroWebSrv.route('/esp/control/i2cexpander', "POST")  # Set device
    def _httpHandlerSetI2CExpander(httpClient, httpResponse):
        if expander is None:
            print("I2C expander is not initialized!")
            httpResponse.WriteResponseOk(None)
            return

        from components.i2c_expander import neg
        data = httpClient.ReadRequestContent()
        print("i2cexpander.data: " + str(data) + str(bin(int(data))))
        try:
            expander.write_8bit(neg(int(data)))
        except Exception as e:
            print("Exception: {0}".format(e))
            raise
        finally:
            httpResponse.WriteResponseOk(None)

    @MicroWebSrv.route('/setup/device')  # Get actual device
    def _httpHandlerGetDevice(httpClient, httpResponse):
        dev = "null"
        try:
            os.stat('config/device.json')
            with open('config/device.json', 'r') as f:
                dev = f.read()
        except:
            pass
        httpResponse.WriteResponseOk(contentType="application/json",
                                     content=dev)

    @MicroWebSrv.route('/setup/device', "POST")  # Set device
    def _httpHandlerSetDevice(httpClient, httpResponse):
        data = httpClient.ReadRequestContent()

        with open('config/device.json', 'w') as f:
            f.write(data)
        httpResponse.WriteResponseOk(None)

    @MicroWebSrv.route('/setup/io')  # Get IO configuration
    def _httpHandlerIOConfigGet(httpClient, httpResponse):
        from utils.io_config import io_conf_file, io_menu_layout, get_from_file as get_io_config_from_file
        io_conf = get_io_config_from_file()
        config = [{
            'attr': item['attr'],
            'descr': item['descr'],
            'value': io_conf.get(item['attr'], None)
        } for item in io_menu_layout]
        httpResponse.WriteResponseJSONOk(config)

    @MicroWebSrv.route('/setup/io', "POST")  # Set IO configuration
    def _httpHandlerIOConfigSet(httpClient, httpResponse):
        from ujson import dump as json_dump
        data = httpClient.ReadRequestContentAsJSON()
        if type(data['value']) is not int:
            httpResponse.WriteResponse(code=400,
                                       headers=None,
                                       contentType="text/plain",
                                       contentCharset="UTF-8",
                                       content="Value is not integer")
            return

        from utils.io_config import io_conf_file, io_menu_layout, get_from_file as get_io_config_from_file
        io_conf = get_io_config_from_file()
        io_conf[data['attr']] = data['value']

        with open(io_conf_file, 'w') as f:
            json_dump(io_conf, f)
        httpResponse.WriteResponseOk(None)

    @MicroWebSrv.route('/file_list')
    def _httpHandlerTestGet(httpClient, httpResponse):
        path = "/"

        if "path" in httpClient._queryParams:
            path = httpClient._queryParams["path"]

        if len(path) > 1 and path[-1] == '/':
            path = path[:-1]

        files = [
            "{0}/".format(name) if os.stat(path + "/" + name)[0]
            & 0o170000 == 0o040000 else name for name in os.listdir(path)
        ]
        files.sort()
        content = ";".join(files)
        httpResponse.WriteResponseOk(headers=None,
                                     contentType="text/html",
                                     contentCharset="UTF-8",
                                     content=content)

    mws = MicroWebSrv(webPath='www/')  # TCP port 80 and files in /flash/www
    mws.LetCacheStaticContentLevel = 0
    mws.Start(threaded=True)  # Starts server in a new thread
    getFree(True)
    webrepl.start()
    print("Web server started on http://{0}".format(wc.sta_if.ifconfig()[0]))
    return mws

    @MicroWebSrv.route('/esp/control/relay', "POST")
    def _httpRelaySet(httpClient, httpResponse):
        print("Relay Call")

        data = httpClient.ReadRequestContent()
        print(data)

        if RELAY is None:
            httpResponse.WriteResponse(
                code=500,
                headers=None,
                contentType="text/plain",
                contentCharset="UTF-8",
                content="RELAY is not defined, check setup()")
            return
        try:
            value = int(data)
            RELAY.value(value)
        except Exception as e:
            print("Exception: {0}".format(e))
            raise
        finally:
            httpResponse.WriteResponseOk(None)
        httpResponse.WriteResponse(code=204,
                                   headers=None,
                                   contentType="text/plain",
                                   contentCharset="UTF-8",
                                   content=None)
Example #18
0
# move step pixels with each button press
step = 5
# debounce: read 10 samples, only tolerate one false reading
debounce = 9

o.fill(0)
o.hline(0, 51, 128, 1)
o.text("octopusLAB 2019", 3, 64 - 7)
o.show()

# draw first position
o.draw_icon(ICON_arrow, x, y)
# init helper var
old_x = x

printTitle("button2oled.py")
print("this is simple Micropython example | ESP32 & octopusLAB")
print()

while True:
    # get new position
    old_x = x
    if button(L)[0] >= debounce: x -= step
    if button(R)[0] >= debounce: x += step
    # only if changed
    if old_x != x:
        # clear current position
        o.draw_icon(ICON_clr, old_x, y)
        # draw new icon
        o.draw_icon(ICON_arrow, x, y)
    # sleep
Example #19
0
def getApiTest():
    printTitle("data from url")
    #print("https://urlApi/"+urljson)
    print("htts://public_unsecure_web/data.json")
    print(getApiJson())
Example #20
0
PADDLE_HEIGHT = 3
PADDLE_Y = 54
BALL_SIZE = 5

OLED = oled_init(SCREEN_WIDTH, SCREEN_HEIGHT)  # init oled display
OLED.clear()  # clear
L, R, C = buttons_init()

# def displayNum(num):
#     num = str(num)
#     for n in range(len(num)):
#         displayDigit(OLED, int(num[n]), n, 2, 6)

# default coordinates for position

printTitle("oled_pong.py")
print("this is simple Micropython example | ESP32 & octopusLAB")
print()


class oled_pong:
    def __init__(self):
        #print("__init__")
        self.start_game(self)

    def start_game(self, start_lives=3):
        x = int(SCREEN_WIDTH / 2)
        y = 50
        paddle_x = x - int(PADDLE_WIDTH / 2)
        self.score = 0
Example #21
0
# simple basic example - ESP32 + 7segment display
# cp("examples/clock.py") > main.py

from time import sleep
from utils.octopus import w, disp7_init, get_hhmm, time_init
from shell.terminal import printTitle

w()  # wifi connect
d7 = disp7_init()  # 8 x 7segment display init


def clock():
    d7.show(get_hhmm("-"))
    sleep(0.5)
    d7.show(get_hhmm(" "))
    sleep(0.5)


time_init()  # server > time setup

printTitle("examples/clock.py")
print("this is simple Micropython example | ESP32 & octopusLAB")
print()

while True:
    clock()
Example #22
0
from time import sleep
from utils.octopus import button_init, button, disp7_init
from shell.terminal import printTitle

BB = button_init(0)  # button boot = 0
# debounce: read 10 samples, only tolerate one false reading
debounce = 9

d7 = disp7_init()

select = 0
sec = 0
run = False

printTitle("stopwatch.py")
print("this is simple Micropython example | ESP32 & octopusLAB")
print()

while True:
    # print(select)
    if run:
        sec += 1
        d7.show(sec / 10)
        print(sec / 10)
        sleep(0.1)

    if button(BB)[0] >= debounce:
        # beep()
        select += 1
        sleep(0.3)
# octopusLAB simple example 2019
# HW: ESP32 + i2c OLED display
# ampy -p /COM6 put examples/oled_random_lines.py main.py
# start: import examples/oled_random_lines

from utils.octopus import oled_init
from shell.terminal import printTitle
from os import urandom

o = oled_init()  # init oled display
o.fill(0)  # clear

# default coordinates for position
x = 0
y = 0

printTitle("oled_random_lines.py")
print("this is simple Micropython example | ESP32 & octopusLAB")
print()

while True:
    old_x = x
    old_y = y
    # get new position
    x = int(urandom(1)[0] / 2)
    y = int(urandom(1)[0] / 4)

    o.line(old_x, old_y, x, y, 1)
    o.show()
    # sleep(0.1) # slow or fast