Matrix/API/main.py
2023-11-23 10:47:40 +01:00

139 lines
2.8 KiB
Python

#!/usr/bin/env python
from deps.samplebase import SampleBase
from rgbmatrix import graphics
from flask import Flask, request, jsonify
from waitress import serve
import time, threading
api = Flask(__name__)
@api.route('/text', methods=['POST'])
def display_text():
response = { 'success': True }
try:
global matrix
data = request.get_json()
text = data.get('text')
x_coord = data.get('x')
y_coord = data.get('y')
matrix.text(x_coord, y_coord, text)
except Exception as e:
print(e)
response['success'] = False
return jsonify(response)
@api.route('/pixel', methods=['POST'])
def set_pixel():
response = { 'success': True }
try:
global matrix
data = request.get_json()
x_coord = data.get('x')
y_coord = data.get('y')
matrix.pixel(x_coord, y_coord)
except Exception as e:
print(e)
response['success'] = False
return jsonify(response)
@api.route('/circle', methods=['POST'])
def draw_circle():
response = { 'success': True }
try:
global matrix
data = request.get_json()
radius = data.get('r')
x_coord = data.get('x')
y_coord = data.get('y')
matrix.circle(x_coord, y_coord, radius)
except Exception as e:
print(e)
response['success'] = False
return jsonify(response)
@api.route('/color', methods=['POST'])
def set_color():
response = { 'success': True }
try:
global matrix
data = request.get_json()
red = data.get('r')
green = data.get('g')
blue = data.get('b')
matrix.set_color(red, green, blue)
except Exception as e:
print(e)
response['success'] = False
return jsonify(response)
@api.route('/update', methods=['GET'])
def update_matrix():
response = { 'success': True }
try:
global matrix
matrix.update()
except Exception as e:
print(e)
response['success'] = False
return jsonify(response)
class Matrix(SampleBase):
def __init__(self, *args, **kwargs):
super(Matrix, self).__init__(*args, **kwargs)
def run(self):
self.font = graphics.Font()
self.font.LoadFont("deps/fonts/9x18B.bdf")
self.color = graphics.Color(255, 255, 255)
self.canvas = self.matrix.CreateFrameCanvas()
self.canvas.Clear()
while True:
time.sleep(.05)
def clear(self):
self.canvas.Clear()
def update(self):
self.canvas = self.matrix.SwapOnVSync(self.canvas)
self.clear()
def set_color(self, r, g, b):
self.color = graphics.Color(r, g, b)
def pixel(self, x, y):
self.canvas.SetPixel(x, y, self.color.red, self.color.green, self.color.blue)
def text(self, x, y, t):
graphics.DrawText(self.canvas, self.font, x*9, (y+1)*18, self.color, t)
def circle(self, x, y, r):
graphics.DrawCircle(self.canvas, self.font, x, y, r, self.color)
matrix = None
if __name__ == "__main__":
matrix = Matrix()
threading.Thread(target=lambda: serve(api, host="0.0.0.0", port=8080)).start()
if not matrix.process():
matrix.print_help()