hardware n monitoring
This commit is contained in:
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv" // Digunakan untuk mengubah teks Watt menjadi angka
|
||||
"time"
|
||||
|
||||
"s-class-backend/config" // Import database
|
||||
@@ -170,7 +171,7 @@ func ControlHardware(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 🌟 BLOK 1: KONTROL GEMBOK / OTORISASI RELAY (SANGAT PENTING)
|
||||
// 🌟 BLOK 1: KONTROL GEMBOK / OTORISASI RELAY
|
||||
if req.Device == "auth" {
|
||||
broker := os.Getenv("MQTT_BROKER")
|
||||
user := os.Getenv("MQTT_USER")
|
||||
@@ -179,7 +180,6 @@ func ControlHardware(c *gin.Context) {
|
||||
opts := mqtt.NewClientOptions().AddBroker(broker).SetUsername(user).SetPassword(pass).SetClientID(fmt.Sprintf("Golang-Lock-%d", time.Now().Unix()))
|
||||
client := mqtt.NewClient(opts)
|
||||
if token := client.Connect(); token.Wait() && token.Error() == nil {
|
||||
// Retain = true untuk menimpa status UNLOCK lama di server MQTT
|
||||
client.Publish("sclass/d101/auth", 0, true, req.Action).Wait()
|
||||
client.Disconnect(250)
|
||||
fmt.Println("[MQTT] Status Gembok Relay diubah menjadi:", req.Action)
|
||||
@@ -263,45 +263,100 @@ func ControlHardware(c *gin.Context) {
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// FUNGSI 3: MENDAPATKAN STATUS DAYA DARI HOME ASSISTANT
|
||||
// HELPER: MENGAMBIL STATE DARI HOME ASSISTANT
|
||||
// =========================================================================
|
||||
func GetPowerStatus(c *gin.Context) {
|
||||
haURL := os.Getenv("HA_URL")
|
||||
haToken := os.Getenv("HA_TOKEN")
|
||||
|
||||
entityID := "sensor.kwh_meter_power"
|
||||
func fetchHAState(haURL string, haToken string, entityID string) float64 {
|
||||
apiURL := fmt.Sprintf("%s/api/states/%s", haURL, entityID)
|
||||
|
||||
req, _ := http.NewRequest("GET", apiURL, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+haToken)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
client := &http.Client{}
|
||||
client := &http.Client{Timeout: 3 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"power": 0})
|
||||
return
|
||||
return 0
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var result map[string]interface{}
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
|
||||
powerStr, ok := result["state"].(string)
|
||||
if !ok {
|
||||
c.JSON(http.StatusOK, gin.H{"power": 0})
|
||||
return
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"power": powerStr})
|
||||
stateStr, ok := result["state"].(string)
|
||||
if !ok {
|
||||
return 0
|
||||
}
|
||||
|
||||
// Ubah string angka menjadi float
|
||||
val, _ := strconv.ParseFloat(stateStr, 64)
|
||||
return val
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// FUNGSI 4: MENGIRIM STATUS REAL-TIME KE WEB FRONTEND
|
||||
// FUNGSI 3: MENDAPATKAN STATUS DAYA DARI 3 MCB SEKALIGUS
|
||||
// =========================================================================
|
||||
func GetPowerStatus(c *gin.Context) {
|
||||
haURL := os.Getenv("HA_URL")
|
||||
haToken := os.Getenv("HA_TOKEN")
|
||||
|
||||
powerUmum := fetchHAState(haURL, haToken, "sensor.wifi_smart_meter_pro_power")
|
||||
powerAC1 := fetchHAState(haURL, haToken, "sensor.wifi_smart_meter_pro_2_power")
|
||||
powerAC2 := fetchHAState(haURL, haToken, "sensor.wifi_smart_meter_pro_3_power")
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"umum": powerUmum,
|
||||
"ac1": powerAC1,
|
||||
"ac2": powerAC2,
|
||||
})
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// FUNGSI 4: CUT OFF SEMUA POWER (MATIKAN 3 MCB)
|
||||
// =========================================================================
|
||||
func CutOffAllPower(c *gin.Context) {
|
||||
haURL := os.Getenv("HA_URL")
|
||||
haToken := os.Getenv("HA_TOKEN")
|
||||
|
||||
apiURL := fmt.Sprintf("%s/api/services/switch/turn_off", haURL)
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"entity_id": []string{
|
||||
"switch.wifi_smart_meter_pro_switch",
|
||||
"switch.wifi_smart_meter_pro_2_switch",
|
||||
"switch.wifi_smart_meter_pro_3_switch",
|
||||
},
|
||||
}
|
||||
|
||||
jsonPayload, _ := json.Marshal(payload)
|
||||
req, _ := http.NewRequest("POST", apiURL, bytes.NewBuffer(jsonPayload))
|
||||
req.Header.Set("Authorization", "Bearer "+haToken)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
client := &http.Client{Timeout: 5 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Gagal menghubungi Home Assistant"})
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Update cache
|
||||
DeviceStatusCache["lampu1"] = "off"
|
||||
DeviceStatusCache["lampu2"] = "off"
|
||||
DeviceStatusCache["ac"] = "off"
|
||||
DeviceStatusCache["projector"] = "off"
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"status": "success", "message": "Semua daya ruangan (MCB) berhasil diputus"})
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// FUNGSI 5: MENGIRIM STATUS REAL-TIME KE WEB FRONTEND
|
||||
// =========================================================================
|
||||
func GetHardwareStatus(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"status": "success",
|
||||
"data": DeviceStatusCache,
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user