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', options = {}) ⇒ Meter

Constructor. ‘port’ is the name of the serial port that the physical meter is connected to. Connection is to a classic meter by default. To connect to a new-stlye CC128, pass :cc128 => true at the end This function will automatically start processing serial data on the specified port. To stop this processing, call close.



42
43
44
45
46
47
# File 'lib/currentcost/meter.rb', line 42

def initialize(port = '/dev/ttyS0', options = {})
  @port = RB232::Port.new(port, :baud_rate => (options[:cc128] == true ? 57600 : 9600), :data_bits => 8, :stop_bits => 1, :parity => false)
  @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.



73
74
75
# File 'lib/currentcost/meter.rb', line 73

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.



67
68
69
# File 'lib/currentcost/meter.rb', line 67

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.



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

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