Class: MqttSN

Inherits:
Object
  • Object
show all
Defined in:
lib/mqtt-sn-ruby.rb

Constant Summary collapse

Nretry =

Max retry

3
Tretry =

Timeout before retry

3
MAX_IDLE =

Forwarder will disconnect parties after this idle time

60*3
SEARCHGW_TYPE =
0x01
GWINFO_TYPE =
0x02
0x03
CONNECT_TYPE =
0x04
CONNACK_TYPE =
0x05
WILLTOPICREQ_TYPE =
0x06
WILLTOPIC_TYPE =
0x07
WILLMSGREQ_TYPE =
0x08
WILLMSG_TYPE =
0x09
REGISTER_TYPE =
0x0A
REGACK_TYPE =
0x0B
PUBLISH_TYPE =
0x0C
PUBACK_TYPE =
0x0D
PUBCOMP_TYPE =
0x0E
PUBREC_TYPE =
0x0F
PUBREL_TYPE =
0x10
SUBSCRIBE_TYPE =
0x12
SUBACK_TYPE =
0x13
UNSUBSCRIBE_TYPE =
0x14
UNSUBACK_TYPE =
0x15
PINGREQ_TYPE =
0x16
PINGRESP_TYPE =
0x17
DISCONNECT_TYPE =
0x18
WILLTOPICUPD_TYPE =
0x1A
WILLTOPICRESP_TYPE =
0x1B
WILLMSGUPD_TYPE =
0x1C
WILLMSGRESP_TYPE =
0x1D
RETAIN_FLAG =
0x10
WILL_FLAG =
0x08
CLEAN_FLAG =
0x04
QOSM1_FLAG =
0x60
QOS2_FLAG =
0x40
QOS1_FLAG =
0x20
QOS0_FLAG =
0x00
TOPIC_PREDEFINED_FLAG =
0x01
TOPIC_SHORT_FLAG =
0x02

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ MqttSN

Returns a new instance of MqttSN.



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/mqtt-sn-ruby.rb', line 171

def initialize(hash={})
    @options=hash #save these
    @server_uri=hash[:server_uri]
    @debug=hash[:debug]
    @verbose=hash[:verbose]
    @state=:disconnected
    @bcast_port=5000
    @keepalive=(hash[:keepalive]||25).to_i
    @forwarder=hash[:forwarder] #flag to indicate forward mode
    @will_topic=nil
    @will_msg=nil
    @active_gw_id=nil
    @http_log=[]
    @local_ifs=Socket.getifaddrs.map { |i| i.addr.ip_address if i.addr.ipv4? }.compact


    @sem=Mutex.new
    @gsem=Mutex.new
    @log_q = Queue.new #log queue :)
    @msg_id=1
    @clients={}
    @gateways={}
    @autodiscovery=false
    @broadcast_uri=hash[:broadcast_uri]

    if @server_uri
      note "Using Default Gateway: #{@server_uri}"
      add_gateway(0,{uri: @server_uri,source: "default"})
      pick_new_gateway
    elsif @broadcast_uri
      note "Autodiscovery Active, using #{@broadcast_uri}"
      @autodiscovery=true
    else
      puts "No autodiscovery and no Default Gateway -- cannot proceed"
      exit -1
    end


    @log_t=Thread.new do
      log_thread
    end

    @topics={} #hash of registered topics is stored here
    @iq = Queue.new
    @dataq = Queue.new

    if @broadcast_uri
      @bcast_s=open_multicast_send_port
      @bcast=open_multicast_recv_port

      @roam_t=Thread.new do
        roam_thread @bcast
      end
    end
    if @forwarder
      @s,@server,@port = MqttSN::open_port @server_uri
      @local_port=hash[:local_port]||1882
      note "Open port to Gateway: #{@server_uri}: #{@server},#{@port} -- Listening local port: #{@local_port} @ IPs: #{@local_ifs}"
      @s.bind("0.0.0.0",@local_port)
      @bcast_period=60
    else
      client_thread
    end
end

Instance Attribute Details

#active_gw_idObject

Returns the value of attribute active_gw_id.



155
156
157
# File 'lib/mqtt-sn-ruby.rb', line 155

def active_gw_id
  @active_gw_id
end

#clientsObject

Returns the value of attribute clients.



151
152
153
# File 'lib/mqtt-sn-ruby.rb', line 151

def clients
  @clients
end

#gatewaysObject

Returns the value of attribute gateways.



152
153
154
# File 'lib/mqtt-sn-ruby.rb', line 152

def gateways
  @gateways
end

#http_logObject

Returns the value of attribute http_log.



156
157
158
# File 'lib/mqtt-sn-ruby.rb', line 156

def http_log
  @http_log
end

#optionsObject

Returns the value of attribute options.



154
155
156
# File 'lib/mqtt-sn-ruby.rb', line 154

def options
  @options
end

#stateObject

Returns the value of attribute state.



153
154
155
# File 'lib/mqtt-sn-ruby.rb', line 153

def state
  @state
end

Class Method Details

.build_packet(m) ⇒ Object



358
359
360
361
362
363
364
365
366
367
# File 'lib/mqtt-sn-ruby.rb', line 358

def self.build_packet m
  msg=" "
  len=1
  m.each_with_index do |b,i|
    msg[i+1]=b.chr
    len+=1
  end
  msg[0]=len.chr
  msg
end

.hexdump(data) ⇒ Object



349
350
351
352
353
354
355
356
# File 'lib/mqtt-sn-ruby.rb', line 349

