Exemplo n.º 1
0
def wifi(comm="on"):
    global _wc

    if _wc is None:
        from util.wifi_connect import WiFiConnect
        _wc = WiFiConnect()

    if comm == "on":
        if _wc.connect():
            print("WiFi: OK")
        else:
            print("WiFi: Connect error, check configuration")

    if comm == "scan":
        staactive = _wc.sta_if.active()
        if not staactive:
            _wc.sta_if.active(True)

        from ubinascii import hexlify
        print("networks:")
        print('-' * SEPARATOR_WIDTH)
        nets = [[item[0].decode('utf-8'), hexlify(item[1], ":").decode(), item[2], item[3], item[4]] for item in _wc.sta_if.scan()]
        for net in nets:
            print(str(net))
        print('-' * SEPARATOR_WIDTH)
        _wc.sta_if.active(staactive)

    if comm == "off":
        try:
            _wc.sta_if.disconnect()
            _wc.sta_if.active(False)
        except Exception as e:
            print("Exception: {0}".format(e))
Exemplo n.º 2
0
def w_connect():
    from util.wifi_connect import read_wifi_config, WiFiConnect
    time.sleep_ms(1000)
    wifi_config = read_wifi_config()
    if Debug: print("config for: " + wifi_config["wifi_ssid"])
    w = WiFiConnect()
    w.events_add_connecting(connecting_callback)
    w.events_add_connected(connected_callback)
    w.connect(wifi_config["wifi_ssid"], wifi_config["wifi_pass"])
    if Debug: print("WiFi: OK")
Exemplo n.º 3
0
def ap_init(): #192.168.4.1
    printTitle("AP init > ")
    from util.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
def w_connect():
    global wifi
    time.sleep_ms(1000)
    wifi_config = read_wifi_config()
    if Debug: print("config for: " + wifi_config["wifi_ssid"])
    wifi = WiFiConnect(wifi_config["wifi_retries"] if "wifi_retries" in
                       wifi_config else wifi_retries)
    wifi.events_add_connecting(connecting_callback)
    wifi.events_add_connected(connected_callback)
    wifi.events_add_timeout(connecting_timeout_callback)
    wifi.events_add_disconnected(disconnected_callback)
    wifi_status = wifi.connect(wifi_config["wifi_ssid"],
                               wifi_config["wifi_pass"])
    if Debug: print("WiFi: OK" if wifi_status else "WiFi: Error")
Exemplo n.º 5
0
def w_connect():
    led.value(1)

    from util.wifi_connect import WiFiConnect
    sleep(1)
    w = WiFiConnect()
    if w.connect():
        print("WiFi: OK")
    else:
        print("WiFi: Connect error, check configuration")

    led.value(0)
    print('Network config:', w.sta_if.ifconfig())
    return w
Exemplo n.º 6
0
def w_connect():
    global _is_wifi_connect
    # led.value(1)

    from util.wifi_connect import WiFiConnect
    sleep(1)
    w = WiFiConnect()
    if w.connect():
        print("*")
        _is_wifi_connect = True
    else:
        print("WiFi: Connect error, check configuration")

    # led.value(0)
    return w
Exemplo n.º 7
0
def w_connect():
    from network import WLAN, STA_IF
    led.value(1)

    from util.wifi_connect import WiFiConnect
    sleep(1)
    w = WiFiConnect()
    if w.connect():
        print("WiFi: OK")
    else:
        print("WiFi: Connect error, check configuration")

    led.value(0)
    wlan = WLAN(STA_IF)
    print('network config:', wlan.ifconfig())
    return wlan
Exemplo n.º 8
0
def web_server():
    # from util.octopus import w, web_server
    printTitle("web_server start > ")
    from lib.microWebSrv import MicroWebSrv
    import os, webrepl
    from ubinascii import hexlify
    from util.wifi_connect import WiFiConnect
    if Env.wscExp8:
        from util.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 util.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]))
        ## infoJ = ujson.dumps(infoDict)

        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):
        from util.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 util.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 util.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)
