def ensure_wifi(): if wlan.isconnected(): return True wlan.connect(SSID, PASSWORD) for _ in range(10): if wlan.isconnected(): return True time.sleep(1) return False
print("connecting wifi...") ensure_wifi() ip = wlan.ifconfig()[0] print("wifi ok:", ip)
# ===== Ambient送信 ===== def send_ambient(temp, hum): if not ensure_wifi(): return try: url = "https://ambidata.io/api/v2/channels/{}/data".format(AMBIENT_CHANNEL_ID) data = {"writeKey": AMBIENT_WRITE_KEY, "d1": temp, "d2": hum} r = urequests.post(url, json=data) print("ambient:", r.status_code) r.close() gc.collect() except Exception as e: print("ambient error:", e)
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
while not wlan.isconnected():
time.sleep(1)
ip = wlan.ifconfig()[0]
print("IP:", ip)
# ===== Webサーバー準備 =====
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('0.0.0.0', 80))
s.listen(1)
s.settimeout(0.1) # 非ブロッキング
print("Server running at http://{}".format(ip))
# ===== メインループ =====
while True:
# ---- センサー更新 ----
if time.time() - last_update > 2:
t, h = sensor.read()
if t is not None:
latest_temp = t
latest_hum = h