def self.hexdump data
  raw=""
  data.each_byte do |b|
    raw=raw+"," if raw!=""
    raw=raw+sprintf("%02X",b)
  end
  raw
end

.open_port(uri_s) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/mqtt-sn-ruby.rb', line 113

def self.open_port uri_s
  begin
    uri = URI.parse(uri_s)
   if uri.scheme== 'udp'
      return [UDPSocket.new,uri.host,uri.port]
    else
      raise "Error: Cannot open socket for '#{uri_s}', unsupported scheme: '#{uri.scheme}'"
    end
  rescue => e
      pp e.backtrace
      raise "Error: Cannot open socket for '#{uri_s}': #{e}"
  end
end

.parse_message(r) ⇒ Object



799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
# File 'lib/mqtt-sn-ruby.rb', line 799

def self.parse_message r
  m=nil
  if not r[0]
    puts "Malformed empty packet #{r}"
    return {}
  end
  len=r[0].ord
  if len!= r.size
    puts "Malformed packet #{r}"
    return {}
  end
  case r[len-1].ord
  when 0x00
    status=:ok
  when 0x01
    status=:rejected_congestion
  when 0x02
    status=:rejected_invalid_topic_id
  when 0x03
    status=:rejected_not_supported
  else
    status=:unknown_error
  end
  type_byte=r[1].ord
  done=false

  case type_byte
  when CONNECT_TYPE
    duration=(r[4].ord<<8)+r[5].ord
    id=r[6,len-6]
    m={type: :connect, flags: r[2].ord, duration: duration, client_id: id, status: :ok}
  when CONNACK_TYPE
    m={type: :connect_ack,status: status}
  when SUBACK_TYPE
    topic_id=(r[3].ord<<8)+r[4].ord
    msg_id=(r[5].ord<<8)+r[6].ord
    m={type: :sub_ack, topic_id: topic_id, msg_id: msg_id, status: status}
  when SUBSCRIBE_TYPE
    msg_id=(r[3].ord<<8)+r[4].ord
    topic=r[5,len-5]
    m={type: :subscribe, flags: r[2].ord, topic: topic, msg_id: msg_id, status: :ok}
  when UNSUBACK_TYPE
    msg_id=(r[2].ord<<8)+r[3].ord
    m={type: :unsub_ack, msg_id: msg_id, status: :ok}
  when PUBLISH_TYPE
    topic_id=(r[3].ord<<8)+r[4].ord
    msg_id=(r[5].ord<<8)+r[6].ord
    msg=r[7,len-7].force_encoding("UTF-8")
    flags=r[2].ord
    topic_type=:long
    topic=""
    if flags&0x03==TOPIC_SHORT_FLAG
      topic_type=:short
      topic=r[3].chr+r[4].chr
    elsif flags&0x03==TOPIC_PREDEFINED_FLAG
      topic_type=:predefined
      topic=""
    end
    qos=(flags>>5)&0x03
    qos=-1 if qos==3
    m={type: :publish, qos: qos, topic_id: topic_id, topic_type:topic_type, topic: topic, msg_id: msg_id, msg: msg,flags: flags, status: :ok}
    m[:retain]=true if flags & RETAIN_FLAG == RETAIN_FLAG
  when PUBREL_TYPE
    msg_id=(r[2].ord<<8)+r[3].ord
    m={type: :pub_rel, msg_id: msg_id, status: :ok}
  when DISCONNECT_TYPE
    m={type: :disconnect,status: :ok}
  when REGISTER_TYPE
    topic_id=(r[2].ord<<8)+r[3].ord
    msg_id=(r[4].ord<<8)+r[5].ord
    topic=r[6,len-6]
    m={type: :register, topic_id: topic_id, msg_id: msg_id, topic: topic,status: :ok}
  when REGACK_TYPE
    topic_id=(r[2].ord<<8)+r[3].ord
    m={type: :register_ack,topic_id: topic_id,status: status}
  when PUBREC_TYPE
    msg_id=(r[2].ord<<8)+r[3].ord
    m={type: :pubrec,msg_id: msg_id,status: :ok}
  when PUBACK_TYPE
    topic_id=(r[2].ord<<8)+r[3].ord
    msg_id=(r[4].ord<<8)+r[5].ord
    m={type: :publish_ack,topic_id: topic_id,msg_id: msg_id, status: status}
  when PUBCOMP_TYPE
    msg_id=(r[2].ord<<8)+r[3].ord
    m={type: :pubcomp,status: :ok, msg_id: msg_id}

  when WILLTOPICREQ_TYPE
    m={type: :will_topic_req, status: :ok}
  when WILLMSGREQ_TYPE
    m={type: :will_msg_req, status: :ok}

  when WILLTOPICRESP_TYPE
    m={type: :will_topic_resp, status: :ok}
  when WILLMSGRESP_TYPE
    m={type: :will_msg_resp, status: :ok}

  when SEARCHGW_TYPE
    m={type: :searchgw, radius: r[2].ord, status: :ok}
  when GWINFO_TYPE
    m={type: :gwinfo, gw_id: r[2].ord, status: :ok}
  when ADVERTISE_TYPE
    duration=(r[3].ord<<8)+r[4].ord
    m={type: :advertise, gw_id: r[2].ord, duration: duration, status: :ok}

  when PINGREQ_TYPE
    m={type: :ping, status: :ok}
  when PINGRESP_TYPE
    m={type: :pong, status: :ok}

  else
    m={type: :unknown, type_byte: type_byte }
  end
  m
