Skip to content

Commit

Permalink
Refactored a lot code. Updated form processing. Added timers in the e…
Browse files Browse the repository at this point in the history
…nvironment system based on #47. Code cleanup by more re-using code.
  • Loading branch information
theyosh committed Feb 3, 2018
1 parent 1e9b558 commit e0322df
Show file tree
Hide file tree
Showing 18 changed files with 787 additions and 550 deletions.
20 changes: 13 additions & 7 deletions static/js/terrariumpi.js
Original file line number Diff line number Diff line change
Expand Up @@ -563,6 +563,8 @@ function update_online_indicator(online) {
function init_form_settings(pType) {
$('.page-title').append('<div class="title_right"><h3><button type="button" class="btn btn-primary alignright" data-toggle="modal" data-target=".add-form"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span></button></h3> </div>');

$('.form-group:has([required="required"]) > label').append('<span class="required"> *</span>');

var submit_button = $('.modal-footer button.btn.btn-primary');
switch (pType) {
case 'sensor':
Expand Down Expand Up @@ -609,6 +611,14 @@ function init_form_settings(pType) {
add_audio_playlist();
});
break;

case 'environment':
$('form').on('submit',function() {
$(this).find('input[type="radio"]').removeAttr('checked').removeAttr('disabled');
$(this).find('label.active > input[type="radio"]').attr('checked','checked');
$(this).find('label:not(.active) > input[type="radio"]').attr('disabled','disabled');
});
break;
}

}
Expand Down Expand Up @@ -709,12 +719,8 @@ function prepare_form_data(form) {
objectdata = {};
prev_nr = current_nr;
}
if (matches[3] === 'on' || matches[3] === 'off') {
field_value = moment(field_value, 'LT').unix();
}

if (['timer_start','timer_stop','start','stop'].indexOf(matches[3]) != -1) {
// TODO: new way of storing time values. Should be used at all other time fields
if (['timer_start','timer_stop','start','stop','on','off'].indexOf(matches[3]) != -1) {
// Load from local format, and store in 24h format. Do not use UNIX timestamp formats
field_value = moment(field_value, 'LT').format('HH:mm');
}
Expand Down Expand Up @@ -1459,8 +1465,8 @@ function update_dashboard_environment(name, data) {
break;
case 'on':
case 'off':
systempart.find('.' + key).text(moment(value * 1000).format('LT')).parent().toggle(data.mode != 'sensor');
systempart.find('.duration').text(moment.duration(Math.abs(data.off - data.on) * 1000).humanize()).parent().toggle(data.mode != 'sensor');
systempart.find('.' + key).text(moment(value,'HH:mm').format('LT')).parent().toggle(data.mode != 'sensor');
systempart.find('.duration').text(moment.duration(data.duration * 1000).humanize()).parent().toggle(data.mode != 'sensor');
break;

case 'current':
Expand Down
13 changes: 2 additions & 11 deletions terrariumAudio.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,16 +308,7 @@ def set_started(self):

def is_time(self):
logger.info('Checking timer time table for switch %s with %s entries.', self.get_name(),len(self.__timer_time_table))
is_time = None
now = datetime.datetime.today()
for time_schedule in self.__timer_time_table:
if now > time_schedule[0] and now < time_schedule[1]:
is_time = True
break

elif now < time_schedule[0]:
is_time = False
break
is_time = terrariumUtils.is_time(self.__timer_time_table)

if is_time is None:
self.__calculate_time_table()
Expand All @@ -327,7 +318,7 @@ def is_time(self):
return is_time

def get_duration(self):
return (self.__timer_time_table[0][1] - self.__timer_time_table[0][0]).total_seconds()
return terrariumUtils.duration(self.__timer_time_table)

def get_songs_duration(self):
return 0.0 + sum(self.__files[fileid].get_track_duration() for fileid in self.__files)
Expand Down
89 changes: 57 additions & 32 deletions terrariumConfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import ConfigParser
from glob import glob
import datetime

from terrariumUtils import terrariumUtils

Expand Down Expand Up @@ -109,13 +110,22 @@ def __upgrade_config(self,to_version):
for section in self.__config.sections():
if section[:8] == 'playlist':
playlist_data = self.__get_config(section)
self.__config.set(section, 'start', str(datetime.datetime.fromtimestamp(playlist_data['start']).strftime('%H:%M')))
self.__config.set(section, 'stop', str(datetime.datetime.fromtimestamp(playlist_data['stop']).strftime('%H:%M')))
self.__config.set(section, 'start', str(datetime.datetime.fromtimestamp(float(playlist_data['start'])).strftime('%H:%M')))
self.__config.set(section, 'stop', str(datetime.datetime.fromtimestamp(float(playlist_data['stop'])).strftime('%H:%M')))

if section == 'environment':
environment_data = self.__get_config(section)
self.__config.set(section, 'light_on', str(datetime.datetime.fromtimestamp(float(environment_data['light_on'])).strftime('%H:%M')))
self.__config.set(section, 'light_off', str(datetime.datetime.fromtimestamp(float(environment_data['light_off'])).strftime('%H:%M')))
self.__config.set(section, 'heater_on', str(datetime.datetime.fromtimestamp(float(environment_data['heater_on'])).strftime('%H:%M')))
self.__config.set(section, 'heater_off', str(datetime.datetime.fromtimestamp(float(environment_data['heater_off'])).strftime('%H:%M')))
self.__config.set(section, 'cooler_on', str(datetime.datetime.fromtimestamp(float(environment_data['cooler_on'])).strftime('%H:%M')))
self.__config.set(section, 'cooler_off', str(datetime.datetime.fromtimestamp(float(environment_data['cooler_off'])).strftime('%H:%M')))

# Update version number
self.__config.set('terrariumpi', 'version', str(to_version))
#self.__save_config()
#self.__config.read(terrariumConfig.CUSTOM_CONFIG)
self.__save_config()
self.__config.read(terrariumConfig.CUSTOM_CONFIG)
logger.info('Updated configuration. Set version to: %s' % (to_version,))

def __reload_config(self):
Expand Down Expand Up @@ -200,21 +210,6 @@ def set_system(self,data):
'''
return self.__update_config('terrariumpi',data,['cur_password','new_password','available_languages'])

def get_pi_power_wattage(self):
'''Get terrariumPI power usage'''
config = self.get_system()
return float(config['power_usage'])

def get_admin(self):
'''Get terrariumPI admin name'''
config = self.get_system()
return config['admin']

def get_password(self):
'''Get terrariumPI admin password'''
config = self.get_system()
return config['password']

def get_available_languages(self):
'''Get terrariumPI available languages'''
if self.__cache_available_languages is None:
Expand All @@ -230,6 +225,37 @@ def get_language(self):

return config['language']

def get_weather_location(self):
data = self.get_weather()
return data['location'] if 'location' in data else None

def get_weather_windspeed(self):
data = self.get_weather()
return data['windspeed'] if 'windspeed' in data else None

def get_temperature_indicator(self):
config = self.get_system()
return config['temperature_indicator'].upper()

def get_admin(self):
'''Get terrariumPI admin name'''
config = self.get_system()
return config['admin']

def get_password(self):
'''Get terrariumPI admin password'''
config = self.get_system()
return config['password']

def get_active_soundcard(self):
config = self.get_system()
return config['soundcard']

def get_pi_power_wattage(self):
'''Get terrariumPI power usage'''
config = self.get_system()
return float(config['power_usage'])

def get_power_price(self):
'''Get terrariumPI power price. Price is entered as euro/kWh'''
config = self.get_system()
Expand All @@ -240,13 +266,14 @@ def get_water_price(self):
config = self.get_system()
return float(config['water_price'])

def get_temperature_indicator(self):
def get_hostname(self):
config = self.get_system()
return config['temperature_indicator'].upper()
return config['host']

def get_active_soundcard(self):
def get_port_number(self):
config = self.get_system()
return config['soundcard']
return config['port']


# Environment functions
def save_environment(self,data):
Expand All @@ -260,7 +287,11 @@ def save_environment(self,data):
data[environment_part][part] = ''
config[environment_part + '_' + part] = data[environment_part][part]

return self.__update_config('environment',config)
return self.__update_config('environment',config,['light_enabled','light_time_table',
'sprayer_enabled','sprayer_time_table',
'heater_enabled','heater_time_table',
'cooler_enabled','cooler_time_table',
'cooler_temperature','sprayer_humidity','heater_temperature'])

def get_environment(self):
config = self.__get_config('environment')
Expand Down Expand Up @@ -298,13 +329,7 @@ def save_weather(self,data):
def get_weather(self):
return self.__get_config('weather')

def get_weather_location(self):
data = self.get_weather()
return data['location'] if 'location' in data else None

def get_weather_windspeed(self):
data = self.get_weather()
return data['windspeed'] if 'windspeed' in data else None
# End weather config functions


Expand All @@ -317,8 +342,8 @@ def save_sensor(self,data):

def save_sensors(self,data):
update_ok = True
for sensorid in self.get_sensors():
self.__config.remove_section('sensor' + sensorid)
for sensor in self.get_sensors():
self.__config.remove_section('sensor' + sensor['id'])

for sensorid in data:
update_ok = update_ok and self.save_sensor(data[sensorid].get_data())
Expand Down
41 changes: 16 additions & 25 deletions terrariumEngine.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import uptime
import os
import psutil
import copy
from hashlib import md5

from terrariumConfig import terrariumConfig
Expand Down Expand Up @@ -79,7 +78,7 @@ def __init__(self):

# Load the environment system. This will controll the lights, sprayer and heaters
logger.debug('Loading terrariumPI environment system')
self.environment = terrariumEnvironment(self.sensors, self.power_switches, self.weather, self.is_door_open, self.config)
self.environment = terrariumEnvironment(self.sensors, self.power_switches, self.weather, self.is_door_open, self.config.get_environment)
logger.debug('Done loading terrariumPI environment system')

# Load webcams from config
Expand Down Expand Up @@ -673,13 +672,13 @@ def get_environment(self, parameters = [], socket = False):
filter = parameters[0]

data = self.get_sensors(['average'])['sensors']
data['light'] = self.environment.get_light_state()
data['light'] = self.environment.get_light_state()
data['sprayer'] = self.environment.get_sprayer_state()
data['heater'] = self.environment.get_heater_state()
data['cooler'] = self.environment.get_cooler_state()
data['heater'] = self.environment.get_heater_state()
data['cooler'] = self.environment.get_cooler_state()

if filter is not None:
data = { filter: data[filter]}
if filter is not None and filter in data:
data = { filter : data[filter]}

if socket:
self.__send_message({'type':'environment','data':data})
Expand All @@ -690,22 +689,8 @@ def get_environment_config(self):
return self.environment.get_config()

def set_environment_config(self,data):
if 'light' in data:
self.environment.set_light_config(data['light'])

if 'sprayer' in data:
self.environment.set_sprayer_config(data['sprayer'])

if 'heater' in data:
self.environment.set_heater_config(data['heater'])

if 'cooler' in data:
self.environment.set_cooler_config(data['cooler'])

update_ok = self.config.save_environment(self.environment.get_config())
if update_ok:
self.environment.reload_config()
return update_ok
self.environment.load_environment(data)
return self.config.save_environment(self.environment.get_config())
# End Environment part

# Profile part
Expand Down Expand Up @@ -745,8 +730,7 @@ def set_profile(self,data,files):
return update_ok
# End profile part



# System functions part
def authenticate(self,username, password):
return password and (username in self.authentication) and self.authentication[username] == password

Expand Down Expand Up @@ -827,6 +811,8 @@ def get_power_usage_water_flow(self, socket = False):
def get_temperature_indicator(self):
return self.temperature_indicator

# End system functions part

# API Config calls
def get_config(self, part = None):
data = {}
Expand Down Expand Up @@ -896,6 +882,9 @@ def set_config(self,part,data,files = None):
else:
return False

# Update weather data
self.set_weather_config({'location' : data['location'], 'windspeed' : data['windspeed']})

update_ok = self.set_system_config(data)
if update_ok:
# Update config settings
Expand All @@ -913,6 +902,8 @@ def get_system_config(self):
def set_system_config(self,data):
return self.config.set_system(data)

# End system functions part

# Histroy part (Collector)
def get_history(self, parameters = [], socket = False):
data = {}
Expand Down
Loading

0 comments on commit e0322df

Please sign in to comment.