ifttt.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // support ifttt action between two devices.
  2. package rule
  3. import (
  4. "sparrow/pkg/models"
  5. "sparrow/pkg/productconfig"
  6. "sparrow/pkg/server"
  7. )
  8. type Ifttt struct{}
  9. func NewIfttt() *Ifttt {
  10. return &Ifttt{}
  11. }
  12. func (ift *Ifttt) Check(deviceid uint64, eventid uint16) error {
  13. actions := &[]models.Rule{}
  14. query := &models.Rule{
  15. RuleType: "ifttt",
  16. DeviceID: int64(deviceid),
  17. }
  18. err := server.RPCCallByName("registry", "Registry.QueryRules", query, actions)
  19. if err != nil {
  20. server.Log.Warnf("load ifttt rules error : %v", err)
  21. return err
  22. }
  23. if len(*actions) > 0 {
  24. device := &models.Device{}
  25. err := server.RPCCallByName("registry", "Registry.FindDeviceById", int64(deviceid), device)
  26. if err != nil {
  27. server.Log.Errorf("find device error : %v", err)
  28. return err
  29. }
  30. product := &models.Product{}
  31. err = server.RPCCallByName("registry", "Registry.FindProduct", device.ProductID, product)
  32. if err != nil {
  33. server.Log.Errorf("find product error : %v", err)
  34. return err
  35. }
  36. c, err := productconfig.New(product.ProductConfig)
  37. if err != nil {
  38. server.Log.Errorf("product config error : %v", err)
  39. return err
  40. }
  41. name := ""
  42. for _, ev := range c.Events {
  43. if ev.No == int(eventid) {
  44. name = ev.Name
  45. }
  46. }
  47. for _, action := range *actions {
  48. if action.Trigger == name {
  49. err := performRuleAction(action.Target, action.Action)
  50. if err != nil {
  51. server.Log.Warnf("ifttt action failed: %v", err)
  52. }
  53. }
  54. }
  55. }
  56. return nil
  57. }