Class: SerialPortGPS

Inherits:
Object
  • Object
show all
Defined in:
lib/serialport_gps.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(port: "/dev/ttyAMA0", baud_rate: 9600, refresh_rate: 8, callback: Proc.new {puts self.to_h.inspect}) ⇒ SerialPortGPS

Returns a new instance of SerialPortGPS.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/serialport_gps.rb', line 14

def initialize(port: "/dev/ttyAMA0", baud_rate: 9600, 
              refresh_rate: 8, callback: Proc.new {puts self.to_h.inspect})


  # if the refresh rate is any less than 8 seconds the serial connection
  # will have a higher probability of containing corrupted data

  refresh_rate = 8 if refresh_rate < 8
  @refresh_rate = refresh_rate - 4
  @callback = callback

  #params for serial port    
  @port, @baud_rate, @data_bits, @stop_bits, @parity = port, baud_rate, 
                                                       8, 1, SerialPort::NONE
  @np = NMEAParser.new
end

Instance Attribute Details

#latitudeObject (readonly)

Returns the value of attribute latitude.



12
13
14
# File 'lib/serialport_gps.rb', line 12

def latitude
  @latitude
end

#longitudeObject (readonly)

Returns the value of attribute longitude.



12
13
14
# File 'lib/serialport_gps.rb', line 12

def longitude
  @longitude
end

#timeObject (readonly)

Returns the value of attribute time.



12
13
14
# File 'lib/serialport_gps.rb', line 12

def time
  @time
end

#to_hObject (readonly)

Returns the value of attribute to_h.



12
13
14
# File 'lib/serialport_gps.rb', line 12

def to_h
  @to_h
end

Instance Method Details

#startObject



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/serialport_gps.rb', line 31

def start

  @running = true

  RunEvery.new(seconds: @refresh_rate, thread_name: 'GPS listener') do 

    Thread.stop unless @running

    begin

      sp = SerialPort.new(@port, @baud_rate, @data_bits, @stop_bits, @parity)
      sleep 4
      s = ''

      (s = sp.gets.scrub; @np.parse(s)) until s =~ /^\$GPGGA/
      sp.close

    rescue
      puts 'warning: ' + ($!).inspect
      retry
    end

    @time, @latitude, @longitude, @to_h = @np.time, @np.latitude, 
                                                      @np.longitude, @np.to_h
    @callback.call
  end
end

#stopObject



59
60
61
# File 'lib/serialport_gps.rb', line 59

def stop()
  @running = false
end