end

.poll_packet(socket) ⇒ Object



627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
# File 'lib/mqtt-sn-ruby.rb', line 627

def self.poll_packet socket
  #decide how to get data -- UDP-socket or FM-radio
  begin
    r,stuff=socket.recvfrom_nonblock(200) #get_packet --high level func!
    client_ip=stuff[2]
    client_port=stuff[1]
    return [r,client_ip,client_port]
  rescue IO::WaitReadable
    sleep 0.1
  rescue => e
    puts "Error: receive thread died: #{e}"
    pp e.backtrace
  end
  return nil
end

.poll_packet_block(socket) ⇒ Object



643
644
645
646
647
648
649
# File 'lib/mqtt-sn-ruby.rb', line 643

def self.poll_packet_block socket
  #decide how to get data -- UDP-socket or FM-radio
  r,stuff=socket.recvfrom(200) #get_packet --high level func!
  client_ip=stuff[2]
  client_port=stuff[1]
  return [r,client_ip,client_port]
end

.send_raw_packet(msg, socket, server, port) ⇒ Object



558
559
560
561
562
563
564
565
# File 'lib/mqtt-sn-ruby.rb', line 558

def self.send_raw_packet msg,socket,server,port
  if socket
    socket.send(msg, 0, server, port)
    MqttSN::hexdump msg
  else
    puts "Error: no socket at send_raw_packet"
  end
end

Instance Method Details

#add_gateway(gw_id, hash) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/mqtt-sn-ruby.rb', line 158

def add_gateway gw_id,hash
  if not @gateways[gw_id]
     @gateways[gw_id]={stamp: Time.now.to_i, status: :ok, last_use: 0,last_ping: 0,counter_send:0, last_send: 0,counter_recv:0, last_recv: 0}.merge(hash)
  else
    if @gateways[gw_id][:uri]!=hash[:uri]
      note "conflict -- gateway has moved? or duplicate"
    else
      @gateways[gw_id][:stamp]=Time.now.to_i
      @gateways[gw_id]=@gateways[gw_id].merge hash
    end
  end
end

#client_threadObject



967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
# File 'lib/mqtt-sn-ruby.rb', line 967

def client_thread
  Thread.new do #ping thread
    while true do
      begin
        while @state==:disconnected
          sleep 1
        end
        sleep @keepalive
        if @active_gw_id and @gateways[@active_gw_id] and @gateways[@active_gw_id][:socket] #if we are connected...
          send :ping, timeout: 5,expect: :pong do |status,message|
            if status!=:ok
              note "Error:#{@id} no pong! -- sending disconnect to app"
              @state=:disconnected
              gateway_close :timeout
            end
          end
        end
      rescue => e
        puts "Error: receive thread died: #{e}"
        pp e.backtrace
      end
    end
  end

  Thread.new do #work thread
    while true do
      begin
        do_sleep=true
          if @active_gw_id and @gateways[@active_gw_id] and @gateways[@active_gw_id][:socket] #if we are connected...
            if pac=MqttSN::poll_packet(@gateways[@active_gw_id][:socket]) #cannot block -- gateway may change...
              r,client_ip,client_port=pac
              m=MqttSN::parse_message r
              if @debug and m
                m[:debug]=MqttSN::hexdump r
              end
              _,port,_,_= @gateways[@active_gw_id][:socket].addr
              src="udp://0.0.0.0:#{port}"
              logger "id %-24.24s -> %-24.24s | %s",@gateways[@active_gw_id][:uri],src,m.to_json
              process_message m
              do_sleep=false
              @gateways[@active_gw_id][:last_recv]=Time.now.to_i
              @gateways[@active_gw_id][:counter_recv]+=1
            end
          end
        if do_sleep
          sleep 0.01
        end
      rescue => e
        puts "Error: receive thread died: #{e}"
        pp e.backtrace
      end
    end
  end
end

#connect(id, &block) ⇒ Object



676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
# File 'lib/mqtt-sn-ruby.rb', line 676

def connect id,&block
  send :connect,id: id, clean: false, duration: @keepalive, expect: [:connect_ack,:will_topic_req] do |s,m| #add will here!
    if s==:ok
      if m[:type]==:will_topic_req
        send :will_topic, topic: @will_topic, expect: [:will_msg_req] do |s,m| #add will here!
          if s==:ok
            send :will_msg, msg: @will_msg, expect: [:connect_ack] do |s,m|
            end
          end
        end
      elsif m[:type]==:connect_ack
        block.call :ok,m if block
      end
    else
      block.call :fail,m if block
    end
  end
end

#disconnectObject



695
696
697
698
# File 'lib/mqtt-sn-ruby.rb', line 695

def disconnect
  send :disconnect, expect: :disconnect do |status,message|
  end
end

#forwarder_threadObject



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/mqtt-sn-ruby.rb', line 236

