1
0

mqtt_agent.rb 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. require "json"
  2. module Agents
  3. class MqttAgent < Agent
  4. gem_dependency_check { defined?(MQTT) }
  5. description <<~MD
  6. The MQTT Agent allows both publication and subscription to an MQTT topic.
  7. #{'## Include `mqtt` in your Gemfile to use this Agent!' if dependencies_missing?}
  8. MQTT is a generic transport protocol for machine to machine communication.
  9. You can do things like:
  10. * Publish to [RabbitMQ](http://www.rabbitmq.com/mqtt.html)
  11. * Run [OwnTracks, a location tracking tool](http://owntracks.org/) for iOS and Android
  12. * Subscribe to your home automation setup like [Ninjablocks](http://forums.ninjablocks.com/index.php?p=/discussion/661/today-i-learned-about-mqtt/p1) or [TheThingSystem](http://thethingsystem.com/dev/supported-things.html)
  13. Simply choose a topic (think email subject line) to publish/listen to, and configure your service.
  14. It's easy to setup your own [broker](http://jpmens.net/2013/09/01/installing-mosquitto-on-a-raspberry-pi/) or connect to a [cloud service](http://www.cloudmqtt.com)
  15. Hints:
  16. Many services run mqtts (mqtt over SSL) often with a custom certificate.
  17. You'll want to download their cert and install it locally, specifying the ```certificate_path``` configuration.
  18. Example configuration:
  19. <pre><code>{
  20. 'uri' => 'mqtts://user:pass@localhost:8883'
  21. 'ssl' => :TLSv1,
  22. 'ca_file' => './ca.pem',
  23. 'cert_file' => './client.crt',
  24. 'key_file' => './client.key',
  25. 'topic' => 'huginn'
  26. }
  27. </code></pre>
  28. Subscribe to CloCkWeRX's TheThingSystem instance (thethingsystem.com), where
  29. temperature and other events are being published.
  30. <pre><code>{
  31. 'uri' => 'mqtt://kcqlmkgx:sVNoccqwvXxE@m10.cloudmqtt.com:13858',
  32. 'topic' => 'the_thing_system/demo'
  33. }
  34. </code></pre>
  35. Subscribe to all topics
  36. <pre><code>{
  37. 'uri' => 'mqtt://kcqlmkgx:sVNoccqwvXxE@m10.cloudmqtt.com:13858',
  38. 'topic' => '/#'
  39. }
  40. </code></pre>
  41. Find out more detail on [subscription wildcards](http://www.eclipse.org/paho/files/mqttdoc/Cclient/wildcard.html)
  42. MD
  43. event_description <<~MD
  44. Events are simply nested MQTT payloads. For example, an MQTT payload for Owntracks
  45. {
  46. "topic": "owntracks/kcqlmkgx/Dan",
  47. "message": {"_type": "location", "lat": "-34.8493644", "lon": "138.5218119", "tst": "1401771049", "acc": "50.0", "batt": "31", "desc": "Home", "event": "enter"},
  48. "time": 1401771051
  49. }
  50. MD
  51. def validate_options
  52. unless options['uri'].present? &&
  53. options['topic'].present?
  54. errors.add(:base, "topic and uri are required")
  55. end
  56. end
  57. def working?
  58. (event_created_within?(interpolated['expected_update_period_in_days']) && !recent_error_logs?) || received_event_without_error?
  59. end
  60. def default_options
  61. {
  62. 'uri' => 'mqtts://user:pass@localhost:8883',
  63. 'ssl' => :TLSv1,
  64. 'ca_file' => './ca.pem',
  65. 'cert_file' => './client.crt',
  66. 'key_file' => './client.key',
  67. 'topic' => 'huginn',
  68. 'max_read_time' => '10',
  69. 'expected_update_period_in_days' => '2'
  70. }
  71. end
  72. def mqtt_client
  73. @client ||= MQTT::Client.new(interpolated['uri']).tap { |c|
  74. if interpolated['ssl']
  75. c.ssl = interpolated['ssl'].to_sym
  76. c.ca_file = interpolated['ca_file']
  77. c.cert_file = interpolated['cert_file']
  78. c.key_file = interpolated['key_file']
  79. end
  80. }
  81. end
  82. def receive(incoming_events)
  83. mqtt_client.connect do |c|
  84. incoming_events.each do |event|
  85. c.publish(interpolated(event)['topic'], event.payload['message'])
  86. end
  87. end
  88. end
  89. def check
  90. last_message = memory['last_message']
  91. mqtt_client.connect
  92. poll_thread = Thread.new do
  93. mqtt_client.get_packet(interpolated['topic']) do |packet|
  94. topic, payload = message = [packet.topic, packet.payload]
  95. # Ignore a message if it is previously received
  96. next if (packet.retain || packet.duplicate) && message == last_message
  97. last_message = message
  98. # A lot of services generate JSON, so try that.
  99. begin
  100. payload = JSON.parse(payload)
  101. rescue StandardError
  102. end
  103. create_event payload: {
  104. 'topic' => topic,
  105. 'message' => payload,
  106. 'time' => Time.now.to_i
  107. }
  108. end
  109. end
  110. sleep (interpolated['max_read_time'].presence || 15).to_f
  111. mqtt_client.disconnect
  112. poll_thread.kill
  113. # Remember the last original (non-retain, non-duplicate) message
  114. self.memory['last_message'] = last_message
  115. save!
  116. end
  117. end
  118. end