154 lines
4.9 KiB
Ruby
154 lines
4.9 KiB
Ruby
require "socket"
|
|
require "openssl"
|
|
require "securerandom"
|
|
require "uri"
|
|
|
|
module Maptool
|
|
# A minimal MQTT 3.1.1 subscriber (stdlib only): connects,
|
|
# subscribes to a few topics at QoS 0 and yields every message, for as long
|
|
# as the block keeps running. Enough for reading sensor topics off the home
|
|
# broker; no publishing, no QoS 1/2 delivery guarantees, no persistent
|
|
# session. mqtt:// is plain TCP, mqtts:// is TLS.
|
|
class MqttClient
|
|
class ProtocolError < StandardError; end
|
|
|
|
RECONNECT_DELAY = 5 # seconds
|
|
KEEPALIVE = 30 # seconds, sent in CONNECT; a PINGREQ goes out at half of it
|
|
|
|
def initialize(url:, topics:, username: nil, password: nil, client_id: "maptool-#{SecureRandom.hex(4)}")
|
|
@uri = URI(url)
|
|
raise ArgumentError, "unsupported MQTT URL #{url}" unless %w[mqtt mqtts].include?(@uri.scheme)
|
|
|
|
@topics = topics
|
|
@username = username.to_s.empty? ? nil : username
|
|
@password = password.to_s.empty? ? nil : password
|
|
@client_id = client_id
|
|
end
|
|
|
|
# Never returns under normal operation: reconnects after any I/O or
|
|
# protocol error, so a broker that's down or restarting isn't fatal.
|
|
def each_message(&block)
|
|
loop do
|
|
session(&block)
|
|
rescue SystemCallError, IOError, SocketError, OpenSSL::SSL::SSLError, ProtocolError => e
|
|
warn "[mqtt] #{e.class}: #{e.message} — retrying in #{RECONNECT_DELAY}s"
|
|
sleep RECONNECT_DELAY
|
|
end
|
|
end
|
|
|
|
private
|
|
|
|
def session
|
|
socket = open_socket
|
|
write_packet(socket, 0x10, connect_payload)
|
|
type, _flags, body = read_packet(socket)
|
|
raise ProtocolError, "no CONNACK" unless type == 2
|
|
raise ProtocolError, "connection refused (code #{body.getbyte(1)})" unless body.getbyte(1).zero?
|
|
|
|
write_packet(socket, 0x82, [1].pack("n") + @topics.map { |t| utf8(t) + "\x00".b }.join)
|
|
last_sent = last_received = now
|
|
loop do
|
|
if readable?(socket, 1)
|
|
type, flags, body = read_packet(socket)
|
|
last_received = now
|
|
yield(*parse_publish(socket, flags, body)) if type == 3
|
|
end
|
|
if now - last_sent >= KEEPALIVE / 2
|
|
write_packet(socket, 0xC0, "".b)
|
|
last_sent = now
|
|
end
|
|
raise ProtocolError, "broker silent for #{KEEPALIVE * 2}s" if now - last_received > KEEPALIVE * 2
|
|
end
|
|
ensure
|
|
socket&.close
|
|
end
|
|
|
|
def open_socket
|
|
tls = @uri.scheme == "mqtts"
|
|
tcp = Socket.tcp(@uri.host, @uri.port || (tls ? 8883 : 1883), connect_timeout: 10)
|
|
return tcp unless tls
|
|
|
|
context = OpenSSL::SSL::SSLContext.new
|
|
context.set_params(verify_mode: OpenSSL::SSL::VERIFY_PEER)
|
|
ssl = OpenSSL::SSL::SSLSocket.new(tcp, context)
|
|
ssl.hostname = @uri.host
|
|
ssl.sync_close = true
|
|
ssl.connect
|
|
ssl
|
|
end
|
|
|
|
def connect_payload
|
|
flags = 0x02 # clean session
|
|
flags |= 0x80 if @username
|
|
flags |= 0x40 if @password
|
|
utf8("MQTT") + [4, flags, KEEPALIVE].pack("CCn") + utf8(@client_id) +
|
|
(@username ? utf8(@username) : "".b) + (@password ? utf8(@password) : "".b)
|
|
end
|
|
|
|
# [topic, payload]; a QoS 1 message (the broker may downgrade to our 0,
|
|
# but don't count on it) is acknowledged so it isn't redelivered.
|
|
def parse_publish(socket, flags, body)
|
|
qos = (flags >> 1) & 0x03
|
|
length = body.unpack1("n")
|
|
topic = body.byteslice(2, length).force_encoding("UTF-8")
|
|
offset = 2 + length
|
|
if qos.positive?
|
|
packet_id = body.byteslice(offset, 2)
|
|
write_packet(socket, 0x40, packet_id) if qos == 1
|
|
offset += 2
|
|
end
|
|
[topic, body.byteslice(offset..).force_encoding("UTF-8")]
|
|
end
|
|
|
|
def write_packet(socket, header, body)
|
|
socket.write([header].pack("C") + encode_length(body.bytesize) + body)
|
|
end
|
|
|
|
def read_packet(socket)
|
|
header = read_exactly(socket, 1).ord
|
|
length = 0
|
|
multiplier = 1
|
|
loop do
|
|
byte = read_exactly(socket, 1).ord
|
|
length += (byte & 0x7F) * multiplier
|
|
break if byte < 0x80
|
|
|
|
multiplier *= 128
|
|
raise ProtocolError, "bad remaining length" if multiplier > 128**3
|
|
end
|
|
[header >> 4, header & 0x0F, length.zero? ? "".b : read_exactly(socket, length)]
|
|
end
|
|
|
|
def read_exactly(socket, count)
|
|
data = socket.read(count)
|
|
raise EOFError, "connection closed" if data.nil? || data.bytesize < count
|
|
|
|
data
|
|
end
|
|
|
|
def encode_length(length)
|
|
bytes = []
|
|
loop do
|
|
byte = length % 128
|
|
length /= 128
|
|
bytes << (length.positive? ? byte | 0x80 : byte)
|
|
break unless length.positive?
|
|
end
|
|
bytes.pack("C*")
|
|
end
|
|
|
|
def utf8(string)
|
|
[string.bytesize].pack("n") + string.b
|
|
end
|
|
|
|
# An SSLSocket may hold already-decrypted bytes IO.select can't see.
|
|
def readable?(socket, timeout)
|
|
(socket.respond_to?(:pending) && socket.pending.positive?) || IO.select([socket], nil, nil, timeout)
|
|
end
|
|
|
|
def now
|
|
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
end
|
|
end
|
|
end
|