def forwarder_thread
  if not @forwarder
    raise "Cannot Forward if no Forwarder!"
  end
  begin
    last_kill=0
    stime=Time.now.to_i
    Thread.new do #maintenance
      while true do
        sleep 1
        now=Time.now.to_i
        changes=false
        @clients.dup.each do |key,data|
          if data[:state]==:disconnected
            dest="#{data[:ip]}:#{data[:port]}"
            note "- %s",dest
            @clients.delete key
            changes=true
          elsif data[:last_send]<now-MAX_IDLE and data[:last_recv]<now-MAX_IDLE
            dest="#{data[:ip]}:#{data[:port]}"
            note "-- %s",dest
            kill_client key
            @clients.delete key
            changes=true
          end
        end
        if changes
           note "cli:#{@clients.to_json}"
        end
      end
    end
    while true
      pac=MqttSN::poll_packet_block(@s) #data from clients to our service sovket
      r,client_ip,client_port=pac
      key="#{client_ip}:#{client_port}"
      if not @clients[key]
        uri="udp://#{client_ip}:#{client_port}"
        @clients[key]={ip:client_ip, port:client_port, socket: UDPSocket.new, uri: uri, state: :active, counter_send:0, last_send:0 , counter_recv:0, last_recv:0}
        c=@clients[key]
        puts "thread start for #{key}"

        @clients[key][:thread]=Thread.new(key) do |my_key|
          while true
            pacc=MqttSN::poll_packet_block(@clients[my_key][:socket]) #if we get data from server destined to our client
            rr,client_ip,client_port=pacc
            @s.send(rr, 0, @clients[my_key][:ip], @clients[my_key][:port]) # send_packet to client
            mm=MqttSN::parse_message rr
            _,port,_,_ = @clients[my_key][:socket].addr
            dest="#{@server}:#{port}"
            logger "sc %-24.24s <- %-24.24s | %s",@clients[my_key][:uri],@gateways[@active_gw_id][:uri],mm.to_json
            @gateways[@active_gw_id][:last_recv]=Time.now.to_i
            @gateways[@active_gw_id][:counter_recv]+=1
            @clients[my_key][:last_send]=Time.now.to_i
            @clients[my_key][:counter_send]+=1

            case mm[:type]
            when :disconnect
              @clients[my_key][:state]=:disconnected
            end
          end
        end
        dest="#{client_ip}:#{client_port}"
        note "+ %s\n",dest
        note "cli: #{@clients.to_json}"
      end
      @clients[key][:stamp]=Time.now.to_i
      m=MqttSN::parse_message r
      case m[:type]
      when :publish
        if m[:qos]==-1
          @clients[key][:state]=:disconnected #one shot
        end
      end
      sbytes=@clients[key][:socket].send(r, 0, @server, @port) # to rsmb -- ok as is
      _,port,_,_ = @clients[key][:socket].addr
      dest="#{@server}:#{port}"
      @gateways[@active_gw_id][:last_send]=Time.now.to_i
      @gateways[@active_gw_id][:counter_send]+=1
      @clients[key][:last_recv]=Time.now.to_i
      @clients[key][:counter_recv]+=1
      begin
        if @active_gw_id
          logger "cs %-24.24s -> %-24.24s | %s", @clients[key][:uri],@gateways[@active_gw_id][:uri],m.to_json
        else
          logger "cs %-24.24s -> %-24.24s | %s", @clients[key][:uri],"??",m.to_json
        end
      rescue Exception =>e
        puts "logging fails #{e}"
      end
     end
  end
end

#gateway_close(cause) ⇒ Object



1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
# File 'lib/mqtt-sn-ruby.rb', line 1039

def gateway_close cause
  @gsem.synchronize do #one command at a time --

    if @active_gw_id # if using one, mark it used, so it will be last reused
      note "Closing gw #{@active_gw_id} cause: #{cause}"
      @gateways[@active_gw_id][:last_use]=Time.now.to_i
      if @gateways[@active_gw_id][:socket]
        @gateways[@active_gw_id][:socket].close
        @gateways[@active_gw_id][:socket]=nil
      end
      @active_gw_id=nil
    end
  end
end

#goto_sleep(duration) ⇒ Object



700
701
702
703
# File 'lib/mqtt-sn-ruby.rb', line 700

def goto_sleep duration
  send :disconnect, duration: duration, expect: :disconnect do |status,message|
  end
end

#kill_client(key) ⇒ Object



329
330
331
332
333
334
335
336
# File 'lib/mqtt-sn-ruby.rb', line 329

def kill_client key
  puts "Killing Client #{key}:"
  if c=@clients[key]
    puts "Really Killing #{key}"
    send_packet [DISCONNECT_TYPE],@s,c[:ip], c[:port]
    send_packet [DISCONNECT_TYPE],c[:socket], @server,@port
  end
end

#kill_clientsObject



338
339
340
341
342
343
344
345
346
# File 'lib/mqtt-sn-ruby.rb', line 338

def kill_clients
  puts "Killing Clients:"
  @clients.each do |key,c|
    puts "Killing #{key}"
    send_packet [DISCONNECT_TYPE],@s,c[:ip], c[:port]
    send_packet [DISCONNECT_TYPE],c[:socket], @server,@port
  end
  puts "Killing Clients Done."
end

#log_empty?Boolean

Returns:

  • (Boolean)


87
88
89
# File 'lib/mqtt-sn-ruby.rb', line 87

def log_empty?
  @log_q.empty? or not @verbose
end

#log_flushObject



91
92
93
94
95
# File 'lib/mqtt-sn-ruby.rb', line 91

def log_flush
  while not log_empty?
    sleep 0.1
  end
end

#log_threadObject



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/mqtt-sn-ruby.rb', line 97

def log_thread
  while true do
    begin
      if not @log_q.empty?
        l=@log_q.pop
        puts l
      else
        sleep 0.01
      end
    rescue => e
      puts "Error: receive thread died: #{e}"
      pp e.backtrace
    end
  end
end

#logger(str, *args) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/mqtt-sn-ruby.rb', line 58

