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.

70 lines
1.6 KiB

  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. Event TriggerEvent `json:"event"`
  20. DeviceMatch string `json:"deviceMatch"`
  21. Parameter string `json:"parameter"`
  22. ScriptTarget string `json:"scriptTarget"`
  23. ScriptName string `json:"scriptName"`
  24. ScriptPre []Line `json:"scriptPre"`
  25. ScriptPost []Line `json:"scriptPost"`
  26. }
  27. func (t *Trigger) Check(event lucifer3.Event, res device.Resolver) bool {
  28. devices := res.Resolve(t.DeviceMatch)
  29. switch event := event.(type) {
  30. case events.ButtonPressed:
  31. if t.Event != TEButton {
  32. return false
  33. }
  34. for _, dev := range devices {
  35. if dev.ID == event.ID {
  36. return t.Parameter == event.Name
  37. }
  38. }
  39. case events.Time:
  40. if t.Event != TETime {
  41. return false
  42. }
  43. return fmt.Sprintf("%02d:%02d", event.Hour, event.Minute) == t.Parameter
  44. case events.TemperatureChanged:
  45. if t.Event != TETemperatureAbove && t.Event != TETemperatureBelow {
  46. return false
  47. }
  48. num, err := strconv.ParseFloat(t.Parameter, 64)
  49. if err != nil {
  50. return false
  51. }
  52. for _, dev := range devices {
  53. if dev.ID == event.ID {
  54. return (event.Temperature >= num) == (t.Event == TETemperatureAbove)
  55. }
  56. }
  57. }
  58. return false
  59. }