66 lines
1.7 KiB
Go
66 lines
1.7 KiB
Go
package controllers
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// Struktur Data Timer
|
|
type AutoTimer struct {
|
|
IsActive bool `json:"is_active"`
|
|
OffTime string `json:"off_time"`
|
|
OnTime string `json:"on_time"`
|
|
}
|
|
|
|
// Disimpan di RAM sementara agar cepat (reset saat server mati)
|
|
var AppTimer = AutoTimer{IsActive: false, OffTime: "22:00", OnTime: "05:00"}
|
|
|
|
// API: Ambil Pengaturan Timer
|
|
func GetTimerConfig(c *gin.Context) {
|
|
c.JSON(http.StatusOK, AppTimer)
|
|
}
|
|
|
|
// API: Simpan Pengaturan Timer
|
|
func SetTimerConfig(c *gin.Context) {
|
|
if err := c.ShouldBindJSON(&AppTimer); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Data tidak valid"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"message": "Jadwal Auto-Cutoff berhasil disimpan", "data": AppTimer})
|
|
}
|
|
|
|
// MESIN CRON: Berjalan di latar belakang mengecek jam setiap menit
|
|
func StartPowerCronWorker() {
|
|
go func() {
|
|
ticker := time.NewTicker(1 * time.Minute)
|
|
for range ticker.C {
|
|
if !AppTimer.IsActive {
|
|
continue
|
|
}
|
|
|
|
loc, _ := time.LoadLocation("Asia/Jakarta")
|
|
now := time.Now().In(loc).Format("15:04") // Format 24 Jam (HH:MM)
|
|
|
|
if now == AppTimer.OffTime {
|
|
fmt.Println("🕰️ [TIMER] Waktunya OFF! Memutus daya...")
|
|
triggerGlobalPower("off")
|
|
} else if now == AppTimer.OnTime {
|
|
fmt.Println("🕰️ [TIMER] Waktunya ON! Menyalakan daya...")
|
|
triggerGlobalPower("on")
|
|
}
|
|
}
|
|
}()
|
|
}
|
|
|
|
// Helper untuk menembak API Global Power yang sudah kamu miliki
|
|
func triggerGlobalPower(action string) {
|
|
payload := map[string]string{"action": action}
|
|
jsonPayload, _ := json.Marshal(payload)
|
|
// Memanggil API lokal kita sendiri
|
|
http.Post("http://127.0.0.1:8080/api/power/global", "application/json", bytes.NewBuffer(jsonPayload))
|
|
} |