def logger str,*args
  s=sprintf(str,*args)
  if not @forwarder
    text=sprintf("%s: (%3.3s) | %s",Time.now.iso8601,@active_gw_id,s)
  else
    text=sprintf("%s: [%3.3s] | %s",Time.now.iso8601,@options[:gw_id],s)
  end
  if @verbose or @debug
    @log_q << text
  end
  if @options[:http_port] and @http_log
    @http_log << {stamp: Time.now.to_i, text: text}
  end
end

#note(str, *args) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/mqtt-sn-ruby.rb', line 73

def note str,*args
  begin
    s=sprintf(str,*args)
    text=sprintf("%s: %s",Time.now.iso8601,s)
    @log_q << text
    if @options[:http_port] and @http_log
      @http_log << {stamp: Time.now.to_i, text: text}
    end
  rescue => e
    pp e.backtrace
    puts "note dies: #{e} '#{str}'"
  end
end

#open_multicast_recv_portObject



136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/mqtt-sn-ruby.rb', line 136

def open_multicast_recv_port
  uri = URI.parse(@broadcast_uri)
  ip =  IPAddr.new(uri.host).hton + IPAddr.new("0.0.0.0").hton
  s = UDPSocket.new
  s.setsockopt(Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, ip)
  begin
    s.setsockopt(:SOL_SOCKET, :SO_REUSEPORT, 1)
  rescue #on raspian this is needed...
    puts "WARNING: :SO_REUSEPORT not defined -- guessing it is 15 ;)"
    s.setsockopt(:SOL_SOCKET, 15, 1)
  end
  s.bind(Socket::INADDR_ANY, uri.port)
  s
end

#open_multicast_send_portObject



127
128
129
130
131
132
133
134
# File 'lib/mqtt-sn-ruby.rb', line 127

def open_multicast_send_port
  uri = URI.parse(@broadcast_uri)

  ip =  IPAddr.new(uri.host).hton + IPAddr.new("0.0.0.0").hton
  socket_b = UDPSocket.new
  socket_b.setsockopt(Socket::IPPROTO_IP, Socket::IP_TTL, [1].pack('i'))
  socket_b
end

#pick_new_gatewayObject



1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
# File 'lib/mqtt-sn-ruby.rb', line 1054

def pick_new_gateway
  begin
    gateway_close nil
    @gsem.synchronize do #one command at a time --
      pick=nil
      pick_t=0
      @gateways.each do |gw_id,data|
        if data[:uri] and data[:status]==:ok
          if not pick or data[:last_use]==0  or pick_t>data[:last_use]
            pick=gw_id
            pick_t=data[:last_use]
          end
        end
      end
      if pick
        @active_gw_id=pick
        note "Opening Gateway #{@active_gw_id}: #{@gateways[@active_gw_id][:uri]}"
        @s,@server,@port = MqttSN::open_port @gateways[@active_gw_id][:uri]
        @gateways[@active_gw_id][:socket]=@s
        @gateways[@active_gw_id][:last_use]=Time.now.to_i
      else
        #note "Error: no usable gw found !!"
      end
    end
  rescue => e
    puts "Error: receive thread died: #{e}"
    pp e.backtrace
  end
  return @active_gw_id
end

#pingObject



743
744
745
746
747
748
749
750
# File 'lib/mqtt-sn-ruby.rb', line 743

def ping
  send :ping, timeout: 2,expect: :pong do |status,message|
    if status==:ok
    else
      puts "Error:#{@id} no pong!"
    end
  end
end

#process_broadcast_message(m, client_ip, client_port) ⇒ Object



1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
# File 'lib/mqtt-sn-ruby.rb', line 1022

def process_broadcast_message m,client_ip,client_port
  case m[:type]
  when :searchgw
    if @forwarder
      _,port,_,_=@bcast.addr
      #logger "ib %-24.24s -> %-24.24s | %s","udp://0.0.0.0:#{port}",@broadcast_uri,m.to_json
      send_packet_bcast [GWINFO_TYPE,@options[:gw_id]]
    end
  when :advertise,:gwinfo
    gw_id=m[:gw_id]
    duration=m[:duration]||180
    uri="udp://#{client_ip}:1882"
    add_gateway(gw_id,{uri: uri, source: m[:type], duration:duration,stamp: Time.now.to_i})
  end
end

#process_message(m) ⇒ Object



914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
# File 'lib/mqtt-sn-ruby.rb', line 914

def process_message m
  done=false
  case m[:type]
  when :register
    @topics[m[:topic]]=m[:topic_id]
    if not @transfer
      send :register_ack,topic_id: m[:topic_id], msg_id: m[:msg_id], return_code: 0
      done=true
    end
  when :disconnect
    @state=:disconnected if not @transfer
  when :pub_rel
    if not @transfer
      send :pub_comp, msg_id: m[:msg_id]
      done=true
    end
  when :publish
    if m[:topic_type]==:long
      m[:topic]=@topics.key(m[:topic_id])
    end
    if not @transfer
      @dataq<<m
      if m[:qos]==1
        send :publish_ack,topic_id: m[:topic_id], msg_id: m[:msg_id], return_code: 0
      elsif m[:qos]==2
        send :pub_rec, msg_id: m[:msg_id]
      end
      done=true
    end
  when :connect_ack
    @state=:connected
  when :sub_ack
    @state=:subscribed
  when :pong
    @gsem.synchronize do #one command at a time --
      if @active_gw_id and @gateways[@active_gw_id]
        @gateways[@active_gw_id][:last_ping]=Time.now.to_i
      end
    end
  when :searchgw
    done=true
  when :advertise
    done=true
  when :gwinfo
    done=true
  end
 # puts "got :#{@id} #{m.to_json}"  if @verbose
  if not done
    @iq<<m if m
  end
  m
