Method: MQTT::Client#publish

Defined in:
lib/mqtt/client.rb

#publish(topic, payload = '', retain = false, qos = 0) ⇒ Object

Publish a message on a particular topic to the MQTT server.

Raises:

  • (ArgumentError)

341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/mqtt/client.rb', line 341

def publish(topic, payload='', retain=false, qos=0)
  raise ArgumentError.new("Topic name cannot be nil") if topic.nil?
  raise ArgumentError.new("Topic name cannot be empty") if topic.empty?

  packet = MQTT::Packet::Publish.new(
    :id => next_packet_id,
    :qos => qos,
    :retain => retain,
    :topic => topic,
    :payload => payload
  )

  # Send the packet
  res = send_packet(packet)

  if packet.qos > 0
    Timeout.timeout(@ack_timeout) do
      while connected? do
        @pubacks_semaphore.synchronize do
          return res if @pubacks.delete(packet.id)
        end
        # FIXME: make threads communicate with each other, instead of polling
        # (using a pipe and select ?)
        sleep 0.01
      end
    end
    return -1
  end
end