You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
1.7 KiB

1 year ago
  1. package script
  2. import (
  3. "fmt"
  4. lucifer3 "git.aiterp.net/lucifer3/server"
  5. "git.aiterp.net/lucifer3/server/device"
  6. "git.aiterp.net/lucifer3/server/events"
  7. "github.com/google/uuid"
  8. "strconv"
  9. )
  10. type TriggerEvent string
  11. const (
  12. TEButton TriggerEvent = "Button"
  13. TETime TriggerEvent = "Time"
  14. TETemperatureAbove TriggerEvent = "TemperatureAbove"
  15. TETemperatureBelow TriggerEvent = "TemperatureBelow"
  16. )
  17. type Trigger struct {
  18. ID uuid.UUID `json:"id"`
  19. Name string `json:"name"`
  20. Event TriggerEvent `json:"event"`
  21. DeviceMatch string `json:"deviceMatch"`
  22. Parameter string `json:"parameter"`
  23. ScriptTarget string `json:"scriptTarget"`
  24. ScriptName string `json:"scriptName"`
  25. ScriptPre []Line `json:"scriptPre"`
  26. ScriptPost []Line `json:"scriptPost"`
  27. }
  28. func (t *Trigger) Check(event lucifer3.Event, res device.Resolver) bool {
  29. devices := res.Resolve(t.DeviceMatch)
  30. switch event := event.(type) {
  31. case events.ButtonPressed:
  32. if t.Event != TEButton {
  33. return false
  34. }
  35. for _, dev := range devices {
  36. if dev.ID == event.ID {
  37. return t.Parameter == event.Name
  38. }
  39. }
  40. case events.Time:
  41. if t.Event != TETime {
  42. return false
  43. }
  44. return fmt.Sprintf("%02d:%02d", event.Hour, event.Minute) == t.Parameter
  45. case events.TemperatureChanged:
  46. if t.Event != TETemperatureAbove && t.Event != TETemperatureBelow {
  47. return false
  48. }
  49. num, err := strconv.ParseFloat(t.Parameter, 64)
  50. if err != nil {
  51. return false
  52. }
  53. for _, dev := range devices {
  54. if dev.ID == event.ID {
  55. return (event.Temperature >= num) == (t.Event == TETemperatureAbove)
  56. }
  57. }
  58. }
  59. return false
  60. }