mqtt_agent.rb 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. # encoding: utf-8
  2. require "mqtt"
  3. require "json"
  4. module Agents
  5. class MqttAgent < Agent
  6. description <<-MD
  7. The MQTT agent allows both publication and subscription to an MQTT topic.
  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](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@locahost: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. <pre><code>{
  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. }</code></pre>
  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_options['expected_update_period_in_days']) && !recent_error_logs?
  59. end
  60. def default_options
  61. {
  62. 'uri' => 'mqtts://user:pass@locahost: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_options['uri'])
  74. if interpolated_options['ssl']
  75. @client.ssl = interpolated_options['ssl'].to_sym
  76. @client.ca_file = interpolated_options['ca_file']
  77. @client.cert_file = interpolated_options['cert_file']
  78. @client.key_file = interpolated_options['key_file']
  79. end
  80. @client
  81. end
  82. def receive(incoming_events)
  83. mqtt_client.connect do |c|
  84. incoming_events.each do |event|
  85. c.publish(interpolated_options(event.payload)['topic'], event.payload)
  86. end
  87. c.disconnect
  88. end
  89. end
  90. def check
  91. mqtt_client.connect do |c|
  92. Timeout::timeout((interpolated_options['max_read_time'].presence || 15).to_i) {
  93. c.get(interpolated_options['topic']) do |topic, message|
  94. # A lot of services generate JSON. Try that first
  95. payload = JSON.parse(message) rescue message
  96. create_event :payload => {
  97. 'topic' => topic,
  98. 'message' => payload,
  99. 'time' => Time.now.to_i
  100. }
  101. end
  102. } rescue TimeoutError
  103. c.disconnect
  104. end
  105. end
  106. end
  107. end