context.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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() {
  42. c.currentHandlerIndex = 0
  43. for c.currentHandlerIndex < len(c.handlers) {
  44. c.handlers[c.currentHandlerIndex](c)
  45. c.currentHandlerIndex++
  46. }
  47. }
  48. func (c *Context) Response(responseIdentifier string, data []byte) error {
  49. err := c.mqttClient.response(c.Topic, responseIdentifier, data)
  50. if err != nil {
  51. return err
  52. }
  53. return nil
  54. }
  55. func (c *Context) Next() {
  56. c.currentHandlerIndex++
  57. if c.currentHandlerIndex < len(c.handlers) {
  58. c.handlers[c.currentHandlerIndex](c)
  59. }
  60. }