在冰箱周遭,沒有安裝有線網路的情況下,也想讓冰箱資訊同步出來,因此透過 Meshtastic 讓手機和冰箱互相連線。 本日目標,是希望系統自己判斷網路狀態,如果主要網路失效,就自動改走 Meshtastic 通知。
Primary Path
Wi-Fi / Internet
│
├── OK → 正常使用
│
└── FAIL
↓
Secondary Path
Meshtastic
↓
發送告警
在冰箱的連接 ESP32 / Raspberry Pi / Meshtastic 的情況,有三種網路狀態需要進行偵測。
import subprocess
def check_ping(host: str) -> bool:
result = subprocess.run(
[
"ping",
"-c",
"1",
"-W",
"2",
host,
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
return result.returncode == 0
分別檢查可以找到 DNS 和連外網 HTTPS
import socket
def check_dns() -> bool:
try:
socket.gethostbyname(
"example.com"
)
return True
except OSError:
return False
import requests
def check_internet() -> bool:
try:
response = requests.get(
"https://example.com",
timeout=5,
)
return (
200 <= response.status_code < 500
)
except requests.RequestException:
return False
app/
└── services/
├── network_health_service.py
└── meshtastic_service.py
class NetworkHealthService:
def check(self):
lan_ok = self.check_gateway()
internet_ok = False
if lan_ok:
internet_ok = (
self.check_internet()
)
return {
"lan_ok": lan_ok,
"internet_ok": internet_ok,
}
def handle_network_state(
old_state,
new_state,
):
if (
old_state["internet_ok"]
and not new_state["internet_ok"]
):
mesh.send(
"ALERT|WAN|DOWN"
)
if (
not old_state["internet_ok"]
and new_state["internet_ok"]
):
mesh.send(
"RECOVERY|WAN|UP"
)