Exemplo n.º 1
0
def host_server(event=None, callback=None):
    app = picoweb.WebApp(__name__)
    content = []

    @app.route("/liga")
    def index(req, resp):
        yield from picoweb.start_response(resp)
        if req.method == "POST":
            blue.on()
            red.on()
            green.off()
            
        yield from app.render_template(resp, "index.tpl", (req,))

    @app.route("/desliga")
    def index(req, resp):
        yield from picoweb.start_response(resp)
        if req.method == "POST":
            blue.off()
            red.on()
            green.on()
            
        yield from app.render_template(resp, "index.tpl", (req,))

    @app.route("/")
    def index(req, resp):
        yield from picoweb.start_response(resp)
        yield from app.render_template(resp, "index.tpl", (req,))

    import logging as logging
    logging.basicConfig(level=logging.INFO)

    app.run(debug=True, host='0.0.0.0')
    def __init__(self, address, port, debug=-1):
        # debug values:
        # -1 disable all logging
        # 0 (False) normal logging: requests and errors
        # 1 (True) debug logging
        # 2 extra debug logging
        self.debug = debug
        logging.basicConfig(level=logging.DEBUG)
        self.address = address
        self.port = port
        self.ROUTES = [
            # You can specify exact URI string matches...
            ("/", self.index),
            ("/ncsi.txt", self.ncsi),  # microsoft
            ("/connecttest.txt", self.connecttest),  # microsoft
            ("/redirect", self.redirect),  # microsoft
            ("/gen_204", self.redirect),  # android
            ("/generate_204", self.redirect),  # android
            ("/hotspot-detect.html", self.redirect),  # apple
            ("/squares", self.squares),
            ("/file", lambda req, resp:
             (yield from self.app.sendfile(resp, "captiveportal.py"))),
            # ... or match using a regex, the match result available as req.url_match
            # for match group extraction in your view.
            (re.compile("^/iam/(.+)"), self.hello),
        ]

        self.app = picoweb.WebApp("__main__", routes=self.ROUTES)
Exemplo n.º 3
0
def main(name):
    loop = asyncio.get_event_loop()
    loop.create_task(updateValues())

    ROUTES = [
        # You can specify exact URI string matches...
        ("/", lambda req, resp:
         (yield from app.sendfile(resp, "tanque.html"))),
        ("/indicators.js", lambda req, resp:
         (yield from app.sendfile(resp, "indicators.js"))),
        ("/w3.css", lambda req, resp:
         (yield from app.sendfile(resp, "w3.css"))),
        ("/webrepl.html", lambda req, resp:
         (yield from app.sendfile(resp, "webrepl.html"))),
        ("/FileSaver.js", lambda req, resp:
         (yield from app.sendfile(resp, "FileSaver.js"))),
        ("/term.js", lambda req, resp:
         (yield from app.sendfile(resp, "term.js"))),
        ('/get_values', get_values),
        ('/get_indicator_config', sendIndicatorConfigs),
        ('/webrepl', webreplHandle),
    ]
    app = picoweb.WebApp(name, ROUTES)

    # debug values:
    # -1 disable all logging
    # 0 (False) normal logging: requests and errors
    # 1 (True) debug logging
    # 2 extra debug logging
    app.run(host="0.0.0.0", port=80, debug=0)
Exemplo n.º 4
0
    def __init__(self, display_web):
        ROUTES = [
            ("/events", self.events),
        ]

        # logging.basicConfig(level=logging.INFO)
        logging.basicConfig(level=logging.DEBUG)

        self.display_web = display_web
        self.webapp = picoweb.WebApp(__name__, ROUTES)
