Class: SmarterMeter::Samples

Inherits:
Array
  • Object
show all
Defined in:
lib/smartermeter/samples.rb

Overview

Represents a collection of samples. In some cases it's useful to operate on groups of samples and this class provides that functionality.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.parse_espi(data) ⇒ Samples

Parses the XML returned by PG&E and creates a Samples collection.

Parameters:

  • data (String)

    the string containing the XML returned by PG&E

Returns:

  • (Samples)

    creates a Samples collection from the given data.



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

def self.parse_espi(data)
  samples = Samples.new
  doc = Nokogiri::HTML(data)

  doc.xpath("//intervalreading").each do |reading|
    timestamp = reading.xpath("./timeperiod/start").first.content.to_i
    timestamp = Time.at(timestamp).utc

    value = reading.xpath("./value").first.content.to_i / 900.0
    value = ((value * 100).truncate / 100.0)

    samples << Sample.new(timestamp, value)
  end

  samples
end

Instance Method Details

#on(date_time) ⇒ Samples

Selects all samples starting from the given time until 24 hours into the future.

Parameters:

  • date_time (DateTime)

    The start date of the samples to include within the total.

Returns:

  • (Samples)

    a sample collection containing only the selected samples. If none are found, a samples object with no samples is returned.



42
43
44
45
46
# File 'lib/smartermeter/samples.rb', line 42

def on(date_time)
  start_time = date_time.to_time
  end_time = (date_time + 1).to_time
  Samples.new(select { |s| start_time <= s.time && s.time < end_time })
end

#total_kwhFloat

Calculates the total number of kilowatt hours for all samples.

Returns:

  • (Float)

    the sum of kilowatt hours for all samples within this collection. If no samples are found 0 is returned.



33
34
35
# File 'lib/smartermeter/samples.rb', line 33

def total_kwh
  map { |s| s.kwh || 0 }.reduce(:+) || 0
end

#total_kwh_on(date_time) ⇒ Float

Calculates the total number of kilowatt hours

Parameters:

  • date_time (DateTime)

    The start date of the samples to include within the total.

Returns:

  • (Float)

    the sum of kilowatt hours for samples made of the given day. If none are found 0 is returned.



53
54
55
# File 'lib/smartermeter/samples.rb', line 53

def total_kwh_on(date_time)
  on(date_time).total_kwh
end