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.

77 lines
1.4 KiB

1 year ago
1 year ago
1 year ago
  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. func (v VariableSet) With(sv SetVariable) VariableSet {
  19. curr := gentools.CopyMap(v)
  20. key := "global"
  21. if sv.Match != nil {
  22. key = "match:" + *sv.Match
  23. } else if sv.Devices != nil {
  24. key = "devices:" + strings.Join(sv.Devices, ";")
  25. }
  26. curr[key] = gentools.CopyMap(curr["global"])
  27. if sv.Value == "" {
  28. delete(curr[key], sv.Key)
  29. } else {
  30. curr[key][sv.Key] = sv.Value
  31. }
  32. return curr
  33. }
  34. type Variables struct {
  35. mu sync.Mutex
  36. vars VariableSet
  37. }
  38. func NewVariables() *Variables {
  39. return &Variables{
  40. vars: make(VariableSet, 8),
  41. }
  42. }
  43. func (s *Variables) Get() VariableSet {
  44. s.mu.Lock()
  45. defer s.mu.Unlock()
  46. return s.vars
  47. }
  48. func (s *Variables) Active() bool {
  49. return true
  50. }
  51. func (s *Variables) HandleEvent(_ *lucifer3.EventBus, _ lucifer3.Event) {}
  52. func (s *Variables) HandleCommand(bus *lucifer3.EventBus, command lucifer3.Command) {
  53. if sv, ok := command.(SetVariable); ok {
  54. newVariables := s.Get().With(sv)
  55. s.mu.Lock()
  56. s.vars = newVariables
  57. s.mu.Unlock()
  58. }
  59. }