Compare commits
3 Commits
d45846ec74
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| af9b63565a | |||
| e1b844241d | |||
| 14b87f40ef |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,3 +1,2 @@
|
|||||||
settings.json
|
settings.json
|
||||||
.venv
|
.venv
|
||||||
__pycache__
|
|
||||||
2
dev.py
2
dev.py
@@ -28,8 +28,6 @@ for cmd in sys.argv[1:]:
|
|||||||
if ser.in_waiting > 0: # Check if there is data in the buffer
|
if ser.in_waiting > 0: # Check if there is data in the buffer
|
||||||
data = ser.readline().decode('utf-8').strip() # Read and decode the data
|
data = ser.readline().decode('utf-8').strip() # Read and decode the data
|
||||||
print(data)
|
print(data)
|
||||||
case "clean":
|
|
||||||
subprocess.call(["mpremote", "connect", port, "fs", "rm", ":/settings.json"])
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -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)
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 26 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 26 KiB |
@@ -1,9 +0,0 @@
|
|||||||
import settings
|
|
||||||
import wifi
|
|
||||||
from settings import Settings
|
|
||||||
|
|
||||||
s = Settings()
|
|
||||||
|
|
||||||
name = s.get('name', 'led')
|
|
||||||
password = s.get("ap_password", "")
|
|
||||||
wifi.ap(name, password)
|
|
||||||
100
src/main.py
100
src/main.py
@@ -1,51 +1,79 @@
|
|||||||
import asyncio
|
|
||||||
import aioespnow
|
|
||||||
from settings import Settings
|
from settings import Settings
|
||||||
from web import web
|
from web import web
|
||||||
from patterns import Patterns
|
from patterns import Patterns
|
||||||
import gc
|
import gc
|
||||||
import utime
|
|
||||||
import machine
|
|
||||||
import time
|
|
||||||
import wifi
|
|
||||||
import json
|
import json
|
||||||
from p2p import p2p
|
import espnow
|
||||||
|
import network
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import machine
|
||||||
|
|
||||||
async def main():
|
def main():
|
||||||
settings = Settings()
|
settings = Settings()
|
||||||
|
|
||||||
patterns = Patterns(settings["led_pin"], settings["num_leds"], selected=settings["pattern"])
|
|
||||||
if settings["color_order"] == "rbg":
|
|
||||||
color_order = (1, 5, 3)
|
|
||||||
print("RBG")
|
|
||||||
if settings["color_order"] == "grb":
|
|
||||||
color_order = (3, 1, 5)
|
|
||||||
else: color_order = (1, 3, 5)
|
|
||||||
patterns.colors = [(8,0,0)]
|
|
||||||
|
|
||||||
async def system():
|
|
||||||
while True:
|
|
||||||
gc.collect()
|
|
||||||
for i in range(60):
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep(1)
|
|
||||||
|
|
||||||
w = web(settings, patterns)
|
|
||||||
print(settings)
|
print(settings)
|
||||||
# start the server in a bacakground task
|
|
||||||
print("Starting")
|
if settings.get("color_order", "rgb") == "rbg":
|
||||||
server = asyncio.create_task(w.start_server(host="0.0.0.0", port=80))
|
color_order = (1, 5, 3)
|
||||||
|
else:
|
||||||
|
color_order = (1, 3, 5)
|
||||||
|
patterns = Patterns(settings["led_pin"], settings["num_leds"], brightness=255)
|
||||||
|
|
||||||
|
sta_if = network.WLAN(network.STA_IF)
|
||||||
|
sta_if.active(True)
|
||||||
|
|
||||||
|
e = espnow.ESPNow()
|
||||||
|
e.config(rxbuf=1024)
|
||||||
|
e.active(True)
|
||||||
|
# Increase buffer size for 8-bar payloads (default 526 bytes might be too small) # Set to 1KB to handle larger multi-bar payloads
|
||||||
|
|
||||||
wdt = machine.WDT(timeout=10000)
|
wdt = machine.WDT(timeout=10000)
|
||||||
wdt.feed()
|
wdt.feed()
|
||||||
|
|
||||||
asyncio.create_task(p2p(settings, patterns))
|
#print mac in hex
|
||||||
asyncio.create_task(system())
|
print("Mac address", sta_if.config("mac").hex())
|
||||||
patterns.select(settings["pattern"])
|
print("Patterns", patterns.colors)
|
||||||
await patterns.run()
|
print("Patterns", patterns.selected)
|
||||||
|
|
||||||
|
patterns.select(patterns.selected)
|
||||||
|
while True:
|
||||||
|
# advance pattern based on its own returned schedule
|
||||||
|
# due = patterns.tick(due)
|
||||||
|
wdt.feed()
|
||||||
|
patterns.tick()
|
||||||
|
# Drain all pending packets and only process the latest
|
||||||
|
last_msg = None
|
||||||
|
while True:
|
||||||
|
|
||||||
|
host, msg = e.recv(0)
|
||||||
|
if not msg:
|
||||||
|
break
|
||||||
|
last_msg = msg
|
||||||
|
|
||||||
# cleanup before ending the application
|
if last_msg:
|
||||||
await server
|
try:
|
||||||
|
data = json.loads(last_msg)
|
||||||
|
print(data)
|
||||||
|
|
||||||
asyncio.run(main())
|
# Always update parameters from message
|
||||||
|
patterns.brightness = data.get("brightness", patterns.brightness)
|
||||||
|
patterns.delay = data.get("delay", patterns.delay)
|
||||||
|
patterns.colors = data.get("colors", patterns.colors)
|
||||||
|
patterns.selected = data.get("pattern", patterns.selected)
|
||||||
|
patterns.n1 = data.get("n1", patterns.n1)
|
||||||
|
patterns.n2 = data.get("n2", patterns.n2)
|
||||||
|
patterns.n3 = data.get("n3", patterns.n3)
|
||||||
|
patterns.n4 = data.get("n4", patterns.n4)
|
||||||
|
patterns.step = data.get("step", patterns.step)
|
||||||
|
patterns.auto = data.get("auto", patterns.auto)
|
||||||
|
|
||||||
|
patterns.select(patterns.selected)
|
||||||
|
print("Selected pattern", patterns.selected)
|
||||||
|
|
||||||
|
except Exception as ex:
|
||||||
|
print(f"Failed to load espnow data {last_msg}: {ex}")
|
||||||
|
continue
|
||||||
|
finally:
|
||||||
|
gc.collect()
|
||||||
|
main()
|
||||||
|
|||||||
16
src/p2p.py
16
src/p2p.py
@@ -1,16 +0,0 @@
|
|||||||
import asyncio
|
|
||||||
import aioespnow
|
|
||||||
import json
|
|
||||||
|
|
||||||
async def p2p(settings, patterns):
|
|
||||||
e = aioespnow.AIOESPNow() # Returns AIOESPNow enhanced with async support
|
|
||||||
e.active(True)
|
|
||||||
async for mac, msg in e:
|
|
||||||
try:
|
|
||||||
data = json.loads(msg)
|
|
||||||
except:
|
|
||||||
print(f"Failed to load espnow data {msg}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
if "names" not in data or settings.get("name") in data.get("names", []):
|
|
||||||
await settings.set_settings(data.get("settings", {}), patterns, data.get("save", False))
|
|
||||||
757
src/patterns.py
757
src/patterns.py
@@ -2,446 +2,395 @@ from machine import Pin
|
|||||||
from neopixel import NeoPixel
|
from neopixel import NeoPixel
|
||||||
import utime
|
import utime
|
||||||
import random
|
import random
|
||||||
import _thread
|
|
||||||
import asyncio
|
|
||||||
from patterns_base import Patterns as PatternsBase
|
|
||||||
|
|
||||||
# Short-key parameter mapping for convenience setters
|
class Patterns:
|
||||||
param_mapping = {
|
def __init__(self, pin, num_leds, color1=(0,0,0), color2=(0,0,0), brightness=127, selected="rainbow_cycle", delay=100):
|
||||||
"pt": "selected",
|
self.n = NeoPixel(Pin(pin, Pin.OUT), num_leds)
|
||||||
"pa": "selected",
|
self.num_leds = num_leds
|
||||||
"cl": "colors",
|
self.pattern_step = 0
|
||||||
"br": "brightness",
|
self.last_update = utime.ticks_ms()
|
||||||
"dl": "delay",
|
self.delay = delay
|
||||||
"nl": "num_leds",
|
self.brightness = brightness
|
||||||
"co": "color_order",
|
|
||||||
"lp": "led_pin",
|
|
||||||
"n1": "n1",
|
|
||||||
"n2": "n2",
|
|
||||||
"n3": "n3",
|
|
||||||
"n4": "n4",
|
|
||||||
"n5": "n5",
|
|
||||||
"n6": "n6",
|
|
||||||
"auto": "auto",
|
|
||||||
}
|
|
||||||
|
|
||||||
class Patterns(PatternsBase):
|
|
||||||
def __init__(self, pin, num_leds, color1=(0,0,0), color2=(0,0,0), brightness=127, selected="off", delay=100):
|
|
||||||
super().__init__(pin, num_leds, color1, color2, brightness, selected, delay)
|
|
||||||
self.auto = True
|
|
||||||
self.step = 0
|
|
||||||
self.patterns = {
|
self.patterns = {
|
||||||
"off": self.off,
|
"off": self.off,
|
||||||
"on" : self.on,
|
"on" : self.on,
|
||||||
"blink": self.blink,
|
"color_wipe": self.color_wipe_step,
|
||||||
"rainbow": self.rainbow,
|
"rainbow_cycle": self.rainbow_cycle_step,
|
||||||
"pulse": self.pulse,
|
"theater_chase": self.theater_chase_step,
|
||||||
"transition": self.transition,
|
"blink": self.blink_step,
|
||||||
"chase": self.n_chase,
|
"color_transition": self.color_transition_step, # Added new pattern
|
||||||
"n_chase": self.n_chase,
|
"flicker": self.flicker_step,
|
||||||
"circle": self.circle,
|
"scanner": self.scanner_step, # New: Single direction scanner
|
||||||
|
"bidirectional_scanner": self.bidirectional_scanner_step, # New: Bidirectional scanner
|
||||||
|
"external": None
|
||||||
}
|
}
|
||||||
|
self.selected = selected
|
||||||
|
# Ensure colors list always starts with at least two for robust transition handling
|
||||||
|
self.colors = [color1, color2] if color1 != color2 else [color1, (255, 255, 255)] # Fallback if initial colors are same
|
||||||
|
if not self.colors: # Ensure at least one color exists
|
||||||
|
self.colors = [(0, 0, 0)]
|
||||||
|
|
||||||
|
self.transition_duration = delay * 50 # Default transition duration
|
||||||
|
self.hold_duration = delay * 10 # Default hold duration at each color
|
||||||
|
self.transition_step = 0 # Current step in the transition
|
||||||
|
self.current_color_idx = 0 # Index of the color currently being held/transitioned from
|
||||||
|
self.current_color = self.colors[self.current_color_idx] # The actual blended color
|
||||||
|
|
||||||
|
self.hold_start_time = utime.ticks_ms() # Time when the current color hold started
|
||||||
|
|
||||||
|
# New attributes for scanner patterns
|
||||||
|
self.scanner_direction = 1 # 1 for forward, -1 for backward
|
||||||
|
self.scanner_tail_length = 3 # Number of trailing pixels
|
||||||
|
|
||||||
|
def sync(self):
|
||||||
|
self.pattern_step=0
|
||||||
|
self.last_update = utime.ticks_ms() - self.delay
|
||||||
|
if self.selected == "color_transition":
|
||||||
|
self.transition_step = 0
|
||||||
|
self.current_color_idx = 0
|
||||||
|
self.current_color = self.colors[self.current_color_idx]
|
||||||
|
self.hold_start_time = utime.ticks_ms() # Reset hold time
|
||||||
|
# Reset scanner specific variables
|
||||||
|
self.scanner_direction = 1
|
||||||
|
self.tick()
|
||||||
|
|
||||||
|
def set_pattern_step(self, step):
|
||||||
|
self.pattern_step = step
|
||||||
|
|
||||||
|
def tick(self):
|
||||||
|
if self.patterns[self.selected]:
|
||||||
|
self.patterns[self.selected]()
|
||||||
|
|
||||||
|
def update_num_leds(self, pin, num_leds):
|
||||||
|
self.n = NeoPixel(Pin(pin, Pin.OUT), num_leds)
|
||||||
|
self.num_leds = num_leds
|
||||||
|
self.pattern_step = 0
|
||||||
|
|
||||||
|
def set_delay(self, delay):
|
||||||
|
self.delay = delay
|
||||||
|
# Update transition duration and hold duration when delay changes
|
||||||
|
self.transition_duration = self.delay * 50
|
||||||
|
self.hold_duration = self.delay * 10
|
||||||
|
|
||||||
|
|
||||||
def blink(self):
|
def set_brightness(self, brightness):
|
||||||
self.stopped = False
|
self.brightness = brightness
|
||||||
self.running = True
|
|
||||||
state = True # True = on, False = off
|
|
||||||
last_update = utime.ticks_ms()
|
|
||||||
|
|
||||||
# Only continue running this pattern while it is the selected one
|
def set_color1(self, color):
|
||||||
while self.running and self.selected == "blink":
|
if len(self.colors) > 0:
|
||||||
|
self.colors[0] = color
|
||||||
|
if self.selected == "color_transition":
|
||||||
|
# If the first color is changed, potentially reset transition
|
||||||
|
# to start from this new color if we were about to transition from it
|
||||||
|
if self.current_color_idx == 0:
|
||||||
|
self.transition_step = 0
|
||||||
|
self.current_color = self.colors[0]
|
||||||
|
self.hold_start_time = utime.ticks_ms()
|
||||||
|
else:
|
||||||
|
self.colors.append(color)
|
||||||
|
|
||||||
|
|
||||||
|
def set_color2(self, color):
|
||||||
|
if len(self.colors) > 1:
|
||||||
|
self.colors[1] = color
|
||||||
|
elif len(self.colors) == 1:
|
||||||
|
self.colors.append(color)
|
||||||
|
else: # List is empty
|
||||||
|
self.colors.append((0,0,0)) # Dummy color
|
||||||
|
self.colors.append(color)
|
||||||
|
|
||||||
|
|
||||||
|
def set_colors(self, colors):
|
||||||
|
if colors and len(colors) >= 2:
|
||||||
|
self.colors = colors
|
||||||
|
if self.selected == "color_transition":
|
||||||
|
self.sync() # Reset transition if new color list is provided
|
||||||
|
elif colors and len(colors) == 1:
|
||||||
|
self.colors = [colors[0], (255,255,255)] # Add a default second color
|
||||||
|
if self.selected == "color_transition":
|
||||||
|
print("Warning: 'color_transition' requires at least two colors. Adding a default second color.")
|
||||||
|
self.sync()
|
||||||
|
else:
|
||||||
|
print("Error: set_colors requires a list of at least one color.")
|
||||||
|
self.colors = [(0,0,0), (255,255,255)] # Fallback
|
||||||
|
if self.selected == "color_transition":
|
||||||
|
self.sync()
|
||||||
|
|
||||||
|
def set_color(self, num, color):
|
||||||
|
# Changed: More robust index check
|
||||||
|
if 0 <= num < len(self.colors):
|
||||||
|
self.colors[num] = color
|
||||||
|
# If the changed color is part of the current or next transition,
|
||||||
|
# restart the transition for smoother updates
|
||||||
|
if self.selected == "color_transition":
|
||||||
|
current_from_idx = self.current_color_idx
|
||||||
|
current_to_idx = (self.current_color_idx + 1) % len(self.colors)
|
||||||
|
if num == current_from_idx or num == current_to_idx:
|
||||||
|
# If we change a color involved in the current transition,
|
||||||
|
# it's best to restart the transition state for smoothness.
|
||||||
|
self.transition_step = 0
|
||||||
|
self.current_color_idx = current_from_idx # Stay at the current starting color
|
||||||
|
self.current_color = self.colors[self.current_color_idx]
|
||||||
|
self.hold_start_time = utime.ticks_ms() # Reset hold
|
||||||
|
return True
|
||||||
|
elif num == len(self.colors): # Allow setting a new color at the end
|
||||||
|
self.colors.append(color)
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def add_color(self, color):
|
||||||
|
self.colors.append(color)
|
||||||
|
if self.selected == "color_transition" and len(self.colors) == 2:
|
||||||
|
# If we just added the second color needed for transition
|
||||||
|
self.sync()
|
||||||
|
|
||||||
|
|
||||||
|
def del_color(self, num):
|
||||||
|
# Changed: More robust index check and using del for lists
|
||||||
|
if 0 <= num < len(self.colors):
|
||||||
|
del self.colors[num]
|
||||||
|
# If the color being deleted was part of the current transition,
|
||||||
|
# re-evaluate the current_color_idx
|
||||||
|
if self.selected == "color_transition":
|
||||||
|
if len(self.colors) < 2: # Need at least two colors for transition
|
||||||
|
print("Warning: Not enough colors for 'color_transition'. Switching to 'on'.")
|
||||||
|
self.select("on") # Or some other default
|
||||||
|
else:
|
||||||
|
# Adjust index if it's out of bounds after deletion or was the one transitioning from
|
||||||
|
self.current_color_idx %= len(self.colors)
|
||||||
|
self.transition_step = 0
|
||||||
|
self.current_color = self.colors[self.current_color_idx]
|
||||||
|
self.hold_start_time = utime.ticks_ms()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def apply_brightness(self, color, brightness_override=None):
|
||||||
|
effective_brightness = brightness_override if brightness_override is not None else self.brightness
|
||||||
|
return tuple(int(c * effective_brightness / 255) for c in color)
|
||||||
|
|
||||||
|
def select(self, pattern):
|
||||||
|
if pattern in self.patterns:
|
||||||
|
self.selected = pattern
|
||||||
|
self.sync() # Reset pattern state when selecting a new pattern
|
||||||
|
if pattern == "color_transition":
|
||||||
|
if len(self.colors) < 2:
|
||||||
|
print("Warning: 'color_transition' requires at least two colors. Switching to 'on'.")
|
||||||
|
self.selected = "on" # Fallback if not enough colors
|
||||||
|
self.sync() # Re-sync for the new pattern
|
||||||
|
else:
|
||||||
|
self.transition_step = 0
|
||||||
|
self.current_color_idx = 0 # Start from the first color in the list
|
||||||
|
self.current_color = self.colors[self.current_color_idx]
|
||||||
|
self.hold_start_time = utime.ticks_ms() # Reset hold timer
|
||||||
|
self.transition_duration = self.delay * 50 # Initialize transition duration
|
||||||
|
self.hold_duration = self.delay * 10 # Initialize hold duration
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def set(self, i, color):
|
||||||
|
self.n[i] = color
|
||||||
|
|
||||||
|
def write(self):
|
||||||
|
self.n.write()
|
||||||
|
|
||||||
|
def fill(self, color=None):
|
||||||
|
fill_color = color if color is not None else self.colors[0]
|
||||||
|
for i in range(self.num_leds):
|
||||||
|
self.n[i] = fill_color
|
||||||
|
self.n.write()
|
||||||
|
|
||||||
|
def off(self):
|
||||||
|
self.fill((0, 0, 0))
|
||||||
|
|
||||||
|
def on(self):
|
||||||
|
self.fill(self.apply_brightness(self.colors[0]))
|
||||||
|
|
||||||
|
def color_wipe_step(self):
|
||||||
|
color = self.apply_brightness(self.colors[0])
|
||||||
current_time = utime.ticks_ms()
|
current_time = utime.ticks_ms()
|
||||||
if utime.ticks_diff(current_time, last_update) >= self.delay:
|
if utime.ticks_diff(current_time, self.last_update) >= self.delay:
|
||||||
if state:
|
if self.pattern_step < self.num_leds:
|
||||||
|
for i in range(self.num_leds):
|
||||||
|
self.n[i] = (0, 0, 0)
|
||||||
|
self.n[self.pattern_step] = self.apply_brightness(color)
|
||||||
|
self.n.write()
|
||||||
|
self.pattern_step += 1
|
||||||
|
else:
|
||||||
|
self.pattern_step = 0
|
||||||
|
self.last_update = current_time
|
||||||
|
|
||||||
|
def rainbow_cycle_step(self):
|
||||||
|
current_time = utime.ticks_ms()
|
||||||
|
if utime.ticks_diff(current_time, self.last_update) >= self.delay/5:
|
||||||
|
def wheel(pos):
|
||||||
|
if pos < 85:
|
||||||
|
return (pos * 3, 255 - pos * 3, 0)
|
||||||
|
elif pos < 170:
|
||||||
|
pos -= 85
|
||||||
|
return (255 - pos * 3, 0, pos * 3)
|
||||||
|
else:
|
||||||
|
pos -= 170
|
||||||
|
return (0, pos * 3, 255 - pos * 3)
|
||||||
|
|
||||||
|
for i in range(self.num_leds):
|
||||||
|
rc_index = (i * 256 // self.num_leds) + self.pattern_step
|
||||||
|
self.n[i] = self.apply_brightness(wheel(rc_index & 255))
|
||||||
|
self.n.write()
|
||||||
|
self.pattern_step = (self.pattern_step + 1) % 256
|
||||||
|
self.last_update = current_time
|
||||||
|
|
||||||
|
def theater_chase_step(self):
|
||||||
|
current_time = utime.ticks_ms()
|
||||||
|
if utime.ticks_diff(current_time, self.last_update) >= self.delay:
|
||||||
|
for i in range(self.num_leds):
|
||||||
|
if (i + self.pattern_step) % 3 == 0:
|
||||||
|
self.n[i] = self.apply_brightness(self.colors[0])
|
||||||
|
else:
|
||||||
|
self.n[i] = (0, 0, 0)
|
||||||
|
self.n.write()
|
||||||
|
self.pattern_step = (self.pattern_step + 1) % 3
|
||||||
|
self.last_update = current_time
|
||||||
|
|
||||||
|
def blink_step(self):
|
||||||
|
current_time = utime.ticks_ms()
|
||||||
|
if utime.ticks_diff(current_time, self.last_update) >= self.delay:
|
||||||
|
if self.pattern_step % 2 == 0:
|
||||||
self.fill(self.apply_brightness(self.colors[0]))
|
self.fill(self.apply_brightness(self.colors[0]))
|
||||||
else:
|
else:
|
||||||
self.fill((0, 0, 0))
|
self.fill((0, 0, 0))
|
||||||
state = not state
|
self.pattern_step = (self.pattern_step + 1) % 2
|
||||||
last_update = current_time
|
self.last_update = current_time
|
||||||
self.running = False
|
|
||||||
self.stopped = True
|
|
||||||
|
|
||||||
|
def color_transition_step(self):
|
||||||
def rainbow(self):
|
|
||||||
self.stopped = False
|
|
||||||
self.running = True
|
|
||||||
step = self.step % 256
|
|
||||||
step_amount = max(1, int(self.n1)) # n1 controls step increment
|
|
||||||
|
|
||||||
# If auto is False, run once and update step
|
|
||||||
if not self.auto:
|
|
||||||
for i in range(self.num_leds):
|
|
||||||
rc_index = (i * 256 // self.num_leds) + step
|
|
||||||
self.n[i] = self.apply_brightness(self.wheel(rc_index & 255))
|
|
||||||
self.n.write()
|
|
||||||
# Increment step by n1 for next call
|
|
||||||
self.step = (step + step_amount) % 256
|
|
||||||
self.running = False
|
|
||||||
self.stopped = True
|
|
||||||
return
|
|
||||||
|
|
||||||
# Auto is True: run continuously
|
|
||||||
last_update = utime.ticks_ms()
|
|
||||||
|
|
||||||
# Only continue running this pattern while it is the selected one
|
|
||||||
while self.running and self.selected == "rainbow":
|
|
||||||
current_time = utime.ticks_ms()
|
current_time = utime.ticks_ms()
|
||||||
sleep_ms = max(1, int(self.delay)) # Access delay directly
|
|
||||||
if utime.ticks_diff(current_time, last_update) >= sleep_ms:
|
|
||||||
for i in range(self.num_leds):
|
|
||||||
rc_index = (i * 256 // self.num_leds) + step
|
|
||||||
self.n[i] = self.apply_brightness(self.wheel(rc_index & 255))
|
|
||||||
self.n.write()
|
|
||||||
step = (step + step_amount) % 256
|
|
||||||
self.step = step
|
|
||||||
last_update = current_time
|
|
||||||
self.running = False
|
|
||||||
self.stopped = True
|
|
||||||
|
|
||||||
|
# Check for hold duration first
|
||||||
def pulse(self):
|
if utime.ticks_diff(current_time, self.hold_start_time) < self.hold_duration:
|
||||||
self.stopped = False
|
# Still in hold phase, just display the current solid color
|
||||||
self.running = True
|
self.fill(self.apply_brightness(self.current_color))
|
||||||
self.off()
|
self.last_update = current_time # Keep updating last_update to avoid skipping frames
|
||||||
|
|
||||||
# Get timing parameters, ensure non-negative
|
|
||||||
attack_ms = max(0, int(self.n1)) # Attack time in ms
|
|
||||||
hold_ms = max(0, int(self.n2)) # Hold time in ms
|
|
||||||
decay_ms = max(0, int(self.n3)) # Decay time in ms
|
|
||||||
|
|
||||||
# Ensure we have at least one color
|
|
||||||
if not self.colors:
|
|
||||||
self.colors = [(255, 255, 255)]
|
|
||||||
|
|
||||||
color_index = 0
|
|
||||||
# Calculate minimum update interval based on LED count
|
|
||||||
# NeoPixel timing: ~30µs per LED + reset time = ~6ms for 200 LEDs
|
|
||||||
# Use 10ms minimum to ensure writes complete + overhead
|
|
||||||
min_write_time_ms = (self.num_leds * 30) // 1000 + 1 # Convert µs to ms, add 1ms overhead
|
|
||||||
update_interval = max(10, min_write_time_ms + 4) # At least 10ms, add margin for safety
|
|
||||||
|
|
||||||
# Only continue running this pattern while it is the selected one
|
|
||||||
while self.running and self.selected == "pulse":
|
|
||||||
cycle_start = utime.ticks_ms()
|
|
||||||
|
|
||||||
# Get the current color from the cycle
|
|
||||||
base_color = self.colors[color_index % len(self.colors)]
|
|
||||||
|
|
||||||
# Attack phase: fade from 0 to full brightness
|
|
||||||
if attack_ms > 0:
|
|
||||||
attack_start = utime.ticks_ms()
|
|
||||||
last_update = attack_start
|
|
||||||
while self.running and utime.ticks_diff(utime.ticks_ms(), attack_start) < attack_ms:
|
|
||||||
now = utime.ticks_ms()
|
|
||||||
if utime.ticks_diff(now, last_update) >= update_interval:
|
|
||||||
elapsed = utime.ticks_diff(now, attack_start)
|
|
||||||
brightness_factor = min(1.0, elapsed / attack_ms)
|
|
||||||
color = tuple(int(c * brightness_factor) for c in base_color)
|
|
||||||
self.fill(self.apply_brightness(color))
|
|
||||||
last_update = now
|
|
||||||
|
|
||||||
# Hold phase: maintain full brightness
|
|
||||||
if hold_ms > 0 and self.running:
|
|
||||||
self.fill(self.apply_brightness(base_color))
|
|
||||||
hold_start = utime.ticks_ms()
|
|
||||||
while self.running and utime.ticks_diff(utime.ticks_ms(), hold_start) < hold_ms:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# Decay phase: fade from full brightness to 0
|
|
||||||
if decay_ms > 0:
|
|
||||||
decay_start = utime.ticks_ms()
|
|
||||||
last_update = decay_start
|
|
||||||
while self.running and utime.ticks_diff(utime.ticks_ms(), decay_start) < decay_ms:
|
|
||||||
now = utime.ticks_ms()
|
|
||||||
if utime.ticks_diff(now, last_update) >= update_interval:
|
|
||||||
elapsed = utime.ticks_diff(now, decay_start)
|
|
||||||
brightness_factor = max(0.0, 1.0 - (elapsed / decay_ms))
|
|
||||||
color = tuple(int(c * brightness_factor) for c in base_color)
|
|
||||||
self.fill(self.apply_brightness(color))
|
|
||||||
last_update = now
|
|
||||||
|
|
||||||
# Move to next color in the cycle
|
|
||||||
color_index += 1
|
|
||||||
|
|
||||||
# If auto flag is False, run only once and exit
|
|
||||||
if not self.auto:
|
|
||||||
break
|
|
||||||
|
|
||||||
# Ensure the cycle takes exactly delay milliseconds before restarting
|
|
||||||
if self.running:
|
|
||||||
self.off()
|
|
||||||
delay_ms = int(self.delay) # Access delay directly
|
|
||||||
wait_until = utime.ticks_add(cycle_start, delay_ms)
|
|
||||||
while self.running and utime.ticks_diff(wait_until, utime.ticks_ms()) > 0:
|
|
||||||
pass
|
|
||||||
|
|
||||||
self.running = False
|
|
||||||
self.stopped = True
|
|
||||||
|
|
||||||
def transition(self):
|
|
||||||
"""Transition between colors, taking delay ms between each color"""
|
|
||||||
self.stopped = False
|
|
||||||
self.running = True
|
|
||||||
|
|
||||||
if not self.colors:
|
|
||||||
# No colors, turn off
|
|
||||||
self.off()
|
|
||||||
self.running = False
|
|
||||||
self.stopped = True
|
|
||||||
return
|
return
|
||||||
|
|
||||||
if len(self.colors) == 1:
|
# If hold duration is over, proceed with transition
|
||||||
# Only one color, just stay that color
|
if utime.ticks_diff(current_time, self.last_update) >= self.delay:
|
||||||
last_update = utime.ticks_ms()
|
num_colors = len(self.colors)
|
||||||
while self.running and self.selected == "transition":
|
if num_colors < 2:
|
||||||
current_time = utime.ticks_ms()
|
# Should not happen if select handles it, but as a safeguard
|
||||||
if utime.ticks_diff(current_time, last_update) >= 100:
|
self.select("on")
|
||||||
self.fill(self.apply_brightness(self.colors[0]))
|
|
||||||
last_update = current_time
|
|
||||||
self.running = False
|
|
||||||
self.stopped = True
|
|
||||||
return
|
return
|
||||||
|
|
||||||
# If auto is False, only transition between color1 and color2
|
from_color = self.colors[self.current_color_idx]
|
||||||
if not self.auto:
|
to_color_idx = (self.current_color_idx + 1) % num_colors
|
||||||
if len(self.colors) < 2:
|
to_color = self.colors[to_color_idx]
|
||||||
# Need at least 2 colors for transition
|
|
||||||
self.running = False
|
|
||||||
self.stopped = True
|
|
||||||
return
|
|
||||||
|
|
||||||
transition_start = utime.ticks_ms()
|
|
||||||
last_update = transition_start
|
|
||||||
|
|
||||||
while self.running:
|
|
||||||
# Access delay and colors directly for live updates
|
|
||||||
transition_duration = max(10, int(self.delay)) # At least 10ms
|
|
||||||
update_interval = max(10, transition_duration // 50) # Update every ~2% of transition
|
|
||||||
color1 = self.colors[0] if len(self.colors) > 0 else (0, 0, 0)
|
|
||||||
color2 = self.colors[1] if len(self.colors) > 1 else color1
|
|
||||||
|
|
||||||
if utime.ticks_diff(utime.ticks_ms(), transition_start) >= transition_duration:
|
|
||||||
break
|
|
||||||
now = utime.ticks_ms()
|
|
||||||
if utime.ticks_diff(now, last_update) >= update_interval:
|
|
||||||
# Calculate interpolation factor (0.0 to 1.0)
|
# Calculate interpolation factor (0.0 to 1.0)
|
||||||
elapsed = utime.ticks_diff(now, transition_start)
|
# transition_step goes from 0 to transition_duration - 1
|
||||||
factor = min(1.0, elapsed / transition_duration)
|
if self.transition_duration > 0:
|
||||||
|
interp_factor = self.transition_step / self.transition_duration
|
||||||
# Interpolate between color1 and color2
|
|
||||||
interpolated = tuple(
|
|
||||||
int(color1[i] + (color2[i] - color1[i]) * factor)
|
|
||||||
for i in range(3)
|
|
||||||
)
|
|
||||||
|
|
||||||
# Apply brightness and fill
|
|
||||||
self.fill(self.apply_brightness(interpolated))
|
|
||||||
last_update = now
|
|
||||||
|
|
||||||
self.running = False
|
|
||||||
self.stopped = True
|
|
||||||
return
|
|
||||||
|
|
||||||
# Auto is True: cycle through all colors continuously
|
|
||||||
color_index = 0
|
|
||||||
|
|
||||||
# Auto is True: cycle through all colors continuously
|
|
||||||
while self.running and self.selected == "transition":
|
|
||||||
# Access colors directly for live updates
|
|
||||||
if not self.colors:
|
|
||||||
break
|
|
||||||
# Get current and next color
|
|
||||||
current_color = self.colors[color_index % len(self.colors)]
|
|
||||||
next_color = self.colors[(color_index + 1) % len(self.colors)]
|
|
||||||
|
|
||||||
# Transition from current to next color
|
|
||||||
transition_start = utime.ticks_ms()
|
|
||||||
last_update = transition_start
|
|
||||||
|
|
||||||
while self.running:
|
|
||||||
# Access delay directly for live updates
|
|
||||||
transition_duration = max(10, int(self.delay)) # At least 10ms
|
|
||||||
update_interval = max(10, transition_duration // 50) # Update every ~2% of transition
|
|
||||||
|
|
||||||
if utime.ticks_diff(utime.ticks_ms(), transition_start) >= transition_duration:
|
|
||||||
break
|
|
||||||
now = utime.ticks_ms()
|
|
||||||
if utime.ticks_diff(now, last_update) >= update_interval:
|
|
||||||
# Calculate interpolation factor (0.0 to 1.0)
|
|
||||||
elapsed = utime.ticks_diff(now, transition_start)
|
|
||||||
factor = min(1.0, elapsed / transition_duration)
|
|
||||||
|
|
||||||
# Interpolate between colors
|
|
||||||
interpolated = tuple(
|
|
||||||
int(current_color[i] + (next_color[i] - current_color[i]) * factor)
|
|
||||||
for i in range(3)
|
|
||||||
)
|
|
||||||
|
|
||||||
# Apply brightness and fill
|
|
||||||
self.fill(self.apply_brightness(interpolated))
|
|
||||||
last_update = now
|
|
||||||
|
|
||||||
# Move to next color
|
|
||||||
color_index = (color_index + 1) % len(self.colors)
|
|
||||||
|
|
||||||
self.running = False
|
|
||||||
self.stopped = True
|
|
||||||
|
|
||||||
def n_chase(self):
|
|
||||||
"""N-chase pattern: n1 LEDs of color0, n2 LEDs of color1, repeating.
|
|
||||||
Moves by n3 on even steps, n4 on odd steps (n3/n4 can be positive or negative)"""
|
|
||||||
self.stopped = False
|
|
||||||
self.running = True
|
|
||||||
|
|
||||||
if len(self.colors) < 1:
|
|
||||||
# Need at least 1 color
|
|
||||||
self.running = False
|
|
||||||
self.stopped = True
|
|
||||||
return
|
|
||||||
|
|
||||||
segment_length = 0 # Will be calculated in loop
|
|
||||||
position = 0 # Current position offset
|
|
||||||
step_count = 0 # Track which step we're on
|
|
||||||
|
|
||||||
last_update = utime.ticks_ms()
|
|
||||||
|
|
||||||
# Only continue running this pattern while it is the selected one
|
|
||||||
# Note: this pattern can be selected as "n_chase" or "chase"
|
|
||||||
while self.running and self.selected in ("n_chase", "chase"):
|
|
||||||
# Access colors, delay, and n values directly for live updates
|
|
||||||
if not self.colors:
|
|
||||||
break
|
|
||||||
# If only one color provided, use it for both colors
|
|
||||||
if len(self.colors) < 2:
|
|
||||||
color0 = self.colors[0]
|
|
||||||
color1 = self.colors[0]
|
|
||||||
else:
|
else:
|
||||||
color0 = self.colors[0]
|
interp_factor = 1.0 # Immediately transition if duration is zero
|
||||||
color1 = self.colors[1]
|
|
||||||
|
|
||||||
color0 = self.apply_brightness(color0)
|
# Interpolate each color component
|
||||||
color1 = self.apply_brightness(color1)
|
r = int(from_color[0] + (to_color[0] - from_color[0]) * interp_factor)
|
||||||
|
g = int(from_color[1] + (to_color[1] - from_color[1]) * interp_factor)
|
||||||
|
b = int(from_color[2] + (to_color[2] - from_color[2]) * interp_factor)
|
||||||
|
|
||||||
n1 = max(1, int(self.n1)) # LEDs of color 0
|
self.current_color = (r, g, b)
|
||||||
n2 = max(1, int(self.n2)) # LEDs of color 1
|
self.fill(self.apply_brightness(self.current_color))
|
||||||
n3 = int(self.n3) # Step movement on odd steps (can be negative)
|
|
||||||
n4 = int(self.n4) # Step movement on even steps (can be negative)
|
|
||||||
|
|
||||||
segment_length = n1 + n2
|
self.transition_step += self.delay # Advance the transition step by the delay
|
||||||
transition_duration = max(10, int(self.delay))
|
|
||||||
|
|
||||||
|
if self.transition_step >= self.transition_duration:
|
||||||
|
# Transition complete, move to the next color and reset for hold phase
|
||||||
|
self.current_color_idx = to_color_idx
|
||||||
|
self.current_color = self.colors[self.current_color_idx] # Ensure current_color is the exact target color
|
||||||
|
self.transition_step = 0 # Reset transition progress
|
||||||
|
self.hold_start_time = current_time # Start hold phase for the new color
|
||||||
|
|
||||||
|
self.last_update = current_time
|
||||||
|
|
||||||
|
def flicker_step(self):
|
||||||
current_time = utime.ticks_ms()
|
current_time = utime.ticks_ms()
|
||||||
if utime.ticks_diff(current_time, last_update) >= transition_duration:
|
if utime.ticks_diff(current_time, self.last_update) >= self.delay/5:
|
||||||
# Clear all LEDs
|
base_color = self.colors[0]
|
||||||
self.n.fill((0, 0, 0))
|
# Increase the range for flicker_brightness_offset
|
||||||
|
# Changed from self.brightness // 4 to self.brightness // 2 (or even self.brightness for max intensity)
|
||||||
|
flicker_brightness_offset = random.randint(-int(self.brightness // 1.5), int(self.brightness // 1.5))
|
||||||
|
flicker_brightness = max(0, min(255, self.brightness + flicker_brightness_offset))
|
||||||
|
|
||||||
# Draw repeating pattern starting at position
|
flicker_color = self.apply_brightness(base_color, brightness_override=flicker_brightness)
|
||||||
for i in range(self.num_leds):
|
self.fill(flicker_color)
|
||||||
# Calculate position in the repeating segment
|
self.last_update = current_time
|
||||||
relative_pos = (i - position) % segment_length
|
|
||||||
if relative_pos < 0:
|
|
||||||
relative_pos = (relative_pos + segment_length) % segment_length
|
|
||||||
|
|
||||||
# Determine which color based on position in segment
|
def scanner_step(self):
|
||||||
if relative_pos < n1:
|
"""
|
||||||
self.n[i] = color0
|
Mimics a 'Knight Rider' style scanner, moving in one direction.
|
||||||
else:
|
"""
|
||||||
self.n[i] = color1
|
|
||||||
|
|
||||||
self.n.write()
|
|
||||||
|
|
||||||
# Move position by n3 or n4 on alternate steps
|
|
||||||
if step_count % 2 == 0:
|
|
||||||
position = position + n3
|
|
||||||
else:
|
|
||||||
position = position + n4
|
|
||||||
|
|
||||||
# Wrap position to keep it reasonable
|
|
||||||
max_pos = self.num_leds + segment_length
|
|
||||||
position = position % max_pos
|
|
||||||
if position < 0:
|
|
||||||
position += max_pos
|
|
||||||
|
|
||||||
step_count += 1
|
|
||||||
last_update = current_time
|
|
||||||
|
|
||||||
self.running = False
|
|
||||||
self.stopped = True
|
|
||||||
|
|
||||||
def circle(self):
|
|
||||||
"""Circle loading pattern - grows to n2, then tail moves forward at n3 until min length n4"""
|
|
||||||
self.stopped = False
|
|
||||||
self.running = True
|
|
||||||
head = 0
|
|
||||||
tail = 0
|
|
||||||
|
|
||||||
# Calculate timing
|
|
||||||
head_rate = max(1, int(self.n1)) # n1 = head moves per second
|
|
||||||
tail_rate = max(1, int(self.n3)) # n3 = tail moves per second
|
|
||||||
max_length = max(1, int(self.n2)) # n2 = max length
|
|
||||||
min_length = max(0, int(self.n4)) # n4 = min length
|
|
||||||
|
|
||||||
head_delay = 1000 // head_rate # ms between head movements
|
|
||||||
tail_delay = 1000 // tail_rate # ms between tail movements
|
|
||||||
|
|
||||||
last_head_move = utime.ticks_ms()
|
|
||||||
last_tail_move = utime.ticks_ms()
|
|
||||||
|
|
||||||
phase = "growing" # "growing", "shrinking", or "off"
|
|
||||||
|
|
||||||
# Only continue running this pattern while it is the selected one
|
|
||||||
while self.running and self.selected == "circle":
|
|
||||||
current_time = utime.ticks_ms()
|
current_time = utime.ticks_ms()
|
||||||
|
if utime.ticks_diff(current_time, self.last_update) >= self.delay:
|
||||||
|
self.fill((0, 0, 0)) # Clear all LEDs
|
||||||
|
|
||||||
# Clear all LEDs
|
# Calculate the head and tail position
|
||||||
self.n.fill((0, 0, 0))
|
head_pos = self.pattern_step
|
||||||
|
|
||||||
# Calculate segment length
|
|
||||||
segment_length = (head - tail) % self.num_leds
|
|
||||||
if segment_length == 0 and head != tail:
|
|
||||||
segment_length = self.num_leds
|
|
||||||
|
|
||||||
# Draw segment from tail to head
|
|
||||||
color = self.apply_brightness(self.colors[0])
|
color = self.apply_brightness(self.colors[0])
|
||||||
for i in range(segment_length + 1):
|
|
||||||
led_pos = (tail + i) % self.num_leds
|
|
||||||
self.n[led_pos] = color
|
|
||||||
|
|
||||||
# Move head continuously at n1 LEDs per second
|
# Draw the head
|
||||||
if utime.ticks_diff(current_time, last_head_move) >= head_delay:
|
if 0 <= head_pos < self.num_leds:
|
||||||
head = (head + 1) % self.num_leds
|
self.n[head_pos] = color
|
||||||
last_head_move = current_time
|
|
||||||
|
|
||||||
# Tail behavior based on phase
|
# Draw the trailing pixels with decreasing brightness
|
||||||
if phase == "growing":
|
for i in range(1, self.scanner_tail_length + 1):
|
||||||
# Growing phase: tail stays at 0 until max length reached
|
tail_pos = head_pos - i
|
||||||
if segment_length >= max_length:
|
if 0 <= tail_pos < self.num_leds:
|
||||||
phase = "shrinking"
|
# Calculate fading color for tail
|
||||||
elif phase == "shrinking":
|
# Example: linear fade from full brightness to off
|
||||||
# Shrinking phase: move tail forward at n3 LEDs per second
|
fade_factor = 1.0 - (i / (self.scanner_tail_length + 1))
|
||||||
if utime.ticks_diff(current_time, last_tail_move) >= tail_delay:
|
faded_color = tuple(int(c * fade_factor) for c in color)
|
||||||
tail = (tail + 1) % self.num_leds
|
self.n[tail_pos] = faded_color
|
||||||
last_tail_move = current_time
|
|
||||||
|
|
||||||
# Check if we've reached min length
|
|
||||||
current_length = (head - tail) % self.num_leds
|
|
||||||
if current_length == 0 and head != tail:
|
|
||||||
current_length = self.num_leds
|
|
||||||
|
|
||||||
# For min_length = 0, we need at least 1 LED (the head)
|
|
||||||
if min_length == 0 and current_length <= 1:
|
|
||||||
phase = "off" # All LEDs off for 1 step
|
|
||||||
elif min_length > 0 and current_length <= min_length:
|
|
||||||
phase = "growing" # Cycle repeats
|
|
||||||
else: # phase == "off"
|
|
||||||
# Off phase: all LEDs off for 1 step, then restart
|
|
||||||
tail = head # Reset tail to head position to start fresh
|
|
||||||
phase = "growing"
|
|
||||||
|
|
||||||
self.n.write()
|
self.n.write()
|
||||||
|
|
||||||
self.running = False
|
self.pattern_step += 1
|
||||||
self.stopped = True
|
if self.pattern_step >= self.num_leds + self.scanner_tail_length:
|
||||||
|
self.pattern_step = 0 # Reset to start
|
||||||
|
|
||||||
|
self.last_update = current_time
|
||||||
|
|
||||||
|
def bidirectional_scanner_step(self):
|
||||||
|
"""
|
||||||
|
Mimics a 'Knight Rider' style scanner, moving back and forth.
|
||||||
|
"""
|
||||||
|
current_time = utime.ticks_ms()
|
||||||
|
if utime.ticks_diff(current_time, self.last_update) >= self.delay/100:
|
||||||
|
self.fill((0, 0, 0)) # Clear all LEDs
|
||||||
|
|
||||||
|
color = self.apply_brightness(self.colors[0])
|
||||||
|
|
||||||
|
# Calculate the head position based on direction
|
||||||
|
head_pos = self.pattern_step
|
||||||
|
|
||||||
|
# Draw the head
|
||||||
|
if 0 <= head_pos < self.num_leds:
|
||||||
|
self.n[head_pos] = color
|
||||||
|
|
||||||
|
# Draw the trailing pixels with decreasing brightness
|
||||||
|
for i in range(1, self.scanner_tail_length + 1):
|
||||||
|
tail_pos = head_pos - (i * self.scanner_direction)
|
||||||
|
if 0 <= tail_pos < self.num_leds:
|
||||||
|
fade_factor = 1.0 - (i / (self.scanner_tail_length + 1))
|
||||||
|
faded_color = tuple(int(c * fade_factor) for c in color)
|
||||||
|
self.n[tail_pos] = faded_color
|
||||||
|
|
||||||
|
self.n.write()
|
||||||
|
|
||||||
|
self.pattern_step += self.scanner_direction
|
||||||
|
|
||||||
|
# Change direction if boundaries are reached
|
||||||
|
if self.scanner_direction == 1 and self.pattern_step >= self.num_leds:
|
||||||
|
self.scanner_direction = -1
|
||||||
|
self.pattern_step = self.num_leds - 1 # Start moving back from the last LED
|
||||||
|
elif self.scanner_direction == -1 and self.pattern_step < 0:
|
||||||
|
self.scanner_direction = 1
|
||||||
|
self.pattern_step = 0 # Start moving forward from the first LED
|
||||||
|
|
||||||
|
self.last_update = current_time
|
||||||
|
|||||||
@@ -1,167 +0,0 @@
|
|||||||
from machine import Pin
|
|
||||||
from neopixel import NeoPixel
|
|
||||||
import utime
|
|
||||||
import random
|
|
||||||
import _thread
|
|
||||||
import asyncio
|
|
||||||
import json
|
|
||||||
|
|
||||||
# Short-key parameter mapping for convenience setters
|
|
||||||
param_mapping = {
|
|
||||||
"pt": "selected",
|
|
||||||
"pa": "selected",
|
|
||||||
"cl": "colors",
|
|
||||||
"br": "brightness",
|
|
||||||
"dl": "delay",
|
|
||||||
"nl": "num_leds",
|
|
||||||
"co": "color_order",
|
|
||||||
"lp": "led_pin",
|
|
||||||
"n1": "n1",
|
|
||||||
"n2": "n2",
|
|
||||||
"n3": "n3",
|
|
||||||
"n4": "n4",
|
|
||||||
"n5": "n5",
|
|
||||||
"n6": "n6",
|
|
||||||
"auto": "auto",
|
|
||||||
}
|
|
||||||
|
|
||||||
class Patterns:
|
|
||||||
def __init__(self, pin, num_leds, color1=(0,0,0), color2=(0,0,0), brightness=127, selected="off", delay=100):
|
|
||||||
self.n = NeoPixel(Pin(pin, Pin.OUT), num_leds)
|
|
||||||
self.num_leds = num_leds
|
|
||||||
self.pattern_step = 0
|
|
||||||
self.last_update = utime.ticks_ms()
|
|
||||||
self.delay = delay
|
|
||||||
self.brightness = brightness
|
|
||||||
self.auto = False
|
|
||||||
self.patterns = {}
|
|
||||||
self.selected = selected
|
|
||||||
# Ensure colors list always starts with at least two for robust transition handling
|
|
||||||
self.colors = [color1, color2] if color1 != color2 else [color1, (255, 255, 255)] # Fallback if initial colors are same
|
|
||||||
if not self.colors: # Ensure at least one color exists
|
|
||||||
self.colors = [(0, 0, 0)]
|
|
||||||
|
|
||||||
self.transition_duration = delay * 50 # Default transition duration
|
|
||||||
self.hold_duration = delay * 10 # Default hold duration at each color
|
|
||||||
self.transition_step = 0 # Current step in the transition
|
|
||||||
self.current_color_idx = 0 # Index of the color currently being held/transitioned from
|
|
||||||
self.current_color = self.colors[self.current_color_idx] # The actual blended color
|
|
||||||
|
|
||||||
self.hold_start_time = utime.ticks_ms() # Time when the current color hold started
|
|
||||||
|
|
||||||
# New attributes for scanner patterns
|
|
||||||
self.scanner_direction = 1 # 1 for forward, -1 for backward
|
|
||||||
self.scanner_tail_length = 3 # Number of trailing pixels
|
|
||||||
self.running = False
|
|
||||||
self.stopped = True
|
|
||||||
|
|
||||||
self.n1 = 0
|
|
||||||
self.n2 = 0
|
|
||||||
self.n3 = 0
|
|
||||||
self.n4 = 0
|
|
||||||
self.n5 = 0
|
|
||||||
self.n6 = 0
|
|
||||||
|
|
||||||
def select(self, pattern):
|
|
||||||
if pattern in self.patterns:
|
|
||||||
self.selected = pattern
|
|
||||||
return True
|
|
||||||
# If pattern doesn't exist, default to "off"
|
|
||||||
if "off" in self.patterns:
|
|
||||||
self.selected = "off"
|
|
||||||
return False
|
|
||||||
|
|
||||||
async def run(self):
|
|
||||||
await self.stop()
|
|
||||||
# Ensure we wait a bit more to let the thread fully terminate
|
|
||||||
# If selected pattern doesn't exist, default to "off"
|
|
||||||
if self.selected not in self.patterns:
|
|
||||||
print(f"Pattern {self.selected} not found, defaulting to 'off'")
|
|
||||||
if "off" in self.patterns:
|
|
||||||
self.selected = "off"
|
|
||||||
else:
|
|
||||||
print("No patterns available")
|
|
||||||
self.running = False
|
|
||||||
self.stopped = True
|
|
||||||
return
|
|
||||||
print(f"Starting pattern {self.selected}")
|
|
||||||
_thread.start_new_thread(self.patterns[self.selected], ())
|
|
||||||
|
|
||||||
async def stop(self):
|
|
||||||
if not self.running:
|
|
||||||
# Already stopped
|
|
||||||
self.stopped = True
|
|
||||||
return
|
|
||||||
self.running = False
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
timeout = 2000 # Increased timeout to 2 seconds
|
|
||||||
while not self.stopped and utime.ticks_diff(utime.ticks_ms(), start) < timeout:
|
|
||||||
await asyncio.sleep_ms(10) # Check every 10ms instead of 0ms
|
|
||||||
if not self.stopped:
|
|
||||||
# Timeout reached, force stop
|
|
||||||
print("Warning: Pattern did not stop within timeout")
|
|
||||||
self.stopped = True
|
|
||||||
|
|
||||||
def set_param(self, key, value):
|
|
||||||
if key in param_mapping:
|
|
||||||
setattr(self, param_mapping[key], value)
|
|
||||||
return True
|
|
||||||
print(f"Invalid parameter: {key}")
|
|
||||||
return False
|
|
||||||
|
|
||||||
def update_num_leds(self, pin, num_leds):
|
|
||||||
self.n = NeoPixel(Pin(pin, Pin.OUT), num_leds)
|
|
||||||
self.num_leds = num_leds
|
|
||||||
self.pattern_step = 0
|
|
||||||
|
|
||||||
|
|
||||||
def set_color(self, num, color):
|
|
||||||
# Changed: More robust index check
|
|
||||||
if 0 <= num < len(self.colors):
|
|
||||||
self.colors[num] = color
|
|
||||||
# If the changed color is part of the current or next transition,
|
|
||||||
# restart the transition for smoother updates
|
|
||||||
return True
|
|
||||||
elif num == len(self.colors): # Allow setting a new color at the end
|
|
||||||
self.colors.append(color)
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def del_color(self, num):
|
|
||||||
# Changed: More robust index check and using del for lists
|
|
||||||
if 0 <= num < len(self.colors):
|
|
||||||
del self.colors[num]
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
||||||
def apply_brightness(self, color, brightness_override=None):
|
|
||||||
effective_brightness = brightness_override if brightness_override is not None else self.brightness
|
|
||||||
return tuple(int(c * effective_brightness / 255) for c in color)
|
|
||||||
|
|
||||||
def fill(self, color=None):
|
|
||||||
fill_color = color if color is not None else self.colors[0]
|
|
||||||
for i in range(self.num_leds):
|
|
||||||
self.n[i] = fill_color
|
|
||||||
self.n.write()
|
|
||||||
|
|
||||||
def off(self):
|
|
||||||
self.fill((0, 0, 0))
|
|
||||||
|
|
||||||
def on(self):
|
|
||||||
self.fill(self.apply_brightness(self.colors[0]))
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def wheel(self, pos):
|
|
||||||
if pos < 85:
|
|
||||||
return (pos * 3, 255 - pos * 3, 0)
|
|
||||||
elif pos < 170:
|
|
||||||
pos -= 85
|
|
||||||
return (255 - pos * 3, 0, pos * 3)
|
|
||||||
else:
|
|
||||||
pos -= 170
|
|
||||||
return (0, pos * 3, 255 - pos * 3)
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
import json
|
|
||||||
import wifi
|
|
||||||
import ubinascii
|
|
||||||
import machine
|
|
||||||
|
|
||||||
class Presets(dict):
|
|
||||||
FILE = "/presets.json"
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
super().__init__()
|
|
||||||
self.load() # Load settings from file during initialization
|
|
||||||
|
|
||||||
def save(self):
|
|
||||||
try:
|
|
||||||
j = json.dumps(self)
|
|
||||||
with open(self.FILE, 'w') as file:
|
|
||||||
file.write(j)
|
|
||||||
print("Presets saved successfully.")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"Error saving settings: {e}")
|
|
||||||
|
|
||||||
def load(self):
|
|
||||||
try:
|
|
||||||
with open(self.FILE, 'r') as file:
|
|
||||||
self.update(json.load(file))
|
|
||||||
print("Presets loaded successfully.")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"Error loading presets")
|
|
||||||
self.save()
|
|
||||||
|
|
||||||
|
|
||||||
@@ -45,40 +45,31 @@ class Settings(dict):
|
|||||||
self.set_defaults()
|
self.set_defaults()
|
||||||
self.save()
|
self.save()
|
||||||
|
|
||||||
async def set_settings(self, data, patterns, save):
|
def set_settings(self, data, patterns, save):
|
||||||
try:
|
try:
|
||||||
print(f"Setting settings: {data}")
|
print(data)
|
||||||
for key, value in data.items():
|
for key, value in data.items():
|
||||||
print(key, value)
|
print(key, value)
|
||||||
if key == "colors":
|
if key == "colors":
|
||||||
buff = []
|
buff = []
|
||||||
for color in value:
|
for color in value:
|
||||||
buff.append(tuple(int(color[i:i+2], 16) for i in self.color_order))
|
buff.append(tuple(int(color[i:i+2], 16) for i in self.color_order))
|
||||||
patterns.colors = buff
|
patterns.set_colors(buff)
|
||||||
|
elif key == "color1":
|
||||||
|
patterns.set_color1(tuple(int(value[i:i+2], 16) for i in self.color_order)) # Convert hex to RGB
|
||||||
|
elif key == "color2":
|
||||||
|
patterns.set_color2(tuple(int(value[i:i+2], 16) for i in self.color_order)) # Convert hex to RGB
|
||||||
elif key == "num_leds":
|
elif key == "num_leds":
|
||||||
patterns.update_num_leds(self["led_pin"], value)
|
patterns.update_num_leds(self["led_pin"], value)
|
||||||
elif key == "pattern":
|
elif key == "pattern":
|
||||||
if not patterns.select(value):
|
if not patterns.select(value):
|
||||||
return "Pattern doesn't exist", 400
|
return "Pattern doesn't exist", 400
|
||||||
await patterns.run()
|
|
||||||
elif key == "delay":
|
elif key == "delay":
|
||||||
delay = int(data["delay"])
|
delay = int(data["delay"])
|
||||||
patterns.delay = delay
|
patterns.set_delay(delay)
|
||||||
elif key == "brightness":
|
elif key == "brightness":
|
||||||
brightness = int(data["brightness"])
|
brightness = int(data["brightness"])
|
||||||
patterns.brightness = brightness
|
patterns.set_brightness(brightness)
|
||||||
elif key == "n1":
|
|
||||||
patterns.n1 = value
|
|
||||||
elif key == "n2":
|
|
||||||
patterns.n2 = value
|
|
||||||
elif key == "n3":
|
|
||||||
patterns.n3 = value
|
|
||||||
elif key == "n4":
|
|
||||||
patterns.n4 = value
|
|
||||||
elif key == "n5":
|
|
||||||
patterns.n5 = value
|
|
||||||
elif key == "n6":
|
|
||||||
patterns.n6 = value
|
|
||||||
elif key == "name":
|
elif key == "name":
|
||||||
self[key] = value
|
self[key] = value
|
||||||
self.save()
|
self.save()
|
||||||
@@ -95,9 +86,9 @@ class Settings(dict):
|
|||||||
return "Invalid key", 400
|
return "Invalid key", 400
|
||||||
self[key] = value
|
self[key] = value
|
||||||
#print(self)
|
#print(self)
|
||||||
|
patterns.sync()
|
||||||
if save:
|
if save:
|
||||||
self.save()
|
self.save()
|
||||||
print(self)
|
|
||||||
return "OK", 200
|
return "OK", 200
|
||||||
except (KeyError, ValueError):
|
except (KeyError, ValueError):
|
||||||
return "Bad request", 400
|
return "Bad request", 400
|
||||||
|
|||||||
@@ -1,109 +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 0.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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#connection-status {
|
|
||||||
width: 15px;
|
|
||||||
height: 15px;
|
|
||||||
border-radius: 50%;
|
|
||||||
display: inline-block; /* Or block, depending on where you put it */
|
|
||||||
margin-left: 10px; /* Adjust spacing as needed */
|
|
||||||
vertical-align: middle; /* Align with nearby text */
|
|
||||||
background-color: grey; /* Default: Unknown */
|
|
||||||
}
|
|
||||||
|
|
||||||
#connection-status.connecting {
|
|
||||||
background-color: yellow;
|
|
||||||
}
|
|
||||||
|
|
||||||
#connection-status.open {
|
|
||||||
background-color: green;
|
|
||||||
}
|
|
||||||
|
|
||||||
#connection-status.closing,
|
|
||||||
#connection-status.closed {
|
|
||||||
background-color: red;
|
|
||||||
}
|
|
||||||
|
|
||||||
#color_order_form label,
|
|
||||||
#color_order_form input[type="radio"] {
|
|
||||||
/* Ensures they behave as inline elements */
|
|
||||||
display: inline-block;
|
|
||||||
/* Adds some space between them for readability */
|
|
||||||
margin-right: 10px;
|
|
||||||
vertical-align: middle; /* Aligns them nicely if heights vary */
|
|
||||||
}
|
|
||||||
@@ -1,244 +0,0 @@
|
|||||||
let delayTimeout;
|
|
||||||
let brightnessTimeout;
|
|
||||||
let colorTimeout;
|
|
||||||
let color2Timeout;
|
|
||||||
let ws; // Variable to hold the WebSocket connection
|
|
||||||
let connectionStatusElement; // Variable to hold the connection status element
|
|
||||||
|
|
||||||
// Function to update the connection status indicator
|
|
||||||
function updateConnectionStatus(status) {
|
|
||||||
if (!connectionStatusElement) {
|
|
||||||
connectionStatusElement = document.getElementById("connection-status");
|
|
||||||
}
|
|
||||||
if (connectionStatusElement) {
|
|
||||||
connectionStatusElement.className = ""; // Clear existing classes
|
|
||||||
connectionStatusElement.classList.add(status);
|
|
||||||
// Optionally, you could also update text content based on status
|
|
||||||
// connectionStatusElement.textContent = status.charAt(0).toUpperCase() + status.slice(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Function to establish WebSocket connection
|
|
||||||
function connectWebSocket() {
|
|
||||||
// Determine the WebSocket URL based on the current location
|
|
||||||
const wsUrl = `ws://${window.location.host}/ws`;
|
|
||||||
ws = new WebSocket(wsUrl);
|
|
||||||
|
|
||||||
updateConnectionStatus("connecting"); // Indicate connecting state
|
|
||||||
|
|
||||||
ws.onopen = function (event) {
|
|
||||||
console.log("WebSocket connection opened:", event);
|
|
||||||
updateConnectionStatus("open"); // Indicate open state
|
|
||||||
// Optionally, you could send an initial message here
|
|
||||||
};
|
|
||||||
|
|
||||||
ws.onmessage = function (event) {
|
|
||||||
console.log("WebSocket message received:", event.data);
|
|
||||||
};
|
|
||||||
|
|
||||||
ws.onerror = function (event) {
|
|
||||||
console.error("WebSocket error:", event);
|
|
||||||
updateConnectionStatus("closed"); // Indicate error state (treat as closed)
|
|
||||||
};
|
|
||||||
|
|
||||||
ws.onclose = function (event) {
|
|
||||||
if (event.wasClean) {
|
|
||||||
console.log(
|
|
||||||
`WebSocket connection closed cleanly, code=${event.code}, reason=${event.reason}`,
|
|
||||||
);
|
|
||||||
updateConnectionStatus("closed"); // Indicate closed state
|
|
||||||
} else {
|
|
||||||
console.error("WebSocket connection died");
|
|
||||||
updateConnectionStatus("closed"); // Indicate closed state
|
|
||||||
}
|
|
||||||
// Attempt to reconnect after a delay
|
|
||||||
setTimeout(connectWebSocket, 1000);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Function to send data over WebSocket
|
|
||||||
function sendWebSocketData(data) {
|
|
||||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
||||||
console.log("Sending data over WebSocket:", data);
|
|
||||||
ws.send(JSON.stringify(data));
|
|
||||||
} else {
|
|
||||||
console.error("WebSocket is not connected. Cannot send data:", data);
|
|
||||||
// You might want to queue messages or handle this in a different way
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Keep the post and get functions for now, they might still be useful
|
|
||||||
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),
|
|
||||||
});
|
|
||||||
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();
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error during GET request:", error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function updateColor(event) {
|
|
||||||
event.preventDefault();
|
|
||||||
clearTimeout(colorTimeout);
|
|
||||||
colorTimeout = setTimeout(function () {
|
|
||||||
const color = document.getElementById("color").value;
|
|
||||||
sendWebSocketData({ color1: color });
|
|
||||||
}, 500);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function updateColor2(event) {
|
|
||||||
event.preventDefault();
|
|
||||||
clearTimeout(color2Timeout);
|
|
||||||
color2Timeout = setTimeout(function () {
|
|
||||||
const color = document.getElementById("color2").value;
|
|
||||||
sendWebSocketData({ color2: color });
|
|
||||||
}, 500);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function updatePattern(pattern) {
|
|
||||||
sendWebSocketData({ pattern: pattern });
|
|
||||||
}
|
|
||||||
|
|
||||||
async function updateBrightness(event) {
|
|
||||||
event.preventDefault();
|
|
||||||
clearTimeout(brightnessTimeout);
|
|
||||||
brightnessTimeout = setTimeout(function () {
|
|
||||||
const brightness = document.getElementById("brightness").value;
|
|
||||||
sendWebSocketData({ brightness: brightness });
|
|
||||||
}, 500);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function updateDelay(event) {
|
|
||||||
event.preventDefault();
|
|
||||||
clearTimeout(delayTimeout);
|
|
||||||
delayTimeout = setTimeout(function () {
|
|
||||||
const delay = document.getElementById("delay").value;
|
|
||||||
sendWebSocketData({ delay: delay });
|
|
||||||
}, 500);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function updateNumLeds(event) {
|
|
||||||
event.preventDefault();
|
|
||||||
const numLeds = document.getElementById("num_leds").value;
|
|
||||||
sendWebSocketData({ num_leds: parseInt(numLeds) });
|
|
||||||
}
|
|
||||||
|
|
||||||
async function updateName(event) {
|
|
||||||
event.preventDefault();
|
|
||||||
const name = document.getElementById("name").value;
|
|
||||||
sendWebSocketData({ name: name });
|
|
||||||
}
|
|
||||||
|
|
||||||
async function updateID(event) {
|
|
||||||
event.preventDefault();
|
|
||||||
const id = document.getElementById("id").value;
|
|
||||||
sendWebSocketData({ id: parseInt(id) });
|
|
||||||
}
|
|
||||||
|
|
||||||
async function updateLedPin(event) {
|
|
||||||
event.preventDefault();
|
|
||||||
const ledpin = document.getElementById("led_pin").value;
|
|
||||||
sendWebSocketData({ led_pin: parseInt(ledpin) });
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleRadioChange(event) {
|
|
||||||
event.preventDefault();
|
|
||||||
console.log("Selected color order:", event.target.value);
|
|
||||||
// Add your specific logic here
|
|
||||||
if (event.target.value === "rgb") {
|
|
||||||
console.log("RGB order selected!");
|
|
||||||
} else if (event.target.value === "rbg") {
|
|
||||||
console.log("RBG order selected!");
|
|
||||||
}
|
|
||||||
sendWebSocketData({ color_order: event.target.value });
|
|
||||||
}
|
|
||||||
|
|
||||||
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";
|
|
||||||
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 () {
|
|
||||||
// Get the connection status element once the DOM is ready
|
|
||||||
connectionStatusElement = document.getElementById("connection-status");
|
|
||||||
|
|
||||||
// Establish WebSocket connection on page load
|
|
||||||
connectWebSocket();
|
|
||||||
|
|
||||||
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("name_form").addEventListener("submit", updateName);
|
|
||||||
document.getElementById("id_form").addEventListener("submit", updateID);
|
|
||||||
document
|
|
||||||
.getElementById("led_pin_form")
|
|
||||||
.addEventListener("submit", updateLedPin);
|
|
||||||
document.getElementById("delay").addEventListener("touchend", updateDelay);
|
|
||||||
document
|
|
||||||
.getElementById("brightness")
|
|
||||||
.addEventListener("touchend", updateBrightness);
|
|
||||||
|
|
||||||
document.getElementById("rgb").addEventListener("change", handleRadioChange);
|
|
||||||
document.getElementById("rbg").addEventListener("change", handleRadioChange);
|
|
||||||
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,124 +0,0 @@
|
|||||||
{% args settings, patterns, mac %}
|
|
||||||
<!doctype html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
||||||
<title>{{settings['name']}}</title>
|
|
||||||
<script src="static/main.js"></script>
|
|
||||||
<link rel="stylesheet" href="static/main.css" />
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<h1>{{settings['name']}}</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>
|
|
||||||
|
|
||||||
<!-- Settings Menu for num_leds, Wi-Fi SSID, and Password -->
|
|
||||||
|
|
||||||
<div id="settings_menu" style="display: none">
|
|
||||||
<h2>Settings</h2>
|
|
||||||
|
|
||||||
<form id="name_form" method="post" action="/name">
|
|
||||||
<label for="name">Name:</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
id="name"
|
|
||||||
name="num_leds"
|
|
||||||
value="{{settings['name']}}"
|
|
||||||
/>
|
|
||||||
<input type="submit" value="Update Name" />
|
|
||||||
</form>
|
|
||||||
<form id="id_form" method="post" action="/id">
|
|
||||||
<label for="id">ID:</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
id="id"
|
|
||||||
name="id"
|
|
||||||
value="{{settings['id']}}"
|
|
||||||
/>
|
|
||||||
<input type="submit" value="Update ID" />
|
|
||||||
</form>
|
|
||||||
<!-- 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="{{settings['num_leds']}}"
|
|
||||||
/>
|
|
||||||
<input type="submit" value="Update Number of LEDs" />
|
|
||||||
</form>
|
|
||||||
<form id="led_pin_form" method="post" action="/led_pin">
|
|
||||||
<label for="num_leds">Led pin:</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
id="led_pin"
|
|
||||||
name="led_pin"
|
|
||||||
value="{{settings['led_pin']}}"
|
|
||||||
/>
|
|
||||||
<input type="submit" value="Update Led Pin" />
|
|
||||||
</form>
|
|
||||||
<form id="color_order_form">
|
|
||||||
<label for="rgb">RGB:</label>
|
|
||||||
<input type="radio" id="rgb" name="color_order" value="rgb" {{'checked' if settings["color_order"]=="rgb" else ''}} />
|
|
||||||
<label for="rbg">RBG</label>
|
|
||||||
<input type="radio" id="rbg" name="color_order" value="rbg" {{'checked' if settings["color_order"]=="rbg" else ''}}/>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<p>Mac address: {{mac}}</p>
|
|
||||||
</div>
|
|
||||||
<div id="connection-status"></div>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
43
src/web.py
43
src/web.py
@@ -1,43 +0,0 @@
|
|||||||
from microdot import Microdot, send_file, Response
|
|
||||||
from microdot.utemplate import Template
|
|
||||||
from microdot.websocket import with_websocket
|
|
||||||
import machine
|
|
||||||
import wifi
|
|
||||||
import json
|
|
||||||
|
|
||||||
def web(settings, patterns):
|
|
||||||
app = Microdot()
|
|
||||||
Response.default_content_type = 'text/html'
|
|
||||||
|
|
||||||
@app.route('/')
|
|
||||||
async def index_hnadler(request):
|
|
||||||
mac = wifi.get_mac().hex()
|
|
||||||
return Template('index.html').render(settings=settings, patterns=patterns.patterns.keys())
|
|
||||||
|
|
||||||
@app.route("/static/<path:path>")
|
|
||||||
def static_handler(request, path):
|
|
||||||
if '..' in path:
|
|
||||||
# Directory traversal is not allowed
|
|
||||||
return 'Not found', 404
|
|
||||||
return send_file('static/' + path)
|
|
||||||
|
|
||||||
@app.post("/settings")
|
|
||||||
def settings_handler(request):
|
|
||||||
# Keep the POST handler for compatibility or alternative usage if needed
|
|
||||||
# For WebSocket updates, the /ws handler is now primary
|
|
||||||
return settings.set_settings(request.body.decode('utf-8'), patterns)
|
|
||||||
|
|
||||||
@app.route("/ws")
|
|
||||||
@with_websocket
|
|
||||||
async def ws(request, ws):
|
|
||||||
while True:
|
|
||||||
data = await ws.receive()
|
|
||||||
if data:
|
|
||||||
|
|
||||||
# Process the received data
|
|
||||||
_, status_code = await settings.set_settings(json.loads(data), patterns, True)
|
|
||||||
#await ws.send(status_code)
|
|
||||||
else:
|
|
||||||
break
|
|
||||||
|
|
||||||
return app
|
|
||||||
39
src/wifi.py
39
src/wifi.py
@@ -1,39 +0,0 @@
|
|||||||
import network
|
|
||||||
from time import sleep
|
|
||||||
|
|
||||||
def connect(ssid, password, ip, gateway):
|
|
||||||
|
|
||||||
try:
|
|
||||||
sta_if = network.WLAN(network.STA_IF)
|
|
||||||
if not sta_if.isconnected():
|
|
||||||
if ssid == "" or password == "":
|
|
||||||
print("Missing ssid or password")
|
|
||||||
return None
|
|
||||||
if ip != "" and gateway != "":
|
|
||||||
sta_if.ifconfig((ip, '255.255.255.0', gateway, '1.1.1.1'))
|
|
||||||
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(ssid, password):
|
|
||||||
ap_if = network.WLAN(network.AP_IF)
|
|
||||||
ap_mac = ap_if.config('mac')
|
|
||||||
print(ssid)
|
|
||||||
ap_if.active(True)
|
|
||||||
ap_if.config(essid=ssid, password=password)
|
|
||||||
ap_if.active(False)
|
|
||||||
ap_if.active(True)
|
|
||||||
print(ap_if.ifconfig())
|
|
||||||
|
|
||||||
def get_mac():
|
|
||||||
ap_if = network.WLAN(network.AP_IF)
|
|
||||||
return ap_if.config('mac')
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""
|
|
||||||
Circle test: n1=50, n2=100, n3=200, n4=0 (Red)
|
|
||||||
Runs forever
|
|
||||||
Run with: mpremote run test/circle.py
|
|
||||||
"""
|
|
||||||
|
|
||||||
import patterns
|
|
||||||
import utime
|
|
||||||
import _thread
|
|
||||||
from settings import Settings
|
|
||||||
from machine import WDT
|
|
||||||
|
|
||||||
print("Starting Circle Test: n1=50, n2=100, n3=200, n4=0 (Red)")
|
|
||||||
print("Press Ctrl+C to stop")
|
|
||||||
|
|
||||||
# Load settings
|
|
||||||
settings = Settings()
|
|
||||||
|
|
||||||
# Initialize patterns using settings
|
|
||||||
p = patterns.Patterns(
|
|
||||||
pin=settings["led_pin"],
|
|
||||||
num_leds=settings["num_leds"],
|
|
||||||
brightness=255,
|
|
||||||
delay=2000
|
|
||||||
)
|
|
||||||
|
|
||||||
# Configure test parameters
|
|
||||||
p.n1 = 50 # Head moves 50 LEDs/second
|
|
||||||
p.n2 = 100 # Max length 100 LEDs
|
|
||||||
p.n3 = 200 # Tail moves 200 LEDs/second
|
|
||||||
p.n4 = 0 # Min length 0 LEDs
|
|
||||||
p.colors = [(255, 0, 0)] # Red
|
|
||||||
|
|
||||||
print(f"LED Pin: {settings['led_pin']}")
|
|
||||||
print(f"LEDs: {settings['num_leds']}")
|
|
||||||
print(f"Brightness: {p.brightness}")
|
|
||||||
print(f"Parameters: n1={p.n1}, n2={p.n2}, n3={p.n3}, n4={p.n4}")
|
|
||||||
print(f"Color: {p.colors[0]}")
|
|
||||||
|
|
||||||
# Initialize watchdog timer
|
|
||||||
wdt = WDT(timeout=10000)
|
|
||||||
wdt.feed()
|
|
||||||
|
|
||||||
# Start pattern
|
|
||||||
p.select("circle")
|
|
||||||
if p.selected in p.patterns:
|
|
||||||
_thread.start_new_thread(p.patterns[p.selected], ())
|
|
||||||
print("Pattern started. Running forever...")
|
|
||||||
else:
|
|
||||||
print(f"Pattern {p.selected} not found")
|
|
||||||
|
|
||||||
# Run forever
|
|
||||||
try:
|
|
||||||
while True:
|
|
||||||
wdt.feed()
|
|
||||||
utime.sleep_ms(100)
|
|
||||||
except KeyboardInterrupt:
|
|
||||||
print("\nStopping...")
|
|
||||||
p.running = False
|
|
||||||
p.off()
|
|
||||||
print("LEDs turned off")
|
|
||||||
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
import uasyncio as asyncio
|
|
||||||
from machine import WDT
|
|
||||||
from settings import Settings
|
|
||||||
from patterns import Patterns
|
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
|
||||||
s = Settings()
|
|
||||||
pin = s.get("led_pin", 10)
|
|
||||||
num = s.get("num_leds", 30)
|
|
||||||
|
|
||||||
p = Patterns(pin=pin, num_leds=num)
|
|
||||||
p.load()
|
|
||||||
print(p)
|
|
||||||
p.save()
|
|
||||||
# print(p)
|
|
||||||
|
|
||||||
|
|
||||||
# wdt = WDT(timeout=10000)
|
|
||||||
|
|
||||||
# # Baseline params
|
|
||||||
# p.set_param("br", 64)
|
|
||||||
# p.set_param("dl", 500)
|
|
||||||
# p.set_param("cl", [(255, 0, 0), (0, 0, 255)])
|
|
||||||
# p.set_param("n1", 200)
|
|
||||||
# p.set_param("n2", 200)
|
|
||||||
# p.set_param("n3", 1)
|
|
||||||
# p.set_param("n4", 1)
|
|
||||||
|
|
||||||
# for name, fn in p.patterns.items():
|
|
||||||
# if fn is None:
|
|
||||||
# continue
|
|
||||||
# print(name)
|
|
||||||
# p.set_param("pt", name)
|
|
||||||
# task = asyncio.create_task(p.run())
|
|
||||||
# end = asyncio.get_event_loop().time() + 2.0
|
|
||||||
# while asyncio.get_event_loop().time() < end:
|
|
||||||
# wdt.feed()
|
|
||||||
# await asyncio.sleep_ms(10)
|
|
||||||
# p.stopped = True
|
|
||||||
# await task
|
|
||||||
# p.stopped = False
|
|
||||||
|
|
||||||
# p.set_param("pt", "off")
|
|
||||||
# task = asyncio.create_task(p.run())
|
|
||||||
# await asyncio.sleep_ms(200)
|
|
||||||
# p.stopped = True
|
|
||||||
# await task
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
asyncio.run(main())
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
import uasyncio as asyncio
|
|
||||||
import utime
|
|
||||||
from machine import WDT
|
|
||||||
from settings import Settings
|
|
||||||
from patterns import Patterns
|
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
|
||||||
s = Settings()
|
|
||||||
pin = s.get("led_pin", 10)
|
|
||||||
num = s.get("num_leds", 30)
|
|
||||||
|
|
||||||
p = Patterns(pin=pin, num_leds=num)
|
|
||||||
wdt = WDT(timeout=10000)
|
|
||||||
p.set_param("br", 64)
|
|
||||||
p.set_param("dl", 200)
|
|
||||||
p.set_param("cl", [(255, 0, 0), (0, 0, 255)])
|
|
||||||
p.select("blink")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 1500:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
asyncio.run(main())
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,132 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
import uasyncio as asyncio
|
|
||||||
import utime
|
|
||||||
from machine import WDT
|
|
||||||
from settings import Settings
|
|
||||||
from patterns import Patterns
|
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
|
||||||
s = Settings()
|
|
||||||
pin = s.get("led_pin", 10)
|
|
||||||
num = s.get("num_leds", 30)
|
|
||||||
|
|
||||||
p = Patterns(pin=pin, num_leds=num)
|
|
||||||
wdt = WDT(timeout=10000)
|
|
||||||
|
|
||||||
# Test 1: Basic circle (n1=50, n2=100, n3=200, n4=0)
|
|
||||||
print("Test 1: Basic circle (n1=50, n2=100, n3=200, n4=0)")
|
|
||||||
p.set_param("br", 255)
|
|
||||||
p.set_param("n1", 50) # Head moves 50 LEDs/second
|
|
||||||
p.set_param("n2", 100) # Max length 100 LEDs
|
|
||||||
p.set_param("n3", 200) # Tail moves 200 LEDs/second
|
|
||||||
p.set_param("n4", 0) # Min length 0 LEDs
|
|
||||||
p.set_param("cl", [(255, 0, 0)]) # Red
|
|
||||||
p.select("circle")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
# Run for 5 seconds to see full cycle
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 5000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 2: Slow growth, fast shrink (n1=20, n2=50, n3=100, n4=0)
|
|
||||||
print("Test 2: Slow growth, fast shrink (n1=20, n2=50, n3=100, n4=0)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("n1", 20) # Head moves 20 LEDs/second (slow)
|
|
||||||
p.set_param("n2", 50) # Max length 50 LEDs
|
|
||||||
p.set_param("n3", 100) # Tail moves 100 LEDs/second (fast)
|
|
||||||
p.set_param("n4", 0) # Min length 0 LEDs
|
|
||||||
p.set_param("cl", [(0, 255, 0)]) # Green
|
|
||||||
p.select("circle")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 5000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 3: Fast growth, slow shrink (n1=100, n2=30, n3=20, n4=0)
|
|
||||||
print("Test 3: Fast growth, slow shrink (n1=100, n2=30, n3=20, n4=0)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("n1", 100) # Head moves 100 LEDs/second (fast)
|
|
||||||
p.set_param("n2", 30) # Max length 30 LEDs
|
|
||||||
p.set_param("n3", 20) # Tail moves 20 LEDs/second (slow)
|
|
||||||
p.set_param("n4", 0) # Min length 0 LEDs
|
|
||||||
p.set_param("cl", [(0, 0, 255)]) # Blue
|
|
||||||
p.select("circle")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 5000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 4: With minimum length (n1=50, n2=40, n3=100, n4=10)
|
|
||||||
print("Test 4: With minimum length (n1=50, n2=40, n3=100, n4=10)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("n1", 50) # Head moves 50 LEDs/second
|
|
||||||
p.set_param("n2", 40) # Max length 40 LEDs
|
|
||||||
p.set_param("n3", 100) # Tail moves 100 LEDs/second
|
|
||||||
p.set_param("n4", 10) # Min length 10 LEDs (never fully disappears)
|
|
||||||
p.set_param("cl", [(255, 255, 0)]) # Yellow
|
|
||||||
p.select("circle")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 5000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 5: Very fast (n1=200, n2=20, n3=200, n4=0)
|
|
||||||
print("Test 5: Very fast (n1=200, n2=20, n3=200, n4=0)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("n1", 200) # Head moves 200 LEDs/second (very fast)
|
|
||||||
p.set_param("n2", 20) # Max length 20 LEDs
|
|
||||||
p.set_param("n3", 200) # Tail moves 200 LEDs/second (very fast)
|
|
||||||
p.set_param("n4", 0) # Min length 0 LEDs
|
|
||||||
p.set_param("cl", [(255, 0, 255)]) # Magenta
|
|
||||||
p.select("circle")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 3000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 6: Very slow (n1=10, n2=25, n3=10, n4=0)
|
|
||||||
print("Test 6: Very slow (n1=10, n2=25, n3=10, n4=0)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("n1", 10) # Head moves 10 LEDs/second (very slow)
|
|
||||||
p.set_param("n2", 25) # Max length 25 LEDs
|
|
||||||
p.set_param("n3", 10) # Tail moves 10 LEDs/second (very slow)
|
|
||||||
p.set_param("n4", 0) # Min length 0 LEDs
|
|
||||||
p.set_param("cl", [(0, 255, 255)]) # Cyan
|
|
||||||
p.select("circle")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 5000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Cleanup
|
|
||||||
print("Test complete, turning off")
|
|
||||||
p.stopped = False
|
|
||||||
p.select("off")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
await asyncio.sleep_ms(100)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
asyncio.run(main())
|
|
||||||
|
|
||||||
@@ -1,144 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
import uasyncio as asyncio
|
|
||||||
import utime
|
|
||||||
from machine import WDT
|
|
||||||
from settings import Settings
|
|
||||||
from patterns import Patterns
|
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
|
||||||
s = Settings()
|
|
||||||
pin = s.get("led_pin", 10)
|
|
||||||
num = s.get("num_leds", 30)
|
|
||||||
|
|
||||||
p = Patterns(pin=pin, num_leds=num)
|
|
||||||
wdt = WDT(timeout=10000)
|
|
||||||
|
|
||||||
# Test 1: Basic n_chase (n1=5, n2=5, n3=1, n4=1)
|
|
||||||
print("Test 1: Basic n_chase (n1=5, n2=5, n3=1, n4=1)")
|
|
||||||
p.set_param("br", 255)
|
|
||||||
p.set_param("dl", 200)
|
|
||||||
p.set_param("n1", 5) # 5 LEDs color0
|
|
||||||
p.set_param("n2", 5) # 5 LEDs color1
|
|
||||||
p.set_param("n3", 1) # Move 1 forward on even steps
|
|
||||||
p.set_param("n4", 1) # Move 1 forward on odd steps
|
|
||||||
p.set_param("cl", [(255, 0, 0), (0, 255, 0)]) # Red and Green
|
|
||||||
p.select("n_chase")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 3000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 2: Forward and backward (n3=2, n4=-1)
|
|
||||||
print("Test 2: Forward and backward (n3=2, n4=-1)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("n1", 3)
|
|
||||||
p.set_param("n2", 3)
|
|
||||||
p.set_param("n3", 2) # Move 2 forward on even steps
|
|
||||||
p.set_param("n4", -1) # Move 1 backward on odd steps
|
|
||||||
p.set_param("dl", 150)
|
|
||||||
p.set_param("cl", [(0, 0, 255), (255, 255, 0)]) # Blue and Yellow
|
|
||||||
p.select("n_chase")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 3000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 3: Large segments (n1=10, n2=5)
|
|
||||||
print("Test 3: Large segments (n1=10, n2=5, n3=3, n4=3)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("n1", 10) # 10 LEDs color0
|
|
||||||
p.set_param("n2", 5) # 5 LEDs color1
|
|
||||||
p.set_param("n3", 3) # Move 3 forward
|
|
||||||
p.set_param("n4", 3) # Move 3 forward
|
|
||||||
p.set_param("dl", 200)
|
|
||||||
p.set_param("cl", [(255, 128, 0), (128, 0, 255)]) # Orange and Purple
|
|
||||||
p.select("n_chase")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 3000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 4: Fast movement (n3=5, n4=5)
|
|
||||||
print("Test 4: Fast movement (n3=5, n4=5)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("n1", 4)
|
|
||||||
p.set_param("n2", 4)
|
|
||||||
p.set_param("n3", 5) # Move 5 forward
|
|
||||||
p.set_param("n4", 5) # Move 5 forward
|
|
||||||
p.set_param("dl", 100)
|
|
||||||
p.set_param("cl", [(255, 0, 255), (0, 255, 255)]) # Magenta and Cyan
|
|
||||||
p.select("n_chase")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 2000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 5: Backward movement (n3=-2, n4=-2)
|
|
||||||
print("Test 5: Backward movement (n3=-2, n4=-2)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("n1", 6)
|
|
||||||
p.set_param("n2", 4)
|
|
||||||
p.set_param("n3", -2) # Move 2 backward
|
|
||||||
p.set_param("n4", -2) # Move 2 backward
|
|
||||||
p.set_param("dl", 200)
|
|
||||||
p.set_param("cl", [(255, 255, 255), (0, 0, 0)]) # White and Black
|
|
||||||
p.select("n_chase")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 3000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 6: Alternating forward/backward (n3=3, n4=-2)
|
|
||||||
print("Test 6: Alternating forward/backward (n3=3, n4=-2)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("n1", 5)
|
|
||||||
p.set_param("n2", 5)
|
|
||||||
p.set_param("n3", 3) # Move 3 forward on even steps
|
|
||||||
p.set_param("n4", -2) # Move 2 backward on odd steps
|
|
||||||
p.set_param("dl", 250)
|
|
||||||
p.set_param("cl", [(255, 0, 0), (0, 255, 0)]) # Red and Green
|
|
||||||
p.select("n_chase")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 4000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Cleanup
|
|
||||||
print("Test complete, turning off")
|
|
||||||
p.stopped = False
|
|
||||||
p.select("off")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
await asyncio.sleep_ms(100)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
asyncio.run(main())
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
import uasyncio as asyncio
|
|
||||||
from machine import WDT
|
|
||||||
from settings import Settings
|
|
||||||
from patterns import Patterns
|
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
|
||||||
s = Settings()
|
|
||||||
pin = s.get("led_pin", 10)
|
|
||||||
num = s.get("num_leds", 30)
|
|
||||||
|
|
||||||
p = Patterns(pin=pin, num_leds=num)
|
|
||||||
wdt = WDT(timeout=10000)
|
|
||||||
p.select("off")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(200)
|
|
||||||
p.stopped = True
|
|
||||||
await task
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
asyncio.run(main())
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
import uasyncio as asyncio
|
|
||||||
from machine import WDT
|
|
||||||
from settings import Settings
|
|
||||||
from patterns import Patterns
|
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
|
||||||
s = Settings()
|
|
||||||
pin = s.get("led_pin", 10)
|
|
||||||
num = s.get("num_leds", 30)
|
|
||||||
|
|
||||||
p = Patterns(pin=pin, num_leds=num)
|
|
||||||
wdt = WDT(timeout=10000)
|
|
||||||
p.set_param("br", 64)
|
|
||||||
p.set_param("dl", 120)
|
|
||||||
p.set_param("cl", [(255, 0, 0), (0, 0, 255)])
|
|
||||||
p.select("on")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
await asyncio.sleep_ms(800)
|
|
||||||
p.stopped = True
|
|
||||||
await task
|
|
||||||
p.stopped = False
|
|
||||||
p.select("off")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
await asyncio.sleep_ms(100)
|
|
||||||
p.stopped = True
|
|
||||||
await task
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
asyncio.run(main())
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,160 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
import uasyncio as asyncio
|
|
||||||
import utime
|
|
||||||
from machine import WDT
|
|
||||||
from settings import Settings
|
|
||||||
from patterns import Patterns
|
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
|
||||||
s = Settings()
|
|
||||||
pin = s.get("led_pin", 10)
|
|
||||||
num = s.get("num_leds", 30)
|
|
||||||
|
|
||||||
p = Patterns(pin=pin, num_leds=num)
|
|
||||||
wdt = WDT(timeout=10000)
|
|
||||||
|
|
||||||
# Test 1: Basic pulse with attack, hold, and decay
|
|
||||||
print("Test 1: Basic pulse pattern")
|
|
||||||
p.set_param("br", 255)
|
|
||||||
p.set_param("dl", 1000) # 1 second delay between pulses
|
|
||||||
p.set_param("auto", True) # Run continuously
|
|
||||||
p.set_param("cl", [(255, 255, 255), (255, 255, 255)])
|
|
||||||
p.set_param("n1", 200) # Attack: 200ms
|
|
||||||
p.set_param("n2", 200) # Hold: 200ms
|
|
||||||
p.set_param("n3", 200) # Decay: 200ms
|
|
||||||
p.select("pulse")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
# Run for 3 seconds to see multiple pulse cycles
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 3000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
p.stopped = True
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 2: Fast pulse with shorter delay
|
|
||||||
print("Test 2: Fast pulse pattern")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("dl", 500) # 500ms delay between pulses
|
|
||||||
p.set_param("auto", True) # Run continuously
|
|
||||||
p.set_param("n1", 100) # Attack: 100ms
|
|
||||||
p.set_param("n2", 100) # Hold: 100ms
|
|
||||||
p.set_param("n3", 100) # Decay: 100ms
|
|
||||||
p.select("pulse")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
# Run for 2 seconds
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 2000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
p.stopped = True
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 3: Colored pulse
|
|
||||||
print("Test 3: Colored pulse pattern")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("dl", 800)
|
|
||||||
p.set_param("auto", True) # Run continuously
|
|
||||||
p.set_param("cl", [(255, 0, 0), (0, 0, 255)]) # Red pulse
|
|
||||||
p.set_param("n1", 150)
|
|
||||||
p.set_param("n2", 150)
|
|
||||||
p.set_param("n3", 150)
|
|
||||||
p.select("pulse")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
# Run for 2 seconds
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 2000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
p.stopped = True
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 4: Verify delay restart timing
|
|
||||||
print("Test 4: Testing delay restart timing")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("dl", 500) # 500ms delay
|
|
||||||
p.set_param("auto", True) # Run continuously
|
|
||||||
p.set_param("n1", 100) # Total attack+hold+decay = 300ms, should wait 200ms more
|
|
||||||
p.set_param("n2", 100)
|
|
||||||
p.set_param("n3", 100)
|
|
||||||
p.select("pulse")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
|
|
||||||
# Monitor pulse cycles
|
|
||||||
cycle_count = 0
|
|
||||||
last_cycle_time = utime.ticks_ms()
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 3000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
# Check if we're near the start of a new cycle (LEDs off)
|
|
||||||
# This is a simplified check - in practice you'd monitor LED state
|
|
||||||
p.stopped = True
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 5: Single-shot pulse (auto=False)
|
|
||||||
print("Test 5: Single-shot pulse (auto=False)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("dl", 500) # Delay between pulses
|
|
||||||
p.set_param("auto", False) # Run only once
|
|
||||||
p.set_param("cl", [(0, 255, 0), (0, 255, 0)]) # Green pulse
|
|
||||||
p.set_param("n1", 150) # Attack: 150ms
|
|
||||||
p.set_param("n2", 150) # Hold: 150ms
|
|
||||||
p.set_param("n3", 150) # Decay: 150ms
|
|
||||||
p.select("pulse")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
|
|
||||||
# The pulse should complete once and then stop
|
|
||||||
# Total time should be ~450ms (attack + hold + decay)
|
|
||||||
# Wait a bit longer to verify it doesn't repeat
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 1000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
|
|
||||||
# Task should have completed on its own (not stopped manually)
|
|
||||||
# Verify it's stopped
|
|
||||||
if not p.stopped:
|
|
||||||
print("Warning: Pulse should have stopped automatically with auto=False")
|
|
||||||
p.stopped = True
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 6: Pulse cycles through colors
|
|
||||||
print("Test 6: Pulse cycles through colors")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("dl", 300) # cycle interval
|
|
||||||
p.set_param("auto", True) # Run continuously
|
|
||||||
p.set_param("cl", [
|
|
||||||
(255, 0, 0), # red
|
|
||||||
(0, 255, 0), # green
|
|
||||||
(0, 0, 255), # blue
|
|
||||||
(255, 255, 0), # yellow
|
|
||||||
])
|
|
||||||
p.set_param("n1", 50)
|
|
||||||
p.set_param("n2", 0)
|
|
||||||
p.set_param("n3", 50)
|
|
||||||
p.select("pulse")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
# Run long enough to observe multiple color cycles
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 10000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
p.stopped = True
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Cleanup
|
|
||||||
print("Test complete, turning off")
|
|
||||||
p.stopped = False
|
|
||||||
p.select("off")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
await asyncio.sleep_ms(100)
|
|
||||||
p.stopped = True
|
|
||||||
await task
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
asyncio.run(main())
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,167 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
import uasyncio as asyncio
|
|
||||||
import utime
|
|
||||||
from machine import WDT
|
|
||||||
from settings import Settings
|
|
||||||
from patterns import Patterns
|
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
|
||||||
s = Settings()
|
|
||||||
pin = s.get("led_pin", 10)
|
|
||||||
num = s.get("num_leds", 30)
|
|
||||||
|
|
||||||
p = Patterns(pin=pin, num_leds=num)
|
|
||||||
wdt = WDT(timeout=10000)
|
|
||||||
|
|
||||||
# Test 1: Basic rainbow with auto=True (continuous)
|
|
||||||
print("Test 1: Basic rainbow (auto=True, n1=1)")
|
|
||||||
p.set_param("br", 255)
|
|
||||||
p.set_param("dl", 100) # Delay affects animation speed
|
|
||||||
p.set_param("n1", 1) # Step increment of 1
|
|
||||||
p.set_param("auto", True) # Run continuously
|
|
||||||
p.select("rainbow")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
# Run for 3 seconds to see rainbow animation
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 3000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 2: Fast rainbow
|
|
||||||
print("Test 2: Fast rainbow (low delay, n1=1)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("dl", 50) # Faster animation
|
|
||||||
p.set_param("n1", 1)
|
|
||||||
p.set_param("auto", True)
|
|
||||||
p.select("rainbow")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 2000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 3: Slow rainbow
|
|
||||||
print("Test 3: Slow rainbow (high delay, n1=1)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("dl", 500) # Slower animation
|
|
||||||
p.set_param("n1", 1)
|
|
||||||
p.set_param("auto", True)
|
|
||||||
p.select("rainbow")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 3000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 4: Low brightness rainbow
|
|
||||||
print("Test 4: Low brightness rainbow (n1=1)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("br", 64) # Low brightness
|
|
||||||
p.set_param("dl", 100)
|
|
||||||
p.set_param("n1", 1)
|
|
||||||
p.set_param("auto", True)
|
|
||||||
p.select("rainbow")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 2000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 5: Single-step rainbow (auto=False)
|
|
||||||
print("Test 5: Single-step rainbow (auto=False, n1=1)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("br", 255)
|
|
||||||
p.set_param("dl", 100)
|
|
||||||
p.set_param("n1", 1)
|
|
||||||
p.set_param("auto", False) # Run once per call
|
|
||||||
p.set_param("step", 0) # Reset step
|
|
||||||
p.select("rainbow")
|
|
||||||
|
|
||||||
# Call rainbow multiple times to see step progression
|
|
||||||
for i in range(10):
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
await task
|
|
||||||
await asyncio.sleep_ms(100) # Small delay between steps
|
|
||||||
wdt.feed()
|
|
||||||
|
|
||||||
# Test 6: Verify step updates correctly
|
|
||||||
print("Test 6: Verify step updates (auto=False, n1=1)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("n1", 1)
|
|
||||||
initial_step = p.step
|
|
||||||
p.select("rainbow")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
await task
|
|
||||||
final_step = p.step
|
|
||||||
print(f"Step updated from {initial_step} to {final_step} (expected increment: 1)")
|
|
||||||
|
|
||||||
# Test 7: Fast step increment (n1=5)
|
|
||||||
print("Test 7: Fast rainbow (n1=5, auto=True)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("br", 255)
|
|
||||||
p.set_param("dl", 100)
|
|
||||||
p.set_param("n1", 5) # Step increment of 5 (5x faster)
|
|
||||||
p.set_param("auto", True)
|
|
||||||
p.select("rainbow")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 2000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 8: Very fast step increment (n1=10)
|
|
||||||
print("Test 8: Very fast rainbow (n1=10, auto=True)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("n1", 10) # Step increment of 10 (10x faster)
|
|
||||||
p.set_param("auto", True)
|
|
||||||
p.select("rainbow")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 2000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 9: Verify n1 controls step increment (auto=False)
|
|
||||||
print("Test 9: Verify n1 step increment (auto=False, n1=5)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("n1", 5) # Step increment of 5
|
|
||||||
p.set_param("auto", False)
|
|
||||||
p.set_param("step", 0) # Reset step
|
|
||||||
initial_step = p.step
|
|
||||||
p.select("rainbow")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
await task
|
|
||||||
final_step = p.step
|
|
||||||
expected_step = (initial_step + 5) % 256
|
|
||||||
print(f"Step updated from {initial_step} to {final_step} (expected: {expected_step})")
|
|
||||||
if final_step == expected_step:
|
|
||||||
print("✓ n1 step increment working correctly")
|
|
||||||
else:
|
|
||||||
print(f"✗ Step increment mismatch! Expected {expected_step}, got {final_step}")
|
|
||||||
|
|
||||||
# Cleanup
|
|
||||||
print("Test complete, turning off")
|
|
||||||
p.stopped = False
|
|
||||||
p.select("off")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
await asyncio.sleep_ms(100)
|
|
||||||
await p.stop()
|
|
||||||
await task
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
asyncio.run(main())
|
|
||||||
|
|
||||||
@@ -1,165 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
import uasyncio as asyncio
|
|
||||||
import utime
|
|
||||||
from machine import WDT
|
|
||||||
from settings import Settings
|
|
||||||
from patterns import Patterns
|
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
|
||||||
s = Settings()
|
|
||||||
pin = s.get("led_pin", 10)
|
|
||||||
num = s.get("num_leds", 30)
|
|
||||||
|
|
||||||
p = Patterns(pin=pin, num_leds=num)
|
|
||||||
wdt = WDT(timeout=10000)
|
|
||||||
|
|
||||||
# Test 1: Basic transition with 2 colors (auto=True, cycles continuously)
|
|
||||||
print("Test 1: Basic transition (2 colors, 1000ms delay, auto=True)")
|
|
||||||
p.set_param("br", 255)
|
|
||||||
p.set_param("dl", 1000) # 1 second transition time
|
|
||||||
p.set_param("auto", True) # Cycle continuously
|
|
||||||
p.set_param("cl", [(255, 0, 0), (0, 255, 0)]) # Red to Green
|
|
||||||
p.select("transition")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
# Run for 5 seconds to see multiple transitions
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 5000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
p.stopped = True
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 2: Fast transition (auto=True, cycles continuously)
|
|
||||||
print("Test 2: Fast transition (500ms delay, auto=True)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("dl", 500) # 500ms transition time
|
|
||||||
p.set_param("auto", True) # Cycle continuously
|
|
||||||
p.set_param("cl", [(0, 0, 255), (255, 255, 0)]) # Blue to Yellow
|
|
||||||
p.select("transition")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
# Run for 3 seconds
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 3000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
p.stopped = True
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 3: Multiple colors transition (auto=True, cycles continuously)
|
|
||||||
print("Test 3: Multiple colors transition (3 colors, auto=True)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("dl", 800)
|
|
||||||
p.set_param("auto", True) # Cycle continuously
|
|
||||||
p.set_param("cl", [
|
|
||||||
(255, 0, 0), # Red
|
|
||||||
(0, 255, 0), # Green
|
|
||||||
(0, 0, 255), # Blue
|
|
||||||
])
|
|
||||||
p.select("transition")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
# Run for 8 seconds to see full cycles
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 8000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
p.stopped = True
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 4: Single color (should just stay that color)
|
|
||||||
print("Test 4: Single color (should stay that color)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("dl", 1000)
|
|
||||||
p.set_param("cl", [(255, 128, 0)]) # Orange
|
|
||||||
p.select("transition")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
# Run for 3 seconds
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 3000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
p.stopped = True
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 5: Many colors transition (auto=True, cycles continuously)
|
|
||||||
print("Test 5: Many colors transition (5 colors, auto=True)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("dl", 600)
|
|
||||||
p.set_param("auto", True) # Cycle continuously
|
|
||||||
p.set_param("cl", [
|
|
||||||
(255, 0, 0), # Red
|
|
||||||
(255, 128, 0), # Orange
|
|
||||||
(255, 255, 0), # Yellow
|
|
||||||
(0, 255, 0), # Green
|
|
||||||
(0, 0, 255), # Blue
|
|
||||||
])
|
|
||||||
p.select("transition")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
# Run for 10 seconds to see multiple cycles
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 10000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
p.stopped = True
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 6: Low brightness transition (auto=True, cycles continuously)
|
|
||||||
print("Test 6: Low brightness transition (auto=True)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("br", 64) # Low brightness
|
|
||||||
p.set_param("dl", 1000)
|
|
||||||
p.set_param("auto", True) # Cycle continuously
|
|
||||||
p.set_param("cl", [(255, 0, 0), (0, 255, 0)])
|
|
||||||
p.select("transition")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
# Run for 3 seconds
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 3000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
p.stopped = True
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Test 7: Single-shot transition (auto=False, only color1 to color2)
|
|
||||||
print("Test 7: Single-shot transition (auto=False, color1 to color2 only)")
|
|
||||||
p.stopped = False
|
|
||||||
p.set_param("br", 255)
|
|
||||||
p.set_param("dl", 1000) # 1 second transition
|
|
||||||
p.set_param("auto", False) # Run only once
|
|
||||||
p.set_param("cl", [
|
|
||||||
(255, 0, 0), # Red (color1)
|
|
||||||
(0, 255, 0), # Green (color2)
|
|
||||||
(0, 0, 255), # Blue (should be ignored)
|
|
||||||
(255, 255, 0), # Yellow (should be ignored)
|
|
||||||
])
|
|
||||||
p.select("transition")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
|
|
||||||
# The transition should complete once (color1 to color2) and then stop
|
|
||||||
# Total time should be ~1000ms
|
|
||||||
# Wait a bit longer to verify it doesn't continue
|
|
||||||
start = utime.ticks_ms()
|
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 2000:
|
|
||||||
wdt.feed()
|
|
||||||
await asyncio.sleep_ms(10)
|
|
||||||
|
|
||||||
# Task should have completed on its own (not stopped manually)
|
|
||||||
# Verify it's stopped
|
|
||||||
if not p.stopped:
|
|
||||||
print("Warning: Transition should have stopped automatically with auto=False")
|
|
||||||
p.stopped = True
|
|
||||||
await task
|
|
||||||
|
|
||||||
# Cleanup
|
|
||||||
print("Test complete, turning off")
|
|
||||||
p.stopped = False
|
|
||||||
p.select("off")
|
|
||||||
task = asyncio.create_task(p.run())
|
|
||||||
await asyncio.sleep_ms(100)
|
|
||||||
p.stopped = True
|
|
||||||
await task
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
asyncio.run(main())
|
|
||||||
|
|
||||||
@@ -1,111 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""
|
|
||||||
Test for saving and loading patterns
|
|
||||||
Run with: mpremote run test/test_patterns_save_load.py
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import uasyncio as asyncio
|
|
||||||
from settings import Settings
|
|
||||||
from patterns import Patterns
|
|
||||||
|
|
||||||
|
|
||||||
async def test_patterns_save_load():
|
|
||||||
"""Test saving and loading patterns"""
|
|
||||||
print("Testing patterns save and load functionality...")
|
|
||||||
|
|
||||||
# Test 1: Initialize patterns and check initial state
|
|
||||||
print("\nTest 1: Initialize patterns")
|
|
||||||
s = Settings()
|
|
||||||
pin = s.get("led_pin", 10)
|
|
||||||
num_leds = s.get("num_leds", 30)
|
|
||||||
|
|
||||||
p1 = Patterns(pin=pin, num_leds=num_leds)
|
|
||||||
print(f"Initial patterns count: {len(p1.patterns)}")
|
|
||||||
print(f"Available patterns: {list(p1.patterns.keys())}")
|
|
||||||
print(f"Selected pattern: {p1.selected}")
|
|
||||||
|
|
||||||
# Test 2: Try to save patterns (will fail because patterns contain functions)
|
|
||||||
print("\nTest 2: Attempt to save patterns")
|
|
||||||
try:
|
|
||||||
result = p1.save()
|
|
||||||
if result:
|
|
||||||
print("✓ Patterns saved successfully")
|
|
||||||
else:
|
|
||||||
print("✗ Patterns save failed (expected - patterns contain functions)")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"✗ Exception during save: {e}")
|
|
||||||
|
|
||||||
# Test 3: Try to load patterns
|
|
||||||
print("\nTest 3: Attempt to load patterns")
|
|
||||||
try:
|
|
||||||
result = p1.load()
|
|
||||||
if result:
|
|
||||||
print("✓ Patterns loaded successfully")
|
|
||||||
print(f"Patterns after load: {list(p1.patterns.keys())}")
|
|
||||||
else:
|
|
||||||
print("✗ Patterns load failed")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"✗ Exception during load: {e}")
|
|
||||||
|
|
||||||
# Test 4: Test with empty patterns dict (simulating custom patterns)
|
|
||||||
print("\nTest 4: Test save/load with empty patterns dict")
|
|
||||||
p2 = Patterns(pin=pin, num_leds=num_leds)
|
|
||||||
# Store original patterns
|
|
||||||
original_patterns = p2.patterns.copy()
|
|
||||||
# Clear patterns to test save/load with empty dict
|
|
||||||
p2.patterns = {}
|
|
||||||
|
|
||||||
try:
|
|
||||||
result = p2.save()
|
|
||||||
if result:
|
|
||||||
print("✓ Empty patterns dict saved successfully")
|
|
||||||
else:
|
|
||||||
print("✗ Failed to save empty patterns dict")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"✗ Exception saving empty patterns: {e}")
|
|
||||||
|
|
||||||
# Try to load
|
|
||||||
p3 = Patterns(pin=pin, num_leds=num_leds)
|
|
||||||
p3.patterns = {} # Start with empty
|
|
||||||
try:
|
|
||||||
result = p3.load()
|
|
||||||
if result:
|
|
||||||
print("✓ Patterns loaded successfully")
|
|
||||||
print(f"Patterns count after load: {len(p3.patterns)}")
|
|
||||||
else:
|
|
||||||
print("✗ Failed to load patterns")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"✗ Exception loading patterns: {e}")
|
|
||||||
|
|
||||||
# Restore original patterns
|
|
||||||
p2.patterns = original_patterns
|
|
||||||
p3.patterns = original_patterns
|
|
||||||
|
|
||||||
# Test 5: Verify patterns object state
|
|
||||||
print("\nTest 5: Verify patterns object state")
|
|
||||||
print(f"Patterns object type: {type(p1)}")
|
|
||||||
print(f"Has save method: {hasattr(p1, 'save')}")
|
|
||||||
print(f"Has load method: {hasattr(p1, 'load')}")
|
|
||||||
print(f"PATTERNS_FILE: {p1.PATTERNS_FILE}")
|
|
||||||
|
|
||||||
# Test 6: Test pattern selection persists
|
|
||||||
print("\nTest 6: Test pattern selection")
|
|
||||||
test_pattern = "rainbow"
|
|
||||||
if test_pattern in p1.patterns:
|
|
||||||
p1.select(test_pattern)
|
|
||||||
print(f"Selected pattern: {p1.selected}")
|
|
||||||
if p1.selected == test_pattern:
|
|
||||||
print("✓ Pattern selection works")
|
|
||||||
else:
|
|
||||||
print(f"✗ Pattern selection failed. Expected '{test_pattern}', got '{p1.selected}'")
|
|
||||||
else:
|
|
||||||
print(f"Pattern '{test_pattern}' not available")
|
|
||||||
|
|
||||||
print("\n=== Patterns Save/Load test complete ===")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
asyncio.run(test_patterns_save_load())
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""
|
|
||||||
Test for saving and loading settings
|
|
||||||
Run with: mpremote run test/test_save_load.py
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
from settings import Settings
|
|
||||||
from patterns import Patterns
|
|
||||||
|
|
||||||
|
|
||||||
def test_save_load():
|
|
||||||
"""Test saving and loading settings"""
|
|
||||||
print("Testing save and load functionality...")
|
|
||||||
|
|
||||||
# Test 1: Save settings
|
|
||||||
print("\nTest 1: Save settings")
|
|
||||||
settings1 = Settings()
|
|
||||||
|
|
||||||
# Modify some settings
|
|
||||||
original_num_leds = settings1.get("num_leds", 50)
|
|
||||||
original_pattern = settings1.get("pattern", "off")
|
|
||||||
original_brightness = settings1.get("brightness", 127)
|
|
||||||
|
|
||||||
settings1["num_leds"] = 100
|
|
||||||
settings1["pattern"] = "rainbow"
|
|
||||||
settings1["brightness"] = 200
|
|
||||||
settings1["delay"] = 150
|
|
||||||
settings1["color1"] = "#ff0000"
|
|
||||||
settings1["color2"] = "#00ff00"
|
|
||||||
|
|
||||||
print(f"Original num_leds: {original_num_leds}")
|
|
||||||
print(f"Setting num_leds to: {settings1['num_leds']}")
|
|
||||||
print(f"Setting pattern to: {settings1['pattern']}")
|
|
||||||
print(f"Setting brightness to: {settings1['brightness']}")
|
|
||||||
|
|
||||||
# Save settings
|
|
||||||
settings1.save()
|
|
||||||
print("Settings saved")
|
|
||||||
|
|
||||||
# Test 2: Load settings
|
|
||||||
print("\nTest 2: Load settings")
|
|
||||||
settings2 = Settings()
|
|
||||||
|
|
||||||
# Verify loaded values
|
|
||||||
print(f"Loaded num_leds: {settings2['num_leds']}")
|
|
||||||
print(f"Loaded pattern: {settings2['pattern']}")
|
|
||||||
print(f"Loaded brightness: {settings2['brightness']}")
|
|
||||||
print(f"Loaded delay: {settings2.get('delay', 'not set')}")
|
|
||||||
print(f"Loaded color1: {settings2.get('color1', 'not set')}")
|
|
||||||
print(f"Loaded color2: {settings2.get('color2', 'not set')}")
|
|
||||||
|
|
||||||
# Verify values match
|
|
||||||
if settings2["num_leds"] == 100:
|
|
||||||
print("✓ num_leds saved and loaded correctly")
|
|
||||||
else:
|
|
||||||
print(f"✗ num_leds mismatch! Expected 100, got {settings2['num_leds']}")
|
|
||||||
|
|
||||||
if settings2["pattern"] == "rainbow":
|
|
||||||
print("✓ pattern saved and loaded correctly")
|
|
||||||
else:
|
|
||||||
print(f"✗ pattern mismatch! Expected 'rainbow', got '{settings2['pattern']}'")
|
|
||||||
|
|
||||||
if settings2["brightness"] == 200:
|
|
||||||
print("✓ brightness saved and loaded correctly")
|
|
||||||
else:
|
|
||||||
print(f"✗ brightness mismatch! Expected 200, got {settings2['brightness']}")
|
|
||||||
|
|
||||||
# Test 3: Test with patterns
|
|
||||||
print("\nTest 3: Test pattern persistence")
|
|
||||||
pin = settings2.get("led_pin", 10)
|
|
||||||
num_leds = settings2["num_leds"]
|
|
||||||
|
|
||||||
patterns = Patterns(pin=pin, num_leds=num_leds, selected=settings2["pattern"])
|
|
||||||
patterns.set_brightness(settings2["brightness"])
|
|
||||||
patterns.set_delay(settings2["delay"])
|
|
||||||
|
|
||||||
print(f"Pattern selected: {patterns.selected}")
|
|
||||||
print(f"Pattern brightness: {patterns.brightness}")
|
|
||||||
print(f"Pattern delay: {patterns.delay}")
|
|
||||||
|
|
||||||
if patterns.selected == settings2["pattern"]:
|
|
||||||
print("✓ Pattern selection persisted")
|
|
||||||
else:
|
|
||||||
print(f"✗ Pattern mismatch! Expected '{settings2['pattern']}', got '{patterns.selected}'")
|
|
||||||
|
|
||||||
# Test 4: Restore original settings
|
|
||||||
print("\nTest 4: Restore original settings")
|
|
||||||
settings3 = Settings()
|
|
||||||
settings3["num_leds"] = original_num_leds
|
|
||||||
settings3["pattern"] = original_pattern
|
|
||||||
settings3["brightness"] = original_brightness
|
|
||||||
settings3.save()
|
|
||||||
print(f"Restored num_leds to: {original_num_leds}")
|
|
||||||
print(f"Restored pattern to: {original_pattern}")
|
|
||||||
print(f"Restored brightness to: {original_brightness}")
|
|
||||||
|
|
||||||
# Verify restoration
|
|
||||||
settings4 = Settings()
|
|
||||||
if settings4["num_leds"] == original_num_leds:
|
|
||||||
print("✓ Settings restored correctly")
|
|
||||||
else:
|
|
||||||
print(f"✗ Restoration failed! Expected {original_num_leds}, got {settings4['num_leds']}")
|
|
||||||
|
|
||||||
print("\n=== Save/Load test complete ===")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
test_save_load()
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
# LED Bar Configuration Tool
|
|
||||||
|
|
||||||
A tkinter GUI tool for configuring LED bar settings via mpremote.
|
|
||||||
|
|
||||||
## Features
|
|
||||||
|
|
||||||
- Download `settings.json` from MicroPython device using mpremote
|
|
||||||
- Edit LED configuration settings
|
|
||||||
- Upload modified `settings.json` back to device
|
|
||||||
- Load/save settings from/to local files
|
|
||||||
|
|
||||||
## Requirements
|
|
||||||
|
|
||||||
- Python 3.x with tkinter (usually included)
|
|
||||||
- mpremote: `pip install mpremote`
|
|
||||||
|
|
||||||
## Usage
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python3 tool/led_config.py
|
|
||||||
```
|
|
||||||
|
|
||||||
Or make it executable:
|
|
||||||
```bash
|
|
||||||
chmod +x tool/led_config.py
|
|
||||||
./tool/led_config.py
|
|
||||||
```
|
|
||||||
|
|
||||||
## Configuration Fields
|
|
||||||
|
|
||||||
- **LED Pin**: GPIO pin number for LED strip
|
|
||||||
- **Number of LEDs**: Total number of LEDs in the strip
|
|
||||||
- **Color Order**: RGB or RBG color order
|
|
||||||
- **Device Name**: Name identifier for the device
|
|
||||||
- **Pattern**: Current LED pattern
|
|
||||||
- **Color 1/Color 2**: Primary colors (hex format, e.g., #ff0000)
|
|
||||||
- **Delay**: Pattern delay in milliseconds
|
|
||||||
- **Brightness**: LED brightness level
|
|
||||||
- **N1-N6**: Pattern-specific parameters
|
|
||||||
- **AP Password**: WiFi access point password
|
|
||||||
- **ID**: Device ID
|
|
||||||
|
|
||||||
## Device Connection
|
|
||||||
|
|
||||||
Default device is `/dev/ttyUSB0`. Change it in the "Device" field if your device is on a different port (e.g., `/dev/ttyACM0`, `COM3` on Windows).
|
|
||||||
|
|
||||||
## Workflow
|
|
||||||
|
|
||||||
1. Enter your device path (e.g., `/dev/ttyUSB0`)
|
|
||||||
2. Click "Download Settings" to fetch current settings from device
|
|
||||||
3. Edit any settings as needed
|
|
||||||
4. Click "Upload Settings" to save changes back to device
|
|
||||||
|
|
||||||
You can also:
|
|
||||||
- Load settings from a local JSON file
|
|
||||||
- Save current settings to a local JSON file
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,329 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""
|
|
||||||
LED Bar Configuration Tool
|
|
||||||
A tkinter GUI for downloading, editing, and uploading settings.json to/from MicroPython devices via mpremote.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import tkinter as tk
|
|
||||||
from tkinter import ttk, messagebox, filedialog
|
|
||||||
import json
|
|
||||||
import subprocess
|
|
||||||
import os
|
|
||||||
import tempfile
|
|
||||||
import serial
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
|
|
||||||
class LEDConfigTool:
|
|
||||||
def __init__(self, root):
|
|
||||||
self.root = root
|
|
||||||
self.root.title("LED Bar Configuration Tool")
|
|
||||||
self.root.geometry("600x700")
|
|
||||||
|
|
||||||
self.settings = {}
|
|
||||||
self.temp_file = None
|
|
||||||
|
|
||||||
# Create main frame
|
|
||||||
main_frame = ttk.Frame(root, padding="10")
|
|
||||||
main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
|
|
||||||
|
|
||||||
# Title
|
|
||||||
title_label = ttk.Label(main_frame, text="LED Bar Configuration", font=("Arial", 16, "bold"))
|
|
||||||
title_label.grid(row=0, column=0, columnspan=2, pady=(0, 20))
|
|
||||||
|
|
||||||
# Device connection section
|
|
||||||
device_frame = ttk.LabelFrame(main_frame, text="Device Connection", padding="10")
|
|
||||||
device_frame.grid(row=1, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
|
|
||||||
|
|
||||||
ttk.Label(device_frame, text="Device:").grid(row=0, column=0, sticky=tk.W, padx=(0, 5))
|
|
||||||
self.device_entry = ttk.Entry(device_frame, width=30)
|
|
||||||
self.device_entry.insert(0, "/dev/ttyACM0") # Default device
|
|
||||||
self.device_entry.grid(row=0, column=1, sticky=(tk.W, tk.E), padx=(0, 10))
|
|
||||||
|
|
||||||
ttk.Button(device_frame, text="Download Settings", command=self.download_settings).grid(row=0, column=2)
|
|
||||||
|
|
||||||
# Settings section
|
|
||||||
settings_frame = ttk.LabelFrame(main_frame, text="Settings", padding="10")
|
|
||||||
settings_frame.grid(row=2, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S), pady=(0, 10))
|
|
||||||
|
|
||||||
# Create scrollable frame for settings
|
|
||||||
canvas = tk.Canvas(settings_frame, height=400)
|
|
||||||
scrollbar = ttk.Scrollbar(settings_frame, orient="vertical", command=canvas.yview)
|
|
||||||
scrollable_frame = ttk.Frame(canvas)
|
|
||||||
|
|
||||||
scrollable_frame.bind(
|
|
||||||
"<Configure>",
|
|
||||||
lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
|
|
||||||
)
|
|
||||||
|
|
||||||
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
|
|
||||||
canvas.configure(yscrollcommand=scrollbar.set)
|
|
||||||
|
|
||||||
# Settings fields
|
|
||||||
self.setting_widgets = {}
|
|
||||||
settings_config = [
|
|
||||||
("led_pin", "LED Pin", "number"),
|
|
||||||
("num_leds", "Number of LEDs", "number"),
|
|
||||||
("color_order", "Color Order", "choice", ["rgb", "rbg"]),
|
|
||||||
("name", "Device Name", "text"),
|
|
||||||
("pattern", "Pattern", "text"),
|
|
||||||
("color1", "Color 1", "color"),
|
|
||||||
("color2", "Color 2", "color"),
|
|
||||||
("delay", "Delay (ms)", "number"),
|
|
||||||
("brightness", "Brightness", "number"),
|
|
||||||
("n1", "N1", "number"),
|
|
||||||
("n2", "N2", "number"),
|
|
||||||
("n3", "N3", "number"),
|
|
||||||
("n4", "N4", "number"),
|
|
||||||
("n5", "N5", "number"),
|
|
||||||
("n6", "N6", "number"),
|
|
||||||
("ap_password", "AP Password", "text"),
|
|
||||||
("id", "ID", "number"),
|
|
||||||
]
|
|
||||||
|
|
||||||
for idx, config in enumerate(settings_config):
|
|
||||||
key = config[0]
|
|
||||||
label_text = config[1]
|
|
||||||
field_type = config[2]
|
|
||||||
|
|
||||||
ttk.Label(scrollable_frame, text=f"{label_text}:").grid(row=idx, column=0, sticky=tk.W, padx=(0, 10), pady=5)
|
|
||||||
|
|
||||||
if field_type == "number":
|
|
||||||
widget = ttk.Entry(scrollable_frame, width=20)
|
|
||||||
elif field_type == "choice":
|
|
||||||
widget = ttk.Combobox(scrollable_frame, width=17, values=config[3], state="readonly")
|
|
||||||
elif field_type == "color":
|
|
||||||
widget = ttk.Entry(scrollable_frame, width=20)
|
|
||||||
else: # text
|
|
||||||
widget = ttk.Entry(scrollable_frame, width=20)
|
|
||||||
|
|
||||||
widget.grid(row=idx, column=1, sticky=(tk.W, tk.E), pady=5)
|
|
||||||
self.setting_widgets[key] = widget
|
|
||||||
|
|
||||||
canvas.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
|
|
||||||
scrollbar.grid(row=0, column=1, sticky=(tk.N, tk.S))
|
|
||||||
settings_frame.grid_rowconfigure(0, weight=1)
|
|
||||||
settings_frame.grid_columnconfigure(0, weight=1)
|
|
||||||
|
|
||||||
# Buttons section
|
|
||||||
button_frame = ttk.Frame(main_frame)
|
|
||||||
button_frame.grid(row=3, column=0, columnspan=2, pady=(10, 0))
|
|
||||||
|
|
||||||
ttk.Button(button_frame, text="Load from File", command=self.load_from_file).grid(row=0, column=0, padx=5)
|
|
||||||
ttk.Button(button_frame, text="Save to File", command=self.save_to_file).grid(row=0, column=1, padx=5)
|
|
||||||
ttk.Button(button_frame, text="Upload Settings", command=self.upload_settings).grid(row=0, column=2, padx=5)
|
|
||||||
|
|
||||||
# Status bar
|
|
||||||
self.status_label = ttk.Label(main_frame, text="Ready", relief=tk.SUNKEN, anchor=tk.W)
|
|
||||||
self.status_label.grid(row=4, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(10, 0))
|
|
||||||
|
|
||||||
# Configure grid weights
|
|
||||||
root.columnconfigure(0, weight=1)
|
|
||||||
root.rowconfigure(0, weight=1)
|
|
||||||
main_frame.columnconfigure(0, weight=1)
|
|
||||||
main_frame.rowconfigure(2, weight=1)
|
|
||||||
device_frame.columnconfigure(1, weight=1)
|
|
||||||
|
|
||||||
def update_status(self, message):
|
|
||||||
"""Update the status bar message."""
|
|
||||||
self.status_label.config(text=message)
|
|
||||||
self.root.update_idletasks()
|
|
||||||
|
|
||||||
def download_settings(self):
|
|
||||||
"""Download settings.json from the device using mpremote."""
|
|
||||||
device = self.device_entry.get().strip()
|
|
||||||
if not device:
|
|
||||||
messagebox.showerror("Error", "Please specify a device")
|
|
||||||
return
|
|
||||||
|
|
||||||
self.update_status("Downloading settings...")
|
|
||||||
|
|
||||||
try:
|
|
||||||
# Create temporary file
|
|
||||||
self.temp_file = tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False)
|
|
||||||
temp_path = self.temp_file.name
|
|
||||||
self.temp_file.close()
|
|
||||||
|
|
||||||
# Download file using mpremote
|
|
||||||
cmd = ["mpremote", "connect", device, "cp", ":/settings.json", temp_path]
|
|
||||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
|
|
||||||
|
|
||||||
if result.returncode != 0:
|
|
||||||
raise Exception(f"mpremote error: {result.stderr}")
|
|
||||||
|
|
||||||
# Load the downloaded file
|
|
||||||
with open(temp_path, 'r') as f:
|
|
||||||
self.settings = json.load(f)
|
|
||||||
|
|
||||||
# Update UI with loaded settings
|
|
||||||
self.update_ui_from_settings()
|
|
||||||
|
|
||||||
self.update_status(f"Settings downloaded successfully from {device}")
|
|
||||||
messagebox.showinfo("Success", "Settings downloaded successfully!")
|
|
||||||
|
|
||||||
except subprocess.TimeoutExpired:
|
|
||||||
self.update_status("Error: Connection timeout")
|
|
||||||
messagebox.showerror("Error", "Connection timeout. Check device connection.")
|
|
||||||
except FileNotFoundError:
|
|
||||||
self.update_status("Error: mpremote not found")
|
|
||||||
messagebox.showerror("Error", "mpremote not found. Please install it:\npip install mpremote")
|
|
||||||
except Exception as e:
|
|
||||||
self.update_status(f"Error: {str(e)}")
|
|
||||||
messagebox.showerror("Error", f"Failed to download settings:\n{str(e)}")
|
|
||||||
finally:
|
|
||||||
# Clean up temp file
|
|
||||||
if self.temp_file and os.path.exists(temp_path):
|
|
||||||
try:
|
|
||||||
os.unlink(temp_path)
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def upload_settings(self):
|
|
||||||
"""Upload settings.json to the device using mpremote."""
|
|
||||||
device = self.device_entry.get().strip()
|
|
||||||
if not device:
|
|
||||||
messagebox.showerror("Error", "Please specify a device")
|
|
||||||
return
|
|
||||||
|
|
||||||
if not self.settings:
|
|
||||||
messagebox.showerror("Error", "No settings to upload. Please download or load settings first.")
|
|
||||||
return
|
|
||||||
|
|
||||||
self.update_status("Uploading settings...")
|
|
||||||
|
|
||||||
try:
|
|
||||||
# Get current settings from UI
|
|
||||||
self.update_settings_from_ui()
|
|
||||||
|
|
||||||
# Create temporary file with current settings
|
|
||||||
temp_file = tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False)
|
|
||||||
temp_path = temp_file.name
|
|
||||||
json.dump(self.settings, temp_file, indent=2)
|
|
||||||
temp_file.close()
|
|
||||||
|
|
||||||
# Upload file using mpremote
|
|
||||||
cmd = ["mpremote", "connect", device, "cp", temp_path, ":/settings.json"]
|
|
||||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
|
|
||||||
|
|
||||||
if result.returncode != 0:
|
|
||||||
raise Exception(f"mpremote error: {result.stderr}")
|
|
||||||
|
|
||||||
# Reset the device
|
|
||||||
self.update_status("Resetting device...")
|
|
||||||
try:
|
|
||||||
with serial.Serial(device, baudrate=115200) as ser:
|
|
||||||
ser.write(b'\x03\x03\x04')
|
|
||||||
except Exception as e:
|
|
||||||
# If serial reset fails, try mpremote method as fallback
|
|
||||||
reset_cmd = ["mpremote", "connect", device, "exec", "import machine; machine.reset()"]
|
|
||||||
subprocess.run(reset_cmd, capture_output=True, text=True, timeout=5)
|
|
||||||
|
|
||||||
self.update_status(f"Settings uploaded and device reset on {device}")
|
|
||||||
messagebox.showinfo("Success", "Settings uploaded successfully and device reset!")
|
|
||||||
|
|
||||||
except subprocess.TimeoutExpired:
|
|
||||||
self.update_status("Error: Connection timeout")
|
|
||||||
messagebox.showerror("Error", "Connection timeout. Check device connection.")
|
|
||||||
except FileNotFoundError:
|
|
||||||
self.update_status("Error: mpremote not found")
|
|
||||||
messagebox.showerror("Error", "mpremote not found. Please install it:\npip install mpremote")
|
|
||||||
except Exception as e:
|
|
||||||
self.update_status(f"Error: {str(e)}")
|
|
||||||
messagebox.showerror("Error", f"Failed to upload settings:\n{str(e)}")
|
|
||||||
finally:
|
|
||||||
# Clean up temp file
|
|
||||||
if os.path.exists(temp_path):
|
|
||||||
try:
|
|
||||||
os.unlink(temp_path)
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def load_from_file(self):
|
|
||||||
"""Load settings from a local JSON file."""
|
|
||||||
file_path = filedialog.askopenfilename(
|
|
||||||
title="Load Settings",
|
|
||||||
filetypes=[("JSON files", "*.json"), ("All files", "*.*")]
|
|
||||||
)
|
|
||||||
|
|
||||||
if not file_path:
|
|
||||||
return
|
|
||||||
|
|
||||||
try:
|
|
||||||
with open(file_path, 'r') as f:
|
|
||||||
self.settings = json.load(f)
|
|
||||||
|
|
||||||
self.update_ui_from_settings()
|
|
||||||
self.update_status(f"Settings loaded from {os.path.basename(file_path)}")
|
|
||||||
messagebox.showinfo("Success", "Settings loaded successfully!")
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
self.update_status(f"Error: {str(e)}")
|
|
||||||
messagebox.showerror("Error", f"Failed to load settings:\n{str(e)}")
|
|
||||||
|
|
||||||
def save_to_file(self):
|
|
||||||
"""Save current settings to a local JSON file."""
|
|
||||||
if not self.settings:
|
|
||||||
messagebox.showerror("Error", "No settings to save. Please download or load settings first.")
|
|
||||||
return
|
|
||||||
|
|
||||||
file_path = filedialog.asksaveasfilename(
|
|
||||||
title="Save Settings",
|
|
||||||
defaultextension=".json",
|
|
||||||
filetypes=[("JSON files", "*.json"), ("All files", "*.*")]
|
|
||||||
)
|
|
||||||
|
|
||||||
if not file_path:
|
|
||||||
return
|
|
||||||
|
|
||||||
try:
|
|
||||||
# Get current settings from UI
|
|
||||||
self.update_settings_from_ui()
|
|
||||||
|
|
||||||
with open(file_path, 'w') as f:
|
|
||||||
json.dump(self.settings, f, indent=2)
|
|
||||||
|
|
||||||
self.update_status(f"Settings saved to {os.path.basename(file_path)}")
|
|
||||||
messagebox.showinfo("Success", "Settings saved successfully!")
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
self.update_status(f"Error: {str(e)}")
|
|
||||||
messagebox.showerror("Error", f"Failed to save settings:\n{str(e)}")
|
|
||||||
|
|
||||||
def update_ui_from_settings(self):
|
|
||||||
"""Update UI widgets with current settings values."""
|
|
||||||
for key, widget in self.setting_widgets.items():
|
|
||||||
if key in self.settings:
|
|
||||||
value = self.settings[key]
|
|
||||||
if isinstance(widget, ttk.Combobox):
|
|
||||||
widget.set(str(value))
|
|
||||||
else:
|
|
||||||
widget.delete(0, tk.END)
|
|
||||||
widget.insert(0, str(value))
|
|
||||||
|
|
||||||
def update_settings_from_ui(self):
|
|
||||||
"""Update settings dictionary from UI widget values."""
|
|
||||||
for key, widget in self.setting_widgets.items():
|
|
||||||
value = widget.get().strip()
|
|
||||||
if value:
|
|
||||||
# Try to convert to appropriate type
|
|
||||||
if key in ["led_pin", "num_leds", "delay", "brightness", "id", "n1", "n2", "n3", "n4", "n5", "n6"]:
|
|
||||||
try:
|
|
||||||
self.settings[key] = int(value)
|
|
||||||
except ValueError:
|
|
||||||
pass # Keep as string if conversion fails
|
|
||||||
else:
|
|
||||||
self.settings[key] = value
|
|
||||||
elif key in self.settings:
|
|
||||||
# Keep existing value if widget is empty
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
root = tk.Tk()
|
|
||||||
app = LEDConfigTool(root)
|
|
||||||
root.mainloop()
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
|
|
||||||
Reference in New Issue
Block a user