context.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package mqtt_api
  2. import (
  3. "time"
  4. )
  5. type Context struct {
  6. // 主题
  7. Topic string
  8. // 数据
  9. Data []byte
  10. mqttClient *MqttClient
  11. handlers []Handler
  12. currentHandlerIndex int
  13. }
  14. func newContext(mqttClient *MqttClient, topic string, data []byte, handlers []Handler) (*Context, error) {
  15. return &Context{
  16. Topic: topic,
  17. Data: data,
  18. mqttClient: mqttClient,
  19. handlers: handlers,
  20. currentHandlerIndex: 0,
  21. }, nil
  22. }
  23. func destroyContext(c *Context) {
  24. if c == nil {
  25. return
  26. }
  27. if c.currentHandlerIndex == len(c.handlers) {
  28. return
  29. }
  30. ticker := time.NewTicker(100 * time.Millisecond)
  31. defer ticker.Stop()
  32. for {
  33. select {
  34. case <-ticker.C:
  35. if c.currentHandlerIndex == len(c.handlers) {
  36. break
  37. }
  38. }
  39. }
  40. }
  41. func (c *Context) callHandlers(data []byte) {
  42. c.currentHandlerIndex = 0
  43. c.Data = data
  44. c.handlers[c.currentHandlerIndex](c)
  45. }
  46. func (c *Context) Response(responseIdentifier string, data []byte) error {
  47. err := c.mqttClient.response(c.Topic, responseIdentifier, data)
  48. if err != nil {
  49. return err
  50. }
  51. return nil
  52. }
  53. func (c *Context) Next() {
  54. c.currentHandlerIndex++
  55. if c.currentHandlerIndex < len(c.handlers) {
  56. c.handlers[c.currentHandlerIndex](c)
  57. }
  58. }