esp32-timed-switch/html/mockup.py

79 lines
2.3 KiB
Python
Raw Normal View History

2023-11-09 19:07:34 +00:00
#! /usr/bin/env python3
from flask import Flask, request, send_from_directory, Response
import random
import os
app = Flask(__name__)
PORT_FROM_ENV = os.environ.get('PORT')
if PORT_FROM_ENV:
PORT = PORT_FROM_ENV
else:
PORT = "3000"
static_file_dir = os.path.dirname(os.path.realpath(__file__))
@app.route('/', methods=['GET'])
def serve_index():
return send_from_directory(static_file_dir, 'index.html')
2023-11-09 19:07:34 +00:00
@app.route('/<path:path>', methods=['GET'])
def serve_file_in_dir(path):
if not os.path.isfile(os.path.join(static_file_dir, path)):
path = os.path.join(path, 'index.html')
print("Serving local file : {}".format(path))
return send_from_directory(static_file_dir, path)
2023-11-09 19:07:34 +00:00
# Generate a random 12-bit integer (0 to 4095)
def random_12_bit_int():
2024-03-11 08:18:21 +00:00
return random.randint(0, 0b111111111111)
2023-11-09 19:07:34 +00:00
# Convert a binary stream to 24 integers
def binary_stream_to_ints(binary_data):
integers = []
# Every 32-bit integer is represented by 2 bytes
for i in range(0, len(binary_data), 2):
2024-03-11 08:18:21 +00:00
integers.append(int.from_bytes(binary_data[i:i + 2]) & 0b111111111111) # Extract 32-bit value
2023-11-09 19:07:34 +00:00
return integers
2023-11-09 19:07:34 +00:00
@app.route('/api/schedule/<int:plug_id>', methods=['GET'])
2023-11-09 19:07:34 +00:00
def get_schedule(plug_id):
# Generate 24 random 32-bit integers
schedule = [random_12_bit_int() for _ in range(24)]
# Convert 24 integers to a binary stream
def ints_to_binary_stream(integers):
for integer in integers:
# Ensure integer is in 12-bit range
integer &= 0b111111111111
# Convert to bytes and append
2024-03-11 08:18:21 +00:00
yield integer.to_bytes(2) # 2 bytes per integer
# Return as a binary stream
return Response(ints_to_binary_stream(schedule), status=200, content_type='application/octet-stream')
2023-11-09 19:07:34 +00:00
@app.route('/api/schedule/<int:plug_id>', methods=['POST'])
def update_schedule(plug_id):
# Get binary data from the request
binary_data = request.data
# Convert binary stream to integers
new_schedule = binary_stream_to_ints(binary_data)
print(f"Received new schedule for plug {plug_id}: {new_schedule}")
# Respond with a success message in binary format
return Response(b'Update successful', status=200, content_type='text/plain')
2023-11-09 19:07:34 +00:00
if __name__ == '__main__':
app.run(
host="0.0.0.0",
port=PORT,
use_debugger=True
)