end

#pub(options = {}) ⇒ Object

toplevel funcs:



1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
# File 'lib/mqtt-sn-ruby.rb', line 1139

def pub options={}
  sent=false
  if options[:qos]==-1
    publish options[:topic]||"XX", options[:msg]||"test_value", qos: options[:qos]
    puts "Sent."
  else
    while not sent
      connect options[:id] do |s,m|
        if s==:ok
          publish options[:topic]||"test/message/123", options[:msg]||"test_value", qos: options[:qos]
          puts "Sent ok."
          sent=true
        else
          disconnect
        end
      end
    end
  end
  log_flush
end

#publish(topic, msg, hash = {}) ⇒ Object



764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
# File 'lib/mqtt-sn-ruby.rb', line 764

def publish topic,msg,hash={}
  if topic[0]=="="
    topic[0]=""
    topic_id=topic.to_i
    topic_type=:predefined
  elsif topic.size==2
    topic_id=((topic[0].ord&0xff)<<8)+(topic[1].ord&0xff)
    topic_type=:short
  else
    topic_type=:long
    if not @topics[topic]
      register_topic topic
    end
    topic_id=@topics[topic]
  end
  case hash[:qos]
  when 1
    send :publish,msg: msg, retain: hash[:retain], topic_id: topic_id, topic_type: topic_type, qos: 1, expect: [:publish_ack] do |s,m|
      if s==:ok
      end
    end
  when 2
    send :publish,msg: msg, retain: hash[:retain], topic_id: topic_id, topic_type: topic_type, qos: 2, expect: [:pubrec] do |s,m|
      if s==:ok
        if m[:type]==:pubrec
          send :pubrel,msg_id: m[:msg_id], expect: :pubcomp do |s,m|
          end
        end
      end
    end
  else
    send :publish,msg: msg, retain: hash[:retain],topic_id: topic_id, topic_type: topic_type, qos: hash[:qos]||0
  end
end

#register_topic(topic) ⇒ Object



752
753
754
755
756
757
758
759
760
761
762
# File 'lib/mqtt-sn-ruby.rb', line 752

def register_topic topic
  send :register,topic: topic, expect: :register_ack do |s,m|
    if s==:ok
      @topics[topic]=m[:topic_id]
    else
      raise "Error:#{@id} Register topic #{topic} failed!"
    end
    #pp @topics
  end
  @topics[topic]
end

#roam_thread(socket) ⇒ Object



1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
# File 'lib/mqtt-sn-ruby.rb', line 1085

def roam_thread socket
  @last_bcast=0
  if @forwarder
    Thread.new do
      while true do
        send_packet_bcast [ADVERTISE_TYPE,@options[:gw_id],@bcast_period>>8,@bcast_period&0xff]
        sleep @bcast_period
      end
    end
  elsif @autodiscovery  #client should try to find some gateways..
    Thread.new do
      while true do
        send :searchgw #replies may or may not come -- even multiple!
        if @gateways=={}
          sleep 5
        else
          #pp @gateways
          sleep 30
        end
      end
    end
    Thread.new do
      while true do
        if @active_gw_id and @gateways[@active_gw_id] and @gateways[@active_gw_id][:socket]
        else # not so ok -- pick one!
          #pick_new_gateway
        end
        sleep 0.01
      end
    end
  end
  while true do
    begin
      if @bcast
       pac=MqttSN::poll_packet_block(socket)
        r,client_ip,client_port=pac
        m=MqttSN::parse_message r
        if @debug and m
          m[:debug]=MqttSN::hexdump r
        end
        _,port,_,_ = @bcast.addr
        src="udp://#{client_ip}:#{client_port}"
        logger "ib %-24.24s <- %-24.24s | %s",@broadcast_uri,src,m.to_json
        process_broadcast_message m,client_ip,client_port
      end
    rescue => e
      puts "Error: receive thread died: #{e}"
      pp e.backtrace
    end
  end
end

#send(type, hash = {}, &block) ⇒ Object



369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
# File 'lib/mqtt-sn-ruby.rb', line 369

