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)


317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'lib/mqtt/client.rb', line 317

def publish(topic, payload = '', retain = false, qos = 0)
  raise ArgumentError, 'Topic name cannot be nil' if topic.nil?
  raise ArgumentError, '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)

  return if qos.zero?

  queue = Queue.new

  wait_for_puback packet.id, queue

  deadline = current_time + @ack_timeout

  loop do
    response = queue.pop
    case response
    when :read_timeout
      return -1 if current_time > deadline
    when :close
      return -1
    else
      @pubacks_semaphore.synchronize do
        @pubacks.delete packet.id
      end
      break
    end
  end

  res
end