Class: SmarterMeter::Samples

Inherits:
Hash
  • 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
29
30
31
32
33
34
35
36
37
38
39
# 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|
    # NOTE: This is a hack, the ESPI data seems to be assuming that
    # all users live in the Eastern Time Zone. The timestamps
    # returned in the ESPI should really be in UTC and not in local
    # time. I'm going to assume all PG&E customers are in the
    # pacific timezone and since the eastern timezone has the same
    # daylight savings time rules then we can use a constant
    # difference to correct the problem.
    pacific_timezone_correction = 60*60*3

    timestamp = Time.at(reading.xpath("./timeperiod/start").first.content.to_i + pacific_timezone_correction)
    value = reading.xpath("./value").first.content.to_i / 900.0

    year = timestamp.year
    month = timestamp.month
    day = timestamp.day

    (samples[Date.new(year, month, day)] ||= []) << Sample.new(timestamp, value)
  end

  samples
end

Instance Method Details

#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.



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

def total_kwh
  self.keys.reduce(0) { |sum, d| sum + total_kwh_on(d) }
end

#total_kwh_on(date) ⇒ Float

Calculates the total number of kilowatt hours

Parameters:

  • date (Date)

    The 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
56
57
58
59
# File 'lib/smartermeter/samples.rb', line 53

def total_kwh_on(date)
  if self[date]
    self[date].reduce(0) { |sum, s| sum + (s.kwh or 0) }
  else
    0
  end
end