def send type,hash={},&block
  if @state==:disconnected and type!=:connect and type!=:will_topic  and type!=:will_msg  and type!=:searchgw
    if type==:disconnect
      return #already disconnected.. nothing to do
    elsif type==:publish and hash[:qos]==-1
    else
      note "Error: Cannot #{type} while unconnected, send :connect first!"
      return nil
    end
  end
  case type
  when :connect
    if not hash[:id] or hash[:id]=""
      hash[:id]="mqtt-sn-ruby-#{$$}"
    end
    note "Connecting as '#{hash[:id]}'"
    flags=0
    flags+=CLEAN_FLAG if hash[:clean]
    flags+=RETAIN_FLAG if hash[:retain]
    flags+=WILL_FLAG if @will_topic
    p=[CONNECT_TYPE,flags,0x01,hash[:duration]>>8 ,hash[:duration] & 0xff]
    hash[:id].each_byte do |b|
      p<<b
    end
    @id=hash[:id]
  when :register
    raise "Need :topic to Publish!" if not hash[:topic]
    p=[REGISTER_TYPE,0,0,@msg_id >>8 ,@msg_id & 0xff]
    hash[:topic].each_byte do |b|
      p<<b
    end
    @msg_id+=1
  when :register_ack
    p=[REGACK_TYPE,hash[:topic_id]>>8 ,hash[:topic_id] & 0xff,hash[:msg_id]>>8 ,hash[:msg_id] & 0xff,hash[:return_code]]
  when :publish_ack
    p=[PUBACK_TYPE,hash[:topic_id]>>8 ,hash[:topic_id] & 0xff,hash[:msg_id]>>8 ,hash[:msg_id] & 0xff,hash[:return_code]]
  when :pub_rec
    p=[PUBREC_TYPE,hash[:msg_id]>>8 ,hash[:msg_id] & 0xff]
  when :pub_comp
    p=[PUBCOMP_TYPE,hash[:msg_id]>>8 ,hash[:msg_id] & 0xff]
  when :will_topic
    raise "Need :topic to :will_topic" if not hash[:topic]
    p=[WILLTOPIC_TYPE,0]
    hash[:topic].each_byte do |b|
      p<<b
    end
  when :will_topic_upd
    raise "Need :topic to :will_topic_upd" if not hash[:topic]
    p=[WILLTOPICUPD_TYPE,0]
    hash[:topic].each_byte do |b|
      p<<b
    end
  when :will_msg
    raise "Need :msg to :will_msg" if not hash[:msg]
    p=[WILLMSG_TYPE]
    hash[:msg].each_byte do |b|
      p<<b
    end
  when :will_msg_upd
    raise "Need :msg to :will_msg_upd" if not hash[:msg]
    p=[WILLMSGUPD_TYPE]
    hash[:msg].each_byte do |b|
      p<<b
    end

  when :subscribe
    raise "Need :topic to :subscribe" if not hash[:topic]
    qos=hash[:qos]||0
    flags=0
    if qos==-1
      flags+=QOSM1_FLAG
    else
      flags+=QOS1_FLAG*qos
    end
    p=[SUBSCRIBE_TYPE,flags,@msg_id >>8 ,@msg_id & 0xff]
    hash[:topic].each_byte do |b|
      p<<b
    end
    @msg_id+=1

  when :unsubscribe
    raise "Need :topic to :unsubscribe" if not hash[:topic]
    p=[UNSUBSCRIBE_TYPE,0,@msg_id >>8 ,@msg_id & 0xff]
    hash[:topic].each_byte do |b|
      p<<b
    end
    @msg_id+=1

  when :publish
    raise "Need :topic_id to Publish!" if not hash[:topic_id]
    qos=hash[:qos]||0
    flags=0
    flags+=RETAIN_FLAG if hash[:retain]
    if qos==-1
      flags+=QOSM1_FLAG
    else
      flags+=QOS1_FLAG*qos
    end
    if hash[:topic_type]==:short
      flags+=TOPIC_SHORT_FLAG
    elsif hash[:topic_type]==:predefined
      flags+=TOPIC_PREDEFINED_FLAG
    end
    p=[PUBLISH_TYPE,flags,hash[:topic_id] >>8 ,hash[:topic_id] & 0xff,@msg_id >>8 ,@msg_id & 0xff]
    hash[:msg].each_byte do |b|
      p<<b.ord
    end
    @msg_id+=1
  when :pubrel
    raise "Need the original :msg_id of the Publish for PubRel!" if not hash[:msg_id]
    p=[PUBREL_TYPE,hash[:msg_id] >>8 ,hash[:msg_id] & 0xff]
  when :ping
    p=[PINGREQ_TYPE]
   when :searchgw
    p=[SEARCHGW_TYPE,0]
  when :disconnect
    if hash[:duration]
      p=[DISCONNECT_TYPE,hash[:duration] >>8 ,hash[:duration] & 0xff]
    else
      p=[DISCONNECT_TYPE]
    end
  else
    puts "Error: Strange send?? #{type}"
    return nil
  end
  status=:timeout
  m={}
  if not hash[:expect]
    if type==:searchgw
      raw=send_packet_bcast p
    else
      raw=send_packet_gw p
    end
    return
  end
  @sem.synchronize do #one command at a time --
    if hash[:expect]
      while not @iq.empty?
        mp=@iq.pop
        puts "WARN:#{@id} ************** Purged message: #{mp}"
      end
      @iq.clear
    end
    if type==:searchgw
      raw=send_packet_bcast p
    else
      raw=send_packet_gw p
    end
    hash[:debug]=raw if @debug
    #puts "send:#{@id} #{type},#{hash.to_json}" if @verbose
    timeout=hash[:timeout]||Tretry
    retries=0
    if hash[:expect]
      while retries<Nretry do
        stime=Time.now.to_i
        while Time.now.to_i<stime+timeout
          if not @iq.empty?
            m=@iq.pop
            if Array(hash[:expect]).include? m[:type]
              status=:ok
              break
            else
              puts "WARN:#{@id} ************** Discarded message: #{m}"
            end
          end
          sleep 0.1
        end
        if status==:ok
          break
        else
          retries+=1
          send_packet_gw p
          puts "fail to get ack, retry #{retries} :#{@id} #{type},#{hash.to_json}"
          #need to set DUP flag !
        end
      end
      if status==:timeout
        note "Warn: ack timeouted, assume disconnected"
        @state=:disconnect
        gateway_close :timeout
      end
    end
  end #sem
  if block
    block.call  status,m
  end

end

#send_packet(m, socket, server, port) ⇒ Object



567
568
569
570
571
572
573
574
# File 'lib/mqtt-sn-ruby.rb', line 567

