Created
June 17, 2022 16:13
-
-
Save jonathan-ostrander/f1271e13b0b152759189ff5122b0c79a to your computer and use it in GitHub Desktop.
Artisan over FastAPI websocket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
pip install fastapi | |
pip install "uvicorn[standard]" | |
uvicorn main:app --host 0.0.0.0 --port 8000 | |
""" | |
import glob | |
import json | |
import time | |
from fastapi import FastAPI, WebSocket | |
base_dir = '/sys/bus/w1/devices/' | |
device_folder = glob.glob(base_dir + '*-*')[0] | |
device_file = device_folder + '/w1_slave' | |
def read_temp_raw(): | |
with open(device_file, 'r') as f: | |
return f.readlines() | |
def read_temp(): | |
lines = read_temp_raw() | |
while lines[0].strip()[-3:] != 'YES': | |
lines = read_temp_raw() | |
equals_pos = lines[1].find('t=') | |
if equals_pos != -1: | |
temp_string = lines[1][equals_pos+2:] | |
temp_c = float(temp_string) / 1000 | |
temp_f = temp_c * 9 / 5 + 32 | |
return temp_c, temp_f | |
app = FastAPI() | |
@app.websocket("/artisan") | |
async def websocket_endpoint(websocket: WebSocket): | |
await websocket.accept() | |
while True: | |
data = await websocket.receive_text() | |
command = json.loads(data) | |
print(f"Got command: {command}") | |
if command["command"] == "getBT": | |
temp = read_temp()[0] | |
print(f"Read temp: {temp}") | |
resp = json.dumps({"id": command["id"], "data": {"BT": temp}}) | |
print(f"Response: {resp}") | |
await websocket.send_text(resp) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment