Module: Meshtastic::SerialInterface

Defined in:
lib/meshtastic/serial_interface.rb

Overview

rubocop:disable Metrics/ModuleLength

Class Method Summary collapse

Class Method Details

.authorsObject

Author(s)

0day Inc. support@0dayinc.com



671
672
673
674
675
# File 'lib/meshtastic/serial_interface.rb', line 671

public_class_method def self.authors
  "AUTHOR(S):
    0day Inc. <support@0dayinc.com>
  "
end

.connect(opts = {}) ⇒ Object

Supported Method Parameters

serial_obj = Meshtastic::SerialInterface.connect( block_dev: 'optional - serial block device path (defaults to /dev/ttyUSB0)', baud: 'optional - (defaults to 115200)', data_bits: 'optional - (defaults to 8)', stop_bits: 'optional - (defaults to 1)', parity: 'optional - :even|:odd|:none (defaults to :none)', debug_out: 'optional - IO to receive non-protobuf debug console bytes', want_config: 'optional - request full node DB after connect (default: true)' )



225
226
227
228
229
230
231
232
233
234
235
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
# File 'lib/meshtastic/serial_interface.rb', line 225

public_class_method def self.connect(opts = {})
  block_dev = opts[:block_dev] ||= '/dev/ttyUSB0'
  raise "Invalid block device: #{block_dev}" unless File.exist?(block_dev)

  baud = opts[:baud] ||= 115_200
  data_bits = opts[:data_bits] ||= 8
  stop_bits = opts[:stop_bits] ||= 1
  parity = opts[:parity] ||= :none
  debug_out = opts[:debug_out]
  want_config = opts.fetch(:want_config, true)

  parity_char =
    case parity.to_s.to_sym
    when :even then 'E'
    when :odd  then 'O'
    when :none then 'N'
    else
      raise "Invalid parity: #{opts[:parity]}"
    end

  mode = "#{data_bits}#{parity_char}#{stop_bits}"

  clear_hupcl(block_dev)

  serial_conn = UART.open(block_dev, baud, mode)

  serial_obj = {
    serial_conn: serial_conn,
    block_dev: block_dev,
    baud: baud,
    my_info: nil,
    my_node_num: nil,
    metadata: nil
  }

  serial_obj[:rx_thread] = init_rx_thread(
    serial_conn: serial_conn,
    serial_obj: serial_obj,
    debug_out: debug_out
  )

  # Wake / resync the device's framing state-machine.
  wake_up_device(serial_obj: serial_obj)

  if want_config
    mui = Meshtastic::MeshInterface.new
    to_radio_bytes = mui.start_config
    send_to_radio(serial_obj: serial_obj, to_radio: to_radio_bytes)
  end

  serial_obj
rescue StandardError => e
  disconnect(serial_obj: serial_obj) unless serial_obj.nil?
  raise e
end

.disconnect(opts = {}) ⇒ Object

Supported Method Parameters

serial_obj = Meshtastic::SerialInterface.disconnect( serial_obj: 'required - serial_obj returned from #connect method' )



632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
# File 'lib/meshtastic/serial_interface.rb', line 632

public_class_method def self.disconnect(opts = {})
  serial_obj = opts[:serial_obj]
  return nil unless serial_obj

  @want_exit = true

  # Ask device to release the link (best-effort).
  begin
    if serial_obj[:serial_conn] && !serial_obj[:serial_conn].closed?
      to_radio = Meshtastic::ToRadio.new
      to_radio.disconnect = true
      send_to_radio(serial_obj: serial_obj, to_radio: to_radio)
      sleep 0.05
    end
  rescue StandardError
    # ignore during teardown
  end

  rx_thread = serial_obj[:rx_thread]
  serial_conn = serial_obj[:serial_conn]

  begin
    serial_conn&.close
  rescue StandardError
    nil
  end

  if rx_thread&.alive? && rx_thread != Thread.current
    rx_thread.join(1)
    rx_thread.kill if rx_thread.alive?
  end

  nil
rescue StandardError => e
  raise e
end

.drain_from_radio(opts = {}) ⇒ Object

Drain the FromRadio queue without blocking (returns Array of FromRadio msgs).



336
337
338
339
340
341
342
343
344
345
346
347
# File 'lib/meshtastic/serial_interface.rb', line 336

public_class_method def self.drain_from_radio(opts = {})
  max = opts[:max] ||= 256
  msgs = []
  return msgs unless @from_radio_queue

  max.times do
      msgs << @from_radio_queue.pop(true)
  rescue ThreadError
      break
  end
  msgs
end

.dump_stdout_data(opts = {}) ⇒ Object

Supported Method Parameters

stdout_data = Meshtastic::SerialInterface.dump_stdout_data( type: 'required - :proto or :console' )



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/meshtastic/serial_interface.rb', line 300

public_class_method def self.dump_stdout_data(opts = {})
  type = opts[:type]
  valid_types = %i[proto console]
  raise "ERROR: Invalid type: #{type}. Supported types are :proto or :console" unless valid_types.include?(type)

  @rx_mutex.synchronize do
    if block_given?
      if type == :proto
        @proto_data.each { |proto_hash| yield proto_hash }
      else
        @console_data.join.split("\n").each { |line| yield line.force_encoding('UTF-8') }
      end
      nil
    else
      type == :proto ? @proto_data.dup : @console_data.join
    end
  end
end

.flush_data(opts = {}) ⇒ Object

rubocop:disable Naming/PredicateMethod



323
324
325
326
327
328
329
330
331
332
333
# File 'lib/meshtastic/serial_interface.rb', line 323

public_class_method def self.flush_data(opts = {}) # rubocop:disable Naming/PredicateMethod
  type = opts[:type]
  valid_types = %i[proto console]
  raise "ERROR: Invalid type: #{type}. Supported types are :proto or :console" unless valid_types.include?(type)

  @rx_mutex.synchronize do
    @console_data.clear if type == :console
    @proto_data.clear if type == :proto
  end
  true
end

.helpObject

Display Usage for this Module



679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
# File 'lib/meshtastic/serial_interface.rb', line 679

public_class_method def self.help
  puts "USAGE:
    serial_obj = #{self}.connect(
      block_dev: 'optional - serial block device path (defaults to /dev/ttyUSB0)',
      baud: 'optional - (defaults to 115200)',
      data_bits: 'optional - (defaults to 8)',
      stop_bits: 'optional - (defaults to 1)',
      parity: 'optional - :even|:odd|:none (defaults to :none)',
      debug_out: 'optional - IO receiving non-protobuf debug console bytes',
      want_config: 'optional - request full node DB after connect (default: true)'
    )

    #{self}.wake_up_device(
      serial_obj: 'required - serial_obj returned from #connect method'
    )

    #{self}.request(
      serial_obj: 'required serial_obj returned from #connect method',
      payload: 'required - array of bytes OR string to write to serial device'
    )

    #{self}.send_to_radio(
      serial_obj: 'required - serial_obj returned from #connect method',
      to_radio: 'required - Meshtastic::ToRadio OR serialized String'
    )

    from_radio = #{self}.recv_from_radio(
      timeout: 'optional - seconds (default: 5; nil = block forever)'
    )

    msgs = #{self}.drain_from_radio(max: 256)

    stdout_data = #{self}.dump_stdout_data(
      type: 'required - :proto or :console'
    )

    #{self}.flush_data(
      type: 'required - :console or :proto'
    )

    #{self}.monitor_stdout(
      serial_obj: 'required - serial_obj returned from #connect method',
      type: 'required - :proto or :console',
      refresh: 'optional - refresh interval (default: 3)',
      include: 'optional - comma-delimited string(s) to include in message',
      exclude: 'optional - comma-delimited string(s) to exclude in message'
    )

    #{self}.subscribe(
      serial_obj: 'required - serial_obj returned from #connect method',
      psks: 'optional - hash of :channel_id => psk (default: { LongFast: \"AQ==\" })',
      exclude: 'optional - comma-delimited string(s) to exclude',
      include: 'optional - comma-delimited string(s) to include',
      gps_metadata: 'optional - include GPS metadata (default: false)',
      include_raw: 'optional - include raw packet bytes (default: false)',
      timeout: 'optional - seconds per pop (default: nil = forever)'
    )

    #{self}.send_text(
      serial_obj: 'required - serial_obj returned from #connect method',
      from: 'optional - From ID (Default: local my_node_num or \"!00000b0b\")',
      to: 'optional - Destination ID (Default: \"!ffffffff\")',
      channel: 'optional - channel index (Default: 0)',
      text: 'optional - Text Message (Default: SYN)',
      want_ack: 'optional - Want Acknowledgement (Default: false)',
      want_response: 'optional - Want Response (Default: false)',
      hop_limit: 'optional - Hop Limit (Default: 3)'
    )

    #{self}.send_data(
      serial_obj: 'required - serial_obj returned from #connect method',
      from: 'optional - From ID',
      to: 'optional - Destination ID (Default: \"!ffffffff\")',
      channel: 'optional - channel index (Default: 0)',
      data: 'required - Meshtastic::Data',
      want_ack: 'optional - Want Acknowledgement (Default: false)',
      hop_limit: 'optional - Hop Limit (Default: 3)',
      port_num: 'optional - PortNum (Default: PRIVATE_APP)'
    )

    serial_obj = #{self}.disconnect(
      serial_obj: 'required - serial_obj returned from #connect method'
    )

    #{self}.authors
  "
end

.monitor_stdout(opts = {}) ⇒ Object

Supported Method Parameters

Meshtastic::SerialInterface.monitor_stdout( serial_obj: 'required - serial_obj returned from #connect method', type: 'required - :proto or :console', refresh: 'optional - refresh interval (default: 3)', include: 'optional - comma-delimited string(s) to include in message (default: nil)', exclude: 'optional - comma-delimited string(s) to exclude in message (default: nil)' )



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
# File 'lib/meshtastic/serial_interface.rb', line 373

public_class_method def self.monitor_stdout(opts = {})
  serial_obj = opts[:serial_obj]
  type = opts[:type]
  valid_types = %i[proto console]
  raise "ERROR: Invalid type: #{type}. Supported types are :proto or :console" unless valid_types.include?(type)

  refresh = opts[:refresh] ||= 3
  include = opts[:include]
  exclude = opts[:exclude]

  loop do
    exclude_arr = exclude.to_s.split(',').map(&:strip)
    include_arr = include.to_s.split(',').map(&:strip)

    dump_stdout_data(type: type) do |data|
      data_s = data.is_a?(Hash) ? data.inspect : data.to_s
      disp = !exclude_arr.intersect?(data_s) && (
               include_arr.empty? ||
               include_arr.all? { |inc| data_s.include?(inc) }
             )
      puts data_s if disp
    end
    flush_data(type: type)
    sleep refresh
  end
rescue Interrupt
  puts "\nCTRL+C detected. Breaking out of console mode..."
  disconnect(serial_obj: serial_obj) unless serial_obj.nil?
rescue StandardError => e
  disconnect(serial_obj: serial_obj) unless serial_obj.nil?
  raise e
end

.recv_from_radio(opts = {}) ⇒ Object

Block until a FromRadio arrives or timeout (seconds). Returns FromRadio or nil.



350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/meshtastic/serial_interface.rb', line 350

public_class_method def self.recv_from_radio(opts = {})
  timeout = opts[:timeout] ||= 5
  raise 'ERROR: RX queue not initialised — call connect first' unless @from_radio_queue

  if timeout.nil? || timeout.negative?
    @from_radio_queue.pop
  else
    begin
      Timeout.timeout(timeout) { @from_radio_queue.pop }
    rescue Timeout::Error
      nil
    end
  end
end

.request(opts = {}) ⇒ Object

Supported Method Parameters

Meshtastic::SerialInterface.request( serial_obj: 'required serial_obj returned from #connect method', payload: 'required - array of bytes OR string to write to serial device' )



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/meshtastic/serial_interface.rb', line 159

public_class_method def self.request(opts = {})
  serial_obj = opts[:serial_obj]
  serial_conn = serial_obj[:serial_conn]
  payload = opts[:payload]

  bytes =
    case payload
    when String then payload.b
    when Array  then payload.pack('C*')
    else
      raise "ERROR: Invalid payload type: #{payload.class}"
    end

  serial_conn.write(bytes)
  serial_conn.flush
  sleep 0.05
  bytes.bytesize
rescue StandardError => e
  disconnect(serial_obj: serial_obj) unless serial_obj.nil?
  raise e
end

.send_data(opts = {}) ⇒ Object

Supported Method Parameters

