File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 33from sqlalchemy .orm import Session
44from slowapi import _rate_limit_exceeded_handler
55from slowapi .errors import RateLimitExceeded
6+ from app .mqtt .client import start_mqtt
67
78# Import Module Kita
89from app .core .database import engine , get_db , Base
Original file line number Diff line number Diff line change @@ -18,4 +18,14 @@ class Device(Base):
1818 # Status
1919 is_active = Column (Boolean , default = True )
2020 created_at = Column (DateTime (timezone = True ), server_default = func .now ())
21- updated_at = Column (DateTime (timezone = True ), onupdate = func .now ())
21+ updated_at = Column (DateTime (timezone = True ), onupdate = func .now ())
22+
23+
24+ class SensorLog (Base ):
25+ __tablename__ = "sensor_logs"
26+
27+ id = Column (Integer , primary_key = True , index = True )
28+ device_id = Column (String , index = True ) # ID Alat (Misal: 441D...)
29+ topic_type = Column (String ) # Misal: "suhu", "kelembaban", "lampu"
30+ value = Column (String ) # Misal: "30.5", "ON", "AUTO"
31+ created_at = Column (DateTime (timezone = True ), server_default = func .now ())
Original file line number Diff line number Diff line change 1+ import paho .mqtt .client as mqtt
2+ from app .core .config import settings # Asumsi config ada di sini
3+ from app .mqtt .callbacks import on_message # Import logika langkah 2
4+
5+ # Global variable buat client
6+ mqtt_client = mqtt .Client (client_id = "Backend_Listener_Worker" , protocol = mqtt .MQTTv311 )
7+
8+ def start_mqtt ():
9+ # 1. Setup Auth (Sesuaikan dengan kredensial EMQX kamu)
10+ # Lebih baik ambil dari .env/config, tapi hardcode dulu buat test gapapa
11+ MQTT_BROKER = "k2519aa6.ala.asia-southeast1.emqxsl.com"
12+ MQTT_PORT = 8883
13+ MQTT_USER = "PCB01"
14+ MQTT_PASS = "5ywnMzsVX4Ss9vH"
15+
16+ mqtt_client .username_pw_set (MQTT_USER , MQTT_PASS )
17+ mqtt_client .tls_set () # Wajib SSL untuk port 8883
18+
19+ # 2. Hubungkan logic Callback
20+ mqtt_client .on_message = on_message
21+
22+ # 3. Konek
23+ try :
24+ mqtt_client .connect (MQTT_BROKER , MQTT_PORT , 60 )
25+
26+ # 4. Subscribe Dynamic Topic
27+ # Tanda '+' adalah wildcard.
28+ # Artinya kita dengar semua alat di topik status
29+ mqtt_client .subscribe ("alat/+/status/#" )
30+
31+ mqtt_client .loop_start () # Jalankan di background thread
32+ print ("✅ MQTT Listener Berjalan! Mendengarkan: alat/+/status/#" )
33+
34+ except Exception as e :
35+ print (f"❌ Gagal Konek MQTT: { e } " )
You can’t perform that action at this time.
0 commit comments