Exemplo n.º 5
0
def host_server(event=None, callback=None):
    app = picoweb.WebApp(__name__)
    content = []

    @app.route("/confirmacao")
    def index(req, resp):
        yield from picoweb.start_response(resp)
        if req.method == "POST":
            yield from req.read_form_data()
            name = req.form["name"]
            email = req.form["email"]
            yield from app.render_template(resp,
                                           "confirmation.tpl",
                                           args=(req, ))
            nonlocal content
            content = [name, email]
            event.clear()  # limpa o evento _server
        else:
            yield from app.render_template(resp, "404.tpl")

    @app.route("/info")
    def index(req, resp):
        yield from picoweb.start_response(resp)
        if req.method == "POST":
            yield from app.render_template(resp, "info.tpl", (req, ))
            callback.set([content])  # seta o evento _rfid
        else:
            yield from app.render_template(resp, "404.tpl")

    @app.route("/liga")
    def index(req, resp):
        yield from picoweb.start_response(resp)
        if req.method == "POST":
            Pin(18, Pin.OUT).off()
            Pin(19, Pin.OUT).off()
        yield from app.render_template(resp, "index.tpl", (req, ))

    @app.route("/desliga")
    def index(req, resp):
        yield from picoweb.start_response(resp)
        if req.method == "POST":
            Pin(18, Pin.OUT).on()
            Pin(19, Pin.OUT).on()
        yield from app.render_template(resp, "index.tpl", (req, ))

    @app.route("/")
    def index(req, resp):
        yield from picoweb.start_response(resp)
        yield from app.render_template(resp, "index.tpl", (req, ))

    import logging as logging
    logging.basicConfig(level=logging.INFO)

    app.run(debug=True, host='0.0.0.0', event=event)
Exemplo n.º 6
0
    def __init__(self, config, robot, brick):
        self.__config = config
        self.robot = robot
        self.brick = brick
        self.app = picoweb.WebApp("app")
        self.outDict = {'x': 0, 'y': 0, 'a1': 0, 'maxSpeed': 100}
        self.weblock = _thread.allocate_lock()
        self.newData = True

        @self.app.route("/")
        def index(req, resp):
            yield from picoweb.start_response(resp, content_type="text/html")

            htmlFile = open('site/site.html', 'r')

            for line in htmlFile:
                yield from resp.awrite(line)

        @self.app.route("/api")
        def api(req, resp):
            yield from picoweb.start_response(resp, content_type="text/html")

            proc = req.qs.split("&")
            for elm in proc:
                temp = elm.split("=")
                try:
                    self.outDict[temp[0]] = int(temp[1])
                except:
                    self.outDict[temp[0]] = temp[1]
            self.newData = True

        ''' 
            Serving all resources needed for the Webremote
        '''

        @self.app.route("/style.css")
        def style(req, resp):
            yield from picoweb.start_response(resp, content_type="text/css")

            htmlFile = open('site/style.css', 'r')

            for line in htmlFile:
                yield from resp.awrite(line)

        @self.app.route("/code.js")
        def style(req, resp):
            yield from picoweb.start_response(resp,
                                              content_type="text/javascript")

            htmlFile = open('site/code.js', 'r')

            for line in htmlFile:
                yield from resp.awrite(line)
Exemplo n.º 7
0
def static(req, res):
    file = '..' + req.url_match.group(1)
    mime = picoweb.get_mime_type(file)
    app = picoweb.WebApp(__name__)
    if b'gzip' in req.headers[b'Accept-Encoding']:
        gz = file + '.gz'
        try:
            import os
            os.stat(gz)
            yield from app.sendfile(res, gz, mime,
                                    {'Content-Encoding': 'gzip'})
            return
        except OSError:
            pass
    yield from app.sendfile(res, file, mime)
Exemplo n.º 8
0
def main(name):
    loop = asyncio.get_event_loop()
    loop.create_task(clean())

    ROUTES = [
        # You can specify exact URI string matches...
        ("/", lambda req, resp: (yield from app.sendfile(resp, "casa.html"))),
        ('/get_data', get_data),
        ('/get_events', get_events),
        ('/clear_events', clear_events),
        ('/set_alarm', set_alarm),
        ('/ack_error', ack_error),
    ]
    app = picoweb.WebApp(name, ROUTES)

    # debug values:
    # -1 disable all logging
    # 0 (False) normal logging: requests and errors
    # 1 (True) debug logging
    # 2 extra debug logging
    app.run(host="0.0.0.0", port=80, debug=-1)
