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.

73 lines
1.4 KiB

  1. package script
  2. import (
  3. lucifer3 "git.aiterp.net/lucifer3/server"
  4. "git.aiterp.net/lucifer3/server/internal/gentools"
  5. "strings"
  6. "sync"
  7. )
  8. type VariableSet map[string]map[string]string
  9. func (v VariableSet) Global(key string) string {
  10. return v["global"][key]
  11. }
  12. func (v VariableSet) Match(tag string, key string) string {
  13. return v["match:"+tag][key]
  14. }
  15. func (v VariableSet) Devices(list []string, key string) string {
  16. return v["devices:"+strings.Join(list, ";")][key]
  17. }
  18. type Variables struct {
  19. mu sync.Mutex
  20. vars VariableSet
  21. }
  22. func NewVariables() *Variables {
  23. return &Variables{
  24. vars: make(VariableSet, 8),
  25. }
  26. }
  27. func (s *Variables) Get() VariableSet {
  28. s.mu.Lock()
  29. defer s.mu.Unlock()
  30. return s.vars
  31. }
  32. func (s *Variables) Active() bool {
  33. return true
  34. }
  35. func (s *Variables) HandleEvent(_ *lucifer3.EventBus, _ lucifer3.Event) {}
  36. func (s *Variables) HandleCommand(bus *lucifer3.EventBus, command lucifer3.Command) {
  37. if sv, ok := command.(SetVariable); ok {
  38. s.mu.Lock()
  39. curr := gentools.CopyMap(s.vars)
  40. s.mu.Unlock()
  41. key := "global"
  42. if sv.Match != nil {
  43. key = "match:" + *sv.Match
  44. } else if sv.Devices != nil {
  45. key = "devices:" + strings.Join(sv.Devices, ";")
  46. }
  47. curr[key] = gentools.CopyMap(curr["global"])
  48. if sv.Value == "" {
  49. delete(curr[key], sv.Key)
  50. } else {
  51. curr[key][sv.Key] = sv.Value
  52. }
  53. s.mu.Lock()
  54. s.vars = curr
  55. s.mu.Unlock()
  56. }
  57. }