esp32-timed-switch/html/mockup.py

77 lines
2.4 KiB
Python
Executable File

#! /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')
@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)
# Generate a random 12-bit integer (0 to 4095)
def random_32_bit_int():
return random.randint(0, 0xFFF)
# Convert 24 integers to a binary stream
def ints_to_binary_stream(integers):
binary_data = bytearray()
for integer in integers:
# Ensure integer is in 32-bit range
integer &= 0xFFF
# Convert to bytes and append
binary_data.extend(integer.to_bytes(4, byteorder='big')) # 2 bytes per integer (32-bit)
return binary_data
# 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), 4):
integers.append(int.from_bytes(binary_data[i:i+4], byteorder='big') & 0xFFF) # Extract 32-bit value
return integers
@app.route('/api/schedule/<int:plug_id>', methods=['GET'])
def get_schedule(plug_id):
# Generate 24 random 32-bit integers
schedule = [random_32_bit_int() for _ in range(24)]
# Convert to binary stream
binary_data = ints_to_binary_stream(schedule)
# Return as a binary response
return Response(binary_data, content_type='application/octet-stream')
@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, mimetype='text/plain')
if __name__ == '__main__':
app.run(
host="0.0.0.0",
port=PORT,
use_debugger=True
)