Exemplo n.º 9
0
def main(name):
    loop = asyncio.get_event_loop()
    loop.create_task(timer())
    loop.create_task(updateDisplay())
    loop.create_task(runController())

    ROUTES = [
        # You can specify exact URI string matches...
        ("/", lambda req, resp: (yield from app.sendfile(resp, "horno.html"))),
        ("/horno.js", lambda req, resp:
         (yield from app.sendfile(resp, "horno.js"))),
        ("/gauge.min.js", lambda req, resp:
         (yield from app.sendfile(resp, "gauge.min.js"))),
        ("/input-knobs.js", lambda req, resp:
         (yield from app.sendfile(resp, "input-knobs.js"))),
        ("/w3.css", lambda req, resp:
         (yield from app.sendfile(resp, "w3.css"))),
        ("/webrepl.html", lambda req, resp:
         (yield from app.sendfile(resp, "webrepl.html"))),
        ("/FileSaver.js", lambda req, resp:
         (yield from app.sendfile(resp, "FileSaver.js"))),
        ("/term.js", lambda req, resp:
         (yield from app.sendfile(resp, "term.js"))),
        ('/set_auto', set_auto),
        ('/set_manual', set_manual),
        ('/get_values', get_values),
        ('/turn_off', turnOFF),
        ('/set_timer', set_timer),
        ('/webrepl', lambda req, resp:
         (yield from app.sendfile(resp, "webrepl.html"))),
    ]
    app = picoweb.WebApp(name, ROUTES)

    # debug values:
    # -1 disable all logging
    # 0 (False) normal logging: requests and errors
    # 1 (True) debug logging
    # 2 extra debug logging
    app.run(host="0.0.0.0", port=80, debug=-1)
Exemplo n.º 10
0
#
# This is an example of running several sub-applications in one bigger
# application, by "mounting" them under specific URLs.
#
import picoweb
import app1, app2

site = picoweb.WebApp(__name__)
site.mount("/app1", app1.app)
site.mount("/app2", app2.app)


@site.route("/")
def index(req, resp):
    yield from picoweb.start_response(resp)
    yield from resp.awrite("<a href='app1'>app1<a> or <a href='app2'>app2</a>")


site.run(debug=True)
Exemplo n.º 11
0
import picoweb
import gpio
import network
import ujson
import wlanauto

app = picoweb.WebApp("SafeGate")
@app.route("/")
def index(req, resp):
    yield from picoweb.start_response(resp)
    htmFile = open('./static/gate.html','r')
    for line in htmFile:
        yield from resp.awrite(b""+line)
    # yield from resp.awrite()

@app.route("/wlancfg")
def wlan_cfg(req, resp):
    yield from picoweb.start_response(resp)
    htmFile = open('./static/wlancfg.html','r')
    for line in htmFile:
        yield from resp.awrite(b""+line)

@app.route("/wlanscan")
def wlan_scan(req, resp):
    yield from picoweb.start_response(resp, content_type = "application/json")
    wlan_sta = network.WLAN(network.STA_IF)
    wlans = wlanauto.wlannearby(wlan_sta)
    wlans = ujson.dumps(wlans)
    yield from resp.awrite(wlans)

@app.route("/wlanconnect")
Exemplo n.º 12
0
# Uncomment to create new databases
#from datastore import data
#data.make_dbs()

from wifiConnect import *

first_run = True
if first_run:
    start_ap()
else:
    do_connect('blynkspot', 'blynkpass')
ip = get_ip()

#ip = "127.0.0.1"

app = picoweb.WebApp(None)


# TODO: Refile classes (or remove them entirely, they may contribute to memory issues?)
class Alert:
    def __init__(self, type='info', message=''):
        self.type = type
        self.message = message


@app.route("/")
def index(req, resp):
    gc.collect()
    f = open("datastore/logger.db", "r+b")
    db = btree.open(f)
    logger = db['service'].decode('utf-8')
Exemplo n.º 13
0
import picoweb
from renderer import Renderer
from wifi import Wifi
from machine import Pin

wifi = Wifi()

wifi.connect()
renderer = Renderer('templates')
app = picoweb.WebApp('onAir')
pins = [Pin(18, Pin.OUT), Pin(5, Pin.OUT), Pin(33, Pin.OUT), Pin(25, Pin.OUT)]
state = False
for pin in pins:
    pin.value(0)


@app.route('/')
def index(req, resp):
    yield from picoweb.start_response(resp)
    yield from resp.awrite(renderer.render_template('template.html'))


@app.route('/recording')
def recording(req, resp):
    if req.method == 'POST':
        yield from req.read_form_data()
    else:
        yield from resp.awrite('Invalid Method')
    if req.form['on'] == "ON":
        for cpin in pins:
            cpin.value(1)
