Restructure: remove old flat src/lib layout
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
20
box.scad
20
box.scad
@@ -1,20 +0,0 @@
|
|||||||
difference() {
|
|
||||||
cube([30,25,20]);
|
|
||||||
//hoop
|
|
||||||
translate([15,12.5,-905]){
|
|
||||||
rotate([90,0,0])
|
|
||||||
rotate_extrude($fn=300)
|
|
||||||
translate([900,0,0])
|
|
||||||
circle(d=25, $fn=100);
|
|
||||||
};
|
|
||||||
//pico
|
|
||||||
translate([3.25,3.5,0])
|
|
||||||
cube([23.5,18,12]);
|
|
||||||
//pico usb port
|
|
||||||
translate([26.75,8,6.5])
|
|
||||||
cube([3.25,9,5.5]);
|
|
||||||
//wifi
|
|
||||||
translate([2.5,5,12])
|
|
||||||
cube([25,15,5]);
|
|
||||||
|
|
||||||
};
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
from microdot.microdot import Microdot, Request, Response, abort, redirect, \
|
|
||||||
send_file # noqa: F401
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
try:
|
|
||||||
from functools import wraps
|
|
||||||
except ImportError: # pragma: no cover
|
|
||||||
# MicroPython does not currently implement functools.wraps
|
|
||||||
def wraps(wrapped):
|
|
||||||
def _(wrapper):
|
|
||||||
return wrapper
|
|
||||||
return _
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,70 +0,0 @@
|
|||||||
from utemplate import recompile
|
|
||||||
|
|
||||||
_loader = None
|
|
||||||
|
|
||||||
|
|
||||||
class Template:
|
|
||||||
"""A template object.
|
|
||||||
|
|
||||||
:param template: The filename of the template to render, relative to the
|
|
||||||
configured template directory.
|
|
||||||
"""
|
|
||||||
@classmethod
|
|
||||||
def initialize(cls, template_dir='templates',
|
|
||||||
loader_class=recompile.Loader):
|
|
||||||
"""Initialize the templating subsystem.
|
|
||||||
|
|
||||||
:param template_dir: the directory where templates are stored. This
|
|
||||||
argument is optional. The default is to load
|
|
||||||
templates from a *templates* subdirectory.
|
|
||||||
:param loader_class: the ``utemplate.Loader`` class to use when loading
|
|
||||||
templates. This argument is optional. The default
|
|
||||||
is the ``recompile.Loader`` class, which
|
|
||||||
automatically recompiles templates when they
|
|
||||||
change.
|
|
||||||
"""
|
|
||||||
global _loader
|
|
||||||
_loader = loader_class(None, template_dir)
|
|
||||||
|
|
||||||
def __init__(self, template):
|
|
||||||
if _loader is None: # pragma: no cover
|
|
||||||
self.initialize()
|
|
||||||
#: The name of the template
|
|
||||||
self.name = template
|
|
||||||
self.template = _loader.load(template)
|
|
||||||
|
|
||||||
def generate(self, *args, **kwargs):
|
|
||||||
"""Return a generator that renders the template in chunks, with the
|
|
||||||
given arguments."""
|
|
||||||
return self.template(*args, **kwargs)
|
|
||||||
|
|
||||||
def render(self, *args, **kwargs):
|
|
||||||
"""Render the template with the given arguments and return it as a
|
|
||||||
string."""
|
|
||||||
return ''.join(self.generate(*args, **kwargs))
|
|
||||||
|
|
||||||
def generate_async(self, *args, **kwargs):
|
|
||||||
"""Return an asynchronous generator that renders the template in
|
|
||||||
chunks, using the given arguments."""
|
|
||||||
class sync_to_async_iter():
|
|
||||||
def __init__(self, iter):
|
|
||||||
self.iter = iter
|
|
||||||
|
|
||||||
def __aiter__(self):
|
|
||||||
return self
|
|
||||||
|
|
||||||
async def __anext__(self):
|
|
||||||
try:
|
|
||||||
return next(self.iter)
|
|
||||||
except StopIteration:
|
|
||||||
raise StopAsyncIteration
|
|
||||||
|
|
||||||
return sync_to_async_iter(self.generate(*args, **kwargs))
|
|
||||||
|
|
||||||
async def render_async(self, *args, **kwargs):
|
|
||||||
"""Render the template with the given arguments asynchronously and
|
|
||||||
return it as a string."""
|
|
||||||
response = ''
|
|
||||||
async for chunk in self.generate_async(*args, **kwargs):
|
|
||||||
response += chunk
|
|
||||||
return response
|
|
||||||
@@ -1,231 +0,0 @@
|
|||||||
import binascii
|
|
||||||
import hashlib
|
|
||||||
from microdot import Request, Response
|
|
||||||
from microdot.microdot import MUTED_SOCKET_ERRORS, print_exception
|
|
||||||
from microdot.helpers import wraps
|
|
||||||
|
|
||||||
|
|
||||||
class WebSocketError(Exception):
|
|
||||||
"""Exception raised when an error occurs in a WebSocket connection."""
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class WebSocket:
|
|
||||||
"""A WebSocket connection object.
|
|
||||||
|
|
||||||
An instance of this class is sent to handler functions to manage the
|
|
||||||
WebSocket connection.
|
|
||||||
"""
|
|
||||||
CONT = 0
|
|
||||||
TEXT = 1
|
|
||||||
BINARY = 2
|
|
||||||
CLOSE = 8
|
|
||||||
PING = 9
|
|
||||||
PONG = 10
|
|
||||||
|
|
||||||
#: Specify the maximum message size that can be received when calling the
|
|
||||||
#: ``receive()`` method. Messages with payloads that are larger than this
|
|
||||||
#: size will be rejected and the connection closed. Set to 0 to disable
|
|
||||||
#: the size check (be aware of potential security issues if you do this),
|
|
||||||
#: or to -1 to use the value set in
|
|
||||||
#: ``Request.max_body_length``. The default is -1.
|
|
||||||
#:
|
|
||||||
#: Example::
|
|
||||||
#:
|
|
||||||
#: WebSocket.max_message_length = 4 * 1024 # up to 4KB messages
|
|
||||||
max_message_length = -1
|
|
||||||
|
|
||||||
def __init__(self, request):
|
|
||||||
self.request = request
|
|
||||||
self.closed = False
|
|
||||||
|
|
||||||
async def handshake(self):
|
|
||||||
response = self._handshake_response()
|
|
||||||
await self.request.sock[1].awrite(
|
|
||||||
b'HTTP/1.1 101 Switching Protocols\r\n')
|
|
||||||
await self.request.sock[1].awrite(b'Upgrade: websocket\r\n')
|
|
||||||
await self.request.sock[1].awrite(b'Connection: Upgrade\r\n')
|
|
||||||
await self.request.sock[1].awrite(
|
|
||||||
b'Sec-WebSocket-Accept: ' + response + b'\r\n\r\n')
|
|
||||||
|
|
||||||
async def receive(self):
|
|
||||||
"""Receive a message from the client."""
|
|
||||||
while True:
|
|
||||||
opcode, payload = await self._read_frame()
|
|
||||||
send_opcode, data = self._process_websocket_frame(opcode, payload)
|
|
||||||
if send_opcode: # pragma: no cover
|
|
||||||
await self.send(data, send_opcode)
|
|
||||||
elif data: # pragma: no branch
|
|
||||||
return data
|
|
||||||
|
|
||||||
async def send(self, data, opcode=None):
|
|
||||||
"""Send a message to the client.
|
|
||||||
|
|
||||||
:param data: the data to send, given as a string or bytes.
|
|
||||||
:param opcode: a custom frame opcode to use. If not given, the opcode
|
|
||||||
is ``TEXT`` or ``BINARY`` depending on the type of the
|
|
||||||
data.
|
|
||||||
"""
|
|
||||||
frame = self._encode_websocket_frame(
|
|
||||||
opcode or (self.TEXT if isinstance(data, str) else self.BINARY),
|
|
||||||
data)
|
|
||||||
await self.request.sock[1].awrite(frame)
|
|
||||||
|
|
||||||
async def close(self):
|
|
||||||
"""Close the websocket connection."""
|
|
||||||
if not self.closed: # pragma: no cover
|
|
||||||
self.closed = True
|
|
||||||
await self.send(b'', self.CLOSE)
|
|
||||||
|
|
||||||
def _handshake_response(self):
|
|
||||||
connection = False
|
|
||||||
upgrade = False
|
|
||||||
websocket_key = None
|
|
||||||
for header, value in self.request.headers.items():
|
|
||||||
h = header.lower()
|
|
||||||
if h == 'connection':
|
|
||||||
connection = True
|
|
||||||
if 'upgrade' not in value.lower():
|
|
||||||
return self.request.app.abort(400)
|
|
||||||
elif h == 'upgrade':
|
|
||||||
upgrade = True
|
|
||||||
if not value.lower() == 'websocket':
|
|
||||||
return self.request.app.abort(400)
|
|
||||||
elif h == 'sec-websocket-key':
|
|
||||||
websocket_key = value
|
|
||||||
if not connection or not upgrade or not websocket_key:
|
|
||||||
return self.request.app.abort(400)
|
|
||||||
d = hashlib.sha1(websocket_key.encode())
|
|
||||||
d.update(b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
|
|
||||||
return binascii.b2a_base64(d.digest())[:-1]
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _parse_frame_header(cls, header):
|
|
||||||
fin = header[0] & 0x80
|
|
||||||
opcode = header[0] & 0x0f
|
|
||||||
if fin == 0 or opcode == cls.CONT: # pragma: no cover
|
|
||||||
raise WebSocketError('Continuation frames not supported')
|
|
||||||
has_mask = header[1] & 0x80
|
|
||||||
length = header[1] & 0x7f
|
|
||||||
if length == 126:
|
|
||||||
length = -2
|
|
||||||
elif length == 127:
|
|
||||||
length = -8
|
|
||||||
return fin, opcode, has_mask, length
|
|
||||||
|
|
||||||
def _process_websocket_frame(self, opcode, payload):
|
|
||||||
if opcode == self.TEXT:
|
|
||||||
payload = payload.decode()
|
|
||||||
elif opcode == self.BINARY:
|
|
||||||
pass
|
|
||||||
elif opcode == self.CLOSE:
|
|
||||||
raise WebSocketError('Websocket connection closed')
|
|
||||||
elif opcode == self.PING:
|
|
||||||
return self.PONG, payload
|
|
||||||
elif opcode == self.PONG: # pragma: no branch
|
|
||||||
return None, None
|
|
||||||
return None, payload
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _encode_websocket_frame(cls, opcode, payload):
|
|
||||||
frame = bytearray()
|
|
||||||
frame.append(0x80 | opcode)
|
|
||||||
if opcode == cls.TEXT:
|
|
||||||
payload = payload.encode()
|
|
||||||
if len(payload) < 126:
|
|
||||||
frame.append(len(payload))
|
|
||||||
elif len(payload) < (1 << 16):
|
|
||||||
frame.append(126)
|
|
||||||
frame.extend(len(payload).to_bytes(2, 'big'))
|
|
||||||
else:
|
|
||||||
frame.append(127)
|
|
||||||
frame.extend(len(payload).to_bytes(8, 'big'))
|
|
||||||
frame.extend(payload)
|
|
||||||
return frame
|
|
||||||
|
|
||||||
async def _read_frame(self):
|
|
||||||
header = await self.request.sock[0].read(2)
|
|
||||||
if len(header) != 2: # pragma: no cover
|
|
||||||
raise WebSocketError('Websocket connection closed')
|
|
||||||
fin, opcode, has_mask, length = self._parse_frame_header(header)
|
|
||||||
if length == -2:
|
|
||||||
length = await self.request.sock[0].read(2)
|
|
||||||
length = int.from_bytes(length, 'big')
|
|
||||||
elif length == -8:
|
|
||||||
length = await self.request.sock[0].read(8)
|
|
||||||
length = int.from_bytes(length, 'big')
|
|
||||||
max_allowed_length = Request.max_body_length \
|
|
||||||
if self.max_message_length == -1 else self.max_message_length
|
|
||||||
if length > max_allowed_length:
|
|
||||||
raise WebSocketError('Message too large')
|
|
||||||
if has_mask: # pragma: no cover
|
|
||||||
mask = await self.request.sock[0].read(4)
|
|
||||||
payload = await self.request.sock[0].read(length)
|
|
||||||
if has_mask: # pragma: no cover
|
|
||||||
payload = bytes(x ^ mask[i % 4] for i, x in enumerate(payload))
|
|
||||||
return opcode, payload
|
|
||||||
|
|
||||||
|
|
||||||
async def websocket_upgrade(request):
|
|
||||||
"""Upgrade a request handler to a websocket connection.
|
|
||||||
|
|
||||||
This function can be called directly inside a route function to process a
|
|
||||||
WebSocket upgrade handshake, for example after the user's credentials are
|
|
||||||
verified. The function returns the websocket object::
|
|
||||||
|
|
||||||
@app.route('/echo')
|
|
||||||
async def echo(request):
|
|
||||||
if not authenticate_user(request):
|
|
||||||
abort(401)
|
|
||||||
ws = await websocket_upgrade(request)
|
|
||||||
while True:
|
|
||||||
message = await ws.receive()
|
|
||||||
await ws.send(message)
|
|
||||||
"""
|
|
||||||
ws = WebSocket(request)
|
|
||||||
await ws.handshake()
|
|
||||||
|
|
||||||
@request.after_request
|
|
||||||
async def after_request(request, response):
|
|
||||||
return Response.already_handled
|
|
||||||
|
|
||||||
return ws
|
|
||||||
|
|
||||||
|
|
||||||
def websocket_wrapper(f, upgrade_function):
|
|
||||||
@wraps(f)
|
|
||||||
async def wrapper(request, *args, **kwargs):
|
|
||||||
ws = await upgrade_function(request)
|
|
||||||
try:
|
|
||||||
await f(request, ws, *args, **kwargs)
|
|
||||||
except OSError as exc:
|
|
||||||
if exc.errno not in MUTED_SOCKET_ERRORS: # pragma: no cover
|
|
||||||
raise
|
|
||||||
except WebSocketError:
|
|
||||||
pass
|
|
||||||
except Exception as exc:
|
|
||||||
print_exception(exc)
|
|
||||||
finally: # pragma: no cover
|
|
||||||
try:
|
|
||||||
await ws.close()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
return Response.already_handled
|
|
||||||
return wrapper
|
|
||||||
|
|
||||||
|
|
||||||
def with_websocket(f):
|
|
||||||
"""Decorator to make a route a WebSocket endpoint.
|
|
||||||
|
|
||||||
This decorator is used to define a route that accepts websocket
|
|
||||||
connections. The route then receives a websocket object as a second
|
|
||||||
argument that it can use to send and receive messages::
|
|
||||||
|
|
||||||
@app.route('/echo')
|
|
||||||
@with_websocket
|
|
||||||
async def echo(request, ws):
|
|
||||||
while True:
|
|
||||||
message = await ws.receive()
|
|
||||||
await ws.send(message)
|
|
||||||
"""
|
|
||||||
return websocket_wrapper(f, websocket_upgrade)
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
class Loader:
|
|
||||||
|
|
||||||
def __init__(self, pkg, dir):
|
|
||||||
if dir == ".":
|
|
||||||
dir = ""
|
|
||||||
else:
|
|
||||||
dir = dir.replace("/", ".") + "."
|
|
||||||
if pkg and pkg != "__main__":
|
|
||||||
dir = pkg + "." + dir
|
|
||||||
self.p = dir
|
|
||||||
|
|
||||||
def load(self, name):
|
|
||||||
name = name.replace(".", "_")
|
|
||||||
return __import__(self.p + name, None, None, (name,)).render
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
# (c) 2014-2020 Paul Sokolovsky. MIT license.
|
|
||||||
try:
|
|
||||||
from uos import stat, remove
|
|
||||||
except:
|
|
||||||
from os import stat, remove
|
|
||||||
from . import source
|
|
||||||
|
|
||||||
|
|
||||||
class Loader(source.Loader):
|
|
||||||
|
|
||||||
def load(self, name):
|
|
||||||
o_path = self.pkg_path + self.compiled_path(name)
|
|
||||||
i_path = self.pkg_path + self.dir + "/" + name
|
|
||||||
try:
|
|
||||||
o_stat = stat(o_path)
|
|
||||||
i_stat = stat(i_path)
|
|
||||||
if i_stat[8] > o_stat[8]:
|
|
||||||
# input file is newer, remove output to force recompile
|
|
||||||
remove(o_path)
|
|
||||||
finally:
|
|
||||||
return super().load(name)
|
|
||||||
@@ -1,188 +0,0 @@
|
|||||||
# (c) 2014-2019 Paul Sokolovsky. MIT license.
|
|
||||||
from . import compiled
|
|
||||||
|
|
||||||
|
|
||||||
class Compiler:
|
|
||||||
|
|
||||||
START_CHAR = "{"
|
|
||||||
STMNT = "%"
|
|
||||||
STMNT_END = "%}"
|
|
||||||
EXPR = "{"
|
|
||||||
EXPR_END = "}}"
|
|
||||||
|
|
||||||
def __init__(self, file_in, file_out, indent=0, seq=0, loader=None):
|
|
||||||
self.file_in = file_in
|
|
||||||
self.file_out = file_out
|
|
||||||
self.loader = loader
|
|
||||||
self.seq = seq
|
|
||||||
self._indent = indent
|
|
||||||
self.stack = []
|
|
||||||
self.in_literal = False
|
|
||||||
self.flushed_header = False
|
|
||||||
self.args = "*a, **d"
|
|
||||||
|
|
||||||
def indent(self, adjust=0):
|
|
||||||
if not self.flushed_header:
|
|
||||||
self.flushed_header = True
|
|
||||||
self.indent()
|
|
||||||
self.file_out.write("def render%s(%s):\n" % (str(self.seq) if self.seq else "", self.args))
|
|
||||||
self.stack.append("def")
|
|
||||||
self.file_out.write(" " * (len(self.stack) + self._indent + adjust))
|
|
||||||
|
|
||||||
def literal(self, s):
|
|
||||||
if not s:
|
|
||||||
return
|
|
||||||
if not self.in_literal:
|
|
||||||
self.indent()
|
|
||||||
self.file_out.write('yield """')
|
|
||||||
self.in_literal = True
|
|
||||||
self.file_out.write(s.replace('"', '\\"'))
|
|
||||||
|
|
||||||
def close_literal(self):
|
|
||||||
if self.in_literal:
|
|
||||||
self.file_out.write('"""\n')
|
|
||||||
self.in_literal = False
|
|
||||||
|
|
||||||
def render_expr(self, e):
|
|
||||||
self.indent()
|
|
||||||
self.file_out.write('yield str(' + e + ')\n')
|
|
||||||
|
|
||||||
def parse_statement(self, stmt):
|
|
||||||
tokens = stmt.split(None, 1)
|
|
||||||
if tokens[0] == "args":
|
|
||||||
if len(tokens) > 1:
|
|
||||||
self.args = tokens[1]
|
|
||||||
else:
|
|
||||||
self.args = ""
|
|
||||||
elif tokens[0] == "set":
|
|
||||||
self.indent()
|
|
||||||
self.file_out.write(stmt[3:].strip() + "\n")
|
|
||||||
elif tokens[0] == "include":
|
|
||||||
if not self.flushed_header:
|
|
||||||
# If there was no other output, we still need a header now
|
|
||||||
self.indent()
|
|
||||||
tokens = tokens[1].split(None, 1)
|
|
||||||
args = ""
|
|
||||||
if len(tokens) > 1:
|
|
||||||
args = tokens[1]
|
|
||||||
if tokens[0][0] == "{":
|
|
||||||
self.indent()
|
|
||||||
# "1" as fromlist param is uPy hack
|
|
||||||
self.file_out.write('_ = __import__(%s.replace(".", "_"), None, None, 1)\n' % tokens[0][2:-2])
|
|
||||||
self.indent()
|
|
||||||
self.file_out.write("yield from _.render(%s)\n" % args)
|
|
||||||
return
|
|
||||||
|
|
||||||
with self.loader.input_open(tokens[0][1:-1]) as inc:
|
|
||||||
self.seq += 1
|
|
||||||
c = Compiler(inc, self.file_out, len(self.stack) + self._indent, self.seq)
|
|
||||||
inc_id = self.seq
|
|
||||||
self.seq = c.compile()
|
|
||||||
self.indent()
|
|
||||||
self.file_out.write("yield from render%d(%s)\n" % (inc_id, args))
|
|
||||||
elif len(tokens) > 1:
|
|
||||||
if tokens[0] == "elif":
|
|
||||||
assert self.stack[-1] == "if"
|
|
||||||
self.indent(-1)
|
|
||||||
self.file_out.write(stmt + ":\n")
|
|
||||||
else:
|
|
||||||
self.indent()
|
|
||||||
self.file_out.write(stmt + ":\n")
|
|
||||||
self.stack.append(tokens[0])
|
|
||||||
else:
|
|
||||||
if stmt.startswith("end"):
|
|
||||||
assert self.stack[-1] == stmt[3:]
|
|
||||||
self.stack.pop(-1)
|
|
||||||
elif stmt == "else":
|
|
||||||
assert self.stack[-1] == "if"
|
|
||||||
self.indent(-1)
|
|
||||||
self.file_out.write("else:\n")
|
|
||||||
else:
|
|
||||||
assert False
|
|
||||||
|
|
||||||
def parse_line(self, l):
|
|
||||||
while l:
|
|
||||||
start = l.find(self.START_CHAR)
|
|
||||||
if start == -1:
|
|
||||||
self.literal(l)
|
|
||||||
return
|
|
||||||
self.literal(l[:start])
|
|
||||||
self.close_literal()
|
|
||||||
sel = l[start + 1]
|
|
||||||
#print("*%s=%s=" % (sel, EXPR))
|
|
||||||
if sel == self.STMNT:
|
|
||||||
end = l.find(self.STMNT_END)
|
|
||||||
assert end > 0
|
|
||||||
stmt = l[start + len(self.START_CHAR + self.STMNT):end].strip()
|
|
||||||
self.parse_statement(stmt)
|
|
||||||
end += len(self.STMNT_END)
|
|
||||||
l = l[end:]
|
|
||||||
if not self.in_literal and l == "\n":
|
|
||||||
break
|
|
||||||
elif sel == self.EXPR:
|
|
||||||
# print("EXPR")
|
|
||||||
end = l.find(self.EXPR_END)
|
|
||||||
assert end > 0
|
|
||||||
expr = l[start + len(self.START_CHAR + self.EXPR):end].strip()
|
|
||||||
self.render_expr(expr)
|
|
||||||
end += len(self.EXPR_END)
|
|
||||||
l = l[end:]
|
|
||||||
else:
|
|
||||||
self.literal(l[start])
|
|
||||||
l = l[start + 1:]
|
|
||||||
|
|
||||||
def header(self):
|
|
||||||
self.file_out.write("# Autogenerated file\n")
|
|
||||||
|
|
||||||
def compile(self):
|
|
||||||
self.header()
|
|
||||||
for l in self.file_in:
|
|
||||||
self.parse_line(l)
|
|
||||||
self.close_literal()
|
|
||||||
return self.seq
|
|
||||||
|
|
||||||
|
|
||||||
class Loader(compiled.Loader):
|
|
||||||
|
|
||||||
def __init__(self, pkg, dir):
|
|
||||||
super().__init__(pkg, dir)
|
|
||||||
self.dir = dir
|
|
||||||
if pkg == "__main__":
|
|
||||||
# if pkg isn't really a package, don't bother to use it
|
|
||||||
# it means we're running from "filesystem directory", not
|
|
||||||
# from a package.
|
|
||||||
pkg = None
|
|
||||||
|
|
||||||
self.pkg_path = ""
|
|
||||||
if pkg:
|
|
||||||
p = __import__(pkg)
|
|
||||||
if isinstance(p.__path__, str):
|
|
||||||
# uPy
|
|
||||||
self.pkg_path = p.__path__
|
|
||||||
else:
|
|
||||||
# CPy
|
|
||||||
self.pkg_path = p.__path__[0]
|
|
||||||
self.pkg_path += "/"
|
|
||||||
|
|
||||||
def input_open(self, template):
|
|
||||||
path = self.pkg_path + self.dir + "/" + template
|
|
||||||
return open(path)
|
|
||||||
|
|
||||||
def compiled_path(self, template):
|
|
||||||
return self.dir + "/" + template.replace(".", "_") + ".py"
|
|
||||||
|
|
||||||
def load(self, name):
|
|
||||||
try:
|
|
||||||
return super().load(name)
|
|
||||||
except (OSError, ImportError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
compiled_path = self.pkg_path + self.compiled_path(name)
|
|
||||||
|
|
||||||
f_in = self.input_open(name)
|
|
||||||
f_out = open(compiled_path, "w")
|
|
||||||
c = Compiler(f_in, f_out, loader=self)
|
|
||||||
c.compile()
|
|
||||||
f_in.close()
|
|
||||||
f_out.close()
|
|
||||||
return super().load(name)
|
|
||||||
19
src/boot.py
19
src/boot.py
@@ -1,19 +0,0 @@
|
|||||||
import wifi
|
|
||||||
import time
|
|
||||||
from settings import Settings
|
|
||||||
|
|
||||||
print(wifi.ap('qwerty'))
|
|
||||||
|
|
||||||
|
|
||||||
settings = Settings()
|
|
||||||
ssid = settings.get('wifi', {}).get('ssid', None)
|
|
||||||
password = settings.get('wifi', {}).get('password', None)
|
|
||||||
ip = settings.get('wifi', {}).get('ip', None)
|
|
||||||
gateway = settings.get('wifi', {}).get('gateway', None)
|
|
||||||
|
|
||||||
# for i in range(10):
|
|
||||||
# config = wifi.connect(ssid, password, ip, gateway)
|
|
||||||
# if config:
|
|
||||||
# print(config)
|
|
||||||
# break
|
|
||||||
# time.sleep(0.1)
|
|
||||||
113
src/dma.py
113
src/dma.py
@@ -1,113 +0,0 @@
|
|||||||
# DMA driver for Raspberry Pi Pico 2 (RP2350) only.
|
|
||||||
from machine import Pin
|
|
||||||
from rp2 import PIO, StateMachine, asm_pio
|
|
||||||
import array
|
|
||||||
import uctypes
|
|
||||||
from uctypes import BF_POS, BF_LEN, UINT32, BFUINT32, struct
|
|
||||||
|
|
||||||
PIO0_BASE = 0x50200000
|
|
||||||
PIO1_BASE = 0x50300000
|
|
||||||
PIO2_BASE = 0x50400000
|
|
||||||
DMA_BASE = 0x50000000
|
|
||||||
DMA_CHAN_WIDTH = 0x40
|
|
||||||
DMA_CHAN_COUNT = 12
|
|
||||||
|
|
||||||
DMA_SIZE_BYTE = 0x0
|
|
||||||
DMA_SIZE_HALFWORD = 0x1
|
|
||||||
DMA_SIZE_WORD = 0x2
|
|
||||||
|
|
||||||
# RP2350 DMA CTRL_TRIG bit positions
|
|
||||||
DMA_CTRL_TRIG_FIELDS = {
|
|
||||||
"AHB_ERROR": 31<<BF_POS | 1<<BF_LEN | BFUINT32,
|
|
||||||
"READ_ERROR": 30<<BF_POS | 1<<BF_LEN | BFUINT32,
|
|
||||||
"WRITE_ERROR": 29<<BF_POS | 1<<BF_LEN | BFUINT32,
|
|
||||||
"BUSY": 26<<BF_POS | 1<<BF_LEN | BFUINT32,
|
|
||||||
"SNIFF_EN": 25<<BF_POS | 1<<BF_LEN | BFUINT32,
|
|
||||||
"BSWAP": 24<<BF_POS | 1<<BF_LEN | BFUINT32,
|
|
||||||
"IRQ_QUIET": 23<<BF_POS | 1<<BF_LEN | BFUINT32,
|
|
||||||
"TREQ_SEL": 17<<BF_POS | 6<<BF_LEN | BFUINT32,
|
|
||||||
"CHAIN_TO": 13<<BF_POS | 4<<BF_LEN | BFUINT32,
|
|
||||||
"RING_SEL": 12<<BF_POS | 1<<BF_LEN | BFUINT32,
|
|
||||||
"RING_SIZE": 8<<BF_POS | 4<<BF_LEN | BFUINT32,
|
|
||||||
"INCR_WRITE": 6<<BF_POS | 1<<BF_LEN | BFUINT32,
|
|
||||||
"INCR_READ": 4<<BF_POS | 1<<BF_LEN | BFUINT32,
|
|
||||||
"DATA_SIZE": 2<<BF_POS | 2<<BF_LEN | BFUINT32,
|
|
||||||
"HIGH_PRIORITY":1<<BF_POS | 1<<BF_LEN | BFUINT32,
|
|
||||||
"EN": 0<<BF_POS | 1<<BF_LEN | BFUINT32
|
|
||||||
}
|
|
||||||
|
|
||||||
DMA_CHAN_REGS = {
|
|
||||||
"READ_ADDR_REG": 0x00|UINT32,
|
|
||||||
"WRITE_ADDR_REG": 0x04|UINT32,
|
|
||||||
"TRANS_COUNT_REG": 0x08|UINT32,
|
|
||||||
"CTRL_TRIG_REG": 0x0c|UINT32,
|
|
||||||
"CTRL_TRIG": (0x0c, DMA_CTRL_TRIG_FIELDS)
|
|
||||||
}
|
|
||||||
|
|
||||||
DMA_REGS = {
|
|
||||||
"INTR": 0x400|UINT32,
|
|
||||||
"INTE0": 0x404|UINT32,
|
|
||||||
"INTF0": 0x408|UINT32,
|
|
||||||
"INTS0": 0x40c|UINT32,
|
|
||||||
"INTE1": 0x414|UINT32,
|
|
||||||
"INTF1": 0x418|UINT32,
|
|
||||||
"INTS1": 0x41c|UINT32,
|
|
||||||
"TIMER0": 0x420|UINT32,
|
|
||||||
"TIMER1": 0x424|UINT32,
|
|
||||||
"TIMER2": 0x428|UINT32,
|
|
||||||
"TIMER3": 0x42c|UINT32,
|
|
||||||
"MULTI_CHAN_TRIGGER": 0x430|UINT32,
|
|
||||||
"SNIFF_CTRL": 0x434|UINT32,
|
|
||||||
"SNIFF_DATA": 0x438|UINT32,
|
|
||||||
"FIFO_LEVELS": 0x440|UINT32,
|
|
||||||
"CHAN_ABORT": 0x444|UINT32
|
|
||||||
}
|
|
||||||
|
|
||||||
DMA_CHANS = [struct(DMA_BASE + n*DMA_CHAN_WIDTH, DMA_CHAN_REGS) for n in range(DMA_CHAN_COUNT)]
|
|
||||||
DMA_DEVICE = struct(DMA_BASE, DMA_REGS)
|
|
||||||
|
|
||||||
PIO_TX_FIFO_OFFSET = 0x10
|
|
||||||
|
|
||||||
# RP2350 DREQ: PIO0_TX=0-3, PIO0_RX=4-7, PIO1_TX=8-11, PIO1_RX=12-15, PIO2_TX=16-19
|
|
||||||
def _pio_base_and_treq(sm_num):
|
|
||||||
"""Return (PIO_BASE, TREQ_SEL) for state machine 0..11."""
|
|
||||||
if sm_num < 4:
|
|
||||||
return (PIO0_BASE, sm_num)
|
|
||||||
if sm_num < 8:
|
|
||||||
return (PIO1_BASE, sm_num + 4)
|
|
||||||
if sm_num < 12:
|
|
||||||
return (PIO2_BASE, sm_num + 8)
|
|
||||||
raise ValueError("state machine index out of range")
|
|
||||||
|
|
||||||
class PIO_DMA_Transfer():
|
|
||||||
def __init__(self, dma_channel, sm_num, block_size, transfer_count):
|
|
||||||
self.dma_chan = DMA_CHANS[dma_channel]
|
|
||||||
self.channel_number = dma_channel
|
|
||||||
|
|
||||||
pio_base, treq_sel = _pio_base_and_treq(sm_num)
|
|
||||||
sm_offset = (sm_num % 4) * 4
|
|
||||||
self.dma_chan.WRITE_ADDR_REG = pio_base + PIO_TX_FIFO_OFFSET + sm_offset
|
|
||||||
self.dma_chan.CTRL_TRIG.TREQ_SEL = treq_sel
|
|
||||||
|
|
||||||
if block_size == 8:
|
|
||||||
self.dma_chan.CTRL_TRIG.DATA_SIZE = DMA_SIZE_BYTE
|
|
||||||
elif block_size == 16:
|
|
||||||
self.dma_chan.CTRL_TRIG.DATA_SIZE = DMA_SIZE_HALFWORD
|
|
||||||
elif block_size == 32:
|
|
||||||
self.dma_chan.CTRL_TRIG.DATA_SIZE = DMA_SIZE_WORD
|
|
||||||
|
|
||||||
self.dma_chan.TRANS_COUNT_REG = transfer_count
|
|
||||||
|
|
||||||
self.dma_chan.CTRL_TRIG.INCR_WRITE = 0
|
|
||||||
self.dma_chan.CTRL_TRIG.INCR_READ = 1
|
|
||||||
self.dma_chan.CTRL_TRIG.CHAIN_TO = dma_channel
|
|
||||||
|
|
||||||
def start_transfer(self, buffer):
|
|
||||||
self.dma_chan.READ_ADDR_REG = uctypes.addressof(buffer)
|
|
||||||
self.dma_chan.CTRL_TRIG.EN = 1
|
|
||||||
|
|
||||||
def transfer_count(self):
|
|
||||||
return self.dma_chan.TRANS_COUNT_REG
|
|
||||||
|
|
||||||
def busy(self):
|
|
||||||
return bool(self.dma_chan.CTRL_TRIG_REG & (1 << 26))
|
|
||||||
34
src/main.py
34
src/main.py
@@ -1,34 +0,0 @@
|
|||||||
|
|
||||||
from time import sleep
|
|
||||||
from neopixel import NeoPixel
|
|
||||||
from machine import UART, Pin, PWM, ADC
|
|
||||||
import _thread
|
|
||||||
import network
|
|
||||||
import espnow
|
|
||||||
|
|
||||||
from patterns import Patterns
|
|
||||||
|
|
||||||
adc = ADC(2, atten=ADC.ATTN_11DB)
|
|
||||||
sta = network.WLAN(network.WLAN.IF_STA) # Or network.WLAN.IF_AP
|
|
||||||
sta.active(True)
|
|
||||||
|
|
||||||
e = espnow.ESPNow()
|
|
||||||
e.active(True)
|
|
||||||
|
|
||||||
#e.add_peer(broadcast)
|
|
||||||
|
|
||||||
p = Patterns()
|
|
||||||
|
|
||||||
_thread.start_new_thread(p.scan_single_led, ((255,0,0),0))
|
|
||||||
|
|
||||||
while True:
|
|
||||||
value = adc.read_uv()*2
|
|
||||||
if value < 3_500_000:
|
|
||||||
p.run = False
|
|
||||||
p.off()
|
|
||||||
print(f"Voltage {value}")
|
|
||||||
sleep(1)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
i = 0
|
|
||||||
@@ -1,95 +0,0 @@
|
|||||||
from machine import Pin
|
|
||||||
from neopixel import NeoPixel
|
|
||||||
import utime
|
|
||||||
import random
|
|
||||||
|
|
||||||
class Patterns:
|
|
||||||
def __init__(self):
|
|
||||||
self.pin_data = (21, 277) # Example: Pin 21, 277 LEDs
|
|
||||||
self.strip = NeoPixel(Pin(self.pin_data[0]), self.pin_data[1])
|
|
||||||
self.run = False
|
|
||||||
|
|
||||||
self.strip.fill((0,0,0))
|
|
||||||
self.strip.write()
|
|
||||||
print(f"Initialized single strip on Pin {self.pin_data[0]} with {self.pin_data[1]} LEDs.")
|
|
||||||
|
|
||||||
|
|
||||||
def scan_single_led(self, color=(255, 255, 255), delay_ms=0):
|
|
||||||
"""
|
|
||||||
Scans a single LED along the length of the strip, turning it on and then off
|
|
||||||
as it moves. Optimized for speed by batching writes.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
color (tuple): The (R, G, B) color of the scanning LED.
|
|
||||||
delay_ms (int): Optional extra delay in milliseconds between each LED position.
|
|
||||||
Set to 0 for fastest possible without *extra* delay.
|
|
||||||
"""
|
|
||||||
self.run = True
|
|
||||||
num_pixels = len(self.strip)
|
|
||||||
last_pixel_index = num_pixels - 1
|
|
||||||
|
|
||||||
# Turn off all pixels initially for a clean start if not already off
|
|
||||||
self.strip.fill((0, 0, 0))
|
|
||||||
# No write here yet, as the first pixel will be set immediately
|
|
||||||
|
|
||||||
while self.run:
|
|
||||||
# --- Scan Forward ---
|
|
||||||
for i in range(num_pixels):
|
|
||||||
if not self.run:
|
|
||||||
break
|
|
||||||
|
|
||||||
# Turn on the current pixel
|
|
||||||
self.strip[i] = color
|
|
||||||
|
|
||||||
# Turn off the previous pixel if not the first one
|
|
||||||
if i > 0:
|
|
||||||
self.strip[i - 1] = (0, 0, 0)
|
|
||||||
# If it's the first pixel, ensure the last one from previous cycle is off (if applicable)
|
|
||||||
elif i == 0 and num_pixels > 1: # Only relevant if scanning backwards too
|
|
||||||
self.strip[last_pixel_index] = (0,0,0)
|
|
||||||
|
|
||||||
|
|
||||||
self.strip.write() # Write changes to the strip
|
|
||||||
if delay_ms > 0:
|
|
||||||
utime.sleep_ms(delay_ms)
|
|
||||||
|
|
||||||
# Ensure the last pixel of the forward scan is turned off
|
|
||||||
if self.run and num_pixels > 0:
|
|
||||||
self.strip[last_pixel_index] = (0, 0, 0)
|
|
||||||
self.strip.write() # Write this final change
|
|
||||||
|
|
||||||
|
|
||||||
# --- Scan Backward (optional, remove this loop if you only want forward) ---
|
|
||||||
for i in range(num_pixels - 1, -1, -1): # From last_pixel_index down to 0
|
|
||||||
if not self.run:
|
|
||||||
break
|
|
||||||
|
|
||||||
# Turn on the current pixel
|
|
||||||
self.strip[i] = color
|
|
||||||
|
|
||||||
# Turn off the next pixel (which was the previous one in reverse scan)
|
|
||||||
if i < last_pixel_index:
|
|
||||||
self.strip[i + 1] = (0, 0, 0)
|
|
||||||
# If it's the last pixel of the reverse scan, ensure the first one from previous cycle is off (if applicable)
|
|
||||||
elif i == last_pixel_index and num_pixels > 1: # Only relevant if scanning forward too
|
|
||||||
self.strip[0] = (0,0,0)
|
|
||||||
|
|
||||||
self.strip.write() # Write changes to the strip
|
|
||||||
if delay_ms > 0:
|
|
||||||
utime.sleep_ms(delay_ms)
|
|
||||||
|
|
||||||
# Ensure the first pixel of the backward scan is turned off
|
|
||||||
if self.run and num_pixels > 0:
|
|
||||||
self.strip[0] = (0, 0, 0)
|
|
||||||
self.strip.write() # Write this final change
|
|
||||||
|
|
||||||
|
|
||||||
def off(self):
|
|
||||||
print("Turning off LEDs.")
|
|
||||||
self.run = False
|
|
||||||
self.strip.fill((0,0,0))
|
|
||||||
self.strip.write()
|
|
||||||
utime.sleep_ms(50)
|
|
||||||
|
|
||||||
# Example Usage (for MicroPython on actual hardware):
|
|
||||||
# (Same as before, just removed from the main block for brevity)
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
import json
|
|
||||||
|
|
||||||
class Settings(dict):
|
|
||||||
SETTINGS_FILE = "/settings.json"
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
super().__init__()
|
|
||||||
self.load() # Load settings from file during initialization
|
|
||||||
|
|
||||||
def set_defaults(self):
|
|
||||||
self["num_leds"] = 50
|
|
||||||
self["selected_pattern"] = "blink"
|
|
||||||
self["color1"] = "#000f00"
|
|
||||||
self["color2"] = "#0f0000"
|
|
||||||
self["delay"] = 100
|
|
||||||
self["brightness"] = 100
|
|
||||||
self["wifi"] = {"ssid": "", "password": ""}
|
|
||||||
|
|
||||||
def save(self):
|
|
||||||
try:
|
|
||||||
j = json.dumps(self)
|
|
||||||
with open(self.SETTINGS_FILE, 'w') as file:
|
|
||||||
file.write(j)
|
|
||||||
print("Settings saved successfully.")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"Error saving settings: {e}")
|
|
||||||
|
|
||||||
def load(self):
|
|
||||||
try:
|
|
||||||
with open(self.SETTINGS_FILE, 'r') as file:
|
|
||||||
loaded_settings = json.load(file)
|
|
||||||
self.update(loaded_settings)
|
|
||||||
print("Settings loaded successfully.")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"Error loading settings")
|
|
||||||
self.set_defaults()
|
|
||||||
|
|
||||||
# Example usage
|
|
||||||
def main():
|
|
||||||
settings = Settings()
|
|
||||||
print(f"Number of LEDs: {settings['num_leds']}")
|
|
||||||
settings['num_leds'] = 100
|
|
||||||
print(f"Updated number of LEDs: {settings['num_leds']}")
|
|
||||||
settings.save()
|
|
||||||
|
|
||||||
# Create a new Settings object to test loading
|
|
||||||
new_settings = Settings()
|
|
||||||
print(f"Loaded number of LEDs: {new_settings['num_leds']}")
|
|
||||||
print(settings)
|
|
||||||
|
|
||||||
# Run the example
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
body {
|
|
||||||
font-family: Arial, sans-serif;
|
|
||||||
max-width: 600px;
|
|
||||||
margin: 0 auto;
|
|
||||||
padding: 20px;
|
|
||||||
line-height: 1.6;
|
|
||||||
}
|
|
||||||
h1 {
|
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
form {
|
|
||||||
margin-bottom: 20px;
|
|
||||||
}
|
|
||||||
label {
|
|
||||||
display: block;
|
|
||||||
margin-bottom: 5px;
|
|
||||||
}
|
|
||||||
input[type="text"], input[type="submit"], input[type="range"], input[type="color"] {
|
|
||||||
width: 100%;
|
|
||||||
|
|
||||||
margin-bottom: 10px;
|
|
||||||
box-sizing: border-box;
|
|
||||||
}
|
|
||||||
input[type="range"] {
|
|
||||||
-webkit-appearance: none;
|
|
||||||
appearance: none;
|
|
||||||
height: 25px;
|
|
||||||
background: #d3d3d3;
|
|
||||||
outline: none;
|
|
||||||
opacity: 0.7;
|
|
||||||
transition: opacity .2s;
|
|
||||||
}
|
|
||||||
input[type="range"]:hover {
|
|
||||||
opacity: 1;
|
|
||||||
}
|
|
||||||
input[type="range"]::-webkit-slider-thumb {
|
|
||||||
-webkit-appearance: none;
|
|
||||||
appearance: none;
|
|
||||||
width: 25px;
|
|
||||||
height: 25px;
|
|
||||||
background: #4CAF50;
|
|
||||||
cursor: pointer;
|
|
||||||
border-radius: 50%;
|
|
||||||
}
|
|
||||||
input[type="range"]::-moz-range-thumb {
|
|
||||||
width: 25px;
|
|
||||||
height: 25px;
|
|
||||||
background: #4CAF50;
|
|
||||||
cursor: pointer;
|
|
||||||
border-radius: 50%;
|
|
||||||
}
|
|
||||||
#pattern_buttons {
|
|
||||||
display: flex;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
gap: 10px;
|
|
||||||
margin-bottom: 20px;
|
|
||||||
}
|
|
||||||
#pattern_buttons button {
|
|
||||||
flex: 1 0 calc(33.333% - 10px);
|
|
||||||
padding: 10px;
|
|
||||||
background-color: #4CAF50;
|
|
||||||
color: white;
|
|
||||||
border: none;
|
|
||||||
cursor: pointer;
|
|
||||||
transition: background-color 0.3s;
|
|
||||||
}
|
|
||||||
#pattern_buttons button:hover {
|
|
||||||
background-color: #45a049;
|
|
||||||
}
|
|
||||||
@media (max-width: 480px) {
|
|
||||||
#pattern_buttons button {
|
|
||||||
flex: 1 0 calc(50% - 10px);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,147 +0,0 @@
|
|||||||
let delayTimeout;
|
|
||||||
let brightnessTimeout;
|
|
||||||
let colorTimeout;
|
|
||||||
let color2Timeout;
|
|
||||||
|
|
||||||
async function post(path, data) {
|
|
||||||
console.log(`POST to ${path}`, data);
|
|
||||||
try {
|
|
||||||
const response = await fetch(path, {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
|
||||||
body: JSON.stringify(data) // Convert data to JSON string
|
|
||||||
});
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`HTTP error! Status: ${response.status}`);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error during POST request:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function get(path) {
|
|
||||||
try {
|
|
||||||
const response = await fetch(path);
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`HTTP error! Status: ${response.status}`);
|
|
||||||
}
|
|
||||||
return await response.json(); // Assuming you are expecting JSON response
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error during GET request:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function updateColor(event) {
|
|
||||||
event.preventDefault();
|
|
||||||
clearTimeout(colorTimeout);
|
|
||||||
colorTimeout = setTimeout(async function() {
|
|
||||||
const color = document.getElementById('color').value;
|
|
||||||
await post("/color", { color }); // Send as JSON
|
|
||||||
}, 500);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function updateColor2(event) {
|
|
||||||
event.preventDefault();
|
|
||||||
clearTimeout(color2Timeout);
|
|
||||||
color2Timeout = setTimeout(async function() {
|
|
||||||
const color = document.getElementById('color2').value;
|
|
||||||
await post("/color2", { color }); // Send as JSON
|
|
||||||
}, 500);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function updatePattern(pattern) {
|
|
||||||
event.preventDefault();
|
|
||||||
await post("/pattern", { pattern }); // Send as JSON
|
|
||||||
}
|
|
||||||
|
|
||||||
async function updateBrightness(event) {
|
|
||||||
event.preventDefault();
|
|
||||||
clearTimeout(brightnessTimeout);
|
|
||||||
brightnessTimeout = setTimeout(async function() {
|
|
||||||
const brightness = document.getElementById('brightness').value;
|
|
||||||
await post('/brightness', { brightness }); // Send as JSON
|
|
||||||
}, 500);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function updateDelay(event) {
|
|
||||||
event.preventDefault();
|
|
||||||
clearTimeout(delayTimeout);
|
|
||||||
delayTimeout = setTimeout(async function() {
|
|
||||||
const delay = document.getElementById('delay').value;
|
|
||||||
await post('/delay', { delay }); // Send as JSON
|
|
||||||
}, 500);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function updateNumLeds(event) {
|
|
||||||
event.preventDefault();
|
|
||||||
const numLeds = document.getElementById('num_leds').value;
|
|
||||||
await post('/num_leds', { num_leds: numLeds }); // Send as JSON
|
|
||||||
}
|
|
||||||
|
|
||||||
async function updateWifi(event) {
|
|
||||||
event.preventDefault();
|
|
||||||
const ssid = document.getElementById('ssid').value;
|
|
||||||
const password = document.getElementById('password').value;
|
|
||||||
const ip = document.getElementById('ip').value;
|
|
||||||
const gateway = document.getElementById('gateway').value;
|
|
||||||
|
|
||||||
const wifiSettings = { ssid, password, ip, gateway }; // Create JSON object
|
|
||||||
console.log(wifiSettings);
|
|
||||||
const response = await post('/wifi_settings', wifiSettings); // Send as JSON
|
|
||||||
if (response === 500) {
|
|
||||||
alert("Failed to connect to Wi-Fi");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function createPatternButtons(patterns) {
|
|
||||||
const container = document.getElementById('pattern_buttons');
|
|
||||||
container.innerHTML = ''; // Clear previous buttons
|
|
||||||
|
|
||||||
patterns.forEach(pattern => {
|
|
||||||
const button = document.createElement('button');
|
|
||||||
button.type = 'button'; // Use 'button' instead of 'submit'
|
|
||||||
button.textContent = pattern;
|
|
||||||
button.value = pattern;
|
|
||||||
button.addEventListener('click', async function(event) {
|
|
||||||
event.preventDefault();
|
|
||||||
await updatePattern(pattern);
|
|
||||||
});
|
|
||||||
container.appendChild(button);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', async function() {
|
|
||||||
document.getElementById('color').addEventListener('input', updateColor);
|
|
||||||
document.getElementById('color2').addEventListener('input', updateColor2);
|
|
||||||
document.getElementById('delay').addEventListener('input', updateDelay);
|
|
||||||
document.getElementById('brightness').addEventListener('input', updateBrightness);
|
|
||||||
document.getElementById('num_leds_form').addEventListener('submit', updateNumLeds);
|
|
||||||
document.getElementById('wifi_form').addEventListener('submit', updateWifi);
|
|
||||||
document.getElementById('delay').addEventListener('touchend', updateDelay);
|
|
||||||
document.getElementById('brightness').addEventListener('touchend', updateBrightness);
|
|
||||||
|
|
||||||
document.querySelectorAll(".pattern_button").forEach(button => {
|
|
||||||
console.log(button.value);
|
|
||||||
button.addEventListener('click', async event => {
|
|
||||||
event.preventDefault();
|
|
||||||
await updatePattern(button.value);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// Function to toggle the display of the settings menu
|
|
||||||
function selectSettings() {
|
|
||||||
const settingsMenu = document.getElementById('settings_menu');
|
|
||||||
controls = document.getElementById('controls');
|
|
||||||
settingsMenu.style.display = 'block';
|
|
||||||
controls.style.display = 'none';
|
|
||||||
}
|
|
||||||
|
|
||||||
function selectControls() {
|
|
||||||
const settingsMenu = document.getElementById('settings_menu');
|
|
||||||
controls = document.getElementById('controls');
|
|
||||||
settingsMenu.style.display = 'none';
|
|
||||||
controls.style.display = 'block';
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
{% args settings, patterns %}
|
|
||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8">
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
||||||
<title>LED Control</title>
|
|
||||||
<script src="static/main.js"></script>
|
|
||||||
<link rel="stylesheet" href="static/main.css">
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<h1>Control LEDs</h1>
|
|
||||||
<button onclick="selectControls()">Controls</button>
|
|
||||||
<button onclick="selectSettings()">Settings</button>
|
|
||||||
|
|
||||||
<!-- Main LED Controls -->
|
|
||||||
<div id="controls">
|
|
||||||
<div id="pattern_buttons">
|
|
||||||
{% for p in patterns %}
|
|
||||||
<button class="pattern_button" value="{{p}}">{{p}}</button>
|
|
||||||
{% endfor %}
|
|
||||||
|
|
||||||
<!-- Pattern buttons will be inserted here -->
|
|
||||||
</div>
|
|
||||||
<form id="delay_form" method="post" action="/delay">
|
|
||||||
<label for="delay">Delay:</label>
|
|
||||||
<input type="range" id="delay" name="delay" min="1" max="1000" value="{{settings['delay']}}" step="10">
|
|
||||||
</form>
|
|
||||||
<form id="brightness_form" method="post" action="/brightness">
|
|
||||||
<label for="brightness">Brightness:</label>
|
|
||||||
<input type="range" id="brightness" name="brightness" min="0" max="100" value="{{settings['brightness']}}" step="1">
|
|
||||||
</form>
|
|
||||||
<form id="color_form" method="post" action="/color">
|
|
||||||
<input type="color" id="color" name="color" value="{{settings['color1']}}">
|
|
||||||
</form>
|
|
||||||
<form id="color2_form" method="post" action="/color2">
|
|
||||||
<input type="color" id="color2" name="color2" value="{{settings['color2']}}">
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
# Autogenerated file
|
|
||||||
def render(settings, patterns):
|
|
||||||
yield """<!DOCTYPE html>
|
|
||||||
<html lang=\"en\">
|
|
||||||
<head>
|
|
||||||
<meta charset=\"UTF-8\">
|
|
||||||
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
|
|
||||||
<title>LED Control</title>
|
|
||||||
<script src=\"static/main.js\"></script>
|
|
||||||
<link rel=\"stylesheet\" href=\"static/main.css\">
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<h1>Control LEDs</h1>
|
|
||||||
<button onclick=\"selectControls()\">Controls</button>
|
|
||||||
<button onclick=\"selectSettings()\">Settings</button>
|
|
||||||
|
|
||||||
<!-- Main LED Controls -->
|
|
||||||
<div id=\"controls\">
|
|
||||||
<div id=\"pattern_buttons\">
|
|
||||||
"""
|
|
||||||
for p in patterns:
|
|
||||||
yield """ <button class=\"pattern_button\" value=\""""
|
|
||||||
yield str(p)
|
|
||||||
yield """\">"""
|
|
||||||
yield str(p)
|
|
||||||
yield """</button>
|
|
||||||
"""
|
|
||||||
yield """
|
|
||||||
<!-- Pattern buttons will be inserted here -->
|
|
||||||
</div>
|
|
||||||
<form id=\"delay_form\" method=\"post\" action=\"/delay\">
|
|
||||||
<label for=\"delay\">Delay:</label>
|
|
||||||
<input type=\"range\" id=\"delay\" name=\"delay\" min=\"1\" max=\"1000\" value=\""""
|
|
||||||
yield str(settings['delay'])
|
|
||||||
yield """\" step=\"10\">
|
|
||||||
</form>
|
|
||||||
<form id=\"brightness_form\" method=\"post\" action=\"/brightness\">
|
|
||||||
<label for=\"brightness\">Brightness:</label>
|
|
||||||
<input type=\"range\" id=\"brightness\" name=\"brightness\" min=\"0\" max=\"100\" value=\""""
|
|
||||||
yield str(settings['brightness'])
|
|
||||||
yield """\" step=\"1\">
|
|
||||||
</form>
|
|
||||||
<form id=\"color_form\" method=\"post\" action=\"/color\">
|
|
||||||
<input type=\"color\" id=\"color\" name=\"color\" value=\""""
|
|
||||||
yield str(settings['color1'])
|
|
||||||
yield """\">
|
|
||||||
</form>
|
|
||||||
<form id=\"color2_form\" method=\"post\" action=\"/color2\">
|
|
||||||
<input type=\"color\" id=\"color2\" name=\"color2\" value=\""""
|
|
||||||
yield str(settings['color2'])
|
|
||||||
yield """\">
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Settings Menu for num_leds, Wi-Fi SSID, and Password -->
|
|
||||||
|
|
||||||
<div id=\"settings_menu\" style=\"display: none;\">
|
|
||||||
<h2>Settings</h2>
|
|
||||||
|
|
||||||
<!-- Separate form for submitting num_leds -->
|
|
||||||
<form id=\"num_leds_form\" method=\"post\" action=\"/num_leds\">
|
|
||||||
<label for=\"num_leds\">Number of LEDs:</label>
|
|
||||||
<input type=\"text\" id=\"num_leds\" name=\"num_leds\" value=\""""
|
|
||||||
yield str(settings['num_leds'])
|
|
||||||
yield """\">
|
|
||||||
<input type=\"submit\" value=\"Update Number of LEDs\">
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<!-- Form for Wi-Fi SSID and password -->
|
|
||||||
<form id=\"wifi_form\" method=\"post\" action=\"/wifi_settings\">
|
|
||||||
<label for=\"ssid\">Wi-Fi SSID:</label>
|
|
||||||
<input type=\"text\" id=\"ssid\" name=\"ssid\" value=\""""
|
|
||||||
yield str(settings['wifi']['ssid'])
|
|
||||||
yield """\">
|
|
||||||
<br>
|
|
||||||
<label for=\"password\">Wi-Fi Password:</label>
|
|
||||||
<input type=\"password\" id=\"password\" name=\"password\">
|
|
||||||
<br>
|
|
||||||
<label for=\"ip\">Wi-Fi IP:</label>
|
|
||||||
<input type=\"ip\" id=\"ip\" name=\"ip\" value=\""""
|
|
||||||
yield str(settings.get('wifi', {}).get('ip', ''))
|
|
||||||
yield """\">
|
|
||||||
<br>
|
|
||||||
<label for=\"gateway\">Wi-Fi Gateway:</label>
|
|
||||||
<input type=\"gateway\" id=\"gateway\" name=\"gateway\" value=\""""
|
|
||||||
yield str(settings.get('wifi', {}).get('gateway', ''))
|
|
||||||
yield """\">
|
|
||||||
<br>
|
|
||||||
<input type=\"submit\" value=\"Save Wi-Fi Settings\">
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
"""
|
|
||||||
101
src/web.py
101
src/web.py
@@ -1,101 +0,0 @@
|
|||||||
from microdot import Microdot, send_file, Response
|
|
||||||
from microdot.utemplate import Template
|
|
||||||
from microdot.websocket import with_websocket
|
|
||||||
|
|
||||||
import json
|
|
||||||
import wifi
|
|
||||||
|
|
||||||
def web(settings, patterns, patterns2):
|
|
||||||
app = Microdot()
|
|
||||||
Response.default_content_type = 'text/html'
|
|
||||||
|
|
||||||
@app.route('/')
|
|
||||||
async def index(request):
|
|
||||||
return Template('/index.html').render(settings=settings, patterns=patterns.patterns.keys())
|
|
||||||
|
|
||||||
@app.route("/static/<path:path>")
|
|
||||||
def static(request, path):
|
|
||||||
if '..' in path:
|
|
||||||
# Directory traversal is not allowed
|
|
||||||
return 'Not found', 404
|
|
||||||
return send_file('static/' + path)
|
|
||||||
|
|
||||||
@app.post("/pattern")
|
|
||||||
def pattern(request):
|
|
||||||
try:
|
|
||||||
data = json.loads(request.body.decode('utf-8'))
|
|
||||||
pattern = data["pattern"]
|
|
||||||
if patterns.select(pattern):
|
|
||||||
patterns2.select(pattern)
|
|
||||||
settings["selected_pattern"] = pattern
|
|
||||||
settings.save()
|
|
||||||
return "OK", 200
|
|
||||||
else:
|
|
||||||
return "Bad request", 400
|
|
||||||
except (KeyError, json.JSONDecodeError):
|
|
||||||
return "Bad request", 400
|
|
||||||
|
|
||||||
@app.post("/delay")
|
|
||||||
def delay(request):
|
|
||||||
try:
|
|
||||||
data = json.loads(request.body.decode('utf-8'))
|
|
||||||
delay = int(data["delay"])
|
|
||||||
patterns.set_delay(delay)
|
|
||||||
patterns2.set_delay(delay)
|
|
||||||
settings["delay"] = delay
|
|
||||||
settings.save()
|
|
||||||
return "OK", 200
|
|
||||||
except (ValueError, KeyError, json.JSONDecodeError):
|
|
||||||
return "Bad request", 400
|
|
||||||
|
|
||||||
@app.post("/brightness")
|
|
||||||
def brightness(request):
|
|
||||||
try:
|
|
||||||
data = json.loads(request.body.decode('utf-8'))
|
|
||||||
brightness = int(data["brightness"])
|
|
||||||
patterns.set_brightness(brightness)
|
|
||||||
patterns2.set_brightness(brightness)
|
|
||||||
settings["brightness"] = brightness
|
|
||||||
settings.save()
|
|
||||||
return "OK", 200
|
|
||||||
except (ValueError, KeyError, json.JSONDecodeError):
|
|
||||||
return "Bad request", 400
|
|
||||||
|
|
||||||
@app.post("/color")
|
|
||||||
def color(request):
|
|
||||||
try:
|
|
||||||
data = json.loads(request.body.decode('utf-8'))
|
|
||||||
color = data["color"]
|
|
||||||
patterns.set_color1(tuple(int(color[i:i+2], 16) for i in (1, 3, 5))) # Convert hex to RGB
|
|
||||||
patterns2.set_color1(tuple(int(color[i:i+2], 16) for i in (1, 3, 5))) # Convert hex to RGB
|
|
||||||
settings["color1"] = color
|
|
||||||
settings.save()
|
|
||||||
return "OK", 200
|
|
||||||
except (KeyError, json.JSONDecodeError, ValueError):
|
|
||||||
return "Bad request", 400
|
|
||||||
|
|
||||||
@app.post("/color2")
|
|
||||||
def color2(request):
|
|
||||||
try:
|
|
||||||
data = json.loads(request.body.decode('utf-8'))
|
|
||||||
color = data["color2"]
|
|
||||||
patterns.set_color2(tuple(int(color[i:i+2], 16) for i in (1, 3, 5))) # Convert hex to RGB
|
|
||||||
patterns2.set_color2(tuple(int(color[i:i+2], 16) for i in (1, 3, 5))) # Convert hex to RGB
|
|
||||||
settings["color2"] = color
|
|
||||||
settings.save()
|
|
||||||
return "OK", 200
|
|
||||||
except (KeyError, json.JSONDecodeError, ValueError):
|
|
||||||
return "Bad request", 400
|
|
||||||
|
|
||||||
@app.route("/external")
|
|
||||||
@with_websocket
|
|
||||||
async def ws(request, ws):
|
|
||||||
patterns.select("external")
|
|
||||||
while True:
|
|
||||||
data = await ws.receive()
|
|
||||||
print(data)
|
|
||||||
for i in range(min(patterns.num_leds, int(len(data)/3))):
|
|
||||||
patterns.set(i, (data[i*3], data[i*3+1], data[i*3+2]))
|
|
||||||
patterns.write()
|
|
||||||
|
|
||||||
return app
|
|
||||||
46
src/wifi.py
46
src/wifi.py
@@ -1,46 +0,0 @@
|
|||||||
import network
|
|
||||||
from machine import Pin
|
|
||||||
from time import sleep
|
|
||||||
import ubinascii
|
|
||||||
from settings import Settings
|
|
||||||
|
|
||||||
def connect(ssid, password, ip, gateway):
|
|
||||||
if ssid is None or password is None:
|
|
||||||
print("Missing ssid or password")
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
sta_if = network.WLAN(network.STA_IF)
|
|
||||||
if ip is not None and gateway is not None:
|
|
||||||
sta_if.ifconfig((ip, '255.255.255.0', gateway, '1.1.1.1'))
|
|
||||||
if not sta_if.isconnected():
|
|
||||||
print('connecting to network...')
|
|
||||||
sta_if.active(True)
|
|
||||||
sta_if.connect(ssid, password)
|
|
||||||
sleep(0.1)
|
|
||||||
if sta_if.isconnected():
|
|
||||||
return sta_if.ifconfig()
|
|
||||||
return None
|
|
||||||
return sta_if.ifconfig()
|
|
||||||
except Exception as e:
|
|
||||||
print(f"Failed to connect to wifi {e}")
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def ap(password):
|
|
||||||
ap_if = network.WLAN(network.AP_IF)
|
|
||||||
ap_mac = ap_if.config('mac')
|
|
||||||
ssid = f"led-{ubinascii.hexlify(ap_mac).decode()}"
|
|
||||||
print(ssid)
|
|
||||||
ap_if.active(True)
|
|
||||||
ap_if.config(essid=ssid, password="qwerty1234")
|
|
||||||
ap_if.active(False)
|
|
||||||
ap_if.active(True)
|
|
||||||
print(ap_if.ifconfig())
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
|
|
||||||
import array, time
|
|
||||||
from machine import Pin
|
|
||||||
import rp2
|
|
||||||
from time import sleep
|
|
||||||
import dma
|
|
||||||
|
|
||||||
@rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW, out_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=True, pull_thresh=8)
|
|
||||||
def ws2812():
|
|
||||||
T1 = 2
|
|
||||||
T2 = 5
|
|
||||||
T3 = 3
|
|
||||||
wrap_target()
|
|
||||||
label("bitloop")
|
|
||||||
out(x, 1) .side(0) [T3 - 1]
|
|
||||||
jmp(not_x, "do_zero") .side(1) [T1 - 1]
|
|
||||||
jmp("bitloop") .side(1) [T2 - 1]
|
|
||||||
label("do_zero")
|
|
||||||
nop() .side(0) [T2 - 1]
|
|
||||||
wrap()
|
|
||||||
|
|
||||||
class WS2812B:
|
|
||||||
def __init__(self, num_leds, pin, state_machine, brightness=0.1, invert=False):
|
|
||||||
self.sm = rp2.StateMachine(state_machine, ws2812, freq=8_000_000, sideset_base=Pin(pin))
|
|
||||||
self.sm.active(1)
|
|
||||||
self.ar = bytearray(num_leds*3)
|
|
||||||
self.num_leds = num_leds
|
|
||||||
self.brightness = brightness
|
|
||||||
self.invert = invert
|
|
||||||
self.pio_dma = dma.PIO_DMA_Transfer(state_machine+4, state_machine, 8, num_leds*3)
|
|
||||||
|
|
||||||
def show(self):
|
|
||||||
self.pio_dma.start_transfer(self.ar)
|
|
||||||
|
|
||||||
def set(self, i, color):
|
|
||||||
self.ar[i*3] = int(color[1]*self.brightness)
|
|
||||||
self.ar[i*3+1] = int(color[0]*self.brightness)
|
|
||||||
self.ar[i*3+2] = int(color[2]*self.brightness)
|
|
||||||
|
|
||||||
def fill(self, color):
|
|
||||||
for i in range(self.num_leds):
|
|
||||||
self.set(i, color)
|
|
||||||
|
|
||||||
def busy(self):
|
|
||||||
return self.pio_dma.busy()
|
|
||||||
|
|
||||||
BLACK = (0, 0, 0)
|
|
||||||
RED = (255, 0, 0)
|
|
||||||
YELLOW = (255, 150, 0)
|
|
||||||
GREEN = (0, 255, 0)
|
|
||||||
CYAN = (0, 255, 255)
|
|
||||||
BLUE = (0, 0, 255)
|
|
||||||
PURPLE = (180, 0, 255)
|
|
||||||
WHITE = (255, 255, 255)
|
|
||||||
COLORS = (BLACK, RED, YELLOW, GREEN, CYAN, BLUE, PURPLE, WHITE)
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
num_leds, pin, sm, brightness = 10, 0, 0, 1
|
|
||||||
ws0 = WS2812B(num_leds, pin, sm, brightness)
|
|
||||||
while True:
|
|
||||||
for color in ws0.COLORS:
|
|
||||||
ws0.fill(color)
|
|
||||||
ws0.show()
|
|
||||||
time.sleep(1)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Reference in New Issue
Block a user