def send_zwave_message(): metadata = psql_server.get_metadata() table_dict = psql_server.setup_tables(metadata) dfs = {} for flxbx in available_flexboxes: # The next two lines are SQL Alchemy code, ordering each house energy data by date and then last_row = table_dict['twilio_received'].select("hostname='"+flxbx+"'").\ order_by(table_dict['twilio_received'].\ c.datetime.desc()).execute().fetchone() if last_row: last_date = last_row[3] limit = last_row[6] last_text_sent = None # The next two lines are SQL Alchemy code, ordering each house energy data by date and t energia = analysis_tools.get_energy_since_date(flxbx, last_date) print flxbx + ': ' + str(last_date) + ' : ' + str(energia) if (datetime.now() - last_date).days > 31: if flxbx in receive_texts: zwave_message = flxbx+': Hay uno mes desde un limite en el database.'\ +' El ultimo ves es '+str(last_date) send_alert_message(zwave_message) else: print flxbx + ' hasn\'t set a limit but does not receive messages.' elif (datetime.now() - last_date).days < 0: zwave_message = flxbx+': El limite es incorrecta. El limite en el server es '\ +str(last_date)+' pero este en el futuro!' send_alert_message(zwave_message) elif energia == 0 and (datetime.now() - last_date).days > 2: zwave_message = flxbx+': Es possible el zwave no es funcianado. Checar'\ + ' immediatamente en esta casa por favor.' send_alert_message(zwave_message)
def send_outlet_message(this_datetime, look_back_hours): metadata = psql_server.get_metadata() table_dict = psql_server.setup_tables(metadata) peak_shifting_df = get_dataframe_from_sql(table_dict\ ['peak_shifting_dr_table'], this_datetime-timedelta(hours=6),look_back_hours+3,in_utc=False) peak_event = False if len(peak_shifting_df) > 0: start_peak_event = peak_shifting_df.iloc[-1]['datetime'] end_peak_event = start_peak_event +\ timedelta(minutes=peak_shifting_df.iloc[-1]['duration_minutes']) print 'Ommitting Outlet checks for when peak events have recently occurred' print start_peak_event print end_peak_event for hours_back in range(look_back_hours): time_check = this_datetime - timedelta(hours=6 + hours_back) peak_event = (time_check>=start_peak_event) and \ (time_check<=end_peak_event) print time_check print peak_event mfi_df = get_dataframe_from_sql(table_dict['mfi_table'], this_datetime, look_back_hours) hour = (this_datetime - timedelta(hours=(look_back_hours + 6))).hour for flxbx in available_flexboxes: if flxbx not in ['flxbxD21']: is_available = True for val in range(hour, hour + look_back_hours): if val not in available_hours[flxbx]: is_available = False if not peak_event and is_available and\ len(mfi_df[mfi_df['hostname']==flxbx])>0: energy_sum3 = sum( mfi_df[mfi_df['hostname'] == flxbx]['active_pwr3']) energy_sum2 = sum(mfi_df[(mfi_df['hostname']==flxbx)&\ (mfi_df['active_pwr2']<\ max_fridge_power[flxbx])]['active_pwr2']) if not peak_event and energy_sum3<energy_sum2 and \ correct_outlet[flxbx]==3: outlet_message = flxbx + ': El freezer esta conectado en'+\ 'el outlet equivocado (outlet 2 (roja)).'+\ ' Checar inmediatamente en esta casa - telefono: '+\ phone_dictionary_reversed[flxbx] send_alert_message(outlet_message) elif energy_sum3 > energy_sum2 and correct_outlet[flxbx] == 2: outlet_message = flxbx + ': El freezer esta conectado en'+\ 'el outlet equivocado (outlet 3 (negro)).'+\ ' Checar inmediatamente en esta casa - telefono: '+\ phone_dictionary_reversed[flxbx] send_alert_message(outlet_message) elif energy_sum3 == 0 and energy_sum2 == 0 and not peak_event: outlet_message = flxbx + ': El freezer esta conectado en'+\ ' NO outlet.'+\ ' Checar inmediatamente en esta casa - telefono: '+\ phone_dictionary_reversed[flxbx] send_alert_message(outlet_message) print hour print available_hours[flxbx]
def get_energy_since_date(flxbx, last_date, remote=False): if remote: metadata = psql_server.get_remote_metadata() else: metadata = psql_server.get_metadata() table_dict = psql_server.setup_tables(metadata) df = create_monotonically_increasing_energy_vals(table_dict, flxbx) if len(df) > 0 and len(df[last_date:]) > 0: energia = df[last_date:]['houseAll_Energy'][-1:].iloc[0] -\ df[last_date:]['houseAll_Energy'][:1].iloc[0] else: energia = 0 return energia
def save_message(protobuff_message): metadata = psql_server.get_metadata() table_dict = psql_server.setup_tables(metadata) incoming_message = flexbox_pb2.heartbeat_message() incoming_message.ParseFromString(protobuff_message) hostname = incoming_message.hostname message_id = incoming_message.id print(str(hostname) + ' ' + str(message_id)) ambient_keymap = (('id','id'), ('datetime', 'datetime'), ('ambient_temp', 'temperature'), ('humidity', 'humidity')) output_dict = load_columns(hostname, incoming_message.ambient, ambient_keymap) try: output_dict['datetime'] = datetime.fromtimestamp(output_dict['datetime']) psql_server.add_values_to_table(table_dict['ambient_table'],output_dict) except IntegrityError: print('Integrity Error (probably duplicate id) for ambient_table') except Exception: print(traceback.print_exc()) inside_keymap = (('id','id'), ('datetime', 'datetime'), ('inside_temp1', 'temp1'), ('inside_temp2', 'temp2')) output_dict = load_columns(hostname, incoming_message.inside_temps, inside_keymap) try: output_dict['datetime'] = datetime.fromtimestamp(output_dict['datetime']) psql_server.add_values_to_table(table_dict['inside_table'],output_dict) except IntegrityError as ie: print('Integrity Error (probably duplicate id) for inside_table') except: print(traceback.print_exc()) switch_keymap = (('id','id'), ('datetime', 'datetime'), ('switch', 'open')) output_dict = load_columns(hostname, incoming_message.switch, switch_keymap) try: output_dict['datetime'] = datetime.fromtimestamp(output_dict['datetime']) psql_server.add_values_to_table(table_dict['switch_table'],output_dict) except IntegrityError: print('Integrity Error (probably duplicate id) for switch_table') except Exception: print(traceback.print_exc()) fridge_power_keymap = (('id','id'), ('datetime', 'datetime'), ('v_rms1', 'v_rms1'), ('v_rms2', 'v_rms2'), ('v_rms3', 'v_rms3'), ('i_rms1', 'i_rms1'), ('i_rms2', 'i_rms2'), ('i_rms3', 'i_rms3'), ('pf1', 'pf1'), ('pf2', 'pf2'), ('pf3', 'pf3'), ('energy_sum1', 'energy_sum1'), ('energy_sum2', 'energy_sum2'), ('energy_sum3', 'energy_sum3'), ('active_pwr1', 'active_pwr1'), ('active_pwr2', 'active_pwr2'), ('active_pwr3', 'active_pwr3'), ('relay1', 'relay1'), ('relay2', 'relay2'), ('relay3', 'relay3') ) output_dict = load_columns(hostname, incoming_message.fridge_power, fridge_power_keymap) try: output_dict['datetime'] = datetime.fromtimestamp(output_dict['datetime']) psql_server.add_values_to_table(table_dict['mfi_table'],output_dict) except IntegrityError: print('Integrity Error (probably duplicate id) for mfi_table') except Exception: print traceback.print_exc() house_power_keymap = (('id','id'), ('datetime', 'datetime'), ('houseAll_Voltage', 'houseAll_Voltage'), ('houseAll_Current', 'houseAll_Current'), ('houseAll_Power', 'houseAll_Power'), ('houseAll_Energy', 'houseAll_Energy'), ('house1_Voltage', 'house1_Voltage'), ('house1_Current', 'house1_Current'), ('house1_Power', 'house1_Power'), ('house1_Energy', 'house1_Energy'), ('house2_Voltage', 'house2_Voltage'), ('house2_Current', 'house2_Current'), ('house2_Power', 'house2_Power'), ('house2_Energy', 'house2_Energy') ) output_dict = load_columns(hostname, incoming_message.house_power, house_power_keymap) try: output_dict['datetime'] = datetime.fromtimestamp(output_dict['datetime']) psql_server.add_values_to_table(table_dict['zwave_table'],output_dict) if hostname=='flxbxD16': print output_dict except IntegrityError: print('Integrity Error (probably duplicate id) for zwave_table') except Exception: print traceback.print_exc() demand_response_keymap = (('id','id'), ('datetime', 'datetime'), ('local_date', 'local_date'), ('mfi_state', 'mfi_state'), ('control_source', 'control_source'), ('control_type', 'control_type'), ('limit_counter', 'limit_counter'), ('uptime_minutes','uptime_minutes') ) output_dict = load_columns(hostname, incoming_message.demand_response, demand_response_keymap) if 'datetime' in output_dict: output_dict['datetime'] = datetime.fromtimestamp(output_dict['datetime']) output_dict['local_date'] = datetime.fromtimestamp(output_dict['local_date']) if output_dict['datetime']>datetime(2000,1,1): try: psql_server.add_values_to_table(table_dict['demand_response'],output_dict) except IntegrityError: print('Integrity Error (probably duplicate id) for demand_response') except Exception: print traceback.print_exc() else: print 'Error receiving demand response protobuff, incorrect datetime received.'
def create_ewarning(): with open('twilio_auth.yaml') as f: cf = yaml.safe_load(f) client = TwilioRestClient(cf['ACCOUNT_SID'], cf['AUTH_TOKEN']) with open('phonebook.yaml') as f: phone_dictionary = yaml.safe_load(f) phone_dictionary_reversed = dict((value,key) for key,value in phone_dictionary.items()) with open('tariff_codes.yaml') as f: tariff_codes = yaml.safe_load(f) #Grabbing data and pulling it metadata = psql.get_metadata() table_dict = psql.setup_tables(metadata) dfs = {} for flxbx in phone_dictionary.values(): # The next two lines are SQL Alchemy code, ordering each house energy data by date and then executing last_row = table_dict['twilio_received'].select("hostname='"+flxbx+"'").\ order_by(table_dict['twilio_received'].\ c.datetime.desc()).execute().fetchone() if last_row: last_date = last_row[3] limit = last_row[6] phone_number = phone_dictionary_reversed[flxbx] last_text_sent = None # The next two lines are SQL Alchemy code, ordering each house energy data by date and then executing energia = analysis_tools.get_energy_since_date(flxbx,last_date) ''' dfs[flxbx] = create_monotonically_increasing_energy_vals(table_dict,flxbx) if len(dfs[flxbx])>0 and len(dfs[flxbx][last_date:])>0: energia = dfs[flxbx][last_date:]['houseAll_Energy'][-1:].iloc[0] -\ dfs[flxbx][last_date:]['houseAll_Energy'][:1].iloc[0] else: energia = 0 ''' ###################### #Querying the twilio sent table for kWh thresholds (in order find out their price of electricity) tariff_code=tariff_codes[flxbx] last_row_sent_kwh = table_dict['twilio_sent'].select().\ where(text("hostname='"+flxbx+"'")).\ where(text("limit_type='kwh'")).\ where(cast(table_dict['twilio_sent'].c.date_last,Date)==last_date).\ order_by(table_dict['twilio_sent'].\ c.datetime.desc()).execute().fetchone() if last_row_sent_kwh: previously_crossed_start_range = last_row_sent_kwh[6] last_date_sent_kwh = last_row_sent_kwh[3] if last_date_sent_kwh != last_date: previously_crossed_start_range=-1 else: previously_crossed_start_range = -1 last_row_user_prices = table_dict['user_prices'].select().\ where(table_dict['user_prices'].c.start_range<=energia).\ where(table_dict['user_prices'].c.end_range>energia).\ where(table_dict['user_prices'].c.tariff_code==tariff_code).\ order_by(table_dict['user_prices'].\ c.datetime.desc()).execute().fetchone() start_range = last_row_user_prices[2] end_range = last_row_user_prices[3] price = last_row_user_prices[4] recent_price_date = last_row_user_prices[1] output_dict = {} if start_range!=previously_crossed_start_range: if end_range < 1000000: message = 'Su consumo ha rebasado el costo de energia anterior. De ' + str(start_range)+ ' kWh a ' \ +str(end_range) + ' kWh usted estara pagando $C '+str(price)+'/kWh' else: message = 'Su consumo ha rebasado el costo de energia anterior. De ahora en adelante usted estara pagando C$'+str(price)+\ '/kWh.' limit_crossed = start_range client.messages.create( to= phone_number, from_=from_twilio_number, body=flxbx.replace("flxbx","")+":"+message, ) output_dict['hostname']= flxbx output_dict['date_last'] = last_date output_dict['datetime'] = datetime.now() output_dict['phone_number'] = phone_number #Specified by Twilio message output_dict['message'] = message output_dict['limit_crossed'] = limit_crossed output_dict['limit_type'] = 'kwh' print tariff_code + ":" + str(energia) + "kWh:" + message enter_data = psql.add_values_to_table(table_dict['twilio_sent'],output_dict) ######################################################### #Querying the Twilio sent table for percents last_row_sent = table_dict['twilio_sent'].select().\ where(text("hostname='"+flxbx+"'")).\ where(text("limit_type='percent'")).\ where(cast(table_dict['twilio_sent'].c.date_last,Date)==last_date).\ order_by(table_dict['twilio_sent'].\ c.datetime.desc()).execute().fetchone() if last_row_sent: previously_crossed = last_row_sent[6] last_date_sent = last_row_sent[3] last_text_sent = last_row_sent[2] if last_date_sent != last_date: previously_crossed=0 else: last_text_sent = last_date last_date_sent = last_date previously_crossed = 0 ### Creating a Warning for Increased Average Consumption Since last Text Message energia_pct_limit = analysis_tools.get_energy_since_date(flxbx,last_text_sent) if (datetime.now() - last_text_sent).days > 0: daily_pct_warning = energia_pct_limit/float((datetime.now()-last_text_sent).days) else: daily_pct_warning = 0 ### Creating a Value that Calculates the Tarifa Social daily_pct_social = energia/float((datetime.now()-last_date_sent).days) ### ### Determining Tariff Code for SQL queries if daily_pct_social < 5 and tariff_code == 'T-0' and energia <= 150: tariff_code_for_sql = 'T-Social' elif tariff_code == 'T-J': tariff_code_for_sql = 'T-0' else: tariff_code_for_sql = tariff_code ine_user_prices = table_dict['user_prices'].select().\ where(table_dict['user_prices'].c.start_range<=energia).\ where(table_dict['user_prices'].c.tariff_code==tariff_code_for_sql).\ where(cast(table_dict['user_prices'].c.datetime,Date)==recent_price_date).\ order_by(table_dict['user_prices'].\ c.datetime.desc()).execute().fetchall() cost_energia = 0 for val in ine_user_prices: this_start_range = val[2] this_end_range = val[3] #Creating a scalar so that we appropriately assing subsidies to jubilados if tariff_code == 'T-J' and this_end_range <= 150: subsidy_scalar = 0.44 else: subsidy_scalar = 1 if energia <= this_end_range: cost_energia += (energia - this_start_range) * val[4] * subsidy_scalar else: cost_energia += (this_end_range - this_start_range) * val[4] * subsidy_scalar # print str(flxbx) + ':'+ str(energia)+" out of " + str(limit)+" last crossed:"+str(previously_crossed) + ' and cost is ' + str(cost_energia) cost_energia_var = 'El gasto actual en Cordobas de los kWh consumidos (sin incluir IVA, alumbrado, y otros gastos) es de $C' + str(round(cost_energia,2)) + '. ' mensaje_warning = '' if (daily_pct_warning > 5) and (daily_pct_social <= 5): mensaje_warning = 'Desde el ultimo mensaje usted ha estado consumiendo mas de 5 kWh/dia. Si usted sigue consumiendo energia de esta manera lo mismo podria perder la tarifa social.' elif (daily_pct_warning > daily_pct_social) and (daily_pct_social > 5): mensaje_warning = 'Desde el ultimo mensaje que usted recibio, usted ha estado consumiendo ' + str(round((daily_pct_warning - daily_pct_social),3)) + ' mas kWh por dia en promedio. Si quiere llegar a su limite de energia cuide su consumo.' if energia and limit and energia >= 0.1*limit: message = '' if energia >= 1*limit and previously_crossed != 100: message = 'Usted ha pasado su limite :( Sugerimos solo utilizar la luz para cosas indispensables de aqui al siguiente recibo! ' + '(' + str(limit)+'kWh) ' + 'el ' + last_date.strftime('%d/%m/%Y') + '. Ha gastado ' + str(int(round(energia))) + ' kWh hasta el dia de hoy. ' + cost_energia_var limit_crossed = 100 elif energia >= 0.90*limit and previously_crossed < 90: message = 'Cuidado, usted esta apunto de cruzar su limite (90%)! Sugerimos solo utilizar la luz para cosas indispensables de aqui al siguiente recibo. ' + '(' + str(limit)+'kWh) ' + 'el ' + last_date.strftime('%d/%m/%Y') + '. Ha gastado ' + str(int(round(energia))) + ' kWh hasta el dia de hoy. ' + cost_energia_var limit_crossed = 90 elif energia >= 0.80*limit and previously_crossed < 80: message = 'Usted ha pasado el 80% de su limite establecido ' + '(' + str(limit)+'kWh) ' + 'el ' + last_date.strftime('%d/%m/%Y') + '. Ha gastado ' + str(int(round(energia))) + ' kWh hasta el dia de hoy. ' + cost_energia_var + mensaje_warning limit_crossed = 80 elif energia >= 0.7*limit and previously_crossed < 70: limit_crossed = 70 message = 'Usted ha pasado el 70% de su limite establecido ' + '(' + str(limit)+'kWh) ' + 'el ' + last_date.strftime('%d/%m/%Y') + '. Ha gastado ' + str(int(round(energia))) + ' kWh hasta el dia de hoy. ' + cost_energia_var + mensaje_warning elif energia >= 0.6*limit and previously_crossed < 60: limit_crossed = 60 message = 'Usted ha pasado el 60% de su limite establecido ' + '(' + str(limit)+'kWh) ' + 'el ' + last_date.strftime('%d/%m/%Y') + '. Ha gastado ' + str(int(round(energia))) + ' kWh hasta el dia de hoy. ' + cost_energia_var + mensaje_warning elif energia >= 0.5*limit and previously_crossed < 50: limit_crossed = 50 message = 'Usted ha pasado el 50% de su limite establecido ' + '(' + str(limit)+'kWh) ' + 'el ' + last_date.strftime('%d/%m/%Y') + '. Ha gastado ' + str(int(round(energia))) + ' kWh hasta el dia de hoy. ' + cost_energia_var + mensaje_warning elif energia >= 0.4*limit and previously_crossed < 40: limit_crossed = 40 message = 'Usted ha pasado el 40% de su limite establecido ' + '(' + str(limit)+'kWh) ' + 'el ' + last_date.strftime('%d/%m/%Y') + '. Ha gastado ' + str(int(round(energia))) + ' kWh hasta el dia de hoy. ' + cost_energia_var + mensaje_warning elif energia >= 0.3*limit and previously_crossed < 30: limit_crossed = 30 message = 'Usted ha pasado el 30% de su limite establecido ' + '(' + str(limit)+'kWh) ' + 'el ' + last_date.strftime('%d/%m/%Y') + '. Ha gastado ' + str(int(round(energia))) + ' kWh hasta el dia de hoy. ' + cost_energia_var + mensaje_warning elif energia >= 0.2*limit and previously_crossed < 20: limit_crossed = 20 message = 'Usted ha pasado el 20% de su limite establecido ' + '(' + str(limit)+'kWh) ' + 'el ' + last_date.strftime('%d/%m/%Y') + '. Ha gastado ' + str(int(round(energia))) + ' kWh hasta el dia de hoy. ' + cost_energia_var + mensaje_warning elif energia >= 0.10*limit and previously_crossed < 10: limit_crossed = 10 message = 'Usted ha pasado el 10% de su limite establecido ' + '(' + str(limit)+'kWh) ' + 'el ' + last_date.strftime('%d/%m/%Y') + '. Ha gastado ' + str(int(round(energia))) + ' kWh hasta el dia de hoy. ' + cost_energia_var + mensaje_warning ''' else: limit_crossed=0 message = 'Usted ha pasado el X% de su limite establecido ' + '(' + str(limit)+'kWh) ' + 'el ' + last_date.strftime('%d/%m/%Y') + '. Ha gastado ' + str(int(round(energia))) + ' kWh hasta el dia de hoy. ' + 'Su tarifa social es ' + str(daily_pct_social) + ' su tarifa warning es ' + str(daily_pct_warning) + ' Su energia es' + str(energia) ''' print message if len(message) >0: client.messages.create( to= phone_number, from_=from_twilio_number, body=flxbx.replace("flxbx","")+":"+message, ) #2. Output Dictionary output_dict = {} output_dict['hostname']= flxbx output_dict['date_last'] = last_date output_dict['phone_number'] = phone_number #Specified by Twilio message output_dict['message'] = message output_dict['limit_crossed'] = limit_crossed output_dict['limit_type'] = 'percent' enter_data = psql.add_values_to_table(table_dict['twilio_sent'],output_dict)
from pandas.tools.plotting import scatter_matrix from datetime import date, datetime, timedelta import copy import numpy as np import os.path import re import random from sqlalchemy import cast, Date, text import json from flexbox import psql_server json_dict = {} peak_shifting_dict = {} ## Importing Data metadata = psql_server.get_metadata() table_dict = psql_server.setup_tables(metadata) this_datetime = datetime.now() signal_table_peak_shifting = table_dict['peak_shifting_dr_table'].select().\ where(cast(table_dict['peak_shifting_dr_table'].c.datetime,Date) == \ this_datetime.date()).\ where(table_dict['peak_shifting_dr_table'].c.signal == 1).\ order_by(table_dict['peak_shifting_dr_table'].c.datetime.asc())\ .execute().fetchone() if signal_table_peak_shifting and len(signal_table_peak_shifting) > 0: peak_start = signal_table_peak_shifting[0] peak_end = peak_start + timedelta(minutes=signal_table_peak_shifting[4])
import csv import logging from pytz import timezone import json from logging.handlers import RotatingFileHandler import pandas as pd application = Flask(__name__) num = 1 error_seconds_since_last_record_network = 60*5 error_seconds_since_last_record_heartbeat = 60*30 error_seconds_since_last_record_twilio = 60*60*24*7 fmt = "%Y-%m-%d %H:%M:%S" localtz = timezone('America/Managua') now = datetime.now() metadata_flexbox_db_server = psql_server.get_metadata() flexbox_db_server_table_dict = psql_server.setup_tables(metadata_flexbox_db_server) def get_network(flxbxNum,num=1): table_name = 'network_tests' output = get_flexbox_rows(flexbox_db_server_table_dict[table_name],num,flxbxNum, error_seconds_since_last_record_network) return output def get_twilio_sent(flxbxNum,num=1): table_name = 'twilio_sent' output = get_flexbox_rows(flexbox_db_server_table_dict[table_name],num,flxbxNum, error_seconds_since_last_record_twilio) return output def get_flexbox_status(flxbxNum):
def run_flask_twilio(): """Respond to incoming calls with a simple text message.""" #Grabbing data and pulling it metadata = psql.get_metadata() table_dict = psql.setup_tables(metadata) # Opening Twilio resp = twilio.twiml.Response() # Getting data from the message if request.values.get('Body', None): input_flask_message = request.values.get('Body', None).encode( 'ascii', 'ignore') phone_number = request.values.get('From', None).encode('ascii', 'ignore') #1. Extracting values from message message_words = input_flask_message.split(' ') message_words = [word for word in message_words if word != ''] else: message_words = None #Used so that this code can be tested in a web browser without error with open('phonebook.yaml') as f: phone_dictionary = yaml.safe_load(f) admin = False if phone_number in phone_dictionary.keys(): flxbx = phone_dictionary[phone_number] if message_words and (len(re.findall('\d+', input_flask_message)) > 0 or 'kwh' in input_flask_message.lower()): try: #This raises an exception if it can't parse the data from the second element of the message date = datetime.strptime(message_words[1], '%d/%m/%Y') except: #This prematurely returns so that the code doesn't attempt to do anythign with the bad date that was provided. resp.message( "El formato de dia/mes/ano que usted escribio esta mal escrito. Por favor verfique el formato." + " Por ejemplo si el dia es el 6 de Marzo. El mensaje deberia decir 'limite 6/3/2016 150 kWh'" ) return str(resp) #Pulling the third word from the message and getting the first element of the list limit = re.findall("(\d+)", message_words[2])[0] #2. Output Dictionary to be inserted into SQL table output_dict = {} output_dict['hostname'] = phone_dictionary[phone_number] output_dict['date_last'] = date output_dict[ 'phone_number'] = phone_number #Specified by Twilio message output_dict['message'] = input_flask_message output_dict['limit_kwh'] = int(limit) psql.add_values_to_table(table_dict['twilio_received'], output_dict) output_message = "Muchas gracias!" elif message_words and SequenceMatcher( None, "energia", message_words[0].lower()).ratio() > 0.5: # The next two lines are SQL Alchemy code, ordering each house energy data by date and then executing last_row = table_dict['twilio_received'].select("hostname='"+flxbx+"'").\ order_by(table_dict['twilio_received'].c.datetime.desc()).execute().fetchone() if last_row: last_date = last_row[3] energia = analysis_tools.get_energy_since_date( flxbx, last_date) ''' df = create_monotonically_increasing_energy_vals(table_dict,flxbx) if len(df[last_date:])>0: energia=df[last_date:]['houseAll_Energy'][-1:].iloc[0] - \ df[last_date:]['houseAll_Energy'][:1].iloc[0] else: energia=0 ''' output_message = 'Usted ha utilizado ' + str(round( energia)) + ' kWh desde ' + last_date.strftime('%d/%m/%Y') else: output_message = "Primero necesitamos que nos mande su limite!" else: output_message = "Gracias! Si hay algun problema por favor comunicarse con Odaly. De otra manera, tenga un buen dia!" else: output_message = "Hola! Por favor contacte a Odaly para registra su telefono. Gracias!" if admin: output_message = 'Admin Mode-' + flxbx + ' used for testing-' + output_message resp.message(output_message) return str(resp)
from flexbox import psql_server as psql from flexbox import analysis_tools from datetime import datetime import re import pandas as pd import numpy as np import copy import yaml import time import os from multiprocessing import Process from difflib import SequenceMatcher TIMEOUT = 18000 app = Flask(__name__) metadata = psql.get_metadata() table_dict = psql.setup_tables(metadata) @app.route("/", methods=['GET', 'POST']) def run_flask_twilio(): """Respond to incoming calls with a simple text message.""" #Grabbing data and pulling it metadata = psql.get_metadata() table_dict = psql.setup_tables(metadata) # Opening Twilio resp = twilio.twiml.Response() # Getting data from the message if request.values.get('Body', None): input_flask_message = request.values.get('Body', None).encode(
#!/usr/bin/env python2 # Copyright 2016 The Flexbox Authors. All rights reserved. # Licensed under the open source MIT License, which is in the LICENSE file. from flexbox import psql_server import socket import traceback # TODO # Have the server run on both IPv4 and IPv6 RESULTS_PORT = 51337 network_tests = psql_server.setup_tables( psql_server.get_metadata())['network_tests'] def setup_reciever(port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('0.0.0.0', RESULTS_PORT)) s.listen(60) return s def get_result(reciever): while True: c, addr = reciever.accept() c.settimeout(10) stuff = "" try: while not ('|' in stuff): stuff += c.recv(4096) except Exception as e: