Files
smartmeter/app/models/reading.rb
2013-08-09 14:32:43 +02:00

77 lines
3.0 KiB
Ruby

class Reading < ActiveRecord::Base
def eql_reading?(reading)
self.total_kwh_consumed_high == reading.total_kwh_consumed_high &&
self.total_kwh_consumed_low == reading.total_kwh_consumed_low &&
self.total_kwh_produced_high == reading.total_kwh_produced_high &&
self.total_kwh_produced_low == reading.total_kwh_produced_low &&
self.current_kw_consumed == reading.current_kw_consumed &&
self.current_kw_produced == reading.current_kw_produced &&
self.total_m3_gas_consumed == reading.total_m3_gas_consumed &&
self.high_tarif == reading.high_tarif
end
# reduce precision to 1 digit behind comma
def total_kwh_consumed_high=(kwh)
write_attribute(:total_kwh_consumed_high,kwh.round(1))
end
# reduce precision to 1 digit behind comma
def total_kwh_consumed_low=(kwh)
write_attribute(:total_kwh_consumed_low,kwh.round(1))
end
# reduce precision to 1 digit behind comma
def total_kwh_produced_high=(kwh)
write_attribute(:total_kwh_produced_high,kwh.round(1))
end
# reduce precision to 1 digit behind comma
def total_kwh_produced_low=(kwh)
write_attribute(:total_kwh_produced_low,kwh.round(1))
end
# calculate difference with another reading
# return a hash with differences (self - reading)
def diff(reading)
if reading
{ :total_kwh_consumed_high => (self.total_kwh_consumed_high - reading.total_kwh_consumed_high).round(1),
:total_kwh_consumed_low => (self.total_kwh_consumed_low - reading.total_kwh_consumed_low).round(1),
:total_kwh_produced_high => (self.total_kwh_produced_high - reading.total_kwh_produced_high).round(1),
:total_kwh_produced_low => (self.total_kwh_produced_low - reading.total_kwh_produced_low).round(1),
:total_m3_gas_consumed => (self.total_m3_gas_consumed - reading.total_m3_gas_consumed).round(3) }
else
{ :total_kwh_consumed_high => self.total_kwh_consumed_high,
:total_kwh_consumed_low => self.total_kwh_consumed_low,
:total_kwh_produced_high => self.total_kwh_produced_high,
:total_kwh_produced_low => self.total_kwh_produced_low,
:total_m3_gas_consumed => self.total_m3_gas_consumed }
end
end
#
# Class methods
#
class << self
# return readings from beginning of 'from' until end of 'to'
def days(from, to)
Reading.where("created_at > :begin AND created_at < :end", { :begin => from.to_date.beginning_of_day, :end => to.to_date.end_of_day})
end
def day(date)
Reading.where("created_at > :begin AND created_at < :end", { :begin => date.to_date.beginning_of_day, :end => date.to_date.end_of_day})
end
def diff_on(date)
readings_on = day(date)
first = readings_on.first
last = readings_on.last
if last
last.diff(first)
else
{ :total_kwh_consumed_high => 0, :total_kwh_consumed_low => 0, :total_kwh_produced_high => 0, :total_kwh_produced_low => 0, :total_m3_gas_consumed => 0 }
end
end
end
end