import picoweb
from machine import WDT
from rfid_utils import RFID, Buzzer, GLED, RLED
from webserver import eprint
from uasyncio import sleep, sleep_ms, get_event_loop
from ucollections import namedtuple

##################     RFID-READER SETTINGS     ##################
sse_host = ...
sse_port = ...
picoweb_debug = False
message_to_client = "event: card\ndata: {}\n\n"
app = picoweb.WebApp("app")
wdt = WDT(timeout=30000)
buz = Buzzer()
rfid = RFID()
max_clients = 2

##################     ####################     ##################


# Exception raised by get_nowait().
class QueueEmpty(Exception):
    pass


# Exception raised by put_nowait().
class QueueFull(Exception):
    pass

Exemplo n.º 15
0
import picoweb
from machine import WDT
from rfid_utils import RFID, Buzzer, GLED, RLED
from webserver import eprint
# from config import settings
from uasyncio import sleep, sleep_ms, get_event_loop
from ucollections import namedtuple

##################     RFID-READER SETTINGS     ##################
sse_host = "10.10.0.1"
sse_port = 5000
picoweb_debug = False
message_to_client = "event: card\ndata: {}\n\n"
app = picoweb.WebApp("__name__")
wdt = WDT(timeout=30000)
buz = Buzzer()
rfid = RFID()
max_clients = 2

##################     ####################     ##################


# Exception raised by get_nowait().
class QueueEmpty(Exception):
    pass


# Exception raised by put_nowait().
class QueueFull(Exception):
    pass
Exemplo n.º 16
0
    print("Already connected")
#return
station.active(True)
station.connect(ssid, password)
while station.isconnected() == False:
    pass
    print("Connection successful")
    print(station.ifconfig())

import upip
#upip.install('micropython-uasyncio')
#upip.install('micropython-pkg_resources')

import os
#os.listdir()

import uasyncio
import pkg_resources
#os.mkdir("picoweb")
#os.listdir()

import picoweb
app = picoweb.WebApp(none)


@app.route("/")
def index(req, resp):
    yield from picoweb.start_response(resp)
    yield from resp.awrite("Hello world from picoweb running on the ESP32")
    app.run(debug=True, host="192.168.1.67")
Exemplo n.º 17
0
                    display_text="%s" % str(temp)
                    update_display(display_text)
            await push_event("%d %.3f %.3f %.3f %.3f" % (i,temp_acc,temp,pressure,depth))
            i += 1
        except:
            print("some error?")
        blink(.1)
        gc.collect()
        await uasyncio.sleep(1)


loop = uasyncio.get_event_loop()
loop.create_task(push_count())

#app = picoweb.WebApp(__name__, ROUTES)
app = picoweb.WebApp(None, ROUTES)
# debug values:
# -1 disable all logging
# 0 (False) normal logging: requests and errors
# 1 (True) debug logging
# 2 extra debug logging
print("host:"+ip[0])
if DISPLAY:
    oled.fill(0)
    oled.text("IP ADDRESS:",0,0)
    oled.text(ip[0], 0, 10)
    oled.text(':8081',0,20)
    #oled.text(display_text,0,20)
    oled.show()
    
for i in range(3):
Exemplo n.º 18
0
import picoweb
import time
import network
import uasyncio as asyncio
from wifi_connect import *
from machine import Pin

led = Pin(2, Pin.OUT)

print("Connecting to the network")
connect()
ipaddr = getIPAddress()

print("Starting a simple javascript WEB server")

app = picoweb.WebApp("__main__")


@app.route("/")
@app.route("/dummyLED")
def index(req, resp):
    print(req)
    yield from app.sendfile(resp,
                            'html/dummyLED.html',
                            content_type="text/html")