Exemplo n.º 9
0
def setup():
    print("Hello, this will help you initialize your ESP")
    print("Press Ctrl+C to abort")
    print()

    # TODO improve this
    # prepare directory
    if 'config' not in uos.listdir():
       uos.makedirs('config')

    run= True
    while run:
        sele = setupMenu()

        if sele == "e":
            print("Setup - exit >")
            time.sleep_ms(2000)
            print("all OK, press CTRL+D to soft reboot")
            run = False

        if sele == "si": #system_info()
            from util.sys_info import sys_info
            sys_info()

        if sele == "ds":
            print("Device setting:")
            print("   board_type  | soc_type (system on the board)")
            i=0
            for di in devices:
               print(str(i)+": "+str(di[0]) + " | " + str(di[1]))
               i=i+1

            print()
            sd = input("select: ")
            #print(str(devices[int(sd)]))
            print("> " + str(devices[int(sd)][0]) + " | " + str(devices[int(sd)][1]))

            dc = {}
            dc['board_type'] = str(devices[int(sd)][0]) #input("Board type ('oLAB RobotBoard1' or 'oLAB IoTBoard1'): ")
            dc['soc_type'] = str(devices[int(sd)][1])   #input("SoC type ('esp32' or 'esp8266'): ")

            print("Writing to file config/device.json")
            with open('config/device.json', 'w') as f:
                ujson.dump(dc, f)
                # ujson.dump(wc, f, ensure_ascii=False, indent=4)

        if sele == "sw":
            print("Set WiFi >")
            print()
            wc = {}
            wc['wifi_ssid'] = input("SSID: ")
            wc['wifi_pass'] = input("PASSWORD: "******"Writing to file config/wifi.json")
            with open('config/wifi.json', 'w') as f:
                ujson.dump(wc, f)
                # ujson.dump(wc, f, ensure_ascii=False, indent=4)

        if sele == "cw":
              print("Connect WiFi >")
              from util.wifi_connect import read_wifi_config, WiFiConnect
              time.sleep_ms(1000)
              wifi_config = read_wifi_config()
              print("config for: " + wifi_config["wifi_ssid"])
              w = WiFiConnect()
              w.connect(wifi_config["wifi_ssid"], wifi_config["wifi_pass"])
              print("WiFi: OK")

        if sele == "st":
            print("Time setting >")
            rtc = machine.RTC()
            print(str(rtc.datetime()))
            setdatetime = input("input 6 numbers - format: RRRRR,M,D,wd,h,m > ")+(",0,0")
            dt_str = setdatetime.split(",")
            print(str(dt_str))
            dt_int = [int(numeric_string) for numeric_string in dt_str]
            rtc.init(dt_int)
            print(str(rtc.datetime()))

        if sele == "sd":
            print("System download > (initial octopus modules)")
            import upip
            print("Installing shutil")
            upip.install("micropython-shutil")
            print("Running deploy")
            #deplUrl = "http://iot.petrkr.net/olab/latest.tar"
            #deplUrl = "http://octopuslab.cz/download/latest.tar"
            deplUrl = "http://octopusengine.org/download/latest.tar"
            deploy(deplUrl)
Exemplo n.º 10
0
            if "x" in data:
                x = int(data.split('x')[0])
                y = int(data.split('x')[1])
            else:
                y = int(data)

            lcd.move_to(x, y)

        except Exception as e:
            print("Error parse message")
            print(e)


print("wifi_config >")
wifi_config = read_wifi_config()
wifi = WiFiConnect(wifi_config["wifi_retries"] if "wifi_retries" in
                   wifi_config else 250)
wifi.events_add_connecting(connecting_callback)
wifi.events_add_connected(connected_callback)
wifi_status = wifi.connect(wifi_config["wifi_ssid"], wifi_config["wifi_pass"])

