Myu
2025年12月6日土曜日
ESP32+BME280 bottleコードの調整
ESP32からのデータをbottleで表示するコードを少し調整。スマホでの表示が見ずらいので少し調整してみたのがこちら
latest_cap = None LOG_FILE = "cap_log.txt" MAX_LINES = 200 def read_log(): if not os.path.exists(LOG_FILE): return [] with open(LOG_FILE, "r") as f: return f.readlines() def write_log(lines): with open(LOG_FILE, "w") as f: f.writelines(lines) latest_cap = None LOG_FILE = "cap_log.txt" MAX_LINES = 200 def read_log(): if not os.path.exists(LOG_FILE): return [] with open(LOG_FILE, "r") as f: return f.readlines() def write_log(lines): with open(LOG_FILE, "w") as f: f.writelines(lines) @app.route('/py/cap') def cap_handler(): global latest_cap,latest_t,latest_p,latest_h latest_cap = None latest_t = None latest_p = None latest_h = None cap_value = request.query.cap # ?cap=123 または ?cap=list10 list10だと最新の10個データ表示 t_value= request.query.t p_value= request.query.p h_value= request.query.h if cap_value: if cap_value.startswith("list"): # ?cap=listN の場合 try: n = int(cap_value[4:]) lines = read_log() latest_lines = lines[-n:] if n > 0 else [] response.content_type = 'application/json' # JSON形式で返す result = [] for line in latest_lines: dt_str, value_str,value_t,value_p,value_h = line.strip().split(',', 4) result.append({ "datetime": dt_str, "cap": int(value_str), "temp": float(value_t), "hpa": float(value_p), "hum": float(value_h) }) return json.dumps(result) except ValueError: response.status = 400 return "Invalid list parameter" else: # 数値の場合 try: latest_cap = int(cap_value) latest_t=float(t_value) latest_p=float(p_value) latest_h=float(h_value) now_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S") line = f"{now_str},{latest_cap},{latest_t},{latest_p},{latest_h}\n" # ログを読み込んで追記 lines = read_log() lines.append(line) # 最大行数を維持 if len(lines) > MAX_LINES: lines = lines[-MAX_LINES:] write_log(lines) return f"Cap value {latest_cap} saved.\n" except ValueError: response.status = 400 return "Invalid value" else: # パラメータなし → 最新値返す if latest_cap is not None: response.content_type = 'application/json' return json.dumps({"latest_cap": latest_cap}) else: response.status = 404 return "No data yet" @app.route('/py/captable') def captable(): return """
灯油タンク残量概算
残量データ一覧
a:
b:
再計算
日時
cap
残量%
気温
気圧
湿度
""" @app.route('/py/dashboard2') def dashboard2(): return """
Dashboard
Dashboard
""" @app.route('/py/capgraph') def capgraph(): return """
残量グラフ
残量 / 温度 / 気圧 / 湿度 グラフ
"""
0 件のコメント:
コメントを投稿
前の投稿
ホーム
登録:
コメントの投稿 (Atom)
0 件のコメント:
コメントを投稿