@app.route("/ledControl")
def index(req, resp):
    print(req)
    yield from app.sendfile(resp,
Exemplo n.º 19
0
    equalSplit = element.split("=")
    parameters[equalSplit[0]] = equalSplit[1]
 
  return parameters
 
#### WiFi Connection
ssid = "Wifi-A"
password = "******"
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
 
while station.isconnected() == False:
  pass
 
ip = station.ifconfig()
 
#### Picoweb app
app = picoweb.WebApp("myApp")
 
@app.route("/query")
def query(req, resp):
    queryString = req.qs
 
    parameters = qs_parse(queryString)
 
    yield from picoweb.start_response(resp)
    yield from resp.awrite("Parameter 1 value: " + parameters["param1"] + "\n")
    yield from resp.awrite("Parameter 2 value: " + parameters["param2"])
 
app.run(debug=True, host =ip[0])
Exemplo n.º 20
0
import gpio
import ddns
import util

pkg = ['ap', 'gpio', 'ddns']
for i in pkg:
  lib = __import__(i)
  lib.model.setup()

routes = [
  ('/cfg', util.handler(config.crud)),
  ('/cfg/reset', util.handler(config.reset)),
  ('/cfg/factory', util.handler(config.factory)),
  ('/sta', util.handler(sta.crud)),
  ('/sta/scan', util.handler(sta.scan)),
  ('/ap', util.handler(ap.ctl.crud)),
  ('/pwm', util.handler(pwm.list)),
  (re.compile('^/pwm/(\w+)$'), util.handler(pwm.crud)),
  (re.compile('^/pwm/(\w+)/duty$'), util.handler(pwm.duty)),
  ('/gpio', util.handler(gpio.ctl.list)),
  (re.compile('^/gpio/(\w+)$'), util.handler(gpio.ctl.crud)),
  (re.compile('^/ddns$'), util.handler(ddns.ctl.crud)),
  (re.compile('^(.*)$'), util.handler(util.static))
]
app = picoweb.WebApp(__name__, routes, False)
app.run(host="0.0.0.0", port=80)

import uasyncio as asyncio
loop = asyncio.get_event_loop()
loop.run_forever()
Exemplo n.º 21
0
    def run(self):
        webapp = picoweb.WebApp(__name__)

        @webapp.route("/list_nodes", methods=['GET', 'POST', 'DELETE'])
        def index(req, resp):
            method = req.method
            self.log.debug("Method %s called", method)
            if method == "GET":
                displayNodes = DBPanNodes()
                nodes = displayNodes.getPanNodesInfo()
                self.log.debug("Number of Nodes: %d", len(nodes))
                queryString = req.qs
                if queryString != "":
                    parameters = qs_parse(queryString)
                    self.log.debug(str(parameters))
                    yield from picoweb.start_response(resp)
                    if 'nodeid' in parameters:
                        if parameters['nodeid'].isdigit():
                            if int(parameters['nodeid']) in nodes:
                                yield from resp.awrite(
                                    str({
                                        int(parameters['nodeid']):
                                        nodes[int(parameters['nodeid'])]
                                    }))
                            else:
                                yield from resp.awrite(
                                    "Cannot get Node with ID: " +
                                    parameters['nodeid'])
                        else:
                            yield from resp.awrite("NodeID not Valid")

                    else:
                        yield from resp.awrite("Not Found NodeID Param")
                else:
                    self.log.debug("Query String is None")
                    yield from picoweb.start_response(resp)
                    yield from resp.awrite(str(nodes))
            elif method == 'POST':
                yield from req.read_form_data()
                nodeid = req.form['nodeid']
                namenode = req.form['name']
                displayNodes = DBPanNodes()
                nodes = displayNodes.getPanNodesInfo()
                self.log.debug(nodes)
                for node in nodes:
                    if str(node) == nodeid:
                        nodes[node]["name"] = namenode
                displayNodes.setPanNodesInfo(nodes)
                yield from picoweb.start_response(resp)
                yield from resp.awrite("Add name of Node " + nodeid)
            elif method == 'DELETE':
                displayNodes = DBPanNodes()
                nodes = displayNodes.getPanNodesInfo()
                yield from req.read_form_data()
                nodeid = req.form['nodeid']
                try:
                    del nodes[nodeid]
                except:
                    pass
                displayNodes.setPanNodesInfo(nodes)
                self.log.debug("Deleted node: %s", nodeid)
                yield from picoweb.start_response(resp)
                yield from resp.awrite("Deleted Node " + str(nodeid))

        @webapp.route('/control', methods=['POST'])
        def control_device(req, resp):
            yield from req.read_form_data()
            nodeid = int(req.form['nodeid'])
            state = req.form['state']
            id_switch = int(req.form['idx'])
            sendMessage(int(nodeid), state, id_switch)
            yield from picoweb.start_response(resp)
            yield from resp.awrite("Controlled Device " + str(nodeid))

        self.log.info("Running on 0.0.0.0:5050...")
        webapp.run(debug=True, host="0.0.0.0", port=5050)
Exemplo n.º 22
0
import picoweb
import network

application = picoweb.WebApp("app")


@app.route("/")
def index(request, response):
    yield from picoweb.start_response(response, content_type="text/html")

    file = open('index.html', 'r')

    for line in file:
        yield from response.awrite(line)


def get_ip():
    wifi = network.WLAN(network.STA_IF)
    if wifi.active():
        address = wifi.ifconfig()[0]
    else:
        wifi = network.WLAN(network.AP_IF)
        if wifi.active():
            address = wifi.ifconfig()[0]
        else:
            print("No active connection")
    return address


host = get_ip()
application.run(debug=True, host=host)
Exemplo n.º 23
0
    def __init__(self, ip, port=80, debug=False):
        self.ip = ip
        self.port = port
        self.debug = debug

        self.joystickX = 0
        self.joystickY = 0

        self.app = picoweb.WebApp("PyRo Webserver")

        @self.app.route("/")
        def index(req, resp):
            print(req)
            yield from picoweb.start_response(resp, content_type="text/html")
            openFile = open('www/index.html', 'r')

            for line in openFile:
                yield from resp.awrite(line)

        @self.app.route("/favicon.ico")
        def favico(req, resp):
            yield from picoweb.start_response(resp,
                                              content_type="image/x-icon")

            openFile = open("www/favicon.ico")

            for line in openFile:
                yield from resp.awrite(line)

        @self.app.route(re.compile('^\/(.+\.html)$'))
        def hyperText(req, resp):
            file_path = req.url_match.group(1)
            print(file_path)

            yield from picoweb.start_response(resp, content_type="text/html")
            openFile = open('www/' + file_path, 'r')

            for line in openFile:
                yield from resp.awrite(line)

        @self.app.route(re.compile('^\/(.+\.css)$'))
        def styleSheet(req, resp):
            file_path = req.url_match.group(1)
            print(file_path)

            yield from picoweb.start_response(resp, content_type="text/css")
            openFile = open('www/' + file_path, 'r')

            for line in openFile:
                yield from resp.awrite(line)

        @self.app.route(re.compile('^\/(.+\.min.js)$'))
        def minJavascript(req, resp):
            file_path = req.url_match.group(1)
            print(file_path)

            yield from picoweb.start_response(
                resp, content_type="application/javascript")
            openFile = open('www/' + file_path, 'r')

            for line in openFile:
                yield from resp.awrite(line)

        @self.app.route(re.compile('^\/(DATA\/joystick:.+)$'))
        def joystick(req, resp):
            joystick = req.url_match.group(1).split('/')[1]

            self.joystickX, self.joystickY = parseJoystick(joystick)

            yield from picoweb.start_response(resp)
Exemplo n.º 24
0
import picoweb
import machine
import time
import ulid2
import _thread

app = picoweb.WebApp("basic ESP32 functionality")

@app.route("/")
def index(req, resp):
    await picoweb.start_response(resp)
    await resp.awrite("Hello world from picoweb running on the ESP32")

def timestamp(t=None):
    return "%04u-%02u-%02uT%02u:%02u:%02u" % time.localtime(t)[0:6]

@app.route("/timestamp")
def index(req, resp):
    await picoweb.start_response(resp)
    await resp.awrite(timestamp())

@app.route("/uid")
def index(req, resp):
    await picoweb.start_response(resp)
    uid = ulid2.encode_ulid_base32(b"\x00"*10+machine.unique_id())[-10:]
    await resp.awrite(uid)


@app.route("/debug")
def index(req,resp):
    open("debug.py", "wb").write("allowed=True")
Exemplo n.º 25
0
import picoweb


def index(req, resp):
    yield from resp.awrite("HTTP/1.0 200 OK\r\n")
    yield from resp.awrite("Content-Type: text/html\r\n")
    yield from resp.awrite("\r\n")
    yield from resp.awrite(
        "I can show you a table of <a href='squares'>squares</a>.")


def squares(req, resp):
    yield from picoweb.start_response(resp)
    yield from app.render_template(resp, "squares.tpl", (req, ))


ROUTES = [
    ("/", index),
    ("/squares", squares),
    ("/file", lambda req, resp:
     (yield from picoweb.sendfile(resp, "picoweb.py"))),
    (re.compile("^/sq"), index),
]

import logging
logging.basicConfig(level=logging.INFO)
#logging.basicConfig(level=logging.DEBUG)

app = picoweb.WebApp(None, routes=ROUTES, gzip_ext='.gz')
app.run(debug=True)
Exemplo n.º 26
0
    # import network
    wlan = network.WLAN(network.STA_IF)
    if not wlan.active() or not wlan.isconnected():
        wlan.active(True)
        print('connecting to:', ssid)
        wlan.connect(ssid, password)
        while not wlan.isconnected():
            pass
    print('network config:', wlan.ifconfig())


wlan_connect('TangyNet', '7thheaven')
dac = MCP492x()
# app = picoweb.WebApp(__name__)
app = picoweb.WebApp(
    None
)  # workaround for sendfile see: https://github.com/pfalcon/picoweb/issues/15


@app.route("/")
def index(req, resp):
    yield from picoweb.start_response(resp)
    html = open('index.html', 'r')
    for line in html.readlines():
        yield from resp.awrite(line)


@app.route("/main.js")
def js_main(req, resp):
    yield from app.sendfile(resp, 'main.js.gz', b"text/javascript",
                            {"Content-Encoding": "gzip"})
Exemplo n.º 27
0
    ("/", lambda req, resp: (yield from app.sendfile(resp, "index.html"))),
    ("/gauge.min.js", lambda req, resp:
     (yield from app.sendfile(resp, "gauge.min.js"))),
    ("/input-knobs.js", lambda req, resp:
     (yield from app.sendfile(resp, "input-knobs.js"))),
    ('/get_rand_number', get_rand_number),
    ('/send_data', receive_data),
]