print("mqtt_config >")
mqtt_clientid_prefix = read_mqtt_config()["mqtt_clientid_prefix"]
mqtt_host = read_mqtt_config()["mqtt_broker_ip"]
mqtt_root_topic = read_mqtt_config()["mqtt_root_topic"]

mqtt_clientid = mqtt_clientid_prefix + esp_id

c = MQTTClient(mqtt_clientid, mqtt_host, ssl=mqtt_ssl)
c.set_callback(mqtt_sub)

lcd.move_to(14, 0)
Exemplo n.º 11
0
def webconn(s):
  printLog("> webconn ")
  led.blink(50)
  global wnum, web_info, ssidTemp, passTemp, web_wifi
  
  conn, addr = s.accept()
  print('Got a connection from %s' % str(addr))
  request = conn.recv(1024)
  request = str(request)

  try:
    rs = request.split(" ")[1]
    rs = (rs[2:]).split("&")
    ssidTemp = rs[0].split("=")
    passTemp = rs[1].split("=")

    if ssidTemp[0] == "ssid": 
      ssidTemp = ssidTemp[1]
      print("ssid.ok")
      if len(ssidTemp) > 1:
        web_info = "<i>last ssid from form: " + ssidTemp + "</i><hr />"

    if passTemp[0] == "pass": 
      passTemp = passTemp[1]
      print("pass.ok")

  except:
    rs = "err"
    
  print()
  print('Content = ' + str(rs))
  
  # led_on = request.find('/?led=on')
  print()
  print("wifi_config: ")
  from util.wifi_connect import WiFiConnect
  wc = WiFiConnect()

  webWc = "<hr /><b>Saved networks: </b><br />"
  for k, v in wc.config['networks'].items():
      webWc += k + "<br />"

  try:
    print("try save new netw.")
    print("ssid: " + str(ssidTemp) + " | pass: "******"ok")
        led.blink(1000)
        led.blink(1000)
  except:
      print("err")  

  wnum += 1
  web_wifi = webnets + webWc + "<br /> refresh (" + str(wnum) + ")"

  response = web_page()
  conn.send('HTTP/1.1 200 OK\n')
  conn.send('Content-Type: text/html\n')
  conn.send('Connection: close\n\n')
  conn.sendall(response)
  conn.close()
