mqtt_client.rb 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. require 'mqtt'
  2. require 'timeout'
  3. require 'json'
  4. class MqttClient
  5. BreakListenLoopError = Class.new(StandardError)
  6. def initialize(server, username, password, topic_prefix)
  7. @client = MQTT::Client.connect("mqtt://#{username}:#{password}@#{server}")
  8. @topic_prefix = topic_prefix
  9. @listen_threads = []
  10. end
  11. def disconnect
  12. @client.disconnect
  13. end
  14. def reconnect
  15. @client.disconnect
  16. @client.connect
  17. end
  18. def wait_for_message(topic, timeout = 10)
  19. on_message(topic, timeout) { |topic, message| }
  20. wait_for_listeners
  21. end
  22. def id_topic_suffix(params)
  23. if params
  24. "#{sprintf '0x%04X', params[:id]}/#{params[:type]}/#{params[:group_id]}"
  25. else
  26. "+/+/+"
  27. end
  28. end
  29. def on_update(id_params = nil, timeout = 10, &block)
  30. on_id_message('updates', id_params, timeout, &block)
  31. end
  32. def on_state(id_params = nil, timeout = 10, &block)
  33. on_id_message('state', id_params, timeout, &block)
  34. end
  35. def on_id_message(path, id_params, timeout, &block)
  36. topic = "#{@topic_prefix}#{path}/#{id_topic_suffix(id_params)}"
  37. on_message(topic, timeout) do |topic, message|
  38. topic_parts = topic.split('/')
  39. yield(
  40. {
  41. id: topic_parts[2].to_i(16),
  42. type: topic_parts[3],
  43. group_id: topic_parts[4].to_i
  44. },
  45. JSON.parse(message)
  46. )
  47. end
  48. end
  49. def on_message(topic, timeout = 10, &block)
  50. @listen_threads << Thread.new do
  51. begin
  52. Timeout.timeout(timeout) do
  53. @client.get(topic) do |topic, message|
  54. raise BreakListenLoopError if yield(topic, message)
  55. end
  56. end
  57. rescue Timeout::Error => e
  58. puts "Timed out listening for message on: #{topic}"
  59. puts e.backtrace.join("\n")
  60. rescue BreakListenLoopError
  61. end
  62. end
  63. end
  64. def patch_state(id_params, state = {})
  65. @client.publish(
  66. "#{@topic_prefix}commands/#{id_topic_suffix(id_params)}",
  67. state.to_json
  68. )
  69. end
  70. def wait_for_listeners
  71. @listen_threads.each(&:join)
  72. @listen_threads.clear
  73. end
  74. end