Class: CurrentCost::Meter

Inherits:
Object
  • Object
show all
Includes:
Observable
Defined in:
lib/currentcost/meter.rb

Instance Method Summary collapse

Constructor Details

#initialize(port = '/dev/ttyS0') ⇒ Meter

Constructor. ‘port’ is the name of the serial port that the physical meter is connected to. This function will automatically start processing serial data on the specified port. To stop this processing, call close.



40
41
42
43
44
45
# File 'lib/currentcost/meter.rb', line 40

def initialize(port = '/dev/ttyS0')
  @port = RB232::Port.new(port, :baud_rate => 9600)
  @protocol = RB232::TextProtocol.new(@port, "\n")
  @protocol.add_observer(self)
  @protocol.start
end

Instance Method Details

#closeObject

Stops serial data processing. Call this once you’re done with the Meter object.



71
72
73
# File 'lib/currentcost/meter.rb', line 71

def close
  @protocol.stop
end

#latest_readingObject

Get the last Reading received. If no reading has been received yet, returns nil. If you have registered an observer with add_observer(), you will most likely not need this function as the reading will be delivered automatically to your observer’s update() function.



65
66
67
# File 'lib/currentcost/meter.rb', line 65

def latest_reading
  @latest_reading
end

#update(message) ⇒ Object

Internal use only, client code does not need to use this function. Informs the Meter object that a new message has been received by the serial port.



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/currentcost/meter.rb', line 49

def update(message)
  unless message.nil?
    # Parse reading from message
    @latest_reading = Reading.from_xml(message)
    # Inform observers
    changed
    notify_observers(@latest_reading)
  end
rescue CurrentCost::ParseError
  nil
end