Exemplo n.º 12
0
def setup():
    printOctopus()
    print("Hello, this will help you initialize your ESP")
    print("ver: " + ver + " (c)octopusLAB")
    print("Press Ctrl+C to abort")

    # TODO improve this
    # prepare directory
    if 'config' not in uos.listdir():
        uos.mkdir('config')

    run = True
    while run:
        sele = setupMenu()

        if sele == "x":
            print("Setup - exit >")
            time.sleep_ms(2000)
            print("all OK, press CTRL+D to soft reboot")
            run = False

        if sele == "w":
            from util.wifi_connect import WiFiConnect
            w = WiFiConnect()

            sel_w = wifiMenu()

            if sel_w == "a":
                wifi_ssid = input("SSID: ")
                wifi_pass = input("PASSWORD: "******"r":
                wifi_ssid = input("SSID: ")
                w.remove_network(wifi_ssid)

            if sel_w == "s":
                print("Saved wifi networks")

                for k, v in w.config['networks'].items():
                    print("SSID: {0}".format(k))

        if sele == "cw":
            print("Connect WiFi >")
            from util.wifi_connect import WiFiConnect
            w = WiFiConnect()
            if w.connect():
                print("WiFi: OK")
            else:
                print("WiFi: Connect error, check configuration")

        if sele == "cl":
            print("Connect LAN >")
            import network
            lan = network.LAN(mdc=machine.Pin(23),
                              mdio=machine.Pin(18),
                              phy_type=network.PHY_LAN8720,
                              phy_addr=1,
                              clock_mode=network.ETH_CLOCK_GPIO17_OUT)
            lan.active(1)
            retry = 0
            while not lan.isconnected() or lan.ifconfig()[0] is '0.0.0.0':
                retry += 1
                time.sleep_ms(500)

                if retry > 20:
                    break

            if lan.isconnected():
                print("LAN: OK")
            else:
                print("LAN: Connect error, check cable or DHCP server")

        if sele == "sd":
            shutil()
            deplUrl = "https://octopusengine.org/download/micropython/stable.tar"
            deploy(deplUrl)
Exemplo n.º 13
0
    if iurl is None:
        raise Exception(
            "Config error: InfluxDB URL is not set. Check configuration")

    if idb is None:
        raise Exception(
            "Config error: InfluxDB Database is not set. Check configuration")

    if imetric is None:
        raise Exception("Config error: InfluxDB Metric is not set")

    influx = InfluxDB(iurl, idb, iusr, ipsw, imetric, place=iplace)
    print("influx: ", iurl, idb)
except Exception as e:
    print("config Exception: {0}".format(e))
    print("Use config.setup()")
    exit(1)

display = disp7_init()

display.show("wifiConn")
net = WiFiConnect()
net.connect()

display.show("timer on")
tim1 = Timer(0)  # for main 10 sec timer
timer_init(tim1)

# --- run ---
print("--- run --- RAM free: " + str(mem_free()))
Exemplo n.º 14
0
oled.show()

f = open('config/wifi.json', 'r')
d = f.read()
f.close()
j = json.loads(d)
ssid = j["wifi_ssid"]

time.sleep_ms(1000)
simple_blink_pause()
oled.text("wifi_conf OK", x0, y1)
oled.show()

oled.text("wifi_conn", x0, y2)
oled.show()
w = WiFiConnect()
w.connect(ssid, j["wifi_pass"])

time.sleep_ms(1000)
simple_blink_pause()
oled.text("wifi_conn OK", x0, y2)
oled.show()

i = 0
while True:
    r3 = urequests.post(wwwserver)
    j = json.loads(r3.text)
    time.sleep_ms(3000)
    rgb = j["led"]

    oled.fill(0)
Exemplo n.º 15
0
        print("I2C Keypad not found!")
        isKeypad = False
    else:
        from lib.KeyPad_I2C import keypad
        kp = keypad(i2c, KP_ADDRESS)

if isButton:
    print("Initializing Button, delay {0}".format(BTN_Delay))
    btn = Pin(pinout.DEV2_PIN, Pin.IN, Pin.PULL_UP)
    #btn.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=handleButton)

printLog(4, "wifi and mqtt >")
printFree()

print("wifi_config >")
wifi = WiFiConnect(wifi_retries)
wifi.events_add_connecting(connecting_callback)
wifi.events_add_connected(connected_callback)
print("wifi.connect")
wifi_status = wifi.connect()

# url config: TODO > extern.

if isMqtt:
    from umqtt.simple import MQTTClient
    print("mqtt_config >")
    mqtt_clientid_prefix = read_mqtt_config()["mqtt_clientid_prefix"]
    mqtt_host = read_mqtt_config()["mqtt_broker_ip"]
    mqtt_root_topic = read_mqtt_config()["mqtt_root_topic"]
    #mqtt_ssl  = False # Consider to use TLS!
    mqtt_ssl = read_mqtt_config()["mqtt_ssl"]
Exemplo n.º 16
0
def setup():
    mainOctopus()
    print("Hello, this will help you initialize your ESP")
    print(ver)
    print("Press Ctrl+C to abort")
    

    # TODO improve this
    # prepare directory
    if 'config' not in uos.listdir():
       uos.makedirs('config')

    run= True
    while run:
        sele = setupMenu()

        if sele == "e":
            print("Setup - exit >")
            time.sleep_ms(2000)
            print("all OK, press CTRL+D to soft reboot")
            run = False

        if sele == "si": #system_info()
            from util.sys_info import sys_info
            sys_info()

        if sele == "ds":
            print("Device setting:")
            print("   board_type  | soc_type (system on the board)")
            i=0
            for di in devices:
               print(str(i)+": "+str(di[0]) + " | " + str(di[1]))
               i=i+1

            print()
            sd = input("select: ")
            #print(str(devices[int(sd)]))
            print("> " + str(devices[int(sd)][0]) + " | " + str(devices[int(sd)][1]))

            dc = {}
            dc['board_type'] = str(devices[int(sd)][0]) #input("Board type ('oLAB RobotBoard1' or 'oLAB IoTBoard1'): ")
            dc['soc_type'] = str(devices[int(sd)][1])   #input("SoC type ('esp32' or 'esp8266'): ")

            print("Writing to file config/device.json")
            with open('config/device.json', 'w') as f:
                ujson.dump(dc, f)
                # ujson.dump(wc, f, ensure_ascii=False, indent=4)

        if sele == "sw":
            print("Set WiFi >")
            print()
            wc = {}
            wc['wifi_ssid'] = input("SSID: ")
            wc['wifi_pass'] = input("PASSWORD: "******"Writing to file config/wifi.json")
            with open('config/wifi.json', 'w') as f:
                ujson.dump(wc, f)
                # ujson.dump(wc, f, ensure_ascii=False, indent=4)

        if sele == "cw":
              print("Connect WiFi >")
              from util.wifi_connect import read_wifi_config, WiFiConnect
              time.sleep_ms(1000)
              wifi_config = read_wifi_config()
              print("config for: " + wifi_config["wifi_ssid"])
              w = WiFiConnect()
              w.connect(wifi_config["wifi_ssid"], wifi_config["wifi_pass"])
              print("WiFi: OK")

        if sele == "mq":
            print("Set mqtt >")
            print()
            mq = {}
            mq['mqtt_broker_ip'] = input("BROKER IP: ")
            mq['mqtt_ssl'] = input("> SSL (0/1): ")
            mq['mqtt_port'] = input("> PORT (1883/8883/?): ")
            mq['mqtt_clientid_prefix'] = input("CLIENT PREFIX: ")
            mq['mqtt_root_topic'] = input("ROOT TOPIC: ")

            # TODO improve this
            if 'config' not in uos.listdir():
                uos.makedirs('config')

            print("Writing to file config/mqtt.json")
            with open('config/mqtt.json', 'w') as f:
                ujson.dump(mq, f)

        if sele == "st":
            print("Time setting >")
            rtc = machine.RTC()
            print(str(rtc.datetime()))
            setdatetime = input("input 6 numbers - format: RRRRR,M,D,wd,h,m > ")+(",0,0")
            dt_str = setdatetime.split(",")
            print(str(dt_str))
            dt_int = [int(numeric_string) for numeric_string in dt_str]
            rtc.init(dt_int)
            print(str(rtc.datetime()))

        if sele == "sdp":
            shutil()
            deplUrl = "http://iot.petrkr.net/olab/latest.tar"
            deploy(deplUrl)

        if sele == "sdo":
            shutil()
            #deplUrl = "http://octopuslab.cz/download/latest.tar"
            deplUrl = "http://octopusengine.org/download/latest.tar"
            deploy(deplUrl)

        if sele == "o":
            from util.octopus import octopus
            octopus()    
Exemplo n.º 17
0
def setup():
    mainOctopus()
    print("Hello, this will help you initialize your ESP")
    print("ver: " + ver + " (c)octopusLAB")
    print("Press Ctrl+C to abort")

    # TODO improve this
    # prepare directory
    if 'config' not in uos.listdir():
        uos.mkdir('config')

    run = True
    while run:
        sele = setupMenu()

        if sele == "q":
            print("Setup - quit >")
            time.sleep_ms(1000)
            print("all OK, press CTRL+D to soft reboot")
            run = False

        if sele == "si":  #system_info()
            from util.sys_info import sys_info
            sys_info()

        if sele == "ds":
            print("Device setting:")
            print("   board_type  | soc_type (system on the board)")
            i = 0
            for di in devices:
                print(str(i) + ": " + str(di[0]) + " | " + str(di[1]))
                i = i + 1

            print()
            sd = input("select: ")
            #print(str(devices[int(sd)]))
            print("> " + str(devices[int(sd)][0]) + " | " +
                  str(devices[int(sd)][1]))

            dc = {}
            dc['board_type'] = str(
                devices[int(sd)][0]
            )  #input("Board type ('oLAB RobotBoard1' or 'oLAB IoTBoard1'): ")
            dc['soc_type'] = str(devices[int(
                sd)][1])  #input("SoC type ('esp32' or 'esp8266'): ")

            print("Writing to file config/device.json")
            with open('config/device.json', 'w') as f:
                ujson.dump(dc, f)
                # ujson.dump(wc, f, ensure_ascii=False, indent=4)

        if sele == "ios":
            print("I/O setting:")
            # io menu
            ioMenu()

        if sele == "iot":
            print("Testing I/O")
            from util import io_test
            io_test.all()

        if sele == "w":
            from util.wifi_connect import WiFiConnect
            w = WiFiConnect()

            sel_w = wifiMenu()

            if sel_w == "a":
                wifi_ssid = input("SSID: ")
                wifi_pass = input("PASSWORD: "******"r":
                wifi_ssid = input("SSID: ")
                w.remove_network(wifi_ssid)

            if sel_w == "s":
                print("Saved wifi networks")

                for k, v in w.config['networks'].items():
                    print("SSID: {0}".format(k))

        if sele == "cw":
            print("Connect WiFi >")
            from util.wifi_connect import WiFiConnect
            w = WiFiConnect()
            if w.connect():
                print("WiFi: OK")
            else:
                print("WiFi: Connect error, check configuration")

        if sele == "cl":
            print("Connect LAN >")
            import network
            lan = network.LAN(mdc=machine.Pin(23),
                              mdio=machine.Pin(18),
                              phy_type=network.PHY_LAN8720,
                              phy_addr=1,
                              clock_mode=network.ETH_CLOCK_GPIO17_OUT)
            lan.active(1)
            retry = 0
            while not lan.isconnected() or lan.ifconfig()[0] is '0.0.0.0':
                retry += 1
                time.sleep_ms(500)

                if retry > 20:
                    break

            if lan.isconnected():
                print("LAN: OK")
            else:
                print("LAN: Connect error, check cable or DHCP server")

        if sele == "mq":
            print("mqtt setup >")
            try:
                print()
                from util.mqtt import mqtt
                mqtt()
            except:
                print("Err.mqtt() or 'util.mqtt.py' does not exist")

        if sele == "st":
            print("Time setting >")
            rtc = machine.RTC()
            print(str(rtc.datetime()))
            setdatetime = input(
                "input 6 numbers - format: RRRRR,M,D,wd,h,m > ") + (",0,0")
            dt_str = setdatetime.split(",")
            print(str(dt_str))
            dt_int = [int(numeric_string) for numeric_string in dt_str]
            rtc.init(dt_int)
            print(str(rtc.datetime()))

        if sele == "sd":
            shutil()
            deplUrl = "https://octopusengine.org/download/micropython/stable.tar"
            deploy(deplUrl)

        if sele == "sde":
            shutil()
            deplUrl = "https://octopusengine.org/download/micropython/examples.tar"
            deploy(deplUrl)

        if sele == "sdp":
            shutil()
            deplUrl = "http://iot.petrkr.net/olab/latest.tar"
            deploy(deplUrl)

        if sele == "sdo":
            shutil()
            deplUrl = "https://octopusengine.org/download/latest.tar"
            deploy(deplUrl)

        if sele == "sdh":
            shutil()
            deplUrl = "https://octopusengine.org/download/hydroponics.tar"
            deploy(deplUrl)

        if sele == "wr":
            print("under reconstruction <")
            import esp
            esp.osdebug(None)
            import webrepl
            webrepl.start()
Exemplo n.º 18
0
def mqtt():
    mainOctopus()
    print("Hello, this will help you initialize MQTT client")
    print("ver: " + ver + " (c)octopusLAB")
    print("id: " + esp_id)
    print("Press Ctrl+C to abort")

    # TODO improve this
    # prepare directory
    if 'config' not in uos.listdir():
        uos.makedirs('config')

    run = True
    while run:
        sele = setupMenu()

        if sele == "x":
            print("Setup - exit >")
            time.sleep_ms(2000)
            print("all OK, press CTRL+D to soft reboot")
            run = False

        if sele == "si":  #system_info()
            from util.sys_info import sys_info
            sys_info()

        if sele == "cv":
            print("------- Set 0/1/str for settings ------")
            wc = {}
            wc['name'] = input("device (host)name/describe: ")
            wc['time'] = int(input("get time from server? [1/0]: "))
            wc['mysql'] = int(input("send data to mysql db [1/0]: "))
            if wc['mysql']: wc['mysqlURL'] = input("mysql Write URL: ")
            wc['mqtt'] = int(input("mqtt client [1/0]: "))
            wc['influx'] = int(input("send data to influx db [1/0]: "))
            if wc['influx']: wc['influxWriteURL'] = input("influx Write URL: ")
            wc['timer'] = int(input("timer: "))

            print("Writing to file config/mqtt_io.json")
            with open('config/mqtt_io.json', 'w') as f:
                ujson.dump(wc, f)

        if sele == "ms":
            print("Set mqtt >")
            print()
            mq = {}
            mq['mqtt_broker_ip'] = input("BROKER IP: ")
            mq['mqtt_ssl'] = int(input("> SSL (0/1): "))
            mq['mqtt_port'] = int(input("> PORT (1883/8883/?): "))
            mq['mqtt_clientid_prefix'] = input("CLIENT PREFIX: ")
            mq_user = input("Username: "******"" else mq_user
            mq_pass = input("Password: "******"" else mq_pass
            mq['mqtt_root_topic'] = input("ROOT TOPIC: ")

            print("Writing to file config/mqtt.json")
            with open('config/mqtt.json', 'w') as f:
                ujson.dump(mq, f)

        def mqtt_sub(topic, msg):
            print("MQTT Topic {0}: {1}".format(topic, msg))

        if sele == "mt":
            print("mqtt simple test:")

            print("wifi_config >")
            wifi = WiFiConnect(250)
            wifi.events_add_connecting(connecting_callback)
            wifi.events_add_connected(connected_callback)
            print("wifi.connect")
            wifi_status = wifi.connect()

            # url config: TODO > extern.

            print("mqtt_config >")
            mqtt_clientid_prefix = read_mqtt_config()["mqtt_clientid_prefix"]
            mqtt_host = read_mqtt_config()["mqtt_broker_ip"]
            mqtt_root_topic = read_mqtt_config()["mqtt_root_topic"]
            mqtt_ssl = read_mqtt_config()["mqtt_ssl"]
            mqtt_user = read_mqtt_config()["mqtt_user"]
            mqtt_pass = read_mqtt_config()["mqtt_pass"]

            mqtt_clientid = mqtt_clientid_prefix + esp_id
            c = MQTTClient(mqtt_clientid,
                           mqtt_host,
                           ssl=mqtt_ssl,
                           user=mqtt_user,
                           password=mqtt_pass)
            c.set_callback(mqtt_sub)
            print("mqtt.connect to " + mqtt_host)
            c.connect()
            """
            # c.subscribe("/octopus/device/{0}/#".format(esp_id))
            subStr = mqtt_root_topic+"/"+esp_id+"/#"
            print("subscribe (root topic + esp id):" + subStr)
            c.subscribe(subStr)
            """

            mqtt_log_topic = mqtt_root_topic + "/log"
            print("mqtt log > " + mqtt_log_topic)

            print(mqtt_log_topic)
            # mqtt_root_topic_temp = "octopus/device"
            c.publish(mqtt_log_topic,
                      esp_id)  # topic, message (value) to publish