完全自動化智能水族箱系統設計
摘要

本項目構建了一個“全自動智能水族箱系統”。系統以 oneM2M/Mobius 作為核心 IoT 數據樞紐,通過 ESP32 負責環境數據采集與執行器控制,Raspberry Pi 執行魚類疾病檢測 AI 模型,Python 邏輯服務器進行規則判定與自動化,Android 應用提供用戶交互界面。
文中不僅說明系統設計,還在每個模塊中內嵌工程源碼,形成可復現和可落地的技術文檔。
1. 設計背景與目標
水族箱運行依賴多個外設(加熱器、補水泵、過濾器、照明等),但這些設備通常由不同電源、不同開關單獨管理;同時,水溫、水位、光照等關鍵環境信息也難以集中查看。
系統目標:
集中化供電與控制
自動化完成日常維護任務(加熱、換水、喂食等)
實時監測 + 遠程控制 + 手機告警
支持魚類疾病自動檢測(AI)
2. 系統架構總覽

整體架構如圖所示(文字化):
| 模塊 | 角色 | 描述 |
|---|---|---|
| ESP32(AE-Sensor & AE-Actuator) | 采集與控制 | 上傳傳感器數據、接收控制命令并驅動繼電器 |
| Raspberry Pi(AE-Rapi) | AI 判斷 | 捕捉圖像 → CNN → Mobius |
| Mobius CSE | IoT 數據交換 | 提供 AE/CNT/CIN 與訂閱機制 |
| Python Logic Server(AE-Logic) | 自動化邏輯 | 溫控、水位告警、自動喂食、FCM 推送 |
| Android App(AE-App) | 人機交互 | 實時監控、水泵/喂食/LED控制 |
3. 傳感器數據采集與上傳(ESP32:AE-Sensor)
ESP32 定時讀取溫度、光照、水位等傳感器,并向 Mobius 的容器(CNT)寫入內容實例(CIN)。
3.1 上傳 CIN 的核心代碼(集成于敘述中)
Mobius 的數據格式要求如下:
{
"m2m:cin": {
"con": { "value": 26.5 }
}
}傳感器節點的上傳邏輯如下:
#include <WiFi.h>
#include <HTTPClient.h>
// Wi-Fi 與 Mobius 基本信息
const char* WIFI_SSID = "YOUR_SSID";
const char* WIFI_PASSWORD = "YOUR_PASS";
const char* MOBIUS_HOST = "https://your-nginx-domain.com";
const char* CSE_BASE = "/Mobius";
const char* AE_SENSOR = "AE-Sensor";
const char* ORIGIN = "S-Sensor"; // 由 ACP 控制
const char* CONTENT_TYPE = "application/json; ty=4";
// 傳感器模擬
float readTemperature() { return 26.5; }
float readLight() { return 500.0; }
String buildCinPayload(float value) {
return "{"m2m:cin":{"con":{"value":" + String(value,2) + "}}}";
}
bool postSensorData(const char* cnt, float v) {
String url = String(MOBIUS_HOST) + CSE_BASE + "/" + AE_SENSOR + "/" + cnt;
HTTPClient http;
http.begin(url);
http.addHeader("X-M2M-Origin", ORIGIN);
http.addHeader("X-M2M-RI", "req-" + String(millis()));
http.addHeader("Content-Type", CONTENT_TYPE);
int code = http.POST(buildCinPayload(v));
Serial.printf("[Sensor] POST %s -> %dn", cnt, code);
http.end();
return code >= 200 && code < 300;
}
void loop() {
postSensorData("temp", readTemperature());
postSensorData("light", readLight());
delay(10000); // 每10秒上傳一次
}4. 執行器控制(ESP32:AE-Actuator)
ESP32 作為執行器節點,會輪詢 Mobius 的控制容器:
/AE-Actuator/heater/AE-Actuator/feed/AE-Actuator/LED
并根據 CIN 的內容驅動繼電器。
4.1 執行器輪詢邏輯(與文章混排)
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
const char* AE_ACTUATOR = "AE-Actuator";
const int PIN_HEATER = 4, PIN_LED = 5, PIN_FEED = 18;
String getLatestCin(const char* cnt) {
String url = String(MOBIUS_HOST) + CSE_BASE + "/" + AE_ACTUATOR + "/" + cnt + "/la";
HTTPClient http;
http.begin(url);
http.addHeader("X-M2M-Origin", "S-Actuator");
http.addHeader("X-M2M-RI", "ri-" + String(millis()));
int code = http.GET();
String payload = code==200 ? http.getString() : "";
http.end();
return payload;
}
void handleCommand(const char* cnt, const String& json) {
StaticJsonDocument<512> doc;
if (deserializeJson(doc, json)) return;
JsonVariant con = doc["m2m:cin"]["con"];
String cmd = con["heater"] | con["LED"] | con["feed"] | "";
bool on = (cmd == "on");
if(strcmp(cnt,"heater")==0) digitalWrite(PIN_HEATER,on);
if(strcmp(cnt,"LED")==0) digitalWrite(PIN_LED,on);
if(strcmp(cnt,"feed")==0) digitalWrite(PIN_FEED,on);
}5. oneM2M 邏輯服務器(AE-Logic)
邏輯服務器負責:
Mobius 訂閱管理
處理通知(傳感器變化)
根據閾值控制加熱器/LED
低水位推送告警
自動喂食調度
AI 結果處理
5.1 創建訂閱(嵌入說明段落中)
def create_subscription(target, nu="https://your-server/notification"):
url = MOBIUS_BASE + target
sub = {
"m2m:sub": {
"rn": "sub-logic",
"nu": [nu],
"nct": 1,
"enc": {"net": [3]}
}
}
headers = {
"X-M2M-Origin": ORIGIN,
"X-M2M-RI": "ri-" + str(uuid.uuid4()),
"Content-Type": "application/json; ty=23"
}
return requests.post(url, headers=headers, data=json.dumps(sub))5.2 通知接收 + 處理 worker
@app.route("/notification", methods=["POST"])
def notification():
notif = request.get_json() or {}
threading.Thread(
target=process_notification_worker,
args=(notif,)
).start()
return "", 200其中 Worker 解析 CIN:
def process_notification_worker(n):
cin = n["m2m:sgn"]["nev"]["rep"]["m2m:cin"]
con = cin["con"] # 例如 { "value": 26.3 }
sur = n["m2m:sgn"]["sur"] # 訂閱路徑
if "temp" in sur: handle_temp(con["value"])
if "wlevel" in sur: handle_wlevel(con["value"])
if "fish-health" in sur: handle_fish_health(con)5.3 溫度控制邏輯
def handle_temp(temp):
t_thresh = g_state["temp-threshold"]
if temp < t_thresh - 0.5:
send_mobius_command("heater", {"heater":"on"})
elif temp > t_thresh + 0.5:
send_mobius_command("heater", {"heater":"off"})5.4 自動喂食調度
def scheduler_thread_fn():
while True:
t = time.localtime()
if t.tm_min == 0 and t.tm_hour in g_state["feeding_times"]:
send_mobius_command("feed", {"feed":"on"})
time.sleep(1)
send_mobius_command("feed", {"feed":"off"})
time.sleep(60)6. AI:Betta 魚疾病檢測模型(Raspberry Pi)
采用輕量級殘差網絡:
class BettaResNet(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3,64,7,2,3) self.bn1 = nn.BatchNorm2d(64) self.pool = nn.MaxPool2d(3,2,1) self.layer1 = self._block(64,64) self.layer2 = self._block(64,128,stride=2) self.layer3 = self._block(128,256,stride=2) self.layer4 = self._block(256,512,stride=2) self.fc = nn.Linear(512,3) def forward(self,x): x = F.relu(self.bn1(self.conv1(x))) x = self.pool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = torch.flatten(F.adaptive_avg_pool2d(x,1),1) return self.fc(x)
推理結果寫回 Mobius:
payload = {
"m2m:cin": {
"con": {"class":"White Spot","score":0.92}
}
}7. Android App(AE-App)與 Mobius 通信
應用采用 Retrofit2 訪問 Mobius,通過 REST API 拉取數據和下發命令。
7.1 Retrofit 接口(嵌入敘述中)
interface MobiusApi {
@GET("Mobius/AE-Sensor/temp/la")
suspend fun getLatestTemp(): Response<MobiusCinWrapper>
@POST("Mobius/AE-Actuator/pump")
suspend fun sendPumpCmd(
@Body body: MobiusCinWrapper
): Response<Unit>
}7.2 控制命令發送
suspend fun pumpOn(api: MobiusApi) {
val body = MobiusCinWrapper(
MobiusCin(con = CinContent(value = null))
)
api.sendPumpCmd(body)
}7.3 FCM 告警接收
class AquariumFcmService : FirebaseMessagingService() {
override fun onMessageReceived(msg: RemoteMessage) {
showNotification(msg.notification?.title, msg.notification?.body)
}
}8. 安全與訪問控制(ACP + HTTPS)
全文代碼邏輯與系統描述緊密結合:
ACP 控制“誰能寫入/讀取哪個 CNT”
Nginx 提供 HTTPS(TLS)防止中間人攻擊
外部設備永遠不能直連 Mobius,只能訪問 Nginx 入口
9. 總結
本項目展示了一個端到端的智能水族箱系統:
架構:多 AE + Mobius CSE
數據鏈路:ESP32 → Mobius → Logic Server → Actuator
自動化:溫控、光照、水位、喂食
AI:魚類疾病判別
App:實時顯示與控制
全程 HTTPS + ACP 保護








評論