This commit is contained in:
[Valentino Heman Budiarto] 2026-06-05 20:13:35 +07:00
parent 16075c670a
commit 2bedb35863
2 changed files with 26 additions and 4 deletions

View File

@ -70,6 +70,8 @@ func main() {
// PASTIKAN BARIS INI ADA DI SINI:
r.POST("/api/hardware/control", controllers.ControlHardware)
r.GET("/api/hardware/status", controllers.GetHardwareStatus)
r.GET("/api/hardware/power-status", controllers.GetPowerStatus)
r.Run(":8080")

View File

@ -24,6 +24,14 @@ type VerifyRequest struct {
Token string `json:"token"`
}
// --- CACHE STATUS HARDWARE (Mengingat status terakhir perangkat) ---
var DeviceStatusCache = map[string]string{
"lampu1": "off",
"lampu2": "off",
"ac": "off",
"projector": "off",
}
// =========================================================================
// FUNGSI 1: VERIFIKASI HARDWARE & HITUNG SISA WAKTU DINAMIS
// =========================================================================
@ -48,7 +56,7 @@ func VerifyHardwareCode(c *gin.Context) {
// 1. Cek di tabel bookings (Redeem Code)
errBooking := config.DB.Table("bookings").
Select("end_time").
Select("end_time").
Where("redeem_code = ?", tokenInput).
Scan(&result).Error
@ -59,7 +67,7 @@ func VerifyHardwareCode(c *gin.Context) {
} else {
// 2. Cek di tabel class_schedules (Kode MK)
errSchedule := config.DB.Table("class_schedules").
Select("end_time").
Select("end_time").
Where("kode_mk = ?", tokenInput).
Scan(&result).Error
@ -131,6 +139,8 @@ func ControlHardware(c *gin.Context) {
token := client.Publish(topic, 0, false, req.Action)
token.Wait()
DeviceStatusCache[req.Device] = req.Action
c.JSON(http.StatusOK, gin.H{
"status": "success",
"message": fmt.Sprintf("Berhasil mengirim perintah %s ke %s via MQTT", req.Action, req.Device),
@ -195,8 +205,8 @@ func ControlHardware(c *gin.Context) {
func GetPowerStatus(c *gin.Context) {
haURL := os.Getenv("HA_URL")
haToken := os.Getenv("HA_TOKEN")
entityID := "sensor.kwh_meter_power"
entityID := "sensor.kwh_meter_power"
apiURL := fmt.Sprintf("%s/api/states/%s", haURL, entityID)
req, _ := http.NewRequest("GET", apiURL, nil)
@ -221,4 +231,14 @@ func GetPowerStatus(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{"power": powerStr})
}
// =========================================================================
// FUNGSI 4: MENGAMBIL STATUS PERANGKAT SECARA REAL-TIME
// =========================================================================
func GetHardwareStatus(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"status": "success",
"data": DeviceStatusCache,
})
}