Class: CurrentCost::Meter

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

Instance Attribute Summary collapse

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 = SerialPort.new(port, (options[:cc128] == true ? 57600 : 9600), 8, 1, SerialPort::NONE)
  @protocol = TextProtocol.new(@port, "\n")
  @protocol.add_observer(self)
  @protocol.start
end

Instance Attribute Details

#protocolObject

Returns the value of attribute protocol



49
50
51
# File 'lib/currentcost/meter.rb', line 49

def protocol
  @protocol
end

Instance Method Details

#closeObject

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



75
76
77
78
# File 'lib/currentcost/meter.rb', line 75

def close
  @protocol.stop
  @port.close
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.



69
70
71
# File 'lib/currentcost/meter.rb', line 69

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.



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

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