xively / mosquitto

Ruby binding against libmosquitto (http://mosquitto.org/) - a high performance MQTT protocol (http://mqtt.org) client
Other
58 stars 15 forks source link

threaded main loop not running for this client #12

Open rolandjitsu opened 10 years ago

rolandjitsu commented 10 years ago

I keep getting the following message whenever I am trying to loop_stop(true):

`loop_stop': Threaded main loop not running for this client. Are you sure you haven't already called Mosquitto::Client#loop_stop ? (Mosquitto::Error)

I'm running the following program:

# Dependencies

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

# MQTT Application

module Pulsr
    class MQTT
        attr_accessor :client_id
        attr_reader :host, :port, :alive, :qos

        def initialize(options = Hash.new)

            @client ||= Mosquitto::Client.new(SecureRandom.uuid.upcase!)

            @client_id ||= options[:client_id]
            @host = options[:host] || 'iot.eclipse.org'
            @port = options[:port] || 1883
            @alive = options[:alive] || 60
            @qos = options[:qos] || Mosquitto::EXACTLY_ONCE

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

            start
        end

        private

        def on_connect
            Proc.new { |_| @client.subscribe(nil, "/pulsr/#{@client_id || '+'}", @qos) }
        end

        def on_message
            Proc.new { |message| Pulsr::Workers::TrackingEvent.perform_async(message.topic.gsub!(/.*\//, ''), message.to_s) }
        end

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

            @client.on_connect &on_connect
            @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

# example for starting a new client for each app as a forked process

signal = Signal.list.has_key?('INT') ? 'SIGINT' : 'SIGTERM'

pid = Process.fork do
    Pulsr::MQTT.new :client_id => '31C493CF-2B78-43FC-A2F3-D4FF87965BA5'
end

Signal.trap signal do
    $stdout.puts "Kill: ##{pid}"
    Process.kill signal, pid
end

Process.waitpid pid

Is it because I use fork and somehow it fails getting the thread for the right process?

methodmissing commented 10 years ago

Thanks for flagging and the detailed report - I'll take a look ...