lib/mqtt/client.rb in mqtt-0.0.9 vs lib/mqtt/client.rb in mqtt-0.1.0

- old
+ new

@@ -218,11 +218,11 @@ :message_id => @message_id.next ) send_packet(packet) end - # Return the next message recieved from the MQTT broker. + # Return the next message received from the MQTT broker. # An optional topic can be given to subscribe to. # # The method either returns the topic and message as an array: # topic,message = client.get # @@ -246,10 +246,38 @@ packet = @read_queue.pop return packet.topic, packet.payload end end + # Return the next packet object received from the MQTT broker. + # An optional topic can be given to subscribe to. + # + # The method either returns a single packet: + # packet = client.get_packet + # puts packet.topic + # + # Or can be used with a block to keep processing messages: + # client.get_packet('test') do |packet| + # # Do stuff here + # puts packet.topic + # end + # + def get_packet(topic=nil) + # Subscribe to a topic, if an argument is given + subscribe(topic) unless topic.nil? + + if block_given? + # Loop forever! + loop do + yield(@read_queue.pop) + end + else + # Wait for one packet to be available + return @read_queue.pop + end + end + # Returns true if the incoming message queue is empty. def queue_empty? @read_queue.empty? end @@ -287,10 +315,10 @@ # FIXME: implement responses for QOS 1 and 2 end end # Time to send a keep-alive ping request? - if Time.now > @last_pingreq + @keep_alive + if @keep_alive > 0 and Time.now > @last_pingreq + @keep_alive ping end # FIXME: check we received a ping response recently?