Meshtastic::SerialInterface.send_data( serial_obj: 'required - serial_obj returned from #connect method', ...same kwargs as MeshInterface#send_data (via forced to :radio) )



610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
# File 'lib/meshtastic/serial_interface.rb', line 610

public_class_method def self.send_data(opts = {})
  serial_obj = opts[:serial_obj]
  raise 'ERROR: serial_obj is required' unless serial_obj

  opts = opts.dup
  opts[:via] = :radio
  opts[:channel] ||= 0
  opts[:psks] = nil
  opts[:from] = "!#{serial_obj[:my_node_num].to_s(16)}" if opts[:from].nil? && serial_obj[:my_node_num]

  mui = Meshtastic::MeshInterface.new
  protobuf = mui.send_data(opts)
  send_to_radio(serial_obj: serial_obj, to_radio: protobuf)
rescue StandardError => e
  disconnect(serial_obj: serial_obj) unless serial_obj.nil?
  raise e
end

.send_text(opts = {}) ⇒ Object

Supported Method Parameters

Meshtastic::SerialInterface.send_text( serial_obj: 'required - serial_obj returned from #connect method', from: 'optional - From ID (Default: local my_node_num or "!00000b0b")', to: 'optional - Destination ID (Default: "!ffffffff")', channel: 'optional - channel index (Default: 0)', text: 'optional - Text Message (Default: SYN)', want_ack: 'optional - Want Acknowledgement (Default: false)', want_response: 'optional - Want Response (Default: false)', hop_limit: 'optional - Hop Limit (Default: 3)', psks: 'optional - ignored for serial (device owns channel crypto)' )



576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
# File 'lib/meshtastic/serial_interface.rb', line 576

public_class_method def self.send_text(opts = {})
  serial_obj = opts[:serial_obj]
  raise 'ERROR: serial_obj is required' unless serial_obj

  opts = opts.dup
  opts[:via] = :radio
  opts[:channel] ||= 0

  if opts[:from].nil?
    opts[:from] =
      if serial_obj[:my_node_num]
        "!#{serial_obj[:my_node_num].to_s(16)}"
      else
        '!00000b0b'
      end
  end

  # Device performs channel encryption for serial ToRadio packets.
  # Pass empty psks so MeshInterface leaves the payload in :decoded form.
  opts[:psks] = nil

  mui = Meshtastic::MeshInterface.new
  protobuf = mui.send_text(opts)
  send_to_radio(serial_obj: serial_obj, to_radio: protobuf)
rescue StandardError => e
  disconnect(serial_obj: serial_obj) unless serial_obj.nil?
  raise e
end

.send_to_radio(opts = {}) ⇒ Object

Supported Method Parameters

Meshtastic::SerialInterface.send_to_radio( serial_obj: 'required - serial_obj returned from #connect method', to_radio: 'required - Meshtastic::ToRadio OR already-serialized String' )



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
# File 'lib/meshtastic/serial_interface.rb', line 186

public_class_method def self.send_to_radio(opts = {})
  serial_obj = opts[:serial_obj]
  raise 'ERROR: serial_obj is required' unless serial_obj

  to_radio = opts[:to_radio]
  raise 'ERROR: to_radio is required' if to_radio.nil?

  body =
    case to_radio
    when String
      to_radio.b
    when Meshtastic::ToRadio
      to_radio.to_proto
    else
      raise "ERROR: to_radio must be Meshtastic::ToRadio or String, got #{to_radio.class}"
    end

  raise "ERROR: ToRadio payload too large (#{body.bytesize} > #{Meshtastic::MAX_TO_FROM_RADIO_SIZE})" if body.bytesize > Meshtastic::MAX_TO_FROM_RADIO_SIZE

  header = [
    Meshtastic::START1,
    Meshtastic::START2,
    (body.bytesize >> 8) & 0xFF,
    body.bytesize & 0xFF
  ].pack('C*')

  request(serial_obj: serial_obj, payload: header + body)
end

.subscribe(opts = {}) ⇒ Object

Supported Method Parameters

Meshtastic::SerialInterface.subscribe( serial_obj: 'required - serial_obj returned from #connect method', psks: 'optional - hash of :channel_id => psk (default: { LongFast: "AQ==" })', exclude: 'optional - comma-delimited substrings to hide', include: 'optional - comma-delimited substrings required to display', gps_metadata: 'optional - reverse-geocode POSITION payloads (default: false)', include_raw: 'optional - include raw protobuf bytes (default: false)', timeout: 'optional - seconds to block on empty queue per iteration (default: nil = forever)' ) Yields each decoded FromRadio hash. Without a block, pretty-prints packets.



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
557
558
559
560
561
562
# File 'lib/meshtastic/serial_interface.rb', line 470

public_class_method def self.subscribe(opts = {})
  serial_obj = opts[:serial_obj]
  raise 'ERROR: serial_obj is required' unless serial_obj

  public_psk = '1PG7OiApB1nwvP+rz05pAQ=='
  psks = opts[:psks] ||= { LongFast: public_psk }
  raise 'ERROR: psks parameter must be a hash of :channel_id => psk key value pairs' unless psks.is_a?(Hash)

  psks[:LongFast] = public_psk if psks[:LongFast] == 'AQ=='
  mui = Meshtastic::MeshInterface.new
  psks = mui.get_cipher_keys(psks: psks)

  exclude = opts[:exclude]
  include = opts[:include]
   = opts[:gps_metadata] ||= false
  include_raw = opts[:include_raw] ||= false
  timeout = opts[:timeout]

  include_arr = include.to_s.split(',').map(&:strip)
  exclude_arr = exclude.to_s.split(',').map(&:strip)

  puts 'Subscribing to serial FromRadio stream...'

  loop do
    from_radio =
      if timeout
        recv_from_radio(timeout: timeout)
      else
        @from_radio_queue.pop
      end
    next if from_radio.nil?

    begin
      decoded_payload_hash = from_radio.to_h
      raw_packet = from_radio.to_proto if include_raw

      message = {}
      stdout_message = ''

      if decoded_payload_hash[:packet].is_a?(Hash)
        message = enrich_packet(
          message: decoded_payload_hash[:packet],
          psks: psks,
          gps_metadata: ,
          include_raw: include_raw,
          raw_packet: raw_packet
        )
        decoded_payload_hash[:packet] = message
      end

      unless block_given?
        message[:stdout] = 'pretty' if message.is_a?(Hash)
        stdout_message = JSON.pretty_generate(decoded_payload_hash)
      end
    rescue Encoding::CompatibilityError,
           Google::Protobuf::ParseError,
           JSON::GeneratorError,
           ArgumentError => e
      message[:decrypted] = e.message if message.is_a?(Hash)
      decoded_payload_hash[:packet] = message if message.is_a?(Hash)
      unless block_given?
        message[:stdout] = 'inspect' if message.is_a?(Hash)
        stdout_message = decoded_payload_hash.inspect
      end
    ensure
      flat_source = decoded_payload_hash.is_a?(Hash) ? decoded_payload_hash : {}
      flat_message = flat_source.values.join(' ')
      flat_message = "#{flat_message} #{message.values.join(' ')}" if message.is_a?(Hash)

      disp = !exclude_arr.intersect?(flat_message) &&
             include_arr.all? { |inc| flat_message.include?(inc) }

      if disp
        if block_given?
          yield decoded_payload_hash
        else
          puts "\n"
          puts '-' * 80
          puts 'MSG:'
          puts stdout_message
          puts '-' * 80
          puts "\n\n\n"
        end
      end
    end
  end
rescue Interrupt
  puts "\nCTRL+C detected. Exiting..."
  disconnect(serial_obj: serial_obj) unless serial_obj.nil?
rescue StandardError => e
  disconnect(serial_obj: serial_obj) unless serial_obj.nil?
  raise e
end

.wake_up_device(opts = {}) ⇒ Object

Supported Method Parameters

wake_up_device( serial_obj: 'required - serial_obj returned from #connect method' )



285
286
287
288
289
290
291
292
293
294
# File 'lib/meshtastic/serial_interface.rb', line 285

public_class_method def self.wake_up_device(opts = {})
  serial_obj = opts[:serial_obj]
  # START2 * 32 — does not look like a valid header, forces RX state machine resync
  start2_bytes = ([Meshtastic::START2] * 32).pack('C*')
  request(serial_obj: serial_obj, payload: start2_bytes)
  sleep 0.1
rescue StandardError => e
  disconnect(serial_obj: serial_obj) unless serial_obj.nil?
  raise e
end