8

我正在构建一个小型 ruby​​ 程序来运行与MQTT服务器的连接并订阅频道。我正在使用mosquitto gem,它只是libmosquitto C 库的桥梁。

我创建了一个可以运行的程序的非常简单的实现ruby my_prog.rb

# Dependencies

require File.expand_path(File.join('..', 'environment'), __FILE__)


# MQTT Application

module Pulsr
    class MQTT
        attr_reader :host, :port, :alive

        def initialize(host = 'iot.eclipse.org', port = 1883, alive = 60)
            @client ||=  Mosquitto::Client.new SecureRandom.hex(8)

            Signal.trap(Signal.list.has_key?('INT') ? 'SIGINT' : 'SIGTERM') do
            @client.log 'Shutdown'
            shutdown
            end

            @host = host
            @port = port
            @alive = alive

            start
        end


        private

        def on_connect
            Proc.new { |return_code|
                @client.log "Connected RC #{return_code}"

                @client.subscribe(nil, '/pulsr', Mosquitto::EXACTLY_ONCE)
            }
        end

        def on_disconnect
            Proc.new { |return_code| @client.log "Disconnected RC #{return_code}" }
        end

        def on_subscribe
            Proc.new { |message_id, granted_qos| @client.log "Subscribed MID #{message_id} QoS #{granted_qos}" }
        end

        def on_unsubscribe
            Proc.new { |message_id| @client.log "Unsubscribed MID #{message_id}" }
        end

        def on_message
            Proc.new { |message| Pulsr::Workers::TrackingEvent.perform_async message.to_s }
        end

        def configure
            @client.logger = Logger.new(STDOUT)

            @client.on_connect &on_connect
            @client.on_disconnect &on_disconnect
            @client.on_subscribe &on_subscribe
            @client.on_unsubscribe &on_unsubscribe
            @client.on_message &on_message
        end

        def connect
            @client.connect_async(@host, @port, @alive)
        end

        def start
            @client.loop_start

            configure
            connect

            sleep
        end

        def shutdown
            @client.loop_stop(true)
            Process.exit
        end
    end
end


# MQTT Start

Pulsr::MQTT.new :host => 'iot.eclipse.org', :port => 1883, :alive => 60

我想知道,如果我想使用赛璐珞EventMachine来运行 mosquitto gem 提供的循环,我该怎么做?

mosquitto gem 提供了一个很好的文档并提供了一些可以使用的循环方法,但我不知道从哪里开始或如何做,我也没有使用过 EM 或赛璐珞。

任何人都可以帮助开始这个,我认为它可以为社区带来一些价值,它最终可以成为一个开源项目,是 mosquitto gem 的一个小补充?

4

2 回答 2

1

我认为这并不难。Mosquitto 有一个很好的图书馆。

哟需要连接这些功能:

mosquitto_loop_misc() <-> EventMachine::PeriodicTimer.new
mosquitto_read() <-> EventMachine.watch
mosquitto_write() <-> EventMachine.watch
于 2014-11-19T15:00:34.387 回答
0

em-mqttgem为eventmachine提供了一个 MQTT 协议实现。
这使用纯 rubymqtt​​ 实现来处理消息,而不是libmosquitto.

如果您确实必须使用该libmosquitto实现通过mosquittogem进行解析,那么上述描述将成立。该eventmachine组件将几乎保持原样。对协议特定模块的所有调用MQTT都将替换为libmosquitto. 主要问题看起来是libmosquitto公共 API和后续的Ruby API隐藏了所有这些,隐藏在libmosquitto自己的网络实现中,它被替换eventmachine为你可以开始了。

于 2014-08-26T08:50:32.070 回答