Add status WebSocket
This commit is contained in:
10 files changed
+588
-454
No files matched your search
+27
-14
@@ -1,36 +1,49 @@
|
||||
# This file is executed on every boot (including wake-boot from deepsleep)
|
||||
# It is executed before main.py
|
||||
import os, machine
|
||||
import os, machine, time
|
||||
import network
|
||||
import gc
|
||||
|
||||
gc.collect()
|
||||
|
||||
|
||||
# --- WIFI Configuration ---
|
||||
SSID = '<YOUR WIFI SSID>' # Set the WIFI network SSID
|
||||
PASSWORD = '<YOUR WIFI PASSWORD>' # Set the WIFI network password
|
||||
network.country('<YOUR COUNTRY CODE>') # Set the country code for the WIFI (ISO 3166-1 Alpha-2 country code)
|
||||
network.hostname('igox-busylight') # Hostname that will identify this device on the network
|
||||
# --- Configuration ---
|
||||
SSID = '<WIFI SSID>' # Set the WIFI network SSID
|
||||
PASSWORD = '<WIFI PASSWORD>' # Set the WIFI network password
|
||||
HOSTNAME = 'igox-busylight' # Hostname that will identify this device on the network
|
||||
COUNTRY_CODE = 'fr' # Set the country code for the WIFI (ISO 3166-1 Alpha-2 country code)
|
||||
# --------------------------
|
||||
|
||||
# Wifi config
|
||||
network.country(COUNTRY_CODE)
|
||||
network.hostname(HOSTNAME)
|
||||
|
||||
# Function to connect to the WIFI
|
||||
def boot_wifi_connect():
|
||||
def boot_wifi_connect(timeout_s=20):
|
||||
wlan = network.WLAN(network.STA_IF)
|
||||
if not wlan.isconnected():
|
||||
print('connecting to network...')
|
||||
# Restart the interface: a soft reboot can leave a stale connection attempt
|
||||
wlan.active(False)
|
||||
time.sleep_ms(200)
|
||||
wlan.active(True)
|
||||
wlan.connect(SSID, PASSWORD)
|
||||
start = time.ticks_ms()
|
||||
while not wlan.isconnected():
|
||||
pass
|
||||
ip, mask, gateway, dns = wlan.ifconfig()
|
||||
if time.ticks_diff(time.ticks_ms(), start) > timeout_s * 1000:
|
||||
print('WIFI connection failed (status {}), rebooting...'.format(wlan.status()))
|
||||
time.sleep(2)
|
||||
machine.reset()
|
||||
time.sleep_ms(100)
|
||||
IP, MASK, GATEWAY, DNS = wlan.ifconfig()
|
||||
|
||||
# Print the network configuration
|
||||
print('\nNetwork config:')
|
||||
print('- IP address: ' + ip)
|
||||
print('- Network mask: ' + mask)
|
||||
print('- Network gateway: ' + gateway)
|
||||
print('- DNS server: ' + dns + '\n')
|
||||
print('- IP address: ' + IP)
|
||||
print('- Network mask: ' + MASK)
|
||||
print('- Network gateway: ' + GATEWAY)
|
||||
print('- DNS server: ' + DNS)
|
||||
print('- mDNS: ' + HOSTNAME + '\n')
|
||||
|
||||
# Connect to the WIFI when booting
|
||||
boot_wifi_connect()
|
||||
boot_wifi_connect()
|
||||
Binary file not shown.
@@ -0,0 +1,520 @@
|
||||
from microdot import Microdot, send_file
|
||||
from microdot.websocket import with_websocket
|
||||
import machine, neopixel, time, json, gc, esp32
|
||||
import uasyncio as asyncio
|
||||
|
||||
app = Microdot()
|
||||
|
||||
# =========================
|
||||
# NeoPixel setup
|
||||
# =========================
|
||||
nbPixels = 12 * 2
|
||||
pinPixelStrip = 16
|
||||
neoPixelStrip = neopixel.NeoPixel(machine.Pin(pinPixelStrip), nbPixels)
|
||||
|
||||
|
||||
# =========================
|
||||
# LED CONTROLLER
|
||||
# =========================
|
||||
class LedController:
|
||||
def __init__(self, np):
|
||||
self._np = np
|
||||
|
||||
# async control
|
||||
self._flag = asyncio.ThreadSafeFlag()
|
||||
self._cmd = None
|
||||
self._task = None
|
||||
|
||||
# state
|
||||
self.states = {
|
||||
'BUSY': (255, 0, 0),
|
||||
'AVAILABLE': (0, 255, 0),
|
||||
'AWAY': (246, 190, 0),
|
||||
'OFF': (0, 0, 0),
|
||||
'ON': (255, 255, 255)
|
||||
}
|
||||
|
||||
self.color = self.states['OFF']
|
||||
self.status = 'off'
|
||||
self.previousStatus = 'off'
|
||||
self.brightness = 0.1
|
||||
|
||||
self.blinking = False
|
||||
self.blinkFrequency = 0
|
||||
self.blinkDuration = 0
|
||||
self.blinkStart = 0
|
||||
|
||||
self.on_change = None
|
||||
|
||||
# ---------- internal ----------
|
||||
def _notify(self):
|
||||
if self.on_change:
|
||||
self.on_change()
|
||||
|
||||
def _apply_brightness(self, color):
|
||||
r, g, b = color
|
||||
return (
|
||||
int(r * self.brightness),
|
||||
int(g * self.brightness),
|
||||
int(b * self.brightness),
|
||||
)
|
||||
|
||||
def _write(self, color):
|
||||
self._np.fill(self._apply_brightness(color))
|
||||
self._np.write()
|
||||
|
||||
async def run(self):
|
||||
while True:
|
||||
await self._flag.wait()
|
||||
cmd = self._cmd
|
||||
|
||||
# Cancel any ongoing task before starting a new one
|
||||
if self._task:
|
||||
self._task.cancel()
|
||||
try:
|
||||
await self._task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
# Process the new command
|
||||
t = cmd["type"]
|
||||
|
||||
if t == "blink":
|
||||
self._task = asyncio.create_task(self._blink(cmd))
|
||||
elif t == "solid":
|
||||
self._task = asyncio.create_task(self._solid(cmd))
|
||||
elif t == "off":
|
||||
self._task = asyncio.create_task(self._off())
|
||||
|
||||
async def _solid(self, cmd):
|
||||
self.color = cmd["color"]
|
||||
self.status = cmd.get("status", "colored")
|
||||
self._write(self.color)
|
||||
self._notify()
|
||||
|
||||
async def _off(self):
|
||||
self.color = (0, 0, 0)
|
||||
self.previousStatus = self.status
|
||||
self.status = "off"
|
||||
self._write(self.color)
|
||||
self._notify()
|
||||
|
||||
async def _blink(self, cmd):
|
||||
try:
|
||||
self.blinking = True
|
||||
|
||||
self.color = cmd["color"]
|
||||
self.previousStatus = cmd["previousStatus"]
|
||||
self.blinkFrequency = cmd["frequency"]
|
||||
self.blinkDuration = cmd["duration"]
|
||||
self.blinkStart = time.ticks_ms()
|
||||
|
||||
freq = max(0.1, self.blinkFrequency)
|
||||
half_ms = int(500 / freq)
|
||||
self._notify()
|
||||
|
||||
while True:
|
||||
if self.blinkDuration != 0:
|
||||
elapsed = time.ticks_diff(time.ticks_ms(), self.blinkStart)
|
||||
if elapsed > self.blinkDuration * 1000:
|
||||
break
|
||||
|
||||
self._write(self.color)
|
||||
await asyncio.sleep_ms(half_ms)
|
||||
|
||||
self._write((0, 0, 0))
|
||||
await asyncio.sleep_ms(half_ms)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
self.blinking = False
|
||||
self.status = self.previousStatus
|
||||
self._write(self.color)
|
||||
self._notify()
|
||||
|
||||
async def sendCommand(self, cmd):
|
||||
self._cmd = cmd
|
||||
self._flag.set()
|
||||
|
||||
# ---------- public API ----------
|
||||
async def set_color(self, color, brightness=None):
|
||||
if brightness is not None:
|
||||
self.brightness = brightness
|
||||
await self.sendCommand({
|
||||
"type": "solid",
|
||||
"color": color
|
||||
})
|
||||
|
||||
async def set_status(self, status):
|
||||
status = status.upper()
|
||||
color = self.states.get(status)
|
||||
|
||||
if color is None:
|
||||
raise ValueError("invalid status")
|
||||
|
||||
await self.sendCommand({
|
||||
"type": "solid",
|
||||
"color": color,
|
||||
"status": status.lower()
|
||||
})
|
||||
|
||||
async def get_status(self):
|
||||
return self.status
|
||||
|
||||
async def blink(self, frequency, duration):
|
||||
self.previousStatus = self.status
|
||||
|
||||
await self.sendCommand({
|
||||
"type": "blink",
|
||||
"color": self.color,
|
||||
"frequency": frequency,
|
||||
"duration": duration,
|
||||
"previousStatus": self.previousStatus
|
||||
})
|
||||
|
||||
async def stop(self):
|
||||
await self.sendCommand({"type": "off"})
|
||||
|
||||
def getStatus(self):
|
||||
if self.blinking and self.blinkDuration > 0:
|
||||
elapsed = time.ticks_diff(time.ticks_ms(), self.blinkStart) / 1000
|
||||
remains = max(0.0, self.blinkDuration - elapsed)
|
||||
else:
|
||||
remains = 0.0
|
||||
|
||||
return {
|
||||
"status": self.status,
|
||||
"color": self.color,
|
||||
"brightness": self.brightness,
|
||||
"isblinking": self.blinking,
|
||||
"frequency": self.blinkFrequency,
|
||||
"duration": self.blinkDuration,
|
||||
"remains": remains
|
||||
}
|
||||
|
||||
|
||||
# =========================
|
||||
# STATUS BROADCASTER (WebSocket)
|
||||
# =========================
|
||||
class StatusBroadcaster:
|
||||
def __init__(self, led):
|
||||
self._led = led
|
||||
self._clients = set()
|
||||
self._event = asyncio.Event()
|
||||
|
||||
def payload(self):
|
||||
state = self._led.getStatus()
|
||||
return json.dumps({
|
||||
'status': state["status"],
|
||||
'color': state["color"],
|
||||
'brightness': state["brightness"],
|
||||
'isblinking': state["isblinking"],
|
||||
'blinkParameters': {
|
||||
'frequency': state["frequency"],
|
||||
'duration': state["duration"],
|
||||
'remains': state["remains"]}
|
||||
})
|
||||
|
||||
def notify(self):
|
||||
self._event.set()
|
||||
|
||||
def add(self, ws):
|
||||
self._clients.add(ws)
|
||||
|
||||
def remove(self, ws):
|
||||
self._clients.discard(ws)
|
||||
|
||||
async def run(self):
|
||||
while True:
|
||||
await self._event.wait()
|
||||
self._event.clear()
|
||||
if not self._clients:
|
||||
continue
|
||||
message = self.payload()
|
||||
for ws in list(self._clients):
|
||||
try:
|
||||
await ws.send(message)
|
||||
except Exception:
|
||||
self._clients.discard(ws)
|
||||
|
||||
|
||||
# =========================
|
||||
# INIT
|
||||
# =========================
|
||||
led = LedController(neoPixelStrip)
|
||||
broadcaster = StatusBroadcaster(led)
|
||||
led.on_change = broadcaster.notify
|
||||
|
||||
|
||||
# =========================
|
||||
# ROUTES
|
||||
# =========================
|
||||
|
||||
@app.get('/static/<path:path>')
|
||||
async def staticRoutes(request, path):
|
||||
if '..' in path:
|
||||
return {'error': '404 Not found'}, 404
|
||||
return send_file('static/' + path)
|
||||
|
||||
|
||||
@app.get('/')
|
||||
async def getIndex(request):
|
||||
return send_file('static/index.html')
|
||||
|
||||
|
||||
@app.get('/api/brightness')
|
||||
async def getBrightness(request):
|
||||
return {'brightness': led.brightness}
|
||||
|
||||
|
||||
@app.post('/api/brightness')
|
||||
async def setBrightness(request):
|
||||
brightness = request.json.get("brightness")
|
||||
|
||||
if brightness is None:
|
||||
return {'error': 'missing brightness parameter'}, 400
|
||||
|
||||
if not isinstance(brightness, (int, float)):
|
||||
return {'error': 'wrong brightness type'}, 400
|
||||
|
||||
if brightness < 0 or brightness > 1:
|
||||
return {'error': 'brightness out of bound'}, 400
|
||||
|
||||
current_status = led.status
|
||||
current_color = led.color
|
||||
|
||||
await led.set_color(current_color, brightness)
|
||||
|
||||
led.status = current_status
|
||||
return {'brightness': led.brightness}
|
||||
|
||||
|
||||
@app.post('/api/color')
|
||||
async def setColor(request):
|
||||
r = request.json.get("r")
|
||||
g = request.json.get("g")
|
||||
b = request.json.get("b")
|
||||
brightness = request.json.get("brightness")
|
||||
|
||||
if r is None or g is None or b is None:
|
||||
return {'error': 'missing color'}, 400
|
||||
|
||||
if not all(isinstance(v, int) for v in (r, g, b)):
|
||||
return {'error': 'wrong color type'}, 400
|
||||
|
||||
if not (0 <= r <= 255 and 0 <= g <= 255 and 0 <= b <= 255):
|
||||
return {'error': 'color out of bound'}, 400
|
||||
|
||||
if brightness is not None:
|
||||
if not isinstance(brightness, (int, float)):
|
||||
return {'error': 'wrong brightness type'}, 400
|
||||
|
||||
if brightness < 0 or brightness > 1:
|
||||
return {'error': 'brightness out of bound'}, 400
|
||||
|
||||
await led.set_color((r, g, b), brightness)
|
||||
status = await led.get_status()
|
||||
|
||||
state = led.getStatus()
|
||||
return {'status': state["status"],
|
||||
'color': state["color"],
|
||||
'brightness': state["brightness"],
|
||||
'isblinking': state["isblinking"],
|
||||
'blinkParameters': {
|
||||
'frequency': state["frequency"],
|
||||
'duration': state["duration"],
|
||||
'remains': state["remains"]}
|
||||
}
|
||||
|
||||
|
||||
@app.get('/api/color')
|
||||
async def getColor(request):
|
||||
r, g, b = led.color
|
||||
return {'r': r, 'g': g, 'b': b, 'brightness': led.brightness}
|
||||
|
||||
|
||||
@app.get('/api/status')
|
||||
async def getStatus(request):
|
||||
status = await led.get_status()
|
||||
state = led.getStatus()
|
||||
return {'status': state["status"],
|
||||
'color': state["color"],
|
||||
'brightness': state["brightness"],
|
||||
'isblinking': state["isblinking"],
|
||||
'blinkParameters': {
|
||||
'frequency': state["frequency"],
|
||||
'duration': state["duration"],
|
||||
'remains': state["remains"]}
|
||||
}
|
||||
|
||||
|
||||
@app.route('/api/status/<status>', methods=['GET', 'POST'])
|
||||
async def setStatus(request, status):
|
||||
try:
|
||||
await led.set_status(status)
|
||||
except ValueError:
|
||||
return {'error': 'unknown status'}, 404
|
||||
|
||||
status = await led.get_status()
|
||||
state = led.getStatus()
|
||||
return {'status': state["status"],
|
||||
'color': state["color"],
|
||||
'brightness': state["brightness"],
|
||||
'isblinking': state["isblinking"],
|
||||
'blinkParameters': {
|
||||
'frequency': state["frequency"],
|
||||
'duration': state["duration"],
|
||||
'remains': state["remains"]}
|
||||
}
|
||||
|
||||
|
||||
@app.post('/api/blink')
|
||||
async def setBlink(request):
|
||||
freq = request.json.get('frequency')
|
||||
duration = request.json.get('duration')
|
||||
|
||||
if freq is None or duration is None:
|
||||
return {'error': 'missing frequency or duration'}, 400
|
||||
|
||||
if not isinstance(freq, (int, float)) or freq <= 0:
|
||||
return {'error': 'invalid frequency'}, 400
|
||||
|
||||
if not isinstance(duration, (int, float)) or duration < 0:
|
||||
return {'error': 'invalid duration'}, 400
|
||||
|
||||
await led.blink(freq, duration)
|
||||
|
||||
state = led.getStatus()
|
||||
return {'status': state["status"],
|
||||
'color': state["color"],
|
||||
'brightness': state["brightness"],
|
||||
'isblinking': state["isblinking"],
|
||||
'blinkParameters': {
|
||||
'frequency': state["frequency"],
|
||||
'duration': state["duration"],
|
||||
'remains': state["remains"]}
|
||||
}
|
||||
|
||||
|
||||
@app.get('/api/blink')
|
||||
async def getBlinkStatus(request):
|
||||
state = led.getStatus()
|
||||
return {
|
||||
'isblinking': state["isblinking"],
|
||||
'frequency': state["frequency"],
|
||||
'duration': state["duration"],
|
||||
'remains': state["remains"]
|
||||
}
|
||||
|
||||
|
||||
@app.post('/api/blink/stop')
|
||||
async def blinkStop(request):
|
||||
await led.stop()
|
||||
await led.set_status(led.previousStatus)
|
||||
status = await led.get_status()
|
||||
state = led.getStatus()
|
||||
return {'status': state["status"],
|
||||
'color': state["color"],
|
||||
'brightness': state["brightness"],
|
||||
'isblinking': state["isblinking"],
|
||||
'blinkParameters': {
|
||||
'frequency': state["frequency"],
|
||||
'duration': state["duration"],
|
||||
'remains': state["remains"]}
|
||||
}
|
||||
|
||||
|
||||
@app.get('/api/debug')
|
||||
async def getDebugInfo(request):
|
||||
r, g, b = led.color
|
||||
dr, dg, db = led._np[0]
|
||||
|
||||
return {
|
||||
'status': led.status,
|
||||
'brightness': led.brightness,
|
||||
'color': {'r': r, 'g': g, 'b': b},
|
||||
'dimColor': {'r': dr, 'g': dg, 'b': db},
|
||||
'blinking': led.blinking,
|
||||
'blinkFrequency': led.blinkFrequency,
|
||||
'blinkDuration': led.blinkDuration
|
||||
}
|
||||
|
||||
|
||||
@app.post('/api/mutedeck-webhook')
|
||||
async def mutedeckWebhook(request):
|
||||
|
||||
if request.json.get('control') != 'system':
|
||||
if request.json.get('call') == 'active':
|
||||
isMuted = request.json.get('mute') == 'active'
|
||||
|
||||
if isMuted:
|
||||
await led.set_status('away')
|
||||
else:
|
||||
await led.set_status('busy')
|
||||
else:
|
||||
await led.set_status('available')
|
||||
|
||||
state = led.getStatus()
|
||||
return {'status': state["status"],
|
||||
'color': state["color"],
|
||||
'brightness': state["brightness"],
|
||||
'isblinking': state["isblinking"],
|
||||
'blinkParameters': {
|
||||
'frequency': state["frequency"],
|
||||
'duration': state["duration"],
|
||||
'remains': state["remains"]}
|
||||
}
|
||||
|
||||
|
||||
@app.route('/ws/status')
|
||||
@with_websocket
|
||||
async def statusSocket(request, ws):
|
||||
await ws.send(broadcaster.payload())
|
||||
broadcaster.add(ws)
|
||||
try:
|
||||
# Incoming messages are ignored; receive() raises when the client disconnects
|
||||
while True:
|
||||
await ws.receive()
|
||||
finally:
|
||||
broadcaster.remove(ws)
|
||||
|
||||
|
||||
@app.post('/shutdown')
|
||||
async def shutdown(request):
|
||||
request.app.shutdown()
|
||||
return 'The server is shutting down...'
|
||||
|
||||
|
||||
# Collect early so the GC heap doesn't expand into the IDF heap needed by lwIP
|
||||
@app.after_request
|
||||
async def collectGarbage(request, response):
|
||||
gc.collect()
|
||||
return response
|
||||
|
||||
|
||||
# =========================
|
||||
# START
|
||||
# =========================
|
||||
async def main():
|
||||
asyncio.create_task(led.run())
|
||||
asyncio.create_task(broadcaster.run())
|
||||
|
||||
# startup animation
|
||||
await led.set_status('busy')
|
||||
await asyncio.sleep_ms(200)
|
||||
await led.set_status('away')
|
||||
await asyncio.sleep_ms(300)
|
||||
await led.set_status('available')
|
||||
await asyncio.sleep_ms(500)
|
||||
await led.set_status('off')
|
||||
|
||||
gc.collect()
|
||||
gc.threshold(gc.mem_free() // 4 + gc.mem_alloc())
|
||||
idf_free = sum(h[1] for h in esp32.idf_heap_info(esp32.HEAP_DATA))
|
||||
print('Memory: python heap free {} B, IDF heap free {} B'.format(gc.mem_free(), idf_free))
|
||||
await app.start_server(port=80)
|
||||
|
||||
|
||||
def run():
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019 Miguel Grinberg
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+11
-436
@@ -1,436 +1,11 @@
|
||||
from microdot import Microdot, send_file
|
||||
import machine, neopixel, time
|
||||
import uasyncio as asyncio
|
||||
|
||||
app = Microdot()
|
||||
|
||||
# =========================
|
||||
# NeoPixel setup
|
||||
# =========================
|
||||
nbPixels = 12 * 2
|
||||
pinPixelStrip = 16
|
||||
neoPixelStrip = neopixel.NeoPixel(machine.Pin(pinPixelStrip), nbPixels)
|
||||
|
||||
|
||||
# =========================
|
||||
# LED CONTROLLER
|
||||
# =========================
|
||||
class LedController:
|
||||
def __init__(self, np):
|
||||
self._np = np
|
||||
|
||||
# async control
|
||||
self._flag = asyncio.ThreadSafeFlag()
|
||||
self._cmd = None
|
||||
self._task = None
|
||||
|
||||
# state
|
||||
self.states = {
|
||||
'BUSY': (255, 0, 0),
|
||||
'AVAILABLE': (0, 255, 0),
|
||||
'AWAY': (246, 190, 0),
|
||||
'OFF': (0, 0, 0),
|
||||
'ON': (255, 255, 255)
|
||||
}
|
||||
|
||||
self.color = self.states['OFF']
|
||||
self.status = 'off'
|
||||
self.previousStatus = 'off'
|
||||
self.brightness = 0.1
|
||||
|
||||
self.blinking = False
|
||||
self.blinkFrequency = 0
|
||||
self.blinkDuration = 0
|
||||
self.blinkStart = 0
|
||||
|
||||
# ---------- internal ----------
|
||||
def _apply_brightness(self, color):
|
||||
r, g, b = color
|
||||
return (
|
||||
int(r * self.brightness),
|
||||
int(g * self.brightness),
|
||||
int(b * self.brightness),
|
||||
)
|
||||
|
||||
def _write(self, color):
|
||||
self._np.fill(self._apply_brightness(color))
|
||||
self._np.write()
|
||||
|
||||
async def run(self):
|
||||
while True:
|
||||
await self._flag.wait()
|
||||
cmd = self._cmd
|
||||
|
||||
# Cancel any ongoing task before starting a new one
|
||||
if self._task:
|
||||
self._task.cancel()
|
||||
try:
|
||||
await self._task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
# Process the new command
|
||||
t = cmd["type"]
|
||||
|
||||
if t == "blink":
|
||||
self._task = asyncio.create_task(self._blink(cmd))
|
||||
elif t == "solid":
|
||||
self._task = asyncio.create_task(self._solid(cmd))
|
||||
elif t == "off":
|
||||
self._task = asyncio.create_task(self._off())
|
||||
|
||||
async def _solid(self, cmd):
|
||||
self.color = cmd["color"]
|
||||
self.status = cmd.get("status", "colored")
|
||||
self._write(self.color)
|
||||
|
||||
async def _off(self):
|
||||
self.color = (0, 0, 0)
|
||||
self.previousStatus = self.status
|
||||
self.status = "off"
|
||||
self._write(self.color)
|
||||
|
||||
async def _blink(self, cmd):
|
||||
try:
|
||||
self.blinking = True
|
||||
|
||||
self.color = cmd["color"]
|
||||
self.previousStatus = cmd["previousStatus"]
|
||||
self.blinkFrequency = cmd["frequency"]
|
||||
self.blinkDuration = cmd["duration"]
|
||||
self.blinkStart = time.ticks_ms()
|
||||
|
||||
freq = max(0.1, self.blinkFrequency)
|
||||
half_ms = int(500 / freq)
|
||||
|
||||
while True:
|
||||
if self.blinkDuration != 0:
|
||||
elapsed = time.ticks_diff(time.ticks_ms(), self.blinkStart)
|
||||
if elapsed > self.blinkDuration * 1000:
|
||||
break
|
||||
|
||||
self._write(self.color)
|
||||
await asyncio.sleep_ms(half_ms)
|
||||
|
||||
self._write((0, 0, 0))
|
||||
await asyncio.sleep_ms(half_ms)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
self.blinking = False
|
||||
self.status = self.previousStatus
|
||||
self._write(self.color)
|
||||
|
||||
async def sendCommand(self, cmd):
|
||||
self._cmd = cmd
|
||||
self._flag.set()
|
||||
|
||||
# ---------- public API ----------
|
||||
async def set_color(self, color, brightness=None):
|
||||
if brightness is not None:
|
||||
self.brightness = brightness
|
||||
await self.sendCommand({
|
||||
"type": "solid",
|
||||
"color": color
|
||||
})
|
||||
|
||||
async def set_status(self, status):
|
||||
status = status.upper()
|
||||
color = self.states.get(status)
|
||||
|
||||
if color is None:
|
||||
raise ValueError("invalid status")
|
||||
|
||||
await self.sendCommand({
|
||||
"type": "solid",
|
||||
"color": color,
|
||||
"status": status.lower()
|
||||
})
|
||||
|
||||
async def get_status(self):
|
||||
return self.status
|
||||
|
||||
async def blink(self, frequency, duration):
|
||||
self.previousStatus = self.status
|
||||
|
||||
await self.sendCommand({
|
||||
"type": "blink",
|
||||
"color": self.color,
|
||||
"frequency": frequency,
|
||||
"duration": duration,
|
||||
"previousStatus": self.previousStatus
|
||||
})
|
||||
|
||||
async def stop(self):
|
||||
await self.sendCommand({"type": "off"})
|
||||
|
||||
def getStatus(self):
|
||||
if self.blinking and self.blinkDuration > 0:
|
||||
elapsed = time.ticks_diff(time.ticks_ms(), self.blinkStart) / 1000
|
||||
remains = max(0.0, self.blinkDuration - elapsed)
|
||||
else:
|
||||
remains = 0.0
|
||||
|
||||
return {
|
||||
"status": self.status,
|
||||
"color": self.color,
|
||||
"brightness": self.brightness,
|
||||
"isblinking": self.blinking,
|
||||
"frequency": self.blinkFrequency,
|
||||
"duration": self.blinkDuration,
|
||||
"remains": remains
|
||||
}
|
||||
|
||||
|
||||
# =========================
|
||||
# INIT
|
||||
# =========================
|
||||
led = LedController(neoPixelStrip)
|
||||
|
||||
|
||||
# =========================
|
||||
# ROUTES
|
||||
# =========================
|
||||
|
||||
@app.get('/static/<path:path>')
|
||||
async def staticRoutes(request, path):
|
||||
if '..' in path:
|
||||
return {'error': '404 Not found'}, 404
|
||||
return send_file('static/' + path)
|
||||
|
||||
|
||||
@app.get('/')
|
||||
async def getIndex(request):
|
||||
return send_file('static/index.html')
|
||||
|
||||
|
||||
@app.get('/api/brightness')
|
||||
async def getBrightness(request):
|
||||
return {'brightness': led.brightness}
|
||||
|
||||
|
||||
@app.post('/api/brightness')
|
||||
async def setBrightness(request):
|
||||
brightness = request.json.get("brightness")
|
||||
|
||||
if brightness is None:
|
||||
return {'error': 'missing brightness parameter'}, 400
|
||||
|
||||
if not isinstance(brightness, (int, float)):
|
||||
return {'error': 'wrong brightness type'}, 400
|
||||
|
||||
if brightness < 0 or brightness > 1:
|
||||
return {'error': 'brightness out of bound'}, 400
|
||||
|
||||
current_status = led.status
|
||||
current_color = led.color
|
||||
|
||||
await led.set_color(current_color, brightness)
|
||||
|
||||
led.status = current_status
|
||||
return {'brightness': led.brightness}
|
||||
|
||||
|
||||
@app.post('/api/color')
|
||||
async def setColor(request):
|
||||
r = request.json.get("r")
|
||||
g = request.json.get("g")
|
||||
b = request.json.get("b")
|
||||
brightness = request.json.get("brightness")
|
||||
|
||||
if r is None or g is None or b is None:
|
||||
return {'error': 'missing color'}, 400
|
||||
|
||||
if not all(isinstance(v, int) for v in (r, g, b)):
|
||||
return {'error': 'wrong color type'}, 400
|
||||
|
||||
if not (0 <= r <= 255 and 0 <= g <= 255 and 0 <= b <= 255):
|
||||
return {'error': 'color out of bound'}, 400
|
||||
|
||||
if brightness is not None:
|
||||
if not isinstance(brightness, (int, float)):
|
||||
return {'error': 'wrong brightness type'}, 400
|
||||
|
||||
if brightness < 0 or brightness > 1:
|
||||
return {'error': 'brightness out of bound'}, 400
|
||||
|
||||
await led.set_color((r, g, b), brightness)
|
||||
status = await led.get_status()
|
||||
|
||||
state = led.getStatus()
|
||||
return {'status': state["status"],
|
||||
'color': state["color"],
|
||||
'brightness': state["brightness"],
|
||||
'isblinking': state["isblinking"],
|
||||
'blinkParameters': {
|
||||
'frequency': state["frequency"],
|
||||
'duration': state["duration"],
|
||||
'remains': state["remains"]}
|
||||
}
|
||||
|
||||
|
||||
@app.get('/api/color')
|
||||
async def getColor(request):
|
||||
r, g, b = led.color
|
||||
return {'r': r, 'g': g, 'b': b, 'brightness': led.brightness}
|
||||
|
||||
|
||||
@app.get('/api/status')
|
||||
async def getStatus(request):
|
||||
status = await led.get_status()
|
||||
state = led.getStatus()
|
||||
return {'status': state["status"],
|
||||
'color': state["color"],
|
||||
'brightness': state["brightness"],
|
||||
'isblinking': state["isblinking"],
|
||||
'blinkParameters': {
|
||||
'frequency': state["frequency"],
|
||||
'duration': state["duration"],
|
||||
'remains': state["remains"]}
|
||||
}
|
||||
|
||||
|
||||
@app.route('/api/status/<status>', methods=['GET', 'POST'])
|
||||
async def setStatus(request, status):
|
||||
try:
|
||||
await led.set_status(status)
|
||||
except ValueError:
|
||||
return {'error': 'unknown status'}, 404
|
||||
|
||||
status = await led.get_status()
|
||||
state = led.getStatus()
|
||||
return {'status': state["status"],
|
||||
'color': state["color"],
|
||||
'brightness': state["brightness"],
|
||||
'isblinking': state["isblinking"],
|
||||
'blinkParameters': {
|
||||
'frequency': state["frequency"],
|
||||
'duration': state["duration"],
|
||||
'remains': state["remains"]}
|
||||
}
|
||||
|
||||
|
||||
@app.post('/api/blink')
|
||||
async def setBlink(request):
|
||||
freq = request.json.get('frequency')
|
||||
duration = request.json.get('duration')
|
||||
|
||||
if freq is None or duration is None:
|
||||
return {'error': 'missing frequency or duration'}, 400
|
||||
|
||||
if not isinstance(freq, (int, float)) or freq <= 0:
|
||||
return {'error': 'invalid frequency'}, 400
|
||||
|
||||
if not isinstance(duration, (int, float)) or duration < 0:
|
||||
return {'error': 'invalid duration'}, 400
|
||||
|
||||
await led.blink(freq, duration)
|
||||
|
||||
state = led.getStatus()
|
||||
return {'status': state["status"],
|
||||
'color': state["color"],
|
||||
'brightness': state["brightness"],
|
||||
'isblinking': state["isblinking"],
|
||||
'blinkParameters': {
|
||||
'frequency': state["frequency"],
|
||||
'duration': state["duration"],
|
||||
'remains': state["remains"]}
|
||||
}
|
||||
|
||||
|
||||
@app.get('/api/blink')
|
||||
async def getBlinkStatus(request):
|
||||
state = led.getStatus()
|
||||
return {
|
||||
'isblinking': state["isblinking"],
|
||||
'frequency': state["frequency"],
|
||||
'duration': state["duration"],
|
||||
'remains': state["remains"]
|
||||
}
|
||||
|
||||
|
||||
@app.post('/api/blink/stop')
|
||||
async def blinkStop(request):
|
||||
await led.stop()
|
||||
await led.set_status(led.previousStatus)
|
||||
status = await led.get_status()
|
||||
state = led.getStatus()
|
||||
return {'status': state["status"],
|
||||
'color': state["color"],
|
||||
'brightness': state["brightness"],
|
||||
'isblinking': state["isblinking"],
|
||||
'blinkParameters': {
|
||||
'frequency': state["frequency"],
|
||||
'duration': state["duration"],
|
||||
'remains': state["remains"]}
|
||||
}
|
||||
|
||||
|
||||
@app.get('/api/debug')
|
||||
async def getDebugInfo(request):
|
||||
r, g, b = led.color
|
||||
dr, dg, db = led._np[0]
|
||||
|
||||
return {
|
||||
'status': led.status,
|
||||
'brightness': led.brightness,
|
||||
'color': {'r': r, 'g': g, 'b': b},
|
||||
'dimColor': {'r': dr, 'g': dg, 'b': db},
|
||||
'blinking': led.blinking,
|
||||
'blinkFrequency': led.blinkFrequency,
|
||||
'blinkDuration': led.blinkDuration
|
||||
}
|
||||
|
||||
|
||||
@app.post('/api/mutedeck-webhook')
|
||||
async def mutedeckWebhook(request):
|
||||
|
||||
if request.json.get('control') != 'system':
|
||||
if request.json.get('call') == 'active':
|
||||
isMuted = request.json.get('mute') == 'active'
|
||||
|
||||
if isMuted:
|
||||
await led.set_status('away')
|
||||
else:
|
||||
await led.set_status('busy')
|
||||
else:
|
||||
await led.set_status('available')
|
||||
|
||||
state = led.getStatus()
|
||||
return {'status': state["status"],
|
||||
'color': state["color"],
|
||||
'brightness': state["brightness"],
|
||||
'isblinking': state["isblinking"],
|
||||
'blinkParameters': {
|
||||
'frequency': state["frequency"],
|
||||
'duration': state["duration"],
|
||||
'remains': state["remains"]}
|
||||
}
|
||||
|
||||
|
||||
@app.post('/shutdown')
|
||||
async def shutdown(request):
|
||||
request.app.shutdown()
|
||||
return 'The server is shutting down...'
|
||||
|
||||
|
||||
# =========================
|
||||
# START
|
||||
# =========================
|
||||
async def main():
|
||||
asyncio.create_task(led.run())
|
||||
|
||||
# startup animation
|
||||
await led.set_status('busy')
|
||||
await asyncio.sleep_ms(200)
|
||||
await led.set_status('away')
|
||||
await asyncio.sleep_ms(300)
|
||||
await led.set_status('available')
|
||||
await asyncio.sleep_ms(500)
|
||||
await led.set_status('off')
|
||||
|
||||
await app.start_server(port=80)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
# App code lives in busylight.py (or precompiled busylight.mpy) to avoid compiling it in RAM at boot
|
||||
import machine, sys, time
|
||||
|
||||
try:
|
||||
import busylight
|
||||
busylight.run()
|
||||
except Exception as e:
|
||||
# Keep the light available: reboot if the event loop dies (e.g. lwIP out of memory)
|
||||
sys.print_exception(e)
|
||||
time.sleep(2)
|
||||
machine.reset()
|
||||
@@ -77,6 +77,7 @@ Or directly from **[busyLight-streamdeck-pluing](https://code.igox.org/iGoX/busy
|
||||
| /api/blink | GET | n/a | Retrieve the current BusyLight blink status. Return a `blinkStatus` object. |
|
||||
| /api/blink/stop | POST | n/a | Stop the BusyLight blinking and restore previous state. Return a `status` object. |
|
||||
| /api/debug | GET | n/a | Retreive the full BusyLight status. |
|
||||
| /ws/status | WebSocket | n/a | Subscribe to BusyLight status changes. Sends the current `status` object on connection, then a `status` object on every change (status, color, brightness, blink start/end). |
|
||||
|
||||
## JSON objects
|
||||
|
||||
@@ -198,11 +199,9 @@ It will automatically switch to the BusyLight in:
|
||||
|
||||
**(1)** Flash your ESP32 with [Micropython](https://micropython.org/download/ESP32_GENERIC/) **v1.24.1**.
|
||||
|
||||
**(2)** Install [microdot](https://microdot.readthedocs.io/en/latest/index.html) **v2.0.6** library on the ESP32. This can easily be done using [Thonny](https://thonny.org):
|
||||
**(2)** The [microdot](https://microdot.readthedocs.io/en/latest/index.html) **v2.0.6** library is provided precompiled (`.mpy`) in [ESP32/lib/microdot](ESP32/lib/microdot) and is installed with step (4). Precompiled modules are required: compiling the Microdot sources on the ESP32 at boot exhausts the memory needed by the WIFI/network stack.
|
||||
|
||||
| Tools > Manage plug-ins | lib selection |
|
||||
| --- | --- |
|
||||
|  |  |
|
||||
> ⚠️ If Microdot was previously installed with Thonny's package manager, delete the `.py` files in `/lib/microdot` on the ESP32: they take precedence over the `.mpy` files.
|
||||
|
||||
> ⚠️ **Compatibility note:** MicroPython v1.27 is **not compatible** with Microdot due to breaking changes in the underlying ESP-IDF v5.5. Use MicroPython **v1.24.1** with Microdot **v2.0.6**.
|
||||
|
||||
@@ -212,6 +211,12 @@ It will automatically switch to the BusyLight in:
|
||||
|
||||

|
||||
|
||||
> 💡 **Memory tip:** the application code lives in `busylight.py`. To save RAM at boot, precompile it and copy `busylight.mpy` to the ESP32 instead of `busylight.py` (if both are present, MicroPython loads the `.py` one, so delete `busylight.py` from the device):
|
||||
> ```sh
|
||||
> pip install "mpy-cross>=1.24,<1.25"
|
||||
> mpy-cross -march=xtensawin ESP32/busylight.py
|
||||
> ```
|
||||
|
||||
**Done!**
|
||||
|
||||
# 3D files - Enclosure
|
||||
|
||||
Reference in new issue
Block a user