#! /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('/', 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_12_bit_int(): return random.randint(0, 0b111111111111) # 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): integers.append(int.from_bytes(binary_data[i:i + 2]) & 0b111111111111) # Extract 32-bit value return integers @app.route('/api/schedule/', methods=['GET']) 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 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') @app.route('/api/schedule/', 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') if __name__ == '__main__': app.run( host="0.0.0.0", port=PORT, use_debugger=True )