def send_packet m,socket,server,port
  msg=MqttSN::build_packet m
  MqttSN::send_raw_packet msg,socket,server,port
  dest="#{server}:#{port}"
   _,port,_,_ = socket.addr
  src=":#{port}"
  logger "od %-18.18s <- %-18.18s | %s",dest,src,MqttSN::parse_message(msg).to_json
end

#send_packet_bcast(m) ⇒ Object



576
577
578
579
580
581
582
583
# File 'lib/mqtt-sn-ruby.rb', line 576

def send_packet_bcast m
  uri = URI.parse(@broadcast_uri)
  msg=MqttSN::build_packet m
  MqttSN::send_raw_packet msg,@bcast_s,uri.host,uri.port
   _,port,_,_ = @bcast_s.addr
  src="udp://0.0.0.0:#{port}"
  logger "ob %-24.24s <- %-24.24s | %s",@broadcast_uri,src,MqttSN::parse_message(msg).to_json
end

#send_packet_gw(m) ⇒ Object



585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
# File 'lib/mqtt-sn-ruby.rb', line 585

def send_packet_gw m
  msg=MqttSN::build_packet m
  waits=0
  debug={}
  debug[:debug]=MqttSN::hexdump(msg) if @debug

  if not @active_gw_id or not @gateways[@active_gw_id] or not @gateways[@active_gw_id][:socket]
    note "No active gw, wait ."
    while not @active_gw_id or not @gateways[@active_gw_id] or not @gateways[@active_gw_id][:socket]
      ret="-"
      if  not ret=pick_new_gateway
        sleep 0.5
        #print "."
      end
      waits+=1
      if waits>30
        puts "\nNone Found -- not sending"
        return
      end
    end
    note "Gw Ok!"
  end
  ok=false
  @gsem.synchronize do
    if @active_gw_id and @gateways[@active_gw_id] and @gateways[@active_gw_id][:socket]
      ok=true
      @gateways[@active_gw_id][:last_send]=Time.now.to_i
      @gateways[@active_gw_id][:counter_send]+=1
      uri=URI.parse(@gateways[@active_gw_id][:uri])
      #uri.scheme
      MqttSN::send_raw_packet msg,@gateways[@active_gw_id][:socket],uri.host,uri.port
      _,port,_,_ = @gateways[@active_gw_id][:socket].addr
      src="udp://0.0.0.0:#{port}"
      logger "od %-24.24s <- %-24.24s | %s",@gateways[@active_gw_id][:uri],src,MqttSN::parse_message(msg).merge(debug).to_json  ###utf-8
    end
  end
  if not ok
    puts "no gw to send.."
    sleep 1
  end
end

#sub(options = {}, &block) ⇒ Object



1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
# File 'lib/mqtt-sn-ruby.rb', line 1160

def sub options={},&block
    loop do
      note "Connecting.."
      connect options[:id] do |cs,cm|
        note "connect result: #{cs} #{cm}"
        if cs==:ok
          note "Subscribing.."
          subscribe options[:topic]||"test/message/123", qos: options[:qos] do |s,m|
            if s==:sub_ack
              note "Subscribed Ok! Waiting for Messages!"
            elsif s==:disconnect
              note "Disconnected -- switch to new gateway"
            else
             if block
                block.call s,m
              else
                note "Got Message: #{s}: #{m}"
              end
            end
          end
        end
      end
      puts "Disconnected..."
    end
end

#subscribe(topic, hash = {}, &block) ⇒ Object

Mid-level function to send Subscription to Broker, if code block is provided, it will run the block when new messages are received. When subsciption is established with Broker, a :sub_ack message is given to code block. Incoming messages are indicated with :got_data status. If connection to Broker is disrupted, a :disconnect message is given.!



711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
# File 'lib/mqtt-sn-ruby.rb', line 711

def subscribe topic,hash={},&block  # :yields: status, message
  send :subscribe, topic: topic, qos: hash[:qos],expect: :sub_ack do |s,m|
    if s==:ok
      if m[:topic_id] and m[:topic_id]>0 #when subs topic has no wild cards, we get topic id here:
        if m[:topic_type]==:long
          @topics[topic]=m[:topic_id]
        end
      end
    end
    if block
      block.call :sub_ack,m
      while true
        if not @dataq.empty?
          m=@dataq.pop
          block.call :got_data,m
        end
        sleep 0.1
        if @state==:disconnected
          block.call :disconnect,{}
          #gateway_close :subscribe_disconnected
          break
        end
      end
    end
  end
end

#unsubscribe(topic) ⇒ Object



738
739
740
741
# File 'lib/mqtt-sn-ruby.rb', line 738

def unsubscribe topic
  send :unsubscribe, topic: topic, expect: :unsub_ack do |s,m|
  end
end

#will_and_testament(topic, msg) ⇒ Object



651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
# File 'lib/mqtt-sn-ruby.rb', line 651

def will_and_testament topic,msg
  if @state!=:disconnected #if already connected, send changes, otherwise wait until connect does it.
    if @will_topic!=topic
      send :will_topic_upd, topic: topic, expect: :will_topic_resp do |status,message|
        puts "will topic updated"
        if status==:ok
        else
          puts "Error:#{@id} no pong!"
        end
      end
    end
    if @will_msg!=msg
      send :will_msg_upd, msg: msg, expect: :will_msg_resp do |status,message|
        puts "will msg updated"
        if status==:ok
        else
          puts "Error:#{@id} no pong!"
        end
      end
    end
  end
  @will_topic=topic
  @will_msg=msg
end