async def blinkLed():
    while (1):
        led.value(not (led.value()))
        await asyncio.sleep(blinkDelay / 1000.)


import ulogging as logging
logging.basicConfig(level=logging.INFO)
#logging.basicConfig(level=logging.DEBUG)

loop = asyncio.get_event_loop()
loop.create_task(blinkLed())

app = picoweb.WebApp(__name__, ROUTES)
# debug values:
# -1 disable all logging
# 0 (False) normal logging: requests and errors
# 1 (True) debug logging
# 2 extra debug logging
app.run(host="0.0.0.0", port=80, debug=1)
Exemplo n.º 28
0
import camera
import picoweb
import machine
import time
import uasyncio as asyncio
from config import *

led = machine.Pin(app_config['led'], machine.Pin.OUT)
app = picoweb.WebApp('app')

import ulogging as logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger('app')

@app.route('/')
def index(req, resp):

    # parse query string
    req.parse_qs()
    flash = req.form.get('flash', 'false')
    if flash == 'true':
        led.on()
    stream = req.form.get('stream', 'false')
    stream = True if stream == 'true' else False
        
    # Camera resilience - if we fail to init try to deinit and init again
    if app_config['camera'] == 'ESP32-CAM':
        if (not camera.init(0, format=camera.JPEG)):
            camera.deinit()
            await asyncio.sleep(1)
Exemplo n.º 29
0
#
# This is an example of a (sub)application, which can be made a part of
# bigger site using "app mount" feature, see example_app_router.py.
#
import picoweb

app = picoweb.WebApp(__name__)


@app.route("/")
def index(req, resp):
    yield from picoweb.start_response(resp)
    yield from resp.awrite("This is webapp #1")


if __name__ == "__main__":
    app.run(debug=True)
Exemplo n.º 30
0
import machine
import time
rtc = machine.RTC()
output_pin = machine.Pin(32, mode=machine.Pin.OUT, value=0)
input_pin = machine.Pin(39, mode=machine.Pin.IN)
input_pin.irq(lambda p: output_pin(1))

exit_timer = False
on_minutes = [1, 2, 3, 4, 5]

import picoweb

app = picoweb.WebApp("Adjustable timer.")


@app.route("/")
def index(req, resp):
    picoweb.jsonify(on_minutes, resp)


def hourly_timer():
    global exit_timer
    global on_minutes
    global output_pin
    while not exit_timer:
        hours, minutes, seconds, microseconds = rtc.datetime()[-4:]
        if minutes in on_minutes:
            output_pin(1)
        else:
            output_pin(0)
        time.sleep(10)