Source code for webserver

#   Copyright 2014 Marco Rigoni                                               #
#   ElettronicaOpenSource.com   elettronicaopensource@gmail.com               #
#   This program is free software: you can redistribute it and/or modify      #
#   it under the terms of the GNU General Public License as published by      #
#   the Free Software Foundation, either version 3 of the License, or         #
#   (at your option) any later version.                                       # 
#																			  #
#   This program is distributed in the hope that it will be useful,           #
#   but WITHOUT ANY WARRANTY; without even the implied warranty of            #
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             #
#   GNU General Public License for more details.                              #
#                                                                             #
#   You should have received a copy of the GNU General Public License         #
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.     #

#a way to run it on back ground:  sudo python webserver.py >file.log 2>&1



#usefull sources  http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
# -*- coding: UTF-8 -*-


from conf import *           # import parameter from conf.py  which will read the data from the  json 
from mail_agent import *

global scenarioDict
global object_dict
global zoneDict
global exit  #exit is on conf.py  f exit ==1 all the program stop and exit

exit=0
check_log_len_time=1

default_new_zone_value="TYPE_NEW_ROOM_HERE_AND_CLICK_SUBMIT"
default_new_obj_value="TYPE A NEW OBJECT NAME HERE"
default_new_obj_value2="TYPE_A_NEW_OBJECT_NAME_HERE"
default_rename_zone_value="RENAME IT AND CLICK SUBMIT"
default_rename_zone_value2="RENAME_IT_AND_CLICK_SUBMIT"
#new_head_meta='<meta http-equiv="Refresh" content="1">'
new_head_meta=''''''
in_file=''
onos_automatic_javascript=''
try:
  with codecs.open("refreshPage.html",'r',encoding='utf8') as f:
      in_file = f.read()
      onos_automatic_javascript=in_file

except Exception, e :
  print "error i can't find refreshPage.html,    e:"+str(e.args)
  errorQueue.put("error i can't find refreshPage.html,    e:"+str(e.args))
  onos_automatic_javascript="error_loading refreshPage.html"

#in_file=open("refreshPage.html","r")     #get the javascript code to reload the webpages
#new_javascript= in_file.read()
#onos_automatic_javascript=in_file

#document.getElementById("content").innerHTML = "whatever";

web_page_not_found='<html><head><style type="text/css"></style></head><body>error  no index.html found in the  directory </body></html>' 


print "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"





get_zone_manager_inner_html='''<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="/css/zone-setup-css.css" type="text/css" media="all" />
  <meta name="viewport" content="width=device-width" , initial-scale=1, maximum-scale=1"> 
  <meta charset="utf-8">
  <title>O.N.O.S</title>
<script type="text/javascript" language="javascript">function SelectAll(id){    document.getElementById(id).focus();   document.getElementById(id).select();}</script>
</head>
<body>
<form action="" method="POST"><input type="hidden" name="zone_manager" value="/setup/zone_manager">

  
<div id="buttons">
  <input type="submit" value="Submit">
  <a href="/"><div id="home">HOME</div></a>
  <a href="/setup/"><div id="back">BACK</div></a>

</div>
  

 <div id="header">ZONE SETUP</div>


<div id="riga">

<input type="text" id="new_room_form"  name="new_room" onclick="SelectAll('new_room_form')";  value="TYPE NEW ROOM HERE AND CLICK SUBMIT">

</div>
'''





oldpag=" "
old_zoneDict={}
old_object_dict={}
old_web_page=" "

baseDir=""

nothing_changed=0






#object_dict  contain all the web_object  and the key of the dictionary for each web_object is the name of the web_object


notes="Enter_The_Web_Object_Notes"
no_pin_selected="no_pin"
type_b="checked"
type_sb=""
type_l=""
current_status0=" "
current_status1=" "
style0="/*Enter here the style you want your web object to have when its status is 0 */"
style1="/*Enter here the style you want your web object to have when its status is 0 */"
html0="<!-- Enter here the html you want your web object to display when its status is 0  -->"
html1="<!-- Enter here the html you want your web object to display when its status is 1  -->"
autoCssIndicator='/*soacdnrtc start of automatic css,do not remove this comment*/'
reload_page_indicator='<!--soacdnrtc start of the part reloaded by the browser by javascript --> <div id="ReloadThis" >'
reload_page_end_indicator='<!--soacdnrtc end of the part reloaded by the browser by javascript--></div>'
command0=" "
command1=" "
init_command=" "



 


#os.system('''ntpd -q -p 0.openwrt.pool.ntp.org''') 

#try:
  
#  prof = open('/etc/profile', 'r')
#  profile=prof.read()
#  prof.close()
   #print profile
#  if (string.find(profile,timezone)== -1) :
#    os.system('echo "export TZ='+timezone+'">> /etc/profile') ##export TZ="CET-1CEST,M3.5.0,M10.5.0/3"
#    print " onos set the timezone to:"+timezone
#    os.system("source /etc/profile") #reload the profile to update time
#  else:
#    print "timezone ok"
  #banana to add the change of the line to change the timezone
#except:
#  print "error onos can't set the timezone!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"





def compareText(a,b): #return true if a==b
[docs] ret=0 try: a.decode('UTF-8')==b.decode('UTF-8') ret=1 except: ret=-1 print "error cant decode ",a print "or" print "cant decode ",b return (ret) def sortZonesByOrderNumber():
[docs] print "sortZonesByOrderNumber() executed" zone_list=[] print zoneDict for a in range (0,len(zoneDict.keys())): for b in zoneDict.keys(): if (a==zoneDict[b]["order"]) : # select the next zone by the order number zone_list.append(b) print "list returned:",zone_list return(zone_list) def changeWebObjectType(objName,typeToSet):#change the type of webobject and the relative pin mode in hardware_node class
[docs] print "executed changeWebObjectType() with :"+objName if objName in object_dict.keys(): #if the web object exist object_dict[objName].setType(typeToSet) pinList=object_dict[objName].getAttachedPinList() if pinList!=[9999] : #if there is a pin attached to this webobject obj_type=object_dict[objName].getType() SerialNumber=object_dict[objName].getHwNodeSerialNumber() pins_to_set=object_dict[objName].getAttachedPinList() node_address=nodeDict[SerialNumber].getNodeAddress() if (obj_type=="sr_relay"): if len (pins_to_set)!=2: print "error , number of pins different from 2 for sr_relay type " errorQueue.put("error , number of pins different from 2 for sr_relay type ") return(-1) hardware.setHwPinMode(node_address,pins_to_set[0],"DOUTPUT") hardware.setHwPinMode(node_address,pins_to_set[1],"DOUTPUT") nodeDict[SerialNumber].setNodePinMode(pins_to_set[0],"DOUTPUT") nodeDict[SerialNumber].setNodePinMode(pins_to_set[1],"DOUTPUT") return(1) if len (pins_to_set)!=1: # under this i put every object with one single hardware pin print "error , number of pins different from 1 for this obj type " errorQueue.put("error , number of pins different from 1 for this obj type ") return(-1) if ((typeToSet=="b")|(typeToSet=="sb")): hardware.setHwPinMode(node_address,pins_to_set[0],"DOUTPUT") nodeDict[SerialNumber].setNodePinMode(pins_to_set[0],"DOUTPUT") if (typeToSet=="d_sensor"): hardware.setHwPinMode(node_address,pins_to_set[0],"DINPUT") nodeDict[SerialNumber].setNodePinMode(pins_to_set[0],"DINPUT") if (typeToSet=="a_sensor"): hardware.setHwPinMode(node_address,pins_to_set[0],"AINPUT") nodeDict[SerialNumber].setNodePinMode(pins_to_set[0],"AINPUT") if (typeToSet=="pwm_output"): hardware.setHwPinMode(node_address,pins_to_set[0],"AOUTPUT") nodeDict[SerialNumber].setNodePinMode(pins_to_set[0],"AOUTPUT") else: print "the webobject:"+objName+" doesn't exist" return() def replace_functions(scenario_functions,scenario_name):#given a string ,replace web_object names with their value obsolete
[docs] scenario_functions=scenario_functions.replace("!","not ") while 1: # until all the objects are replaced by their value try: objname=re.search(r"#_.+?_#",scenario_functions).group(0)[2:-2] except Exception, e : print "no objects found in the scenario_functions or scenario_functions fully analyzed "+" e:"+str(e.args) #errorQueue.put("no objects found in the scenario_functions or scenario_functions fully analyzed "+" e:"+str(e.args)) break #errorQueue.put("error00 in the scenario operation search ,scenario_functions: "+scenario_functions) if objname is None: print ("error002 in the scenario operation search ,nonetype "+scenario_functions) errorQueue.put("error002 in the scenario operation search ,nonetype "+scenario_functions) return(-1) try: scenario_functions=scenario_functions.replace("#_"+objname+"_#",str(object_dict[objname].getStatusForScenario())) except Exception, e : print "error01 the webobject does not exist in the dict, i close the scenario check,objname: "+objname+" e:"+str(e.args) errorQueue.put("error01 the webobject does not exist in the dict, i close the scenario check ,objname: "+objname+" e:"+str(e.args)) return(-1) # now all the obj value are replaced try:# replace all the #p_webobjectname_# with the previous webobject status value scenario_functions=re.sub(r'#p_.+?_#',lambda x: str( object_dict[x.group(0)[3:-2]].getPreviousStatusForScenario()),scenario_functions) except Exception, e : print "error1 the webobject does not exist in the dict, i close the scenario check"+" e:"+str(e.args) errorQueue.put("error1 the webobject does not exist in the dict, i close the scenario check: scenario_condition:"+scenario_functions+",scenario_name"+scenario_name+" e:"+str(e.args)) return(-1) print "scenario_functions replaced:",scenario_functions return(scenario_functions) def replace_conditions(scenario_conditions,scenario_name):#given a string ,replace web_object names with their value
[docs] obj_list=[] scenario_conditions=scenario_conditions.replace("!","not ") while 1: # until all the objects are replaced by their value objname_prev="" try: objname=re.search(r"#_.+?_#",scenario_conditions).group(0)[2:-2] except Exception, e : #ended the simple objects status #errorQueue.put("no objects found in the scenario_conditions or scenario_conditions fully analyzed "+" e:"+str(e.args)) try: objname_prev=re.search(r"#p_.+?_#",scenario_conditions).group(0)[3:-2] except: #no previus object status found , serch terminated objname_prev="" print "no objects found in the scenario_conditions or scenario_conditions fully analyzed "+" e:"+str(e.args) break #errorQueue.put("error00 in the scenario operation search ,scenario_conditions: "+scenario_conditions) if objname is None: print ("error002 in the scenario operation search ,nonetype "+scenario_conditions) errorQueue.put("error002 in the scenario operation search ,nonetype "+scenario_conditions) return(-1) try: scenario_conditions=scenario_conditions.replace("#_"+objname+"_#",str(object_dict[objname].getStatusForScenario())) obj_list.append(objname) if (len(objname_prev)>0 )&(objname_prev!="")&(objname_prev not in obj_list ): #if there is a #p_objectName_# obj_list.append(objname) except Exception, e : print "error01 the webobject does not exist in the dict, i close the scenario check,objname: "+objname+" e:"+str(e.args) errorQueue.put("error01 the webobject does not exist in the dict, i close the scenario check ,objname: "+objname+" e:"+str(e.args)) return(-1) # now all the obj value are replaced try:# replace all the #p_webobjectname_# with the previous webobject status value scenario_conditions=re.sub(r'#p_.+?_#',lambda x: str( object_dict[x.group(0)[3:-2]].getPreviousStatusForScenario()),scenario_conditions) except Exception, e : print "error1 the webobject does not exist in the dict, i close the scenario check"+" e:"+str(e.args) errorQueue.put("error1 the webobject does not exist in the dict, i close the scenario check: scenario_condition:"+scenario_conditions+",scenario_name"+scenario_name+" e:"+str(e.args)) return(-1) print "scenario_conditions replaced:",scenario_conditions return([scenario_conditions,obj_list]) def checkwebObjectScenarios(scenario_name):#check all the webobjects in the scenario passed
[docs] print "checkwebObjectScenarios() executed" if scenarios_enable==0 : print "scenario disabled" return() try: scenario_to_check=scenarioDict[scenario_name]#get the scenario from the dictionary except KeyError: print "error scenarioname:"+scenario_name+" not found in the dict" errorQueue.put(" error scenarioname:"+scenario_name+" not found in the dict") return() #scenario dictionary structure: # webObjectScenarios["change_lampobj"]{"enabled":1,"setType":"condition_to_set_status","one_time_shot":0,"autodelete":0,"actType":"nodelay","conditions":[cond1&cond2|cond3],"math":"","functionsToRun":[lamp1=0,lamp2=#_lamp2_#+1...],"afterDelayFunctionsToRun":[],"delayTime":0,"priority":0} # try: #if the index exist # scenario_web_obj_to_read=scenario_to_check["web_obj_to_read"] # except IndexError:#set the value to default # print "warning no object found in this scenario condition or math" # scenario_web_obj_to_read=[] try: #if the reference exist scenario_enabled=scenario_to_check["enabled"] except KeyError:#set the value to default scenario_enabled=1 if scenario_enabled!=1:# if the scenario is disabled exit print "scenario:"+scenario_name+" is disabled" return() # try: #if the reference exist # scenario_set_type=scenario_to_check["setType"] # except KeyError: # print "error scenario_set_type not in the scenario dictionary" try: #if the reference exist type_after_run=scenario_to_check["type_after_run"] except KeyError:#set the value to default type_after_run="0" try: #if the reference exist scenario_priority=scenario_to_check["priority"] except KeyError:#set the value to default scenario_priority=0 # try: #if the reference exist # scenario_math=scenario_to_check["math"] # except KeyError: #set the value to default # scenario_math="" try: #if the reference exist scenario_conditions=scenario_to_check["conditions"] except KeyError:#set the value to default print "error conditions not in scenario dictionary" errorQueue.put("error conditions not in scenario dictionary") scenario_conditions="0" if len(scenario_conditions)<1: scenario_conditions="0" print "error scenario conditions of "+scenario_name+"are a void string" errorQueue.put("error scenario conditions of "+scenario_name+" are a void string") print "scenario scenario_conditions : ",scenario_conditions if (scenario_conditions!="0")and(scenario_conditions!="1"): scenario_conditions=replace_conditions(scenario_conditions,scenario_name)[0] if scenario_conditions==-1: return(-1) print "scenario conditions after replace : ",scenario_conditions cond=0 #if the conditions are a void string .. try: cond=eval(scenario_conditions) except Exception, e : print "error in eval("+scenario_name+"), scenario_conditions="+str(scenario_conditions)+" e:"+str(e.args) errorQueue.put("error in eval("+scenario_name+"), scenario_conditions="+str(scenario_conditions)+" e:"+str(e.args)) if (cond==1): #the condition are true , onos will execute the operations print "scenario conditions are true" # try:# replace all #_webobjectname_# with the webobjectname status value # scenario_math=re.sub(r'#_.+?_#',lambda x: str(object_dict[x.group(0)[2:-2]].getStatus()),scenario_math) # except: # print "error the webobject does not exist in the dict, i close the scenario scenario_math check" # errorQueue.put("error2 the webobject does not exist in the dict, i close the scenario check: scenario_math:"+scenario_math) # return() # try:# and all the #p_webobjectname_# with the previous webobject status value # scenario_math=re.sub(r'#p_.+?_#',lambda x: str(object_dict[x.group(0)[3:-2]].getPreviousStatus()),scenario_math) # except : # print "error the webobject does not exist in the dict, i close the scenario scenario_math check" # errorQueue.put("error3 the webobject does not exist in the dict, i close the scenario check: #scenario_math:"+scenario_math) # return() # print "scenario scenario_math: ",scenario_math # if len(scenario_math)> 1: # try: # mathResultValue=str(eval(scenario_math)) #calculating the math expression from scenario_math # except: # print "error in eval(scenario_math) ,scenario_math="+str(scenario_math) # errorQueue.put("error in eval(scenario_math) ,scenario_math="+str(scenario_math)) # else: # mathResultValue="" executionList=[] #if "functions_to_run" in scenario_to_check.keys(): #if the reference exist try: scenario_functions_to_run=scenario_to_check["functionsToRun"] except Exception, e : print "scenario_functions_to_run of "+scenario_name+ " scenario is empty"+" e:"+str(e.args) errorQueue.put("scenario_functions_to_run of "+scenario_name+ " scenario is empty"+" e:"+str(e.args)) scenario_functions_to_run=[] #if "afterDelayFunctionsToRun" in scenario_to_check.keys(): #if the reference exist try: afterDelayFunctionsToRun=scenario_to_check["afterDelayFunctionsToRun"] except KeyError:#set the value to default afterDelayFunctionsToRun=[] try: delayTime=scenario_to_check["delayTime"] except KeyError:#set the value to default delayTime=0 for f in scenario_functions_to_run: #for each line of the functions_to_run #f=f.replace("#condvalue#","1") #f=f.replace("#mathvalue#",mathResultValue) f=f.replace("==","=") #replace == with = f=f.replace("!","not ") point=f.find("=") f_before_equal_sign=f[0:point] f_before_equal_sign=f_before_equal_sign.replace("#_","") f_before_equal_sign=f_before_equal_sign.replace("#p_","") f_before_equal_sign=f_before_equal_sign.replace("_#","") f=f[point+1:] while 1: # untill all the objects are replaced by their value try: objname=re.search(r"#_.+?_#",f).group(0)[2:-2] except: print "no objects found in the function_to_run or function_to_run fully analyzed " break #errorQueue.put("error00 in the scenario operation search ,scenario_conditions: "+scenario_conditions) if objname is None: print "error003 in the scenario operation search ,nonetype "+f errorQueue.put("error003 in the scenario operation search ,nonetype "+f) break try: f=f.replace("#_"+objname+"_#",str(object_dict[objname].getStatusForScenario())) except Exception, e : print "error003 the webobject does not exist in the dict, i close the scenario check of:"+scenario_name+",objname: "+objname+" e:"+str(e.args) errorQueue.put("error003 the webobject does not exist in the dict, i close the scenario check of:"+scenario_name+",objname: "+objname+" e:"+str(e.args)) return() # now all the obj value are replaced #try:# replace all #_webobjectname_# with the webobjectname status value # f=re.sub(r'#_.+?_#',lambda x: str(object_dict[x.group(0)[2:-2]].getStatus()),f) #except KeyError: # print "error0 the webobject does not exist in the dict, i close the scenario check,operation:"+f # errorQueue.put(" error0 the webobject does not exist in the dict, i close the scenario check,operation:"+f) # return() try:# replcace all the #p_webobjectname_# with the previous webobject status value f=re.sub(r'#p_.+?_#',lambda x: str(object_dict[x.group(0)[3:-2]].getPreviousStatusForScenario()),f) except Exception, e : print "error2 the webobject does not exist in the dict, i close the scenario function to run check"+" e:"+str(e.args) errorQueue.put(" error2 the webobject does not exist in the dict, i close the scenario function to run check"+" e:"+str(e.args)) return() executionList.append(f_before_equal_sign+"="+f) # if (scenario_set_type=="condition_to_set_status") : # scenario_set_type is condition_to_set_status #execute the executionList print "conditions verified and true, i execute the executionList " statusToSet="void" try: for op in executionList: print "operation to execute: ",op obj_to_change="void" str_status="void" try: obj_to_change=op.split("=" )[0] str_status=op.split("=" )[1] except Exception, e : print ("error in the split of op in executionList ,op="+op+"obj_to_change:"+obj_to_change+",str_status:"+str_status+" e:"+str(e.args)) errorQueue.put("error in the split of op in executionList ,op="+op+"obj_to_change:"+obj_to_change+",str_status:"+str_status+" e:"+str(e.args)) try: statusToSet= str(eval(str_status)) except Exception, e : #happens if statusToSet= inactive or onoswait statusToSet=str_status print "error in the eval of for op in executionList :str_status="+str(str_status)+",op="+op+" e:"+str(e.args) errorQueue.put("error in the eval of for op in executionList :str_status="+str(str_status)+",op="+op+" e:"+str(e.args)) if (statusToSet==True)or(statusToSet=="True"): statusToSet="1" if (statusToSet==False)or(statusToSet=="False"): statusToSet="0" if (object_dict[obj_to_change].validateStatusToSetObj(statusToSet)==1): #the status to set is valid for the object if obj_to_change in object_dict: print "scenario act to change the weboject: ",obj_to_change layerExchangeDataQueue.put( {"cmd":"setSts","webObjectName":obj_to_change,"status_to_set":statusToSet,"write_to_hw":1,"user":"scenario","priority":scenario_priority,"mail_report_list":[]}) else: print "error in scenario op,statusToSet is :"+statusToSet errorQueue.put("error in scenario op,statusToSet is :"+statusToSet ) except Exception, e : print "error in the scenario for loop (for op in executionList) "+" e:"+str(e.args) errorQueue.put("error in the scenario for loop (for op in executionList) "+" e:"+str(e.args)) if delayTime>0: print "create a new scenario...banana" currentDayTime=object_dict["dayTime"].getStatusForScenario() if (delayTime+currentDayTime) < 1440: # 1440 is 24 * 60 the max number of minuts in a day selectedMinutes=str(currentDayTime+delayTime) else: selectedMinutes=str((currentDayTime+delayTime)-1440 ) # restart the count from 0 minutes new_scenario_name="delay_from"+scenario_name c=0 while new_scenario_name in scenarioDict.keys(): # if the name already exist try another new_scenario_name=str(c)+"delay_from"+scenario_name c=c+1 print "created delay scenario named:"+new_scenario_name+"with conditions:dayTime=="+selectedMinutes print "now real time is "+str((datetime.datetime.today().minute+(datetime.datetime.today().hour)*60 ))+" obj time is"+str(currentDayTime) scenarioDict[new_scenario_name]={"enabled":1,"type_after_run":"autodelete","conditions":"#_dayTime_#=="+selectedMinutes,"functionsToRun":afterDelayFunctionsToRun,"afterDelayFunctionsToRun":[],"delayTime":0,"priority":scenario_priority} object_dict["dayTime"].attachScenario(new_scenario_name) if type_after_run=="autodelete": del scenarioDict[scenario_name] for a in object_dict.keys(): # delete the reference to this scenario from all the webobjects object_dict[a].removeAttachedScenario(scenario_name) if type_after_run=="one_time_shot": print "i disable the one_time_shot :"+scenario_name scenarioDict[scenario_name]["enabled"]=0 else: # #the condition are false print "the scenarios condition are false" print "end of checkwebObjectScenarios" return() def compose_error_mail(error_type,objName=""):
[docs] print "compose_error_mail executed" mailtext="" if error_type=="so_priority": obj_previous_status=object_dict[objName].getStatus() mailtext="onos_report_message,"+objName+",error_so_priority,obj stays,"+str(obj_previous_status) if error_type=="so_permissions": obj_previous_status=object_dict[objName].getStatus() mailtext="onos_report_message,"+objName+",error_so_permission,obj stays,"+str(obj_previous_status) if error_type=="wrong_password": mailtext="onos_report_message,error_password,the password you send is wrong please check it" if error_type=="wrong_username": mailtext="onos_report_message,error_username,your username does not exist please add it from local web interface" if error_type=="white_list": mailtext="onos_report_message,error_white_list,your mail is not in the white_list please add it from local web interface" if error_type=="so_obj_not_exist": mailtext="onos_report_message,"+objName+",not_exist, webobject name does not exist please check it" if error_type=="so_value": mailtext="onos_report_message,error_so_value,value not compatible with webobject please check it" if error_type=="parse_mail": mailtext="onos_report_message,error_mail_parse,please check your mail syntax" mailtext=mailtext+"\n" return(mailtext) def changeWebObjectStatus(objName,statusToSet,write_to_hardware,user="onos_sys",priority=0,mail_report_list=[]):#change a webobj status and its relative pin in the hardware_node class.
[docs] print "changeWebObjectStatus executed with obj="+objName if objName not in object_dict.keys(): #if the web object does not exist exit print "error the webobject does NOT exist in the dictionary object_dict " errorQueue.put(" error the webobject does NOT exist in the dictionary object_dict") return(-1) obj_previous_status=object_dict[objName].getStatus() # if (obj_previous_status==statusToSet): #&(write_to_hardware==1) : #the obj status didn't change # print "the webobject "+objName+"has already the status value you want to set " # errorQueue.put("the webobject "+objName+" has already the status value you want to set ") # return(1) print "write_to_hardware="+str(write_to_hardware) print "attached pin0 ="+str(object_dict[objName].getAttachedPinList()[0])+";" global nodeDict #print "24444444444444444444444444444444444444444444444444444444444",object_dict[objName].getMailReport() mail_report_list=mail_report_list+object_dict[objName].getMailReport() #summ the 2 list mail_report_list=list(set(mail_report_list)) #removes duplicates #print "2222222222222222222222222222222222222222222222222222222222222",mail_report_list if object_dict[objName].checkRequiredPriority(priority)==1: #check priority print "priority ok" else: #obj_previous_status=object_dict[objName].getStatus() mailText=compose_error_mail("so_priority",objName) mailSubject="onos_report_error"+objName for m in mail_report_list: #sendMail(m,mailtext,mailSubject,onos_mail_conf,smtplib,string) mailQueue.put({"mail_address":m,"mailText":mailText,"mailSubject":mailSubject}) print "error ,required priority is "+str(object_dict[objName].required_priority()) errorQueue.put("error priority not sufficent to change"+objName+" ,required priority is "+str(object_dict[objName].required_priority()) ) return(-1) if object_dict[objName].checkPermissions(user,"x",priority): #check permission print "permission ok, i set the obj" else: #obj_previous_status=object_dict[objName].getStatus() mailText=compose_error_mail("so_permissions",objName) mailSubject="onos_report_error"+objName for m in mail_report_list: #sendMail(m,mailtext,mailSubject,onos_mail_conf,smtplib,string) mailQueue.put({"mail_address":m,"mailText":mailText,"mailSubject":mailSubject}) print "error Permissions not sufficent to change"+objName+",required required permission is "+str(object_dict[objName].getPermissions()) errorQueue.put("error Permissions not sufficent to change"+objName+",required permission is "+str(object_dict[objName].getPermissions())) return(-1) # global object_dict #banana to remove? if (int(object_dict[objName].getAttachedPinList()[0]))==9999 : #if there is no pins attached to this webobject print "no pin attached to this webobject , i change its status" write_to_hardware=0 if (write_to_hardware==0): print "i change the webobject status" object_dict[objName].setStatus(statusToSet)#set the web object status if (priority!=99): #if priority == 99 will not write to webobject the new priority object_dict[objName].setRequiredPriority(priority) #set the webobject priority if len(mail_report_list)>0: print "mail_report,"+objName+" changed to "+str(statusToSet) mailText="onos_report_message,"+objName+",changed to:"+str(statusToSet) mailSubject="onos_report_about"+objName for m in mail_report_list: #sendMail(m,mailtext,mailSubject,onos_mail_conf,smtplib,string) mailQueue.put({"mail_address":m,"mailText":mailText,"mailSubject":mailSubject}) scenarios_list=[] scenarios_list=object_dict[objName].getListAttachedScenarios() #get the list of scenarios where there is a reference to this webobject print "scenarios_list:",scenarios_list for tmp_scenario in scenarios_list: print "scenario name:"+tmp_scenario #banana to add to queue layerExchangeDataQueue.put( {"cmd":"scen_check","scenarioName":tmp_scenario}) #checkwebObjectScenarios(tmp_scenario) return(1) #if write_to_hardware==1 then print "write_to_hardware="+str(write_to_hardware) try:# objName in object_dict.keys(): #if the web object exist banana to remove print "the web object:"+objName+" exist in the dict" nodeSerialNumber=object_dict[objName].getHwNodeSerialNumber() if nodeDict[nodeSerialNumber].getNodeActivity()==0: print "the web_object"+objName+" belongs to a disconnected node, i will not set it" errorQueue.put("the web_object"+objName+" belongs to a disconnected node, i will not set it") return(-1) #except: # print "statusToSet "+statusToSet+"can't be converted to a number " # errorQueue.put("statusToSet "+statusToSet+"can't be converted to a number, obj:"+objName) if (object_dict[objName].validateStatusToSetObj(statusToSet)<1): print "error the state"+str(statusToSet)+"is not valid for the obj:"+objName errorQueue.put("error the state"+str(statusToSet)+"is not valid for the obj:"+objName) return(-1) statusToSet=int(statusToSet) #int nit float otherwise there will be errors #obj_previous_status=object_dict[objName].getStatus() #if statusToSet==obj_previous_status: # print "nothing to change,the webobject status is already :"+str(obj_previous_status) # return(1) #if True: # to remove.. print "there are one or more pins attached to this webobject" object_dict[objName].setStatus("onoswait")#set the wait status pins_to_set=object_dict[objName].getAttachedPinList() #single_pin=pins_to_set[0] #nodeSerialNumber=object_dict[objName].getHwNodeSerialNumber() print "obj node="+str(nodeSerialNumber) #print nodeDict[nodeSerialNumber].getNodeName() print "pins_to_set=",pins_to_set print "status_to_set=",statusToSet obj_type=object_dict[objName].getType() print "obj_name="+objName print "obj_type="+obj_type #nodeAddress=nodeDict[nodeSerialNumber].getNodeAddress() if (obj_type=="sr_relay"): if len (pins_to_set)!=2: print "error , number of pins different from 2 for sr_relay type " errorQueue.put(" error , number of pins different from 2 for sr_relay type") return(-1) if statusToSet==1: # set to 5 volt the set coil of the relay and reset the reset coil of the relay #note the set coil command is the first pin in the list , the second is the reset coil command #nodeDict[nodeSerialNumber].setDigitalPinOutputStatus(pins_to_set[0],1) #nodeDict[nodeSerialNumber].setDigitalPinOutputStatus(pins_to_set[1],0) hardware.outputWrite(nodeSerialNumber,pins_to_set,[1,0],nodeDict[nodeSerialNumber],objName,obj_previous_status,statusToSet,obj_type,user,priority,mail_report_list) # note that hardware=router_handler.RouterHandler(router_hardware,router_sn) in conf.py # put to rest the relay coil (the relay will continue to been mechanical activated) #nodeDict[nodeSerialNumber].setDigitalPinOutputStatus(pins_to_set[0],0) #nodeDict[nodeSerialNumber].setDigitalPinOutputStatus(pins_to_set[1],0) if statusToSet==0: # set to 5 volt the reset coil of the relay and put to 0v the set coil of the relay #nodeDict[nodeSerialNumber].setDigitalPinOutputStatus(pins_to_set[0],0) #nodeDict[nodeSerialNumber].setDigitalPinOutputStatus(pins_to_set[1],1) hardware.outputWrite(nodeSerialNumber,pins_to_set,[0,1],nodeDict[nodeSerialNumber],objName,obj_previous_status,statusToSet,obj_type,user,priority,mail_report_list) # put to rest the relay coil (the relay will continue to been mechanical activated) #nodeDict[nodeSerialNumber].setDigitalPinOutputStatus(pins_to_set[0],0) #nodeDict[nodeSerialNumber].setDigitalPinOutputStatus(pins_to_set[1],0) if (obj_type=="analog_output"): print "analog output still to develop" #banana to implement hardware.outputWrite(nodeSerialNumber,pins_to_set,[statusToSet],nodeDict[nodeSerialNumber],objName,obj_previous_status,statusToSet,obj_type,user,priority,mail_report_list) return(1) if (obj_type=="servo_output"): print "servo_output still to develop" #banana to implement hardware.outputWrite(nodeSerialNumber,pins_to_set,[statusToSet],nodeDict[nodeSerialNumber],objName,obj_previous_status,statusToSet,obj_type,user,priority,mail_report_list) return(1) if ((obj_type=="b")|(obj_type=="sb")|(obj_type=="digital_output")): #banana to check and leave only digital_output if (len (pins_to_set))!=1: print "error , number of pins different from 1 for button type " errorQueue.put("error , number of pins different from 1 for button type , doutput section ") return(-1) #nodeDict[nodeSerialNumber].setDigitalPinOutputStatus(pins_to_set[0],statusToSet) #if (write_to_hardware==1): #only if you tell to write to hardware hardware.outputWrite(nodeSerialNumber,pins_to_set,[statusToSet],nodeDict[nodeSerialNumber],objName,obj_previous_status,statusToSet,obj_type,user,priority,mail_report_list) return(1) if (obj_type=="d_sensor")|(obj_type=="digital_input"): #banana to check and leave only digital_input if (len (pins_to_set))!=1: print "error , number of pins different from 1 for d_sensor type " errorQueue.put("error , number of pins different from 1 for d_sensor type dread section ") return(-1) #nodeDict[nodeSerialNumber].setDigitalPinInputStatus(pins_to_set[0],statusToSet) #if (write_to_hardware==1): #only if you tell to write to hardware hardware.outputWrite(nodeSerialNumber,pins_to_set,[statusToSet],nodeDict[nodeSerialNumber],objName,obj_previous_status,statusToSet,obj_type,user,priority,mail_report_list) return(1) except Exception, e : # the webobject does not exist print "the webobject:"+objName+" doesn't exist,or others error happened"+" e:"+str(e.args) errorQueue.put("the webobject:"+objName+" doesn't exist,or others error happened"+" e:"+str(e.args)) return(-1) return(1) def NodePinToWebObject(node_sn,pin_number,pin_status):#change the webobject status given a node ,a pin and a status to set
[docs] write_hw_enable=0 for a in object_dict.keys(): #print object_dict[a].getHwNodeSerialNumber() if (object_dict[a].getHwNodeSerialNumber()==node_sn): #print "node exist" if object_dict[a].getAttachedPinList()[0]==int(pin_number): if (len(object_dict[a].getAttachedPinList())==1):#the sensor object must have only a pin attached if (object_dict[a].validateStatusToSetObj(pin_status)<1): print "error NodePinToWebObject the state"+str(pin_status)+"is not valid for the obj:"+a errorQueue.put("error NodePinToWebObject the state"+str(pin_status)+"is not valid for the obj:"+a) else:#the status is legit with the webobj type objName=object_dict[a].getName() #changeWebObjectStatus(objName,int (pin_status),write_hw_enable) #banana add to queue layerExchangeDataQueue.put( {"cmd":"setSts","webObjectName":objName,"status_to_set":str (pin_status),"write_to_hw":write_hw_enable,"user":"onos_node","priority":99,"mail_report_list":[]}) print "pin changed from external node" else: print "error number of pin in the NodePinToWebObject section" errorQueue.put("error number of pin in the NodePinToWebObject section" ) return() def setWebObjectDigitalStatusFromReg(node_sn_tmp,section_number,status_byte):
[docs] #change the webobject digital status given a node ,a number of section and the digital status register pinToWrite=nodeDict[node_sn_tmp].setNodeSectionDInputStatus(section_number,ord(status_byte)) if pinToWrite is not None: for pin in pinToWrite.keys(): status=pinToWrite[pin] NodePinToWebObject(node_sn_tmp,pin,status) else: print "void register" return() #def setWebObjectAnalogStatusFromReg(node_sn_tmp,analog_pin,analog_byte0,analog_byte1): def setWebObjectAnalogStatusFromReg(node_sn_tmp,analog_pin,analog_byte0):
[docs] #change the webobject analog status given a node ,an analog pin number and 2 byte register containing the analog value #analogvalue=nodeDict[node_sn_tmp].setNodeAnalogInputStatusFromReg(analog_pin,ord(analog_byte0),ord(analog_byte1)) analogvalue=nodeDict[node_sn_tmp].setNodeAnalogInputStatusFromReg(analog_pin,ord(analog_byte0),0) if analogvalue is not None: NodePinToWebObject(node_sn_tmp,analog_pin,analogvalue) else: print "void register" return() def updateNodeInputStatusFromReg(node_sn0,register):
[docs]#decode the data register and then change the web objects status # and update the node status values print "updateNodeInputStatusFromReg excuted with data="+register print "first byte= "+str(ord(register[0])) print "len reg="+str(len(register)) setWebObjectDigitalStatusFromReg(node_sn0,0,register[0]) setWebObjectDigitalStatusFromReg(node_sn0,1,register[1]) setWebObjectDigitalStatusFromReg(node_sn0,2,register[2]) setWebObjectDigitalStatusFromReg(node_sn0,3,register[3]) setWebObjectDigitalStatusFromReg(node_sn0,4,register[4]) setWebObjectDigitalStatusFromReg(node_sn0,5,register[5]) setWebObjectDigitalStatusFromReg(node_sn0,6,register[6]) setWebObjectDigitalStatusFromReg(node_sn0,7,register[7]) setWebObjectDigitalStatusFromReg(node_sn0,8,register[8]) msgr=" " for b in range (0,len(register)): msgr=msgr+str(ord(register[b]))+"," print "rx reg:"+msgr # time.sleep(3)#banana to remove first_analog_pin=14 last_analog_pin=19 node_hw_type=nodeDict[node_sn0].getHwType() if ( (node_hw_type=="arduino2009")or(node_hw_type=="arduino_promini")or(node_hw_type=="arduino_uno")): first_analog_pin=14 last_analog_pin=19 if ((node_hw_type=="arduino_mega1280")or(node_hw_type=="arduino_mega2560") ): first_analog_pin=54 last_analog_pin=69 #on k=9 there is 'a' k=10 for a_pin in range (first_analog_pin,last_analog_pin+1): #for each analog pin in the hardware (2 bytes) if "analog_input" in (hardwareModelDict["ProminiA"]["pin_mode"]): if "a_sensor" in (hardwareModelDict["ProminiA"]["pin_mode"]["analog_input"]): if a_pin in (hardwareModelDict["ProminiA"]["pin_mode"]["analog_input"]["a_sensor"]): #if the pin is used as analog input then read its value and set it in the node try: # setWebObjectAnalogStatusFromReg(node_sn0,a_pin,register[k+1],register[k]) setWebObjectAnalogStatusFromReg(node_sn0,a_pin,register[k]) #print "analog register=first:"+str(ord(register[k]))+" second:"+str(ord(register[k+1])) print "analog register=first:"+str(ord(register[k])) print "analog real value="+str((ord(register[k]))) except:#banana ? error? print "end of analog" return() print "k="+str(k) #k=k+2 k=k+1 return() def updateNodeAddress(node_sn0,node_ip):# update the node address
[docs] try: #if (node_sn0 in nodeDict.keys()): nodeDict[node_sn0].updateLastNodeSync(time.time()) if (nodeDict[node_sn0].getNodeAddress())!=node_ip: print "node "+node_sn0+" ip changed to "+node_ip nodeDict[node_sn0].setNodeAddress(node_ip) else: print "the node has still the same ip" except: print "error in updateNodeAddress()" errorQueue.put( "error in updateNodeAddress()") return() def createNewWebObjFromNode(hwType0,node_sn):
[docs] progressive_number=node_sn # [-4:] #get 0001 from Plug6way0001 ,now get the full serial Plug6way0001 print "createNewWebObjFromNode executed with hwType0:"+hwType0 global zoneDict global object_dict print hardwareModelDict.keys() if hwType0 in hardwareModelDict.keys(): #if the type exist in the hardwareModelDict #hardwareModelDict["onosPlug6way"]["pin_mode"]["sr_relay"][0] print "i will create a new "+hwType0+"node " #hardwareModelDict["onosPlug6way"]={"max_pin":12,"hardware_type":"arduino_2009","pin_mode":{"sr_relay":{"socket":[(1,2),(3,4),(5,6),(7,8),(9,10),(11,12)]} } } list_of_different_objects_type=hardwareModelDict[hwType0]["pin_mode"].keys() #get a list of different obj print "list_of_different_objects_type:" print list_of_different_objects_type for a in list_of_different_objects_type: #now i'm inside #for example hardwareModelDict["onosPlug6way"]["pin_mode"] # so the first a will be "sr_relay" objType=a i=0 for b in hardwareModelDict[hwType0]["pin_mode"][a]: #now i'm inside #for example hardwareModelDict["onosPlug6way"]["pin_mode"]["sr_relay"] #print hardwareModelDict[hwType0]["pin_mode"][a][b] #so the first b will be "socket" list_of_different_webobject_names=hardwareModelDict[hwType0]["pin_mode"][a][b] i=0 for c in list_of_different_webobject_names: #print c #now i'm inside the last dictionary #the first c will be equal to (1,2) if the hwtype is sr_relay otherwise it will be like 1 #for example hardwareModelDict["onosPlug6way"]["pin_mode"]["sr_relay"]["socket"] #in this example there aren't other webobject names... if type(c) not in (tuple, list): #if c is not a list , trasform it in a list of one element c=[c] new_obj_name=b+str(i)+"_"+progressive_number i=i+1 if new_obj_name not in (zoneDict[node_sn]["objects"]): zoneDict[node_sn]["objects"].append(new_obj_name) #add the object name to the zone else: print "warning000 the object "+new_obj_name+" already exist in the zoneDict " if new_obj_name not in object_dict.keys(): #if the object does not exist yet, create it: print "added new webobj from node" object_dict[new_obj_name]=newNodeWebObj(new_obj_name,objType,node_sn,c) else: print "warning001 the object "+new_obj_name+" already exist in the object_dict" return() for a in objectList : # append to dictionary all the web object
object_dict[a.getName()]=a changeWebObjectType(a.getName(),a.getType()) #i call this in order to setup the node io conf for the webobjects a.InitFunction() s=a.getStartStatus() a.setStatus(s) for a in object_dict.keys():#check and remove the not used scenarios from web_object attachedScenarios for b in scenarioDict.keys(): if scenarioDict[b]["conditions"].find(a+"_#")==-1: # if the object is not in the conditions then remove it from web_object attachedScenarios object_dict[a].removeAttachedScenario(b) else: object_dict[a].attachScenario(b) #object_dict["dayTime"].attachScenario("scenario1") #banana to remove #object_dict["hours"].attachScenario("scenario2") #banana to remove #object_dict["hours"].attachScenario("scenario3") #banana to remove #object_dict["hours"].attachScenario("scenario4") #banana to remove #object_dict["hours"].attachScenario("scenario5") #banana to remove #object_dict["hours"].attachScenario("scenario6") #banana to remove #object_dict["hours"].attachScenario("scenario7") #banana to remove #object_dict["hours"].attachScenario("scenario10") #banana to remove #object_dict["minutes"].attachScenario("scenario2") #banana to remove #object_dict["minutes"].attachScenario("scenario3") #banana to remove #object_dict["minutes"].attachScenario("scenario4") #banana to remove #object_dict["minutes"].attachScenario("scenario5") #banana to remove #object_dict["minutes"].attachScenario("scenario6") #banana to remove #object_dict["minutes"].attachScenario("scenario7") #banana to remove #object_dict["minutes"].attachScenario("scenario8") #banana to remove #object_dict["wifi0_Plug6way0001"].attachScenario("scenario9") #banana to remove #object_dict["Wifi_netgear"].attachScenario("scenario10") #banana to remove #object_dict["Caldaia"].attachScenario("scenario11") #banana to remove #object_dict["button0_RouterGL0000"].setMailReport(["electronicflame@gmail.com"]) #banana to remove #object_dict["wifi0_Plug6way0001=0"].setMailReport(["electronicflame@gmail.com"]) #banana to remove #print "room dict=" #print zoneDict def formParse(text):
[docs] text=string.replace(text, "%20", " ") #removes the %20 that were created instead of the spaces text=string.replace(text, ',&%', '\n') text=string.replace(text, '%7D', '}') text=string.replace(text, '%7B', '{') return (text) #if there is a css of a web_object and option is to remove this web_object then find it and remove the css part #web_object #then find the id=web_object and remove it #if the option is "add" then find the "/*start of automatic css,do not remove this comment*/" and add after this the reative css #add also the id=web_object on the end of the body def findRoomName(path,roomDictionary):
[docs] print "findRoomName() executed" if (len(path)>0): address_list=string.split(path,"/") if address_list[1] in roomDictionary.keys() : #if the path is /anyroomname/.... take the room name room=address_list[1] return(room) else: print "no room name found" return (-1) #no room found return(-1) def modPage(htmlPag,WebObjectdictionary,zone,zoneDictionary):
[docs] #print "java"+onos_automatic_javascript #print htmlPag onos_automatic_meta='''<meta charset="utf-8"> <meta name="viewport" content="width=device-width">''' onos_automatic_css_style='' print "modPage() executed" if zone in zoneDictionary: zoneObjList=zoneDictionary[zone]["objects"] else: print "zone not in the system"+ str(zone) zoneObjList=[] return(htmlPag) tmp_pag=htmlPag try: onos_automatic_body_style=''' body {'''+WebObjectdictionary[zone+'_body'].getStyle()+'''}''' except: onos_automatic_body_style=' ' #print "no body obj found in zone"+zone #print zoneObjList #zoneObjList.sort() for obj in zoneObjList : onos_automatic_css_style=onos_automatic_css_style+'''#'''+obj+'''{'''+WebObjectdictionary[obj].getStyle()+'''}''' #print "zone+body="+zone+'_body' if string.find(obj,zone+"_body")!=-1:#skip to display the body obj continue #print 'obj='+obj status=WebObjectdictionary[obj].getStatus() onos_automatic_local_style='''style="'''+WebObjectdictionary[obj].getStyle()+'''"''' if (status==0)|(status=="0"): #banana to implement a method to allow analog status status_to_set="1" img_html='''<!--start_img'''+obj+'''--><img class="flex" src="/img/on.png" class="image" /> <!--end_img'''+obj+'''-->''' else: status_to_set="0" img_html='''<!--start_img'''+obj+'''--><img class="flex" src="/img/off.png" class="image" /> <!--end_img'''+obj+'''-->''' onos_automatic_object_html=WebObjectdictionary[obj].getHtml() onos_automatic_object_id=''' id="'''+obj+'''" ''' objType=WebObjectdictionary[obj].getType() if (objType=="b")|(objType=="sb")|(objType=="sr_relay")|(objType=="digital_output"): #banana to use group onos_automatic_object_href='''href="?'''+obj+'''='''+status_to_set+'''"''' onos_automatic_object= '''<a id="'''+obj+'''" onmousedown="stopUpdate()" onmouseout="restartUpdate()" '''+ onos_automatic_object_href+''' > '''+onos_automatic_object_html+'''</a>''' onos_automatic_object_a='''<a id="'''+obj+'''" onmousedown="stopUpdate()" onmouseout="restartUpdate()" '''+ onos_automatic_object_href+'''>''' else: onos_automatic_object_href='' onos_automatic_object= '''<a id="'''+obj+'''" > '''+onos_automatic_object_html+'''</a>''' onos_automatic_object_a='' #current_time_hours=(int(strftime("%M", gmtime()))+time_gap+( int(strftime("%H", gmtime())) )*60)//60 #current_time_minutes=(int(strftime("%M", gmtime()))+time_gap+(int(strftime("%H", gmtime())))*60)%60 #tmp_pag=tmp_pag.replace('''<!--onos_system_time-->''',str(current_time_hours)+":"+str(current_time_minutes)+":"+str(time.timezone),1) tmp_pag=tmp_pag.replace('''<!--onos_system_time-->''',str(time.localtime()[3])+":"+str(time.localtime()[4]),1) tmp_pag=tmp_pag.replace('''<!--onos_automatic_local_style-->''',onos_automatic_local_style, 1) tmp_pag=tmp_pag.replace('''<!--onos_automatic_object-->''',onos_automatic_object, 1) tmp_pag=tmp_pag.replace('''<!--onos_automatic_object_a-->''',onos_automatic_object_a, 1) tmp_pag=tmp_pag.replace('''<!--onos_automatic_object_id-->''',onos_automatic_object_id, 1) tmp_pag=tmp_pag.replace('''<!--onos_automatic_object_href-->''',onos_automatic_object_href, 1) tmp_pag=tmp_pag.replace('''<!--onos_automatic_object_html-->''',onos_automatic_object_html, 1) tmp_pag=tmp_pag.replace('''<!--start_img'''+obj+'''--><img class="flex" src="/img/on.png" class="image" /> <!--end_img'''+obj+'''-->''',img_html, 1) tmp_pag=tmp_pag.replace('''<!--start_img'''+obj+'''--><img class="flex" src="/img/off.png" class="image" /> <!--end_img'''+obj+'''-->''',img_html, 1) tmp_pag=tmp_pag.replace('''<!--onos_automatic_object='''+obj+'''-->''',onos_automatic_object) tmp_pag=tmp_pag.replace('''<!--onos_automatic_object_href='''+obj+'''-->''',onos_automatic_object_href) tmp_pag=tmp_pag.replace('''<!--onos_automatic_object_html='''+obj+'''-->''',onos_automatic_object_html) tmp_pag=tmp_pag.replace('''<!--onos_automatic_body_style-->''',onos_automatic_body_style, 1) tmp_pag=tmp_pag.replace('''<!--onos_automatic_meta-->''',onos_automatic_meta); tmp_pag=tmp_pag.replace('''<!--onos_automatic_javascript-->''',onos_automatic_javascript) tmp_pag=tmp_pag.replace('''<!--onos_automatic_css_style-->''',onos_automatic_css_style) # remove the unused reference tmp_pag=tmp_pag.replace('''<!--onos_automatic_local_style-->''',' ') tmp_pag=tmp_pag.replace('''<!--onos_automatic_object-->''',' ') tmp_pag=tmp_pag.replace('''<!--onos_automatic_object_id-->''',' ') tmp_pag=tmp_pag.replace('''<!--onos_automatic_object_href-->''',' ') tmp_pag=tmp_pag.replace('''<!--onos_automatic_object_html-->''',' ') tmp_pag=tmp_pag.replace('''<!--onos_automatic_object_a-->''','''style="visibility: hidden"''') #hide the unused <a> #because there are more request than the number of webobject in the zone ,hide the html for the empty ones.. return (tmp_pag) def getRoomHtml(room,object_dictionary,path,roomDictionary): #render the html to insert in the index.html of a room directory which must be inside the baseRoomPath directory, modify to read the html ..
[docs] print "getRoomHtml()executed" retval = os.getcwd() #you musn't have spaces on the path.. #print "retval:"+retval #x=retval+"/"room+"/index.html" print "room passed="+room x=retval+"/"+baseRoomPath+room+"/index.html" #x=string.replace(x, ',&%', '') #x=string.replace(x, '\n', '') readed_html="nothing" print "file to open="+x try: in_file=open(x,"r") readed_html = in_file.read() in_file.close() #readed_html =os.popen("cat "+x).read() # don't use the standard method because the file is opened otherwere except: print "can't open file:"+x+"end" #print "readed htm="+readed_html+"end" if (len(readed_html)>10)&(string.find(readed_html,'<!--onos_automatic_page-->')==-1): #if the file exist and is not automatic then serve it as it is #roomHtml=readed_html return(readed_html) #print "html parsed " #if (string.find(readed_html,'<!--onos_automatic_page-->')!=-1): #roomHtml=modPage(readed_html,object_dictionary,room,roomDictionary) # return(roomHtml) #else: # print " readed_html is:not <!--onos_automatic_page-->" # return(roomHtml) else: #modify or update the page print "readed_html is:not <!--onos_automatic_page-->" #if the file does not exist #roomHtml=play_zone_start_html+ '''<div id="header">'''+room.upper()+'''</div>''' if room in roomDictionary.keys(): cgi_name="gui/pag_creator.py" zone=zoneDict[room] namespace={} web_page="" try: execfile(cgi_name,locals(),namespace) #execute external script /gui/pag_creator.py roomHtml=namespace["web_page"] except Exception, e: print "error executing /gui/pag_creator.py e:"+str(e.args) errorQueue.put("error executing /gui/pag_creator.py e:"+str(e.args)) roomHtml="error executing /gui/pag_creator.py" return(roomHtml) def updateOneRoom(room):
[docs] retval = os.getcwd() html_file_location=retval+"/"+baseRoomPath+room+"/index.html" print "updateOneRoom() executed with room:"+room+";" if os.path.isfile(html_file_location): #if the directory exist don't create it print room+" exist so i don't create it" fileToWrite=getRoomHtml(room,object_dict,"",zoneDict) file0 = open(baseRoomPath+room+"/index.html", "w") file0.write(fileToWrite) file0.close() #os.system("chmod 777 "+html_file_location) with lock_bash_cmd: subprocess.call("chmod 777 "+html_file_location, shell=True,close_fds=True) else: print "i make the directory"+room #os.system("mkdir "+baseRoomPath+room) with lock_bash_cmd: subprocess.call("mkdir "+baseRoomPath+room, shell=True,close_fds=True) fileToWrite=getRoomHtml(room,object_dict,"",zoneDict) file0 = open(baseRoomPath+room+"/index.html", "w") file0.write(fileToWrite) file0.close() #os.system("chmod 777 "+html_file_location) with lock_bash_cmd: subprocess.call("chmod 777 "+html_file_location, shell=True,close_fds=True) return def updateDir():
[docs] retval = os.getcwd() print "updateDir() executed" for zone in zoneDict.keys() : #will be call updateOneRoom() ....onosimprove index=retval+"/"+baseRoomPath+zone+"/index.html" if os.path.isfile(index): #if the directory exist don't create it print zone+" exist so i don't create it" fileToWrite=getRoomHtml(zone,object_dict,"",zoneDict) file0 = open(baseRoomPath+zone+"/index.html", "w") file0.write(fileToWrite) file0.close() #os.system("chmod 777 "+baseRoomPath+zone+"/index.html") with lock_bash_cmd: subprocess.call("chmod 777 "+baseRoomPath+zone+"/index.html", shell=True,close_fds=True) else: print "create the file"+index #os.system("mkdir "+baseRoomPath+zone) with lock_bash_cmd: subprocess.call("mkdir "+baseRoomPath+zone, shell=True,close_fds=True) fileToWrite=getRoomHtml(zone,object_dict,"",zoneDict) try: file0 = open(index, "w") file0.write(fileToWrite) file0.close() with lock_bash_cmd: subprocess.call("chmod 777 "+baseRoomPath+zone+"/index.html", shell=True,close_fds=True) except Exception, e: print "error creating "+baseRoomPath+zone+"/index.html e:" +str(e.args) errorQueue.put("error creating "+baseRoomPath+zone+"/index.html e:" +str(e.args)) #os.system("chmod 777 "+baseRoomPath+zone+"/index.html") return def createNewNode(node_sn,node_ip,node_fw):
[docs] msg="" if node_sn in nodeDict.keys(): print "found node in the dict" #nodeDict[node_sn].setNodeAddress(node_ip) updateNodeAddress(node_sn,node_ip) msg=nodeDict[node_sn].getSetupMsg() else: #created a new node print "requested setup for a node not existing yet " hwType=node_sn[0:-4] #get Plug6way from Plug6way0001 #cut the last 4 char which are the numeric sn, in order to get only the type of hardware if (hwType in hardwareModelDict.keys()): #if the hardware is in the list print "added node_hw from url :"+hwType print "obj_type_to_add_from_node="+hwType hardware_node_model=hardwareModelDict[hwType] if((len(node_sn)>0)&((node_sn)!=" ")): nodeDict[node_sn]=hw_node.HwNode(node_sn,hardware_node_model,node_ip,node_fw) nodeDict[node_sn].updateLastNodeSync(time.time()) #nodeDict[node_sn].setNodeAddress(node_ip) msg=nodeDict[node_sn].getSetupMsg() #if the room doesn't exist yet ...then: if (node_sn in zoneDict.keys()): print "the node already exist in the zoneDict" else: # if (node_sn+"_body" in object_dict.keys()): # print "the node body already exist in the web_object_dict" # else: # object_dict[node_sn+"_body"]=newDefaultWebObjBody(node_sn+"_body") #zoneDict[node_sn]=[node_sn+"_body"] # modify to update also the webobject dict and list zoneDict[node_sn]={"objects":[],"order":len(zoneDict.keys()),"permissions":"777","group":[],"owner":"onos_sys","hidden":0} #create a new web_object and insert only his name #os.system("mkdir "+baseRoomPath+node_sn) with lock_bash_cmd: subprocess.check_output("mkdir "+baseRoomPath+node_sn, shell=True,close_fds=True) createNewWebObjFromNode(hwType,node_sn) try: text_file = open(baseRoomPath+node_sn+"/index.html", "w") text_file.write(getRoomHtml(node_sn,object_dict,"",zoneDict)) text_file.close() except Exception, e: print "error creating new node index file "+node_sn+" e:"+str(e.args) errorQueue.put("error creating new node index file "+node_sn+" e:"+str(e.args)) #os.system("cat "+getRoomHtml(node_sn,object_dict,"",zoneDict)+" >> "+baseRoomPath+node_sn+"/index.html") #os.system("chmod 777 "+baseRoomPath+node_sn) with lock_bash_cmd: subprocess.check_output("chmod 777 "+baseRoomPath+node_sn, shell=True,close_fds=True) print "create a new zone"+node_sn #print zoneDict updateOneRoom(node_sn) return(msg) def setNodePin(node_sn,pin_number,pin_status,write_hw_enable): # equal to NodePinToWebObject()
[docs] #to change all the webobjects status that have the node and the pin given: print "setNodePin() executed" if node_sn not in nodeDict.keys(): print "the serial number is not in the dictionary...so i add the new node" return("error_the_node_does_not_exist") found=0 for a in object_dict.keys(): print object_dict[a].getHwNodeSerialNumber() if (object_dict[a].getHwNodeSerialNumber()==node_sn): print "node exist" if object_dict[a].getAttachedPinList()[0]==int(pin_number): found=1 if (len(object_dict[a].getAttachedPinList())==1):#the sensor object must have only a pin attached objName=object_dict[a].getName() #changeWebObjectStatus(objName,int (pin_status),write_hw_enable) #banana add to queue layerExchangeDataQueue.put( {"cmd":"setSts","webObjectName":objName,"status_to_set":str(pin_status),"write_to_hw":write_hw_enable }) print "pin"+str(pin_number)+" changed from setNodePin to:"+str(pin_status) else: print "error number of pin in the setNodePin section" errorQueue.put("error number of pin in the setNodePin section" ) return("error_no_pin_found_in_the_node") if found==0: print "error_no_pin_found_in_the_node" errorQueue.put("error_no_pin_found_in_the_node" ) return("error_no_pin_found_in_the_node") else: return("ok") #router_sn is in globalVar.py createNewNode(router_sn,"0",router_hardware_fw_version) #make the router node
def transform_object_to_dict(object_dictionary):
[docs] obj_tmp_dict={} for b in object_dictionary.keys(): a=object_dictionary[b] #bug return ascii and not unicode? name=a.getName() obj_tmp_dict[name]={u"objname":name,u"obj_type":a.getType(),u"obj_status":a.getStatus(),u"obj_style0":a.getStyle0(),u"obj_style1":a.getStyle1(),u"obj_html0":a.getHtml0(),u"obj_html1":a.getHtml1(),u"obj_cmd0":a.getCommand0(),u"obj_cmd1":a.getCommand1(),u"obj_init_cmd":a.getInitCommand(),u"obj_notes":a.getNotes(),u"node_serial_number":a.getHwNodeSerialNumber(),u"obj_Pins":a.getAttachedPinList()} return (obj_tmp_dict) def transform_object_to_dict_to_backup(object_dictionary):
[docs] obj_tmp_dict={} for b in object_dictionary.keys(): a=object_dictionary[b] #bug return ascii and not unicode? name=a.getName() obj_tmp_dict[name]=a.getObjectDictionary() return (obj_tmp_dict) def updateJson(object_dictionary,roomDictionary,scenarioDictionary): # save the current config to a json file named data.json
[docs] print "updateJson executed" #json doesn't support saving objects ..so i save all the variables of each objects #to get back the pin of the object you have to write: # dictionary_group[u"objectDictionary"][u"name_of_the_object"][u"obj_pin"] obj_tmp_dict=transform_object_to_dict_to_backup(object_dictionary) node_tmp_Dict={} for b in nodeDict.keys(): a=nodeDict[b] sn=a.getNodeSerialNumber() node_tmp_Dict[sn]={u"node_serial_number":sn,u"hwModelName":a.getNodeHwModel(),u"nodeAddress":a.getNodeAddress()} # note that the i/o modes for the node pins will be saved in the relative webobjects . # the pins not used by a webobject will be configured as output and cleared to 0 #print object_dictionary #print roomDictionary dictionary_group={u"objectDictionary":obj_tmp_dict,u"roomDictionary":roomDictionary,u"nodeDictionary":node_tmp_Dict,u"scenarioDictionary":scenarioDictionary} #combined dictionary #to add a new dictionary just add it in dictionary_group #print dictionary_group dictionary_group_json=json.dumps(dictionary_group, indent=2,sort_keys=True) #make the json structure file_to_save =codecs.open(base_cfg_path+"config_files/data.json","w","utf8") #utf8 is a type of encoding for unicode strings file_to_save.write(dictionary_group_json) file_to_save.close() conf_option={u"online_server_enable":online_server_enable,u"enable_mail_service":enable_mail_service,u"accept_only_from_white_list":accept_only_from_white_list,u"mail_whiteList":mail_whiteList,u"timezone":timezone,u"login_required":login_required,u"logTimeout":logTimeout,"online_usersDict":online_usersDict,"enable_onos_auto_update":enable_onos_auto_update} conf_option_json=json.dumps(conf_option, indent=2,sort_keys=True) #make the json structure file_to_save2 =codecs.open(base_cfg_path+"config_files/cfg.json","w","utf8") #utf8 is a type of encoding for unicode strings file_to_save2.write(conf_option_json) file_to_save2.close() #banana to load #moved to conf.py #def newDefaultWebObj(name): # return(WebObject(name,"b",0,"/*background-color:green;*/","/*background-color:red;*/",name+"=0",name+"=1"," "," "," "," ",9999)) updateDir()
def getUserFromIp(ipUserAddress):
[docs] print "getUserFromIp() executed" if ipUserAddress in user_active_time_dict.keys(): # the ip is in the dict username=user_active_time_dict[ipUserAddress][0] old_active_time=user_active_time_dict[ipUserAddress][1] current_time=(datetime.datetime.today().minute+(datetime.datetime.today().hour)*60 ) if (current_time >(old_active_time+logTimeout) ): #timeout #if user was not active in the last 10 minutes logout print "user:"+username+"logged out for timeout" del user_active_time_dict[ipUserAddress] #remove the ip from the dict print "deleted ip from user_active_time_dict " return (-1) else: print "user:" +username+"is still active" user_active_time_dict[ipUserAddress][1]=current_time return(username) else: print "ipaddress not in list" return(-1) class MyHandler(BaseHTTPRequestHandler):
[docs] #global object_dict #global roomDict wbufsize = -1 # Disable Nagle's Algorithm (Python 2.7/3.2 and later). disable_nagle_algorithm = True if not hasattr(BaseHTTPRequestHandler, 'disable_nagle_algorithm'): #http://pydoc.net/Python/mrs-mapreduce/0.9/mrs.http/ https://aboutsimon.com/index.html%3Fp=85.html def setup(self): BaseHTTPRequestHandler.setup(self) if self.disable_nagle_algorithm: self.connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True) def finish(self,*args,**kw):
[docs] #print "finish function called to close socket" #if not self.wfile.closed: # self.wfile.flush() #self.wfile.close() #self.rfile.close() if not self.wfile.closed: try: self.wfile.flush() self.wfile.close() except : print "error in flush finish() socket closed " errorQueue.put( "error in flush finish() socket closed ") pass #ignore the error try: self.wfile.close() except: pass #ignore the error print "error in self.wfile.close() finish() socket closed " errorQueue.put( "error in self.wfile.close() finish() socket closed ") try: self.rfile.close() except: pass print "error in self.wfile.close() self.rfile.close() socket closed " errorQueue.put("error in self.wfile.close() self.rfile.close() socket closed " ) return def clear_PostData(self,data):
[docs] if len(data)==0: print "empty form" return ("") tmp_data=data i=0 en=0 while ((i<len(data))&(data[i]==" ")): #remove all the starting spacing i=i+1 tmp_data=data[i:] i=len(tmp_data)-1 while ((i>0)&(tmp_data[i]==" ")): #remove all the spacing after the end of string i=i-1 tmp_data=tmp_data[0:i+1] tmp_data=string.replace(tmp_data, " ", "_") return(tmp_data) # self.path=string.replace(self.path, "%20", " ") #rimuovo i %20 che si formano al posto degli spazii # self.path=string.replace(self.path, ',&%', '\n') # self.path=string.replace(self.path, '%7D', '}') # self.path=string.replace(self.path, '%7B', '{') def get_login(self):
[docs] #self.send_response(301) #self.send_header('Location','/login.html') #self.end_headers() try: h = open("gui/login.html",'r') web_page=h.read() h.close() except: print "no index.html found in root directory" web_page=web_page_not_found try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(web_page) except: pass print "error1 in send_header " errorQueue.put( "error1 in send_header ") return def get_WebOjectManager(self,obj_Dict):
[docs] html_page='''<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="/css/objects_manager.css" type="text/css" media="all" /> <meta charset="utf-8"> <title>Web Objects Manager</title> <script type="text/javascript" language="javascript">function SelectAll(id){ document.getElementById(id).focus(); document.getElementById(id).select();}</script> </head> <body> <form action="" method="POST"><input type="hidden" name="objs_manager" value="/setup/objs_manager"> <div id="buttons"> <a href="/"><div id="home">HOME</div></a> <a href="/setup/"><div id="back">BACK</div></a> </div> <div id="header">WEB OBJECTS MANAGER</div> <div id="testo"> <input type="text" id="create_web_obj" onclick="SelectAll('create_web_obj')"; name="new_web_object" value="TYPE A NEW OBJECT NAME HERE"> <input type="submit" value="CREATE"> </form> </div> ''' l=obj_Dict.keys() l.sort() for a in l: html_page=html_page+''' <div id="riga"> <div id="NOMEOGGETTO">'''+a+'''</div> <a href="/setup/web_obj_modifier/'''+a+'''" ><div id="SETUP">SETUP</div></a> <a href="/setup/web_obj_modifier/delete_item/'''+a+'''"><div id="DELETE">DELETE</div></a> </div> ''' html_page=html_page+''' <div id="riga" style=" visibility: hidden;"> <div id="NOMEOGGETTO"></div> <div id="SETUP"></div> <div id="DELETE"></div> </div> ''' html_page=html_page+'''</body></html>''' return(html_page) def get_zone_manager(self,r_Dict):
[docs] r_list=r_Dict.keys() r_list.sort() #sort room by name html='' for a in r_list : html=html+'''<div id="riga"> <div id="nomezona">'''+a+'''</div> <input type="text" id="'''+a+'''" name="'''+a+'''" value="RENAME IT AND CLICK SUBMIT"> <div id="deletebox"> <div id="DELETE">DELETE</div> <input id="'''+a+'''" type="checkbox" name="delete_room_'''+a+'''" /> </div> <a href="/zone_objects_setup/'''+a+'''"><div id="oggetti">Objects</div> </a> </div> ''' html_p=get_zone_manager_inner_html+html+'''</form> </body> </html>''' return (html_p) def get_Zone_Objects_Setup(self,current_path,objectDictionary,zone):
[docs] print "current_path"+current_path if string.find(current_path,"/setup")!=-1: link_back="/setup/zone_manager/" else: link_back="/zone_list" html_page='''<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="/css/zone_object_setup_css.css" type="text/css" media="all" /> <meta name="viewport" content="width=device-width" > <meta charset="utf-8"> <title>Zone_object_setup</title> <script type="text/javascript" language="javascript">function SelectAll(id){ document.getElementById(id).focus(); document.getElementById(id).select();}</script> </head> <body> <form action="" method="POST"><input type="hidden" name="zone_objects_setup" value="'''+zone+'''"> <div id="buttons"> <input type="submit" value="SUBMIT"> <a href="/"><div id="home">HOME</div></a> <a href="'''+link_back+'''"><div id="back">BACK</div></a> </div> <div id="header">'''+zone+''' objects setup</div> <div id="testo"> <input type="text" name="new_objects" id="create_zone_web_obj" onclick="SelectAll('create_zone_web_obj')"; value="TYPE_NEW_OBJECT_HERE"> </div>''' if zone in zoneDict.keys() : print "zone in zoneDict" obj_name_list=zoneDict[zone]["objects"] tmp_html='<tr><td class="web_obj_name">No web object present in this room</td><td></td><td class="web_obj_name"></td></tr>' obj_name_list.sort() for a in obj_name_list : c=a #c=string.replace(a, "_p_"+zone, "_p") #c=string.replace(c,zone+"_body", zone+"_b_") html_page=html_page+''' <div id="riga"> <div id="object">'''+c+'''</div> <div id="used"> ADD <input type="checkbox" name="'''+a+'''_sl_obj_room" checked="checked" /> </div> </div> ''' l=[] l=objectDictionary.keys() l.sort() for b in l: body_found=string.find(b,"_body") part_without_body=" " en=1 if (body_found!=-1): print "found a body:"+b part_without_body=string.replace(b, "_body", "") #b[0:body_found] if (part_without_body==zone): print "body enabled" en=1 #allow the display of the same body of the zone else: print "body rejected" en=0 #block the display of the body of others zones private_found=string.find(b,"_p_") #private object to show only in its zone part_without_private=" " en2=1 if (private_found!=-1): part_without_private=b[private_found+3:] if (part_without_private==zone): en2=1 #allow the display of private object of the zone else: en2=0 #block the display of private object of others zones if (b not in obj_name_list)&(en==1)&(en2==1) : c=b #c=string.replace(b, "_p_"+zone, "_p") #c=string.replace(c,zone+"_body", zone+"_b_") html_page=html_page+''' <div id="riga"> <div id="object">'''+c+'''</div> <div id="add"> ADD <input type="checkbox" name="'''+b+'''_sl_obj_room" /> </div> </div> ''' html_page=html_page+'''<div id="riga" style=" visibility: hidden;" ><div id="object"></div><div id="add" style="border: 1px"></div></div>''' #to make the last element void in order to not be hidden a webobject under the submit button else: #zone not the room object print "not a room" html_page=html_page+'''</form></body></html>''' return(html_page) def get_RoomList(self):#return the html modifier for the web list of room
[docs] i=0 #<script type="text/javascript" src="/javascript/zone_modifier.js"></script> html_tmp='''<html><head><meta name="viewport" content="width=device-width"><link rel="stylesheet" href="/css/mod-rooms-list.css" type="text/css" media="all" /> <script type="text/javascript" language="javascript">function SelectAll(id){ document.getElementById(id).focus(); document.getElementById(id).select();}</script> <meta charset="utf-8"> <title>ZONE CONFIGURATIONS</title><style> </style></head><body><form action="" method="POST"> <div class="tabella"><div class="riga"><div class="colonna">ZONE NAME</div><div class="colonna">CHANGE ZONE NAME</div></div>''' l=[] l=sortZonesByOrderNumber() #get the zone list sorted by order number i=0 for room in l: #for every object in the dictionary print "room[hidden]:",room["hidden"] #if (zoneDict[room]["hidden"]!=0): #skip the hidden elements # continue delete_room_check_box='''Delete Room<input type="checkbox" name="delete_room_'''+room+'''" value="'''+room+'''"/>''' ##print roomList[i] html_tmp=html_tmp+''' <div class="riga"><div class="colonna"><a href="'''+self.path+room+'''">'''+room+'''</a></div><div class="colonna"><input type="text" id="text_name'''+room+'''" onClick="SelectAll('text_name'''+room+'''');" name='''+room+''' value="'''+room+'''"> </div><div class="colonna" >'''+delete_room_check_box+'''</div> </div>''' i=i+1 new_room='''<div id="last_row" class="riga"><div id="last_row" class="colonna">CREATE NEW ZONE</div><div id="last_row"class="colonna"><input type="text" id="last_row_text" onClick="SelectAll('last_row_text')"; name="new_room" value="'''+default_new_zone_value+'''"></div></div><input type="submit" id="submit_button" value="Submit" ></form>''' pag=html_tmp+new_room+'''</body></html>''' # print "pagina mostrata"+pag return(pag) def get_RoomObjectList(self,room,objectDictionary):#return the html for the web_objects form present in a room
[docs] #room_index=roomList.index(room) #updateOneRoom(room) if uncommented make the htmlobj double... html_tmp='''<html><head><meta name="viewport" content="width=device-width"><link rel="stylesheet" href="/css/zone_object_list_config.css" type="text/css" media="all" /><style> </style><script type="text/javascript" language="javascript">function SelectAll(id){ document.getElementById(id).focus(); document.getElementById(id).select();}</script></head><body><form action="" method="POST"><input type="hidden" name="current_room" value="'''+room+'''"> <table border="1" style="width:100%"><tr class="web_obj_title"> <td>Room web objects , click them to modify:</td><td>Html example to use the web object on a html page</td></tr>''' html='' if room in zoneDict.keys() : #print "room in zoneDict" obj_name_list=zoneDict[room]["objects"] i=0 tmp_html='<tr><td class="web_obj_name">No web object present in this room</td><td></td><td class="web_obj_name"></td></tr>' for a in obj_name_list : tmp_html='' #print "web obj in the room ="+a html=html+'<tr><td class="web_obj_name"><a href="'+self.path+'/'+a+'">'+a+'</a></td><td class="web_obj_code" ><xmp ><a id="'+a+'" href="?'+a+'=0">'+a+'</a> </xmp></td><td class="web_obj_name">Remove this web object from this Room <input type="checkbox" name="rm_obj_'+a+'_from_'+room+'" value="'+a+'"></td></tr>' if (len(tmp_html)>4) : html=html+tmp_html html=html+'</table>' html=html+'<table border="1" style="width:100%"><tr><br/></tr><tr class="web_obj_title" ><td>Manage the web object not present in the room</td></tr></table>' html=html+'<table border="1" style="width:100%"><tr><td class="web_obj_name">Add an existing web object to this room</td><td class="web_obj_name">' #print "room dict values:" #print zoneDict.values() #print zoneDict.values()[0][0] html=html+'<table border="1" style="width:100%;text-align:center">' for s in objectDictionary.keys(): body_found=string.find(s,"_body") part_without_body=" " en=1 if (body_found!=-1): part_without_body=s[0:body_found] if (part_without_body==room): en=1 #allow the display of the same body of the room else: en=0 #block the display of the body of others rooms if (objectDictionary[s].getName() not in zoneDict[room]["objects" ])& (en==1): #if web object not yet present in the room make possible to add it html=html+'<tr><td>Add Web Object</td><td>'+objectDictionary[s].getName()+' </td><td>To This Room <input type="checkbox" name="add_obj_to_room'+objectDictionary[s].getName()+'" value="'+objectDictionary[s].getName()+'"> </td></tr> ' html=html+'</table>' html=html+'''<tr><td class="web_obj_name">Create a new web object</td><td><input type="text" onClick="SelectAll('new_object_text')"; id="new_object_text" name="new_web_object" value="'''+default_new_obj_value+'''" size="50" > </td> </tr>''' html=html+'''</table><input type="submit" value="Submit" ></form>''' #print "stanza" #print room html=html+'''<table border="1" style="width:100%"><tr><td class="web_obj_title">Modify the room html </td></tr><tr><td class="web_obj_name"><a href="/'''+baseDir+room+'''/index.html/?=" >Click Here to go to the room web page </a> </td></tr>''' html=html+'<tr><td><form action="" method="POST"><input type="hidden" name="current_room_text_area" value="'+room+'"><textarea name="html_room_mod" cols=1 rows=5 style="width:100%" >'+getRoomHtml(room,objectDictionary,"",zoneDict)+'</textarea></td></tr>' pag=html_tmp+html+'</table><input type="submit" value="Submit_textarea" ></form></body></html>' self.path="/" return(pag) def get_WebObjForm(self,web_obj):#return the html web form to modify a web object
[docs] style=web_obj.getStyle() name=web_obj.getName() html_obj=web_obj.getHtml() templateFile = open('setup/ModifyWebObjForm.template.html','rb') #get the template to use in order to render the page ModObjFormPage=templateFile.read() templateFile.close() notes="Enter_The_Web_Object_Notes" hardwarePin=no_pin_selected #string display when no pin has been assigned yet containing "no_pin" type_b="" type_sb="" type_l="" type_d_sensor="" type_a_sensor="" current_status0=" " current_status1=" " style0="/*Enter here the style you want your web object to have when its status is 0 */" style1="/*Enter here the style you want your web object to have when its status is 0 */" html0="<!-- Enter here the html you want your web object to display when its status is 0 -->" html1="<!-- Enter here the html you want your web object to display when its status is 1 -->" command0=" " command1=" " init_command=" " if web_obj.getNotes()!=" " : notes=web_obj.getNotes() if web_obj.getAttachedPinList()[0]!=9999 : hardwarePin=str(web_obj.getAttachedPinList()[0]) if web_obj.getType()=="b" : type_b="checked" if web_obj.getType()=="sb" : type_sb="checked" if web_obj.getType()=="l" : type_l="checked" if web_obj.getType()=="d_sensor" : type_d_sensor="checked" if web_obj.getType()=="a_sensor" : type_a_sensor="checked" if web_obj.getStatus()==0 : current_status0="checked" current_status1="" status_link="1" else: current_status0="" current_status1="checked" status_link="0" if web_obj.getStyle0()!=" " : style0=web_obj.getStyle0() if web_obj.getStyle1()!=" " : style1=web_obj.getStyle1() if web_obj.getHtml0()!=" " : html0=web_obj.getHtml0() if web_obj.getHtml1()!=" " : html1=web_obj.getHtml1() if web_obj.getCommand0()!=" " : command0=web_obj.getCommand0() if web_obj.getCommand1()!=" " : command1=web_obj.getCommand1() if web_obj.getInitCommand()!=" " : init_command=web_obj.getInitCommand() try: "style="+style except: style=" " #use the template and replace the parts ONOS+name parts with the right parts from system ModObjFormPage=ModObjFormPage.replace("+ONOSstyle+",style); ModObjFormPage=ModObjFormPage.replace("ONOSself.path+",self.path); ModObjFormPage=ModObjFormPage.replace("+ONOSname+",name); ModObjFormPage=ModObjFormPage.replace("+ONOSnotes+",notes); ModObjFormPage=ModObjFormPage.replace("+ONOSpin+",hardwarePin); ModObjFormPage=ModObjFormPage.replace("+ONOStype_b+",type_b); ModObjFormPage=ModObjFormPage.replace("+ONOStype_sb+",type_sb); ModObjFormPage=ModObjFormPage.replace("+ONOStype_l+",type_l); ModObjFormPage=ModObjFormPage.replace("+ONOStype_d_sensor+",type_d_sensor); ModObjFormPage=ModObjFormPage.replace("+ONOStype_a_sensor+",type_a_sensor); ModObjFormPage=ModObjFormPage.replace("+ONOScurrent_status0+",current_status0); ModObjFormPage=ModObjFormPage.replace("+ONOScurrent_status1+",current_status1); ModObjFormPage=ModObjFormPage.replace("+ONOSstatus_link+",status_link); ModObjFormPage=ModObjFormPage.replace("+ONOShtml_obj+",html_obj); ModObjFormPage=ModObjFormPage.replace("+ONOSstyle0+",style0); ModObjFormPage=ModObjFormPage.replace("+ONOSstyle1+",style1); ModObjFormPage=ModObjFormPage.replace("+ONOShtml0+",html0); ModObjFormPage=ModObjFormPage.replace("+ONOShtml1+",html1); ModObjFormPage=ModObjFormPage.replace("+ONOScommand0+",command0); ModObjFormPage=ModObjFormPage.replace("+ONOScommand1+",command1); ModObjFormPage=ModObjFormPage.replace("+ONOSinit_command+",init_command); # pag='<html><head><style type="text/css">.text{font-size:110%} .title{color: red;font-size:120%}'+style+'</style></head><body><form action="" method="POST"><input type="hidden" name="mod_object" value="'+self.path+'"><table border="1" style="width:100%"><tr><td><div class="title"> Web Object Name: </div><br/><input type="text" name="obj_name" value="'+name+'" size="50" style="width:100%"><br/><br/></td><td><div class="title">Web Object Notes: </div><br/><input type="text" name="obj_notes" value="'+notes+'" size="50" style="width:100%"><br/><br/></td></tr><tr><td><div class="title"> Web Object Type </div><ul><input type="radio" name="obj_type" value="b" '+type_b+'>Normal Button</ul><ul><input type="radio" name="obj_type" value="sb" '+type_sb+'>Static Button</ul><ul><input type="radio" name="obj_type"value="l" '+type_l+' >Web Label</ul><br/><br/><br/></td><td><div class="title"> Web Object Current Status </div><ul><input type="radio" name="obj_current_status" value="0" '+current_status0+' >0</ul><ul><input type="radio" name="obj_current_status" value="1" '+current_status1+' >1</ul><br/> <a id="'+name+'" href="/?'+name+'='+status_link+'">'+html_obj+'</a> <br/><xmp ><a id="'+name+'" href="/?'+name+'='+status_link+'">'+html_obj+'</a></xmp > <br/></td></tr><br/><tr><td class="title">First Web Object Style &nbsp;</td><td class="title">Second Web Object Style</td></tr><tr><td> <textarea name="obj_style0" cols=1 rows=15 style="width:100%" >'+style0+'</textarea></td> <td> <textarea name="obj_style1" cols=1 rows=15 style="width:100%">'+style1+'</textarea></td></tr><tr><td> <div class="title">First Web Object Html </div> Html displayed on web page when the web object status is 0</td><td><div class="title">Second Web Object Html</div>Html displayed on web page when the web object status is 1</td></tr><tr><td> <textarea name="obj_html0" cols=1 rows=15 style="width:100%">'+html0+'</textarea></td> <td> <textarea name="obj_html1" cols=1 rows=15 style="width:100%">'+html1+'</textarea></td> </tr><tr> <td><div class="title">First Web Object Command</div>Bash command executed when the web object status changes from 1 to 0 </td><td><div class="title">Second Web Object Command</div>Bash command executed when the web object status changes from 0 to 1 </td> </tr><tr> <td> <textarea name="obj_cmd0" cols=1 rows=5 style="width:100%">'+command0+'</textarea></td> <td> <textarea name="obj_cmd1" cols=1 rows=5 style="width:100%">'+command1+'</textarea></td> </tr><tr><table border="1" style="width:100%"><tr><td style="width:15%" ><div class="title" > Web Object Init Command</div>Command executed once only when you start the webserver</td> <td> <textarea name="obj_init_cmd" cols=1 rows=5 style="width:100%">'+init_command+'</textarea></td></tr></table></tr></table></div><br/><br/><br/> <input type="submit" value="Submit"><input type="reset" value="Reset"></form></body></html>' return(ModObjFormPage) def do_GET(self):
[docs] try: if (self.path=="/"): #print "rrrrrrrrrrrrrrrrrrrrrooooooooooooooooooooooot" namespace={} cgi_name="gui/play.py" execfile(cgi_name,globals(),namespace) web_page=namespace["web_page"] try: print self.path #h = open("index.html",'r') #web_page=h.read() #h.close() except: print "no index.html found in root directory" web_page=web_page_not_found try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(web_page) except: print "error2 in send_header " errorQueue.put( "error2 in send_header ") return if ( (string.find(self.path,"info_hash=")!=-1)): # if the address contain info_hash= then discard it print "address discarded " return if ( (string.find(self.path,"onos_cmd")!=-1)): # if the url contain onos_cmd then parse it #example1: #localhost/onos_cmd?cmd=setSts&obj=sensor1&status=1&hw=0__ this change only the webobject,use it to change sensor value.. #example2: #localhost/onos_cmd?cmd=setSts&obj=sensor1&status=1&hw=1__ this change both , the webobject and the hardware status # # url=self.path print "onos_cmd received" print url #example: /onos_cmd?cmd=setSts&obj=sensor1&status=1&hw=0__ if string.find(url,"cmd=setSts&obj=")!=-1: msg="ok" #start_obj_name=string.find(url,'obj=')+4 #end_obj_name=string.find(url,'&',start_obj_name) #webobjName=url[start_obj_name:end_obj_name] try: objName=re.search('setSts&obj=(.+?)&',self.path).group(1) #start_status=string.find(url,'&status=')+8 #end_status=string.find(url,'&',start_status) #status_to_set=url[start_status:end_status] status_to_set=re.search('&status=(.+?)&',self.path).group(1) #start_hw_flag=string.find(url,'&hw=')+4 #end_hw_flag=string.find(url,'__',start_hw_flag) #hw_flag=url[start_hw_flag:end_hw_flag] hw_flag=re.search('&hw=(.+?)__',self.path).group(1) except Exception, e: print "error in re.search 1 on onos_cmd url "+url+" e:"+str(e.args) errorQueue.put("error in re.search 1 on onos_cmd url "+url+" e:"+str(e.args)) try: write_hw_enable=int(hw_flag) except Exception, e: print "error in write_hw_enable on onos_cmd url "+" e:"+str(e.args) errorQueue.put( "error in write_hw_enable on onos_cmd url "+" e:"+str(e.args)) write_hw_enable=1 print "------set "+objName+"to"+status_to_set #if objName in object_dict.keys(): #try: #changeWebObjectStatus(objName,int (status_to_set),write_hw_enable) layerExchangeDataQueue.put( {"cmd":"setSts","webObjectName":objName,"status_to_set":status_to_set,"write_to_hw":write_hw_enable }) #except: # print "error objName not in the dict " # errorQueue.put("error objName not in the dict " ) # msg="error objName not in the dict " #banana to add also the status check try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(msg) except Exception, e : pass print "error3 in send_header "+" e:"+str(e.args) errorQueue.put( "error3 in send_header "+" e:"+str(e.args)) return # localhost/onos_cmd?cmd=setNodePin&nodeSn=Plug6way0001&pin=8&status=0&hw=0__ #to set only the status of webobjects that are enclosed in this node and use this pin (without writing to the hardware) # localhost/onos_cmd?cmd=setNodePin&nodeSn=Plug6way0001&pin=8&status=0&hw=1__ #to set only the status of webobjects that are enclosed in this node and use this pin (writing to the hardware) #the webobject status will change only if the write to hardware is succesfull # localhost/onos_cmd?cmd=setNodePin&node_sn=RouterGL0001&pin=22&status=1&hw=0__ # webobjName=re.search('setSts&obj=(.+?)&',self.path).group(1) if string.find(self.path,"onos_cmd?cmd=setNodePin&")!=-1: print "received a onos_cmd?cmd=setNodePin query" #start_node_sn=string.find(url,'node_sn=')+8 #end_node_sn=string.find(url,'&',start_node_sn) #node_sn=url[start_node_sn:end_node_sn] node_sn=re.search('&node_sn=(.+?)&',self.path).group(1) print "node_sn="+node_sn #pin_number_start=string.find(url,'&pin=')+5 #pin_number_end=string.find(url,'&',pin_number_start) #pin_number=url[pin_number_start:pin_number_end] pin_number=re.search('&pin=(.+?)&',self.path).group(1) print "pin_number="+pin_number #pin_status_start=string.find(url,'&status=')+8 #pin_status_end=string.find(url,'&',pin_status_start) #pin_status=url[pin_status_start:pin_status_end] pin_status=re.search('&status=(.+?)&',self.path).group(1) print "pin_status="+pin_status #start_hw_flag=string.find(url,'&hw=')+4 #end_hw_flag=string.find(url,'__') #hw_flag=url[start_hw_flag:end_hw_flag] hw_flag=re.search('&hw=(.+?)__',self.path).group(1) print "hw_flag="+hw_flag try: write_hw_enable=int(hw_flag) except Exception, e : print "error in write_hw_enable on onos_cmd url "+" e:"+str(e.args) errorQueue.put("error in write_hw_enable on onos_cmd url "+" e:"+str(e.args) ) write_hw_enable=1 #now i have to check in all the web obj which one is connected to the pin of this node answer=setNodePin(node_sn,pin_number,pin_status,write_hw_enable) try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(answer) except Exception, e : print "error4 in send_header "+" e:"+str(e.args) errorQueue.put( "error4 in send_header "+" e:"+str(e.args)) return # localhost//onos_cmd?cmd=setNodeDReg&node_sn=RouterGL0001&reg=xxxxxxxxxxxxxx__ #banana to implement ? if string.find(url,"onos_cmd?cmd=setNodeDReg&")!=-1: print "received a onos_cmd?cmd=setNodeDReg query" start_node_sn=string.find(url,'node_sn=')+8 end_node_sn=string.find(url,'&',start_node_sn) node_sn=url[start_node_sn:end_node_sn] print "node_sn="+node_sn data_reg_start=string.find(url,'&pin=')+5 data_reg_end=string.find(url,'__',data_reg_start) data_reg=url[data_reg_start:data_reg_end] print "data reg received="+data_reg print "len data recived="+str(len(data_reg)) #now i have to check in all the web obj which one is connected to the pin of this node #banana not working here? for a in object_dict.keys(): print object_dict[a].getHwNodeSerialNumber() if (object_dict[a].getHwNodeSerialNumber()==node_sn): print "node exist" #banana to implement a decoding mode to get all pin status from the data received try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write("ok") except Exception, e : pass print "error5 in send_header "+" e:"+str(e.args) errorQueue.put( "error5 in send_header "+" e:"+str(e.args)) return #write here the msg get setup__ #example: #localhost/onos_cmd?cmd=pinsetup&node_sn=Plug6way0001&node_fw=4.85__ #localhost/onos_cmd?cmd=pinsetup&node_sn=Plug6way0002&node_fw=4.85__ #localhost/onos_cmd?cmd=pinsetup&node_sn=ProminiA0001&node_fw=4.85__ #localhost/onos_cmd?cmd=pinsetup&node_sn=ProminiA0002&node_fw=4.85__ #OBSOLETE!!! if string.find(url,"onos_cmd?cmd=pinsetup&")!=-1: print "received a onos_cmd?cmd=pinsetup query" #start_node_sn=string.find(url,'node_sn=')+8 #end_node_sn=string.find(url,'&',start_node_sn) #node_sn=url[start_node_sn:end_node_sn] node_sn=re.search('&node_sn=(.+?)&',self.path).group(1) print "node_sn="+node_sn #start_node_fw=string.find(url,'node_fw=')+8 #end_node_fw=string.find(url,'&',start_node_fw) #node_fw=url[start_node_fw:end_node_fw] node_fw=re.search('&node_fw=(.+?)__',self.path).group(1) print "node_fw="+node_fw # start_node_ip=string.find(url,'node_ip=')+8 # end_node_ip=string.find(url,'__',start_node_ip) #node_ip=url[start_node_ip:end_node_ip] node_ip=str(self.client_address[0]) print "node_ip="+node_ip msg="ok" msg=createNewNode(node_sn,node_ip,node_fw) print "i try to send msg: "+msg try: self.send_response(200) self.send_header('Content-Type: application/octet-stream','text/plain') self.end_headers() self.wfile.write(msg) except Exception, e : pass print "error6 in send_header onos cmd 001"+" e:"+str(e.args) errorQueue.put( "error6 in send_header onos cmd 001"+" e:"+str(e.args)) return #localhost/onos_cmd?cmd=sync&node_sn=ProminiA0002&node_fw=4.85__ if string.find(url,"onos_cmd?cmd=sync&")!=-1: print "received a onos_cmd?cmd=sync query" #start_node_sn=string.find(url,'node_sn=')+8 #end_node_sn=string.find(url,'&',start_node_sn) #node_sn=url[start_node_sn:end_node_sn] node_sn=re.search('&node_sn=(.+?)&',self.path).group(1) print "node_sn="+node_sn #start_node_fw=string.find(url,'node_fw=')+8 #end_node_fw=string.find(url,'&',start_node_fw) #node_fw=url[start_node_fw:end_node_fw] node_fw=re.search('&node_fw=(.+?)__',self.path).group(1) print "node_fw="+node_fw # start_node_ip=string.find(url,'node_ip=')+8 # end_node_ip=string.find(url,'__',start_node_ip) #node_ip=url[start_node_ip:end_node_ip] node_ip=str(self.client_address[0]) print "node_ip="+node_ip msg=createNewNode(node_sn,node_ip,node_fw) msg="ok" print "i try to send msg: "+msg try: self.send_response(200) self.send_header('Content-Type: application/octet-stream','text/plain') self.end_headers() self.wfile.write(msg) except Exception, e : pass print "error7 in send_header onos cmd 001"+" e:"+str(e.args) errorQueue.put("error7 in send_header onos cmd 001"+" e:"+str(e.args) ) return # try: # self.send_response(200) # self.send_header('Content-type', 'text/html') # self.end_headers() # self.wfile.write("error_onos_cmd") # except: # pass # print "error in send_header " # return if (self.path=="/login.html"): try: h = open("login.html",'r') web_page=h.read() h.close() except: print "no login.html found in root directory" web_page=web_page_not_found try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(web_page) except Exception, e : pass print "error8 in send_header "+" e:"+str(e.args) errorQueue.put("error8 in send_header "+" e:"+str(e.args) ) return if ((self.path.endswith(".jpg"))|(self.path.endswith(".gif"))|(self.path.endswith(".png"))|(self.path.endswith(".JPG"))|(self.path.endswith(".PNG"))): f = open(curdir + sep + self.path,'rb') #self.path has /test.html photoFile=f.read() f.close() #note that this potentially makes every file on your computer readable by the internet try: self.send_response(200) self.send_header('Content-type', 'image/png') self.send_header('Cache-Control', 'max-age=31536000') #set the cache of the image to a long time to prevent background image flipping self.end_headers() self.wfile.write(photoFile) except Exception, e : pass print "error in send_header img"+" e:"+str(e.args) errorQueue.put( "error in send_header img"+" e:"+str(e.args)) return if (self.path.endswith(".css"))|(self.path.endswith(".CSS")): f = open(curdir + sep + self.path,'rb') #self.path has /test.html cssFile=f.read() f.close() #note that this potentially makes every file on your computer readable by the internet try: self.send_response(200) self.send_header('Content-type', 'text/css') self.send_header('Cache-Control', 'max-age=1') #set the cache of the image to a long time to prevent background image flipping self.end_headers() self.wfile.write(cssFile) #print "served a css file" except Exception, e : pass print "error9a in send_header "+" e:"+str(e.args) errorQueue.put("error9a in send_header "+" e:"+str(e.args) ) return if (self.path.endswith(".ttf"))|(self.path.endswith(".TTF")): f = open(curdir + sep + self.path,'rb') #self.path has /test.html cssFile=f.read() f.close() #note that this potentially makes every file on your computer readable by the internet try: self.send_response(200) self.send_header('Content-type', 'text/ttf') self.send_header('Cache-Control', 'max-age=1') #set the cache of the image to a long time to prevent background image flipping self.end_headers() self.wfile.write(cssFile) #print "served a css file" except Exception, e : pass print "error9b in send_header "+" e:"+str(e.args) errorQueue.put("error9b in send_header "+" e:"+str(e.args) ) return if (self.path.endswith(".js"))| (self.path.endswith(".JS")): f = open(curdir + sep + self.path,'rb') #self.path has /test.html javaFile=f.read() f.close() #note that this potentially makes every file on your computer readable by the internet try: self.send_response(200) self.send_header('Content-type', 'text/javascript') self.send_header('Cache-Control', 'max-age=1') #set the cache of the image to a long time to prevent background image flipping self.end_headers() self.wfile.write(javaFile) except Exception, e : pass print "error10 in send_header "+" e:"+str(e.args) errorQueue.put( "error10 in send_header "+" e:"+str(e.args) ) return #from here to the end the login is required , the above part is for the onos node use. if (login_required==1): current_username=getUserFromIp(self.client_address[0]) if (current_username==-1) : #user not logged print "user not logged ,i show login page" self.get_login() #show login page return() if (len (self.path)<2): print "main address.." #print stato_led1 try: namespace={} cgi_name="/gui/play.py" execfile(cgi_name,globals(),namespace) web_page=namespace["web_page"] #h = open("index.html",'r') #web_page=h.read() #h.close() except: print "no index.html found in root directory" web_page=web_page_not_found try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(web_page) print "percorso=" print self.path print "fine percorso" except Exception, e : pass print "error11 in send_header "+" e:"+str(e.args) errorQueue.put( "error11 in send_header "+" e:"+str(e.args)) return if ( string.find(self.path,"zone_list"))!=-1: #print "indirizzo a pag principale.." #print stato_led1 #address_list=string.split(self.path,"/") home='/' #the home page of onos #back=address_list[0] html='''<!DOCTYPE html><html> <head><link rel="stylesheet" href="/css/zone_list.css" type="text/css" media="all" /><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <meta charset="utf-8"> <title>O.N.O.S</title></head> <body><div id="buttons"> <a href="'''+home+'''"><div id="home">HOME</div><a href="'''+home+'''"><div id="back">BACK</div></div> <div id="header">ZONES</div><div id="riga">''' end_html='''</div></body></html>''' l=[] l=sortZonesByOrderNumber() for a in l : if (zoneDict[a]["hidden"]!=0): #skip the hidden elements continue #html=html+'<div><a href="/'+a+'/index.html?=">'+a+'</a></div>' html=html+'''<a href="/'''+a+'''/index.html?="><div id="zone">'''+a+'''</div></a>''' html=html+'''<a href="/zone_objects_setup/'''+a+'''"><div id="setup"> setup</div></a>''' html=html+'''<div id="zone" style=" visibility: hidden;"></div></a>''' #void elements to make space html=html+'''<div id="setup" style=" visibility: hidden;"> </div></a>'''#void elements to make space pag=html+end_html #+'<a href="/setup/">Rooms Configuration </a><br/>' try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(pag) print "percorso=" print self.path print "fine percorso" except Exception, e : pass print "error12 in send_header "+" e:"+str(e.args) errorQueue.put("error12 in send_header "+" e:"+str(e.args) ) return #/RouterGL0001/index.html?=r_onos_s12 if ( string.find(self.path,"r_onos_s")!=-1)& ( string.find(self.path,"?")!=-1)& ( string.find(self.path,"=")!=-1): #if is the javascript on the page asking to update the webpage / # global object_dict global oldpag global nothing_changed # global old_zoneDict # global old_object_dict # global old_web_page end_file_name=0 end_file_name=string.find(self.path,".html")+5 web_page='' try: b1 = open(baseRoomPath+self.path[1:end_file_name] ,'r') web_page=b1.read() b1.close() except: print "error opening the file" errorQueue.put("error opening the file" ) #if True : #to implement a check to not execute modPag if the dictionary are equal pag=modPage(web_page,object_dict,findRoomName(self.path,zoneDict),zoneDict) p_start=string.find(pag,'<div id="ReloadThis" >') pag=pag[p_start+len('<div id="ReloadThis" >'):] #send only the part of page to update #old_zoneDict=zoneDict #old_object_dict=object_dict #old_web_page=web_page #if (1):# (oldpag!=pag): removed the not updating part for problem with arduino update nothing_changed=0 #print "web page changed" try: self.send_response(202) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write("ok"+strftime("%S", gmtime())+pag) except Exception, e : pass print "error in send_header r_onos_s 0 "+" e:"+str(e.args) errorQueue.put("error in send_header r_onos_s 0 "+" e:"+str(e.args) ) oldpag=pag #else: # print "web page not changed 1" # nothing_changed=nothing_changed+1 # try: # self.send_response(200) # self.send_header('Content-type', 'text/html') # self.end_headers() # try: # self.wfile.write("ok"+strftime("%S", gmtime())+pag) # except Exception, e : # pass # print "error in send_header r_onos_s 2"+" e:"+str(e.args) # errorQueue.put("error in send_header r_onos_s 2"+" e:"+str(e.args) ) #except Exception, e : # pass # print "error in send_header r_onos_s 3"+" e:"+str(e.args) # errorQueue.put("error in send_header r_onos_s 3"+" e:"+str(e.args) ) # return #else: #never executed for now # print "web page not changed 2" # try: # self.send_response(200) # self.send_header('Content-type', 'text/html') #self.send_header('Location', self.path) # self.end_headers() # self.wfile.write("ok"+strftime("%S", gmtime())+"nonews") #remove comment to send page #self.wfile.write("oknothing_changed") #remove comment to send page only when it change # except Exception, e : # pass # print "error in send_header r_onos_s 4 "+" e:"+str(e.args) # errorQueue.put( "error in send_header r_onos_s 4 "+" e:"+str(e.args)) return if ( ( string.find(self.path,"?")!=-1)&(string.find(self.path,"=")!=-1)&(string.find(self.path,"r_onos_s")==-1)): print "get query found############################################################################" end_file_name=0 if ( (string.find(self.path,".html")!=-1) ): #if a html file is called #start_file_name="" #x=(string.find(self.path,"/")) html_filename=re.search('/(.+?).html',self.path).group(1)+".html" print "html_filename=",html_filename #end_file_name=string.find(self.path,".html")+5 #print "addressbar1= "+self.path #print "file:"+self.path[1:end_file_name] try: #b1 = open(baseRoomPath+self.path[1:end_file_name] ,'r') b1 = open(baseRoomPath+html_filename ,'r') web_page=b1.read() b1.close() except Exception, e : print "error opening the htlm file"+" e:"+str(e.args) errorQueue.put( "error opening the htlm file"+" e:"+str(e.args)) web_page="error no html found" #print web_page else: #no .html in the address bar k=0 last_bar=len(self.path) while ((string.find(self.path,"/",k))!=-1): #search for the last / in the address bar last_bar=string.find(self.path,"/",k) k=last_bar+1 print "local address bar ="+self.path[0:last_bar+1] try: b1 = open(baseRoomPath+self.path[1:last_bar+1] +"index.html" ,'r') web_page=b1.read() b1.close() except Exception, e : print "error opening the file"+" e:"+str(e.args) errorQueue.put("error opening the file local address bar ="+self.path[0:last_bar+1] +"index.html"+" e:"+str(e.args)) print "local address bar ="+self.path[0:last_bar+1] +"index.html" web_page=web_page_not_found #print web_page address_bar=self.path[end_file_name:] #print "a---"+address_bar #banana use regex to read all the obj and status to set address_bar=address_bar[string.find(address_bar,"?")+1:] equal_position=string.find(address_bar,"=") next_point_position=string.find(address_bar,"&",equal_position) objName=address_bar[0: equal_position] if (next_point_position!=-1): status_to_set=( address_bar[(equal_position+1):(next_point_position)] ) print "value="+(status_to_set) else: status_to_set=(address_bar[(equal_position+1):]) print "value="+(status_to_set) if status_to_set=="!": # to make a not of the current status #print "make the opposite" status_to_set=not (object_dict[objName].getStatus()) if ( objName in object_dict ): #print "pulsante trovato in dizionario" if status_to_set=="!": # to make a not of the current status #print "make the opposite" status_to_set=not (object_dict[objName].getStatus()) #changeWebObjectStatus(objName,status_to_set,1) #banana to add usr,priority,mail_list_to_report_to priorityCmdQueue.put( {"cmd":"setSts","webObjectName":objName,"status_to_set":status_to_set,"write_to_hw":1}) print "i set"+objName+" to :"+str(status_to_set) else: print "command :"+objName+" not in dictionary" address_bar=address_bar[next_point_position-2:] #address_bar example "http://192.168.0.100/RouterGL0000/index.html?socket0_RouterGL0000=0&socket0_RouterGL0020=1&socket0_ttgg0000=69" while ( ( string.find(address_bar,"&")!=-1)&(len(address_bar)>1 )): point_position=string.find(address_bar,"&") equal_position=string.find(address_bar,"=",point_position) next_point_position=string.find(address_bar,"&",equal_position) objName=address_bar[point_position+1: equal_position] #print "cmd:"+cmd #print "a:"+address_bar[(equal_position):] try : if (next_point_position!=-1): status_to_set=( address_bar[(equal_position+1):(next_point_position)] ) print "value="+(status_to_set) else: status_to_set=(address_bar[(equal_position+1):]) print "value="+(status_to_set) except Exception, e : print "error in the status_to_set_value in the address bar"+address_bar[(equal_position+2):]+" e:"+str(e.args) errorQueue.put("error in the status_to_set_value in the address bar"+address_bar[(equal_position+2):]+" e:"+str(e.args) ) print "next:"+str(next_point_position) print (address_bar[equal_position+2:]) status_to_set=-1 if ( objName in object_dict ): #print "pulsante trovato in dizionario" if status_to_set=="!": # to make a not of the current status #print "make the opposite" status_to_set=not (object_dict[objName].getStatus()) print "path="+address_bar #changeWebObjectStatus(objectName,status_to_set,1) #banana to add usr,priority,mail_list_to_report_to priorityCmdQueue.put( {"cmd":"setSts","webObjectName":objName,"status_to_set":status_to_set,"write_to_hw":1}) print "i set"+objName+" to :"+str(status_to_set) else: print "command :"+objName+" not in dictionary" address_bar=address_bar[(equal_position+1):] #remove the first '?' #print "addressbar= "+address_bar pag=modPage(web_page,object_dict,findRoomName(self.path,zoneDict),zoneDict) try: self.send_response(202) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(pag) # print "percorso="+self.path+"fine percorso" except Exception, e : pass print "error11 in send_header "+" e:"+str(e.args) errorQueue.put("error11 in send_header "+" e:"+str(e.args) ) return if self.path.endswith(".json"): f = open(curdir + sep + self.path) #self.path has /test.html tmpF=f.read() f.close() #note that this potentially makes every file on your computer readable by the internet try: self.send_response(200) self.send_header('Content-Disposition: attachment', 'filename="config_files/data.json"') self.send_header('Content-Type: application/octet-stream','text/json' ) self.end_headers() self.wfile.write(tmpF) except Exception, e : pass print "error12 in send_header "+" e:"+str(e.args) errorQueue.put("error12 in send_header "+" e:"+str(e.args) ) f.close() return if self.path.endswith("gui/new_user.py"): # render the scenario list namespace={} message="" cgi_name="gui/new_user.py" execfile(cgi_name,globals(),namespace) web_page=namespace["web_page"] try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(web_page) except Exception, e : print "error12a in send_header "+" e:"+str(e.args) errorQueue.put( "error13a in send_header "+" e:"+str(e.args)) return if self.path.endswith("scenarios_list/"): # render the scenario list namespace={} cgi_name="gui/scenarios_list.py" execfile(cgi_name,globals(),namespace) web_page=namespace["web_page"] try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(web_page) except Exception, e : print "error13a in send_header "+" e:"+str(e.args) errorQueue.put( "error13a in send_header "+" e:"+str(e.args)) return scenario_to_mod="" if ( string.find(self.path,"/mod_scenario/")!=-1): # render the mod scenario setup menu print "scenario_to_mod",self.path.split("/")[2] try: if (self.path.split("/")[2])in scenarioDict.keys(): namespace={"scenario_to_mod":self.path.split("/")[2]} scenario_to_mod=(self.path.split("/"))[2] cgi_name="gui/mod_scenario.py" execfile(cgi_name,globals(),namespace) web_page=namespace["web_page"] except Exception, e : print "error, scenario name does not exist "+" e:"+str(e.args) errorQueue.put("error, scenario name does not exist "+" e:"+str(e.args)) web_page="error, scenario name does not exist " try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(web_page) except Exception, e : print "error13a in send_header "+" e:"+str(e.args) errorQueue.put( "error13a in send_header "+" e:"+str(e.args)) return if ( string.find(self.path,"/scenario_conditions/")!=-1): # render the conditions mod scenario setup menu try: if (self.path.split("/")[2])in scenarioDict.keys(): namespace={"scenario_to_mod":self.path.split("/")[2]} scenario_to_mod=(self.path.split("/"))[2] cgi_name="gui/scenario_conditions.py" execfile(cgi_name,globals(),namespace) web_page=namespace["web_page"] except Exception, e : print "error, scenario name does not exist "+" e:"+str(e.args) errorQueue.put("error, scenario name does not exist "+" e:"+str(e.args)) web_page="error, scenario name does not exist " try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(web_page) except Exception, e : print "error13ab in send_header "+" e:"+str(e.args) errorQueue.put( "error13ab in send_header "+" e:"+str(e.args)) return if ( string.find(self.path,"/function_to_run/")!=-1): # render the conditions mod scenario setup menu try: if (self.path.split("/")[2])in scenarioDict.keys(): namespace={"scenario_to_mod":self.path.split("/")[2]} scenario_to_mod=(self.path.split("/"))[2] cgi_name="gui/scenario_f_to_run.py" execfile(cgi_name,globals(),namespace) web_page=namespace["web_page"] except Exception, e : print "error, scenario name does not exist "+" e:"+str(e.args) errorQueue.put("error, scenario name does not exist "+" e:"+str(e.args)) web_page="error, scenario name does not exist " try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(web_page) except Exception, e : print "error13ab in send_header "+" e:"+str(e.args) errorQueue.put( "error13ab in send_header "+" e:"+str(e.args)) return if self.path.endswith("setup/"): # render the setup menu #print "enter in room setup" try: b1 = open('setup/select_config_menu.html','r') web_page=b1.read() b1.close() except Exception, e : print "error opening the file"+" e:"+str(e.args) errorQueue.put("error opening the file"+" e:"+str(e.args) ) web_page="ERROR LOADING SELECT CONFIG MENU" try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(web_page) except Exception, e : pass print "error13 in send_header "+" e:"+str(e.args) errorQueue.put("error13 in send_header "+" e:"+str(e.args) ) return if self.path.endswith("setup/obj_manager/"): print "enter in obj_manager" html_page=self.get_WebOjectManager(object_dict) try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(html_page) except Exception, e : pass print "error14 in send_header "+" e:"+str(e.args) errorQueue.put( "error14 in send_header "+" e:"+str(e.args)) return if (( string.find(self.path,"cgi/")!=-1)&( string.find(self.path,".py")!=-1)): cgi_module_name_start=string.find(self.path,"cgi/") #cgi_module_name_stop=len(self.path)-3 #remove the ".py" cgi_name=(self.path[cgi_module_name_start:]) namespace={} web_page="cgi import or execute error" print "cgi_name:",cgi_name if (debug==1): # in debug mode .. execfile(cgi_name,globals(),namespace) web_page=namespace["web_page"] else: try: execfile(cgi_name,globals(),namespace) web_page=namespace["web_page"] except Exception, e : print "error importing a module in cgi directory, cgi name:"+cgi_name+" e:"+str(e.args) errorQueue.put( "error importing a module in cgi directory, cgi name:"+cgi_name+" e:"+str(e.args)) try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(web_page) except Exception, e : pass print "error15 in send_header "+" e:"+str(e.args) errorQueue.put( "error15 in send_header "+" e:"+str(e.args) ) return if ( string.find(self.path,"/zone_objects_setup/")!=-1): # print "enter in obj_manager" zone='' if (len(self.path)>0): address_list=string.split(self.path,"/") if address_list[-1] in zoneDict.keys() : #if the path is setup/zone_objects_setup/anyzonename.... take the room name zone=address_list[-1] else: print "no room name found" else: print "no room name found" html_page= self.get_Zone_Objects_Setup(self.path,object_dict,zone) try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(html_page) except Exception, e : pass print "error16 in send_header "+" e:"+str(e.args) errorQueue.put("error16 in send_header "+" e:"+str(e.args) ) return if self.path.endswith("setup/save_configuration/"): # print "json saved" updateJson( object_dict,zoneDict,scenarioDict) try: b1 = open('setup/select_config_menu.html','r') web_page=b1.read() b1.close() except Exception, e : print "error2 opening the file"+" e:"+str(e.args) errorQueue.put("error2 opening the file"+" e:"+str(e.args) ) web_page="ERROR LOADING SELECT CONFIG MENU" try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(web_page) except Exception, e : pass print "error in send_header "+" e:"+str(e.args) errorQueue.put("error17 in send_header "+" e:"+str(e.args) ) return if self.path.endswith("setup/restore_default_conf/"): # print "JSON RESTORED TO DEFAULT" #os.system('cp -f config_files/default.json config_files/data.json') with lock_bash_cmd: subprocess.check_output('cp -f config_files/default.json config_files/data.json', shell=True,close_fds=True) try: b1 = open('setup/restored_configuration.html','r') web_page=b1.read() b1.close() except Exception, e : print "error3 opening the file"+" e:"+str(e.args) errorQueue.put( "error3 opening the file"+" e:"+str(e.args)) web_page="ERROR LOADING SELECT CONFIG MENU" try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(web_page) except Exception, e : pass print "error18 in send_header "+" e:"+str(e.args) errorQueue.put("error18 in send_header "+" e:"+str(e.args) ) #os.execl(sys.executable, *([sys.executable]+sys.argv)) global exit exit=1 #raise KeyboardInterrupt return if self.path.endswith("setup/zone_manager/"): # render the html list of room with the link to modify them print "enter in zone_manager" html_page=self.get_zone_manager(zoneDict) try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(html_page) except Exception, e : pass print "error19 in send_header "+" e:"+str(e.args) errorQueue.put( "error19 in send_header "+" e:"+str(e.args) ) return if ((string.find(self.path,"/setup/web_obj_modifier/")!=-1)):#render the web_object_form to modify a webobj lista=[] lista=string.split(self.path,"/") #split the path in a list of element divided by "/" pag="no_web_object_to_modify" if ((len(lista))==4): if ((lista[3] in object_dict.keys())): print "edit a web object" pag=self.get_WebObjForm(object_dict[lista[3]]) if ((len(lista))==5): if ((lista[4] in object_dict.keys())&(lista[3]=="delete_item")): print "deleted web object"+lista[4] object_dict.pop(lista[4],None) #bug index=-1 for b in zoneDict.keys(): if lista[4] in zoneDict[b]["objects"]: index=zoneDict[b]["objects"].index(lista[4]) zoneDict[b]["objects"].pop(index) #zoneDict=zoneDictMod #zoneDict.remove() pag=self.get_WebOjectManager(object_dict) updateDir() try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(pag) except Exception, e : pass print "error20 in send_header "+" e:"+str(e.args) errorQueue.put("error20 in send_header "+" e:"+str(e.args) ) return lista=[] setup_start=string.find(self.path,"setup/") lista=string.split(self.path,"/") #split the path in a list of element divided by "/" if (len(lista))>2: room_t=lista[2] else: room_t="not_A_room" #if (setup_start!=-1)&((len(self.path)-setup_start)==11): # if path is like /setup/Room0 if (setup_start!=-1)&(room_t in zoneDict.keys())&(len(lista)<4): # if path is like /setup/Room0 #print len(self.path)-setup_start #print self.path #print self.path[setup_start+6:] for a in zoneDict.keys() : if (self.path[(setup_start+6):]==a): #found a room in the address bar print "found a room in the address bar" pag=self.get_RoomObjectList(a,object_dict) try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(pag) except Exception, e : pass print "error21 in send_header "+" e:"+str(e.args) errorQueue.put( "error21 in send_header "+" e:"+str(e.args) ) return pag="" try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(pag) except Exception, e : pass print "error22 in send_header "+" e:"+str(e.args) errorQueue.put( "error22 in send_header "+" e:"+str(e.args) ) return else: print self.path[setup_start+6:] if ( (setup_start!=-1)&(len(lista)==4)): #if path is like /setup/Room0/body print "not show room modifier but obj modifier" if (lista[3] in object_dict.keys()): print "edit a web object" pag=self.get_WebObjForm(object_dict[lista[3]]) try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(pag) except Exception, e : pass print "error23 in send_header "+" e:"+str(e.args) errorQueue.put("error23 in send_header "+" e:"+str(e.args) ) return #else: #print " '/setup' not found or len list= "+str(len(lista)) if ((self.path.endswith("?="))&(string.find(self.path,"r_onos_s")==-1)): end_file_name=0 end_file_name=string.find(self.path,".html")+5 web_page='' try: b1 = open(baseRoomPath+self.path[1:end_file_name] ,'r') web_page=b1.read() b1.close() except Exception, e : print "error4 opening the file"+" e:"+str(e.args) errorQueue.put( "error4 opening the file"+" e:"+str(e.args)) pag=modPage(web_page,object_dict,findRoomName(self.path,zoneDict),zoneDict) try: self.send_response(202) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(pag) except Exception, e : pass print "error24 in send_header "+" e:"+str(e.args) errorQueue.put("error24 in send_header "+" e:"+str(e.args) ) return if self.path.endswith(".html"): f = open(curdir + sep + self.path) #self.path has /test.html tmpF=f.read() f.close() #note that this potentially makes every file on your computer readable by the internet try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(tmpF) except Exception, e : pass print "error25 in send_header "+" e:"+str(e.args) errorQueue.put("error25 in send_header "+" e:"+str(e.args) ) f.close() return if self.path.endswith("/"): #the address bar end with / so by default i try open the index.html in this directory print "indirizzo a pag principale.." try: b1 = open(self.path[1:]+"index.html" ,'r') web_page=b1.read() b1.close() except Exception, e : print "error5 opening the file"+" e:"+str(e.args) errorQueue.put("error5 opening the file,local address bar ="+self.path+"index.html"+" e:"+str(e.args) ) print "local address bar ="+self.path+"index.html" web_page=web_page_not_found print web_page try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() pag=modPage(web_page,object_dict,findRoomName(self.path,zoneDict),zoneDict) self.wfile.write(pag) except Exception, e : pass print "error26 in send_header "+" e:"+str(e.args) errorQueue.put( "error26 in send_header "+" e:"+str(e.args) ) #print "percorso=" #print self.path #print "fine percorso" return return except Exception, e : self.send_error(404,'File Not Found: %s' % self.path) print "404,'File Not Found"+" e:"+str(e.args) errorQueue.put("404,'File Not Found"+" e:"+str(e.args) ) def do_POST(self): #get posts data
[docs] try: ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) except Exception, e : print "some error occurred in post connection "+" e:"+str(e.args) errorQueue.put( "some error occurred in post connection "+" e:"+str(e.args)) return if ctype == 'onos/form-data': print "received arduino post data!" length = int(self.headers.getheader('content-length')) postvars = cgi.urlparse.parse_qs(self.rfile.read(length), keep_blank_values=1) node_ip=str(self.client_address[0]) try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write("ok") except Exception, e : pass print "error in send_header "+" e:"+str(e.args) errorQueue.put("error in send_header "+" e:"+str(e.args) ) print "postvars=" print postvars.items() print "data_received" print "len data= "+str(len(postvars.keys()[0] )) print postvars.keys()[0] if (postvars.keys()[0][0:4]=="onos"): node_sn0=postvars.keys()[0][4:16] node_fw =postvars.keys()[0][16:20] input_status_register=postvars.keys()[0][21:] #from 21 till the end print "onos node input pin received from: "+node_sn0+" with ip: "+node_ip+"and fw="+node_fw if node_sn0 in nodeDict.keys(): print "the node exist so i update the pin input status" updateNodeAddress(node_sn0,node_ip)# update the node ip else: msg=createNewNode(node_sn0,node_ip,node_fw) print "the serial number is not in the dictionary...so i add the new node" updateNodeInputStatusFromReg(node_sn0,input_status_register) # decode and update the data from the node if ctype == 'multipart/form-data': #postvars = cgi.parse_multipart(self.rfile, pdict) query=cgi.parse_multipart(self.rfile, pdict) try: self.send_response(301) self.end_headers() except Exception, e : pass print "error27 in send_header "+" e:"+str(e.args) errorQueue.put("error27 in send_header "+" e:"+str(e.args) ) upfilecontent = query.get('upfile') print "filecontent", upfilecontent[0] if len (upfilecontent[0])>10: try: self.wfile.write("<HTML>POST OK WAIT 2 SECONDS THEN GO BACK TO HOME<BR><BR>"); self.wfile.write(upfilecontent[0]); except Exception, e : pass print "error28 in send_header "+" e:"+str(e.args) errorQueue.put("error28 in send_header "+" e:"+str(e.args) ) try: file0 = open('config_files/data.json', "w") file0.write(upfilecontent[0]) file0.close() global exit exit=1 #reboot the webserver except Exception, e : print "error importing json from user"+" e:"+str(e.args) errorQueue.put( "error importing json from user"+" e:"+str(e.args)) self.wfile.write("<HTML>error importing file<BR><BR>"); else: self.wfile.write("<HTML>error importing file<BR><BR>"); elif ctype == 'application/x-www-form-urlencoded': #post data from onos web form length = int(self.headers.getheader('content-length')) postvars = cgi.urlparse.parse_qs(self.rfile.read(length), keep_blank_values=1) print "postvars=" print postvars.items() for a in postvars.keys(): for b in range(len(postvars[a])): print postvars[a][b] print "..." postvars[a][b]=postvars[a][b].decode("utf8","replace") postvars[a][b]=postvars[a][b].encode("ascii","replace") postvars[a][b]=postvars[a][b].replace("?", "_") postvars[a][b]=postvars[a][b].replace(".", "_") #postvars[a][b]=postvars[a][b].replace(";", "_") #postvars[a][b]=postvars[a][b].replace("^", "_") #postvars[a][b]=postvars[a][b].replace("!", "_") #postvars[a][b]=postvars[a][b].replace('"', "_") #postvars[a][b]=postvars[a][b].replace("'", "_") #postvars[a][b]=postvars[a][b].replace("/", "_") #postvars[a][b]=postvars[a][b].replace("%", "_") #postvars[a][b]=postvars[a][b].replace("&", "_") #postvars[a][b]=postvars[a][b].replace(':', "_") # postvars[a][b]=postvars[a][b].replace('*', "_") #postvars[a][b]=postvars[a][b].replace('[', "_") # postvars[a][b]=postvars[a][b].replace(']', "_") #postvars is a dictionary that contain all the data sended by the user..the keys are each <input> name.. #the data are the value of the input data_to_update=0 print "POST:" print postvars.keys() #<form action="" method="POST"><input type="hidden" name="zone_manager" value="/setup/zone_manager"> location="zone_manager" if location in postvars: #if the path is ... i=0 for room in zoneDict.keys() : #for every room..read if the name of the room is being modify from user # room=roomList[i] if (room in postvars): #print "trovata:"+room #print postvars[room][0] new_name=self.clear_PostData(postvars[room][0])#the new name of the directory new_name=new_name.replace("/","_") if ((new_name!=default_rename_zone_value)&(new_name!=default_rename_zone_value2)&(new_name!=default_new_zone_value)&(new_name!=room)&(postvars[room]!=" ")&(len(new_name)>0)&(new_name not in zoneDict.keys())) : #value modified by the user #roomList[i]=name if (room+"_body" in object_dict.keys()) : object_dict[new_name+"_body"]=object_dict[room+"_body"] #copy the body object from the old name object_dict.pop(room+"_body",None)#del object_dict[room+"_body"] #and delete the old key if room+"_body" in zoneDict[room]["objects"] : print "i try to remove the object"+room+"_body from zone"+room index=zoneDict[room]["objects"].index(room+"_body") zoneDict[room]["objects"][index]=new_name+"_body" #rename the webobj in the room else: print "object not removed from zone beacuse not present there" data_to_update=1 zoneDict[new_name] = zoneDict[room] #update the zoneDict with the new key zoneDict.pop(room, None) # del zoneDict[room] #and delete the old key #except: # print "can't remove object from object_dict" try : #os.system("mv "+baseRoomPath+room+" "+baseRoomPath+new_name) #rename the directory with lock_bash_cmd: subprocess.check_output("mv "+baseRoomPath+room+" "+baseRoomPath+new_name, shell=True,close_fds=True) updateOneRoom(new_name) print ("mv "+room+" "+new_name) except Exception, e : print "can't rename directory to"+new_name+" e:"+str(e.args) # i=i+1 if "new_room" in postvars: #the user wants to create a new room print postvars["new_room"][0] new_name=self.clear_PostData(postvars["new_room"][0]) new_name=new_name.replace("/", "_") #print new_name if((new_name!=default_new_zone_value)&(new_name!=default_rename_zone_value)&(new_name!=default_rename_zone_value2)&(len(new_name)>0)&((new_name)!=" ")&(new_name not in zoneDict.keys())&(new_name+"_body" not in object_dict.keys() )): #roomList.append(new_name) #create a new room zoneDict[new_name]={"objects":[],"order":len(zoneDict.keys()),"permissions":"777","group":[],"owner":"onos_sys","hidden":0} zoneDict[new_name]["objects"]=[new_name+"_body"] # modify to update also the webobject dict and list object_dict[new_name+"_body"]=newDefaultWebObjBody(new_name+"_body") #create a new web_object and insert only his name #objectList.append(object_dict[new_name+"_body"]) #os.system("mkdir "+baseRoomPath+new_name) #os.system("cat "+getRoomHtml(new_name,object_dict,"",zoneDict)+" >> "+baseRoomPath+new_name+"/index.html") #os.system("chmod 777 "+new_name) with lock_bash_cmd: subprocess.check_output("mkdir "+baseRoomPath+new_name, shell=True,close_fds=True) subprocess.check_output("cat "+getRoomHtml(new_name,object_dict,"",zoneDict)+" >> "+baseRoomPath+new_name+"/index.html", shell=True,close_fds=True) subprocess.check_output("chmod 777 "+new_name, shell=True,close_fds=True) updateOneRoom(new_name) print "create a new room"+new_name data_to_update=1 print "search in all the zones" for a in zoneDict.keys() : #banana very slow.. if ("delete_room_"+a) in postvars: print "delete room:"+postvars["delete_room_"+a][0] if postvars["delete_room_"+a][0]=='on': delete=a # obj_name_list1=zoneDict[a] # if a+"_body" in obj_name_list1: # print "i try to remove the object "+a+"_body from the zone"+a # index=zoneDict[a].index(a+"_body") # zoneDict[a].pop(index) zoneDict.pop(a,None) object_dict.pop(a+"_body",None) # remove also the web_obj body of the pag from the dict #os.system("rm "+baseRoomPath+a+"/*") #os.system("rmdir "+baseRoomPath+a) with lock_bash_cmd: subprocess.check_output("rm "+baseRoomPath+a+"/*", shell=True,close_fds=True) subprocess.check_output("rmdir "+baseRoomPath+a, shell=True,close_fds=True) data_to_update=1 postvars = {} pag=self.get_zone_manager(zoneDict) try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(pag) except Exception, e : pass print "error29 in send_header "+" e:"+str(e.args) errorQueue.put("error29 in send_header "+" e:"+str(e.args) ) #updateJson( object_dict,zoneDict) updateDir() if "zone_objects_setup" in postvars: # to add or remove objects to a zone zone=self.clear_PostData(postvars["zone_objects_setup"][0]) print "zone_objects_setup page send a post to mode zone"+zone obj_name_list=zoneDict[zone]["objects"] for a in object_dict.keys(): #a=b.replace("_sl_obj_room","") if (1): if (a+"_sl_obj_room" in postvars): if (postvars[a+"_sl_obj_room"][0]=='on'): if a not in obj_name_list: print "add obj to zone :"+a zoneDict[zone]["objects"].append(a) #add the else:# not checked , so remove the object from the zone if it is there if a in obj_name_list: print "i try to remove the object "+a+"from the zone"+zone index=zoneDict[zone]["objects"].index(a) zoneDict[zone]["objects"].pop(index) else: # not checked , so remove the object from the zone if it is there if a in obj_name_list: print "i try to remove the object "+a+"from the zone"+zone index=zoneDict[zone]["objects"].index(a) zoneDict[zone]["objects"].pop(index) if ("new_objects" in postvars): new_obj0=self.clear_PostData(postvars["new_objects"][0]) new_obj=new_obj0+'_p_'+zone if ( (new_obj0 !="TYPE_NEW_OBJECT_HERE")&(new_obj not in object_dict.keys())&(len(new_obj)>0)&(new_obj!=" ") ): object_dict[new_obj]=newDefaultWebObj(new_obj) #create a new object and insert it in the dictionary zoneDict[zone]["objects"].append(new_obj) #add the object name to the zone postvars={} updateOneRoom(zone)#to update the zone with the new objects webpag=self.get_Zone_Objects_Setup(self.path,object_dict,zone) try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(webpag) except Exception, e : pass print "error30 in send_header "+" e:"+str(e.args) errorQueue.put("error30 in send_header "+" e:"+str(e.args) ) if "objs_manager" in postvars: objs_manager=self.clear_PostData(postvars["objs_manager"][0]) print "objs_manager"+objs_manager q="new_web_object" if q in postvars: new_obj=self.clear_PostData(postvars[q][0]) print "try to create a new webobj"+new_obj if((new_obj!=default_new_obj_value)&(new_obj!=default_new_obj_value2)&(len(new_obj)>0)&((new_obj)!=" ")&( new_obj not in object_dict.keys() ) ): object_dict[new_obj]=newDefaultWebObj(new_obj) #create a new web_object and insert only his name # objectList.append(object_dict[new_obj]) print "created a new web object "+object_dict[new_obj].getName() data_to_update=1 postvars = {} pag=self.get_WebOjectManager(object_dict) try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(pag) except Exception, e : pass print "error31 in send_header "+" e:"+str(e.args) errorQueue.put( "error31 in send_header "+" e:"+str(e.args)) #updateJson( object_dict,zoneDict) if "current_room" in postvars:#if the current location is /setup/AnyRoomName because "current_room" is a post of that page currentRoom=self.clear_PostData(postvars["current_room"][0]) q="new_web_object" if q in postvars: new_obj=self.clear_PostData(postvars[q][0]) if((new_obj!=default_new_obj_value)&(new_obj!=default_new_obj_value2)&(len(new_obj)>0)&((new_obj)!=" ")&( new_obj not in object_dict.keys() ) ): object_dict[new_obj]=newDefaultWebObj(new_obj) #create a new web_object and insert only his name # objectList.append(object_dict[new_obj]) print "created a new web object "+object_dict[new_obj].getName() data_to_update=1 base_rm="rm_obj_" end_rm="_from_"+currentRoom #enabledToWrite=0 #tell the system if the textarea html has to be ignored or written to the file for a in postvars.keys() : print "postvars=" print postvars[a] if ((string.find(a,"add_obj_to_room")!=-1)&((postvars[a][0]) in object_dict.keys())&(postvars[a][0]not in zoneDict[currentRoom]["objects"] )): #add a obj to the room zoneDict[currentRoom]["objects"].append(postvars[a][0]) updateOneRoom(currentRoom) #html_to_write=getRoomHtml(currentRoom,object_dict,"",zoneDict) #file0 = open(currentRoom+"/index.html", "w") #file0.write(html_to_write) #file0.close() print "found a add_obj post" print "room list" print zoneDict[currentRoom]["objects"] if (string.find(a,"rm_obj_")!=-1)&((postvars[a][0]) in zoneDict[currentRoom]["objects"] ): #remove obj from the room index=zoneDict[currentRoom]["objects"].index(postvars[a][0]) zoneDict[currentRoom]["objects"].pop(index) print "found a rm_obj post" print "now the room is this" print zoneDict[currentRoom]["objects"] data_to_update=1 else: print "error obj to remove not found " errorQueue.put("error obj to remove not found " ) #updateOneRoom(currentRoom) if data_to_update==1: #update the html removing the webobj removed by the form html_to_write=getRoomHtml(currentRoom,object_dict,"",zoneDict) # file0 = open(baseRoomPath+currentRoom+"/index.html", "w") # file0.write(html_to_write) # file0.close() data_to_update=0 print "object removed from html" postvars = {} #print "actual room: "+currentRoom pag=self.get_RoomObjectList(currentRoom,object_dict) try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(pag) except Exception, e : pass print "error32 in send_header "+" e:"+str(e.args) errorQueue.put("error32 in send_header "+" e:"+str(e.args) ) #updateJson( object_dict,zoneDict) #updateOneRoom(currentRoom) if "current_room_text_area" in postvars: currentRoom=self.clear_PostData(postvars["current_room_text_area"][0]) new_html_room=postvars["html_room_mod"][0] print "new_html_room="+new_html_room print "currentroom_modhtm="+currentRoom #updateOneRoom(currentRoom) html_to_write=modPage(new_html_room,object_dict,currentRoom,zoneDict) print "html wrote to the file "+currentRoom+"/index.html="+html_to_write print "correction..not wrote because commented part" #file0 = open(baseRoomPath+currentRoom+"/index.html", "w") #file0.write(html_to_write) #file0.close() postvars = {} pag=self.get_RoomObjectList(currentRoom,object_dict) try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(pag) except Exception, e : pass print "error33 in send_header "+" e:"+str(e.args) errorQueue.put("error33 in send_header "+" e:"+str(e.args) ) #updateJson( object_dict,zoneDict) if "mod_object" in postvars:#if the current page is /setup/AnyRoomName/Anywebobject because "mod_object" is a post of that page print "found a mod_object request with path" path=postvars["mod_object"][0] print path web_object_name=string.split(path,"/")[3] #split the path in a list of string print "modify the web object:"+web_object_name for a in postvars.keys() : if (postvars["obj_notes"]!=notes): object_dict[web_object_name].setNotes(postvars["obj_notes"][0]) if (postvars["obj_hardware_pin"]!=no_pin_selected)&(len(postvars["obj_hardware_pin"])>0): try: object_dict[web_object_name].setAttachedPin(int (postvars["obj_hardware_pin"][0])) except: object_dict[web_object_name].setAttachedPin(9999) # if (postvars["obj_type"]!=object_dict[web_object_name].getType()): # changeWebObjectType(web_object_name,postvars["obj_type"][0]) #object_dict[web_object_name].setType(postvars["obj_type"][0]) if (postvars["obj_current_status"]!=int (object_dict[web_object_name].getStatus())): #object_dict[web_object_name].setStatus(int(postvars["obj_current_status"][0])) changeWebObjectStatus(web_object_name,int (postvars["obj_current_status"][0]),1)#banana add to queue if (postvars["obj_style0"]!=style0): object_dict[web_object_name].setStyle0(postvars["obj_style0"][0]) if (postvars["obj_style1"]!=style1): object_dict[web_object_name].setStyle1(postvars["obj_style1"][0]) if (postvars["obj_html0"]!=html0): object_dict[web_object_name].setHtml0(postvars["obj_html0"][0]) if (postvars["obj_html1"]!=html1): object_dict[web_object_name].setHtml1(postvars["obj_html1"][0]) if (postvars["obj_cmd0"]!=" "): object_dict[web_object_name].setCommand0(formParse(postvars["obj_cmd0"][0])) if (postvars["obj_cmd1"]!=" "): object_dict[web_object_name].setCommand1(formParse(postvars["obj_cmd1"][0])) if (postvars["obj_init_cmd"]!=" "): object_dict[web_object_name].setInitCommand(formParse(postvars["obj_init_cmd"][0])) object_dict[web_object_name].InitFunction() #execute the new init command postvars = {} data_to_update=1 pag=self.get_WebObjForm(object_dict[web_object_name]) try: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(pag) except Exception, e : pass print "error34 in send_header "+" e:"+str(e.args) errorQueue.put( "error34 in send_header "+" e:"+str(e.args)) #updateJson( object_dict,zoneDict) updateDir() if "new_scenario" in postvars:#if the current page is /scenarios_list/ because "new_scenario" is the hidden form name #<input type="hidden" name="new_scenario" value="/scenarios_list/"> pag="" if (postvars["new_scenario_name"]!=" "): new_scenario_name=self.clear_PostData(postvars["new_scenario_name"][0]) if new_scenario_name not in scenarioDict.keys(): #if scenario name doesn't exist already scenarioDict[new_scenario_name]={"enabled":0,"type_after_run":"0","conditions":"0","functionsToRun":[],"delayTime":0,"priority":0} self.send_response(301) self.send_header('Location','/mod_scenario/'+new_scenario_name+'/') self.end_headers() return if "delete_scenario" in postvars:# if(postvars["delete_scenario"][0]!=" "): print "received delete_scenario" , postvars["delete_scenario"][0] del_scenario_name=self.clear_PostData(postvars["delete_scenario"][0]) if del_scenario_name in scenarioDict.keys(): #if scenario name doesn't exist for a in object_dict.keys():#check and remove the not used scenarios from web_object attachedScenarios tmp_list_scenarios=object_dict[a].getListAttachedScenarios() if del_scenario_name in tmp_list_scenarios: object_dict[a].removeAttachedScenario(del_scenario_name) del scenarioDict[del_scenario_name] self.send_response(301) self.send_header('Location','/scenarios_list/') self.end_headers() return if "mod_scenario" in postvars:#if the current page is /mod_scenario/scenario name because "mod_scenario" is the hidden form name #<input type="hidden" name="mod_scenario" value="/scenarios_list/mod_scenario/"> pag="" if (postvars["mod_scenario"]!=" "): scenario_start_name=self.clear_PostData(postvars["mod_scenario"][0])#get the current scenario name if (postvars["new_scenario_name"][0]!=" "): scenario_name=self.clear_PostData(postvars["new_scenario_name"][0])#get the current scenario name if scenario_start_name in scenarioDict: #if the name exist in the dict if scenario_name != scenario_start_name : #the scenario was renamed if scenario_name not in scenarioDict: scenarioDict[scenario_name]=scenarioDict[scenario_start_name] del scenarioDict[scenario_start_name] for obj in object_dict.keys(): object_dict[obj].replaceAttachedScenario(scenario_start_name,scenario_name) #replace the reference in the web object with the new one if "enabling" in postvars: if self.clear_PostData(postvars["enabling"][0])=="on": scenarioDict[scenario_name]['enabled']=1 else: scenarioDict[scenario_name]['enabled']=0 #print "scenario disabled" else: scenarioDict[scenario_name]['enabled']=0 #print "scenario disabled" if "set_type_after_run" in postvars: print "select:",postvars["set_type_after_run"] print "select2:",postvars["set_type_after_run"][0] if self.clear_PostData(postvars["set_type_after_run"][0])=="autodelete": scenarioDict[scenario_name]["type_after_run"]="autodelete" elif self.clear_PostData(postvars["set_type_after_run"][0])=="one_time_shot": scenarioDict[scenario_name]["type_after_run"]="one_time_shot" else: scenarioDict[scenario_name]["type_after_run"]="0" if "delay_time" in postvars: delay=self.clear_PostData(postvars["delay_time"][0]) try: delay=int(delay) scenarioDict[scenario_name]["delayTime"]=delay except Exception, e : print "error in mod_scenario delay_time form post parse "+" e:"+str(e.args) if "priority" in postvars: priority=self.clear_PostData(postvars["priority"][0]) try: priority=int(priority) scenarioDict[scenario_name]["priority"]=priority except Exception, e : print "error in mod_scenario priority form post parse "+" e:"+str(e.args) if "conditions" in postvars: conditions=self.clear_PostData(postvars["conditions"][0]) try:# deny the user to use a void string.. a=eval(replace_conditions(conditions,scenario_name)[0]) scenarioDict[scenario_name]["conditions"]=conditions for a in object_dict.keys():#check and remove the not used scenarios from web_object attachedScenarios tmp_list_scenarios=object_dict[a].getListAttachedScenarios() for b in tmp_list_scenarios: if scenarioDict[b]["conditions"].find(a+"_#")==-1: # if the object is not in the conditions then remove it from web_object attachedScenarios object_dict[a].removeAttachedScenario(b) list_of_object_inside_conditions=replace_conditions(conditions,scenario_name)[1] for a in list_of_object_inside_conditions :# add the scenario to each web_object attachedScenarios if a in object_dict.keys(): object_dict[a].attachScenario(scenario_name) #if the scenario is not included in the web_object attachedScenarios except Exception, e : print "error in mod_scenario conditions form post parse "+" e:"+str(e.args) if "functions" in postvars: functions=self.clear_PostData(postvars["functions"][0]) try: #a=eval(replace_functions(functions,scenario_name)) print "functionsToRun=",functions.split(';;;') scenarioDict[scenario_name]["functionsToRun"]=functions.split(';;;') #banana no check if the functions are right except Exception, e : print "error in mod_scenario functions form post parse "+" e:"+str(e.args) # except Exception, e : # print "error in mod_scenario form post parse "+" e:"+str(e.args) # errorQueue.put( "error in mod_scenario form post parse "+" e:"+str(e.args)) #scenarioDict[scenario_name]={"enabled":0,"type_after_run":"0","conditions":"0","functionsToRun":[],"delayTime":0,"priority":0} if "set_conditions_submit" in postvars: self.send_response(301) self.send_header('Location','/scenario_conditions/'+scenario_name) self.end_headers() elif "set_function_submit" in postvars: self.send_response(301) self.send_header('Location','/function_to_run/'+scenario_name) self.end_headers() elif "finish_scenario_setup" in postvars: self.send_response(301) self.send_header('Location','/scenarios_list/') self.end_headers() return if "mod_conditions" in postvars:#if the current page is /mod_conditions/scenario name because "mod_scenario" is the hidden form name #<input type="hidden" name="mod_conditions" value=""> scenario_name=self.clear_PostData(postvars["mod_conditions"][0])#get the current scenario name if scenario_name not in scenarioDict: return(-1) if (postvars["menu_number"]!=" "): menu_number=int(self.clear_PostData(postvars["menu_number"][0])) print "gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg",menu_number else: return(-1) #print "menu_number",menu_number conditions="" for i in range(1,menu_number+1): try: left_element="#_"+self.clear_PostData(postvars["select_l"+str(i)][0])+"_#" operator=self.clear_PostData(postvars["select_op"+str(i)][0]) if operator=="=": operator="==" right_element=self.clear_PostData(postvars["select_r"+str(i)][0]) try:#detect if is a number a=float(right_element) except: right_element="#_"+right_element+"_#" if i==1: #first time don't add "&" conditions="("+left_element+operator+right_element+")" else: conditions=conditions+"&("+left_element+operator+right_element+")" except: print "error get cond menu" try: l="#_"+self.clear_PostData(postvars["select_new_l"][0])+"_#" o=self.clear_PostData(postvars["select_new_o"][0]) if o=="=": o="==" r=self.clear_PostData(postvars["select_new_r"][0]) try:#detect if is a number a=float(r) except: r="#_"+r+"_#" if (l!="#_select_an_element_#")&(r!="#_select_an_element_#"): if menu_number<1: conditions=conditions+"("+l+o+r+")" else: conditions=conditions+"&("+l+o+r+")" except: print "error2 get cond menu" scenarioDict[scenario_name]["conditions"]=conditions print "conditions",conditions for a in object_dict.keys():#check and remove the not used scenarios from web_object attachedScenarios tmp_list_scenarios=object_dict[a].getListAttachedScenarios() for b in tmp_list_scenarios: if scenarioDict[b]["conditions"].find(a+"_#")==-1: # if the object is not in the conditions then remove it from web_object attachedScenarios object_dict[a].removeAttachedScenario(b) else: object_dict[a].attachScenario(b) list_of_object_inside_conditions=replace_conditions(conditions,scenario_name)[1] for a in list_of_object_inside_conditions :# add the scenario to each web_object attachedScenarios if a in object_dict.keys(): object_dict[a].attachScenario(scenario_name) #if the scenario is not included in the web_object attachedScenarios if "condition_add_submit" in postvars: self.send_response(301) self.send_header('Location','/scenario_conditions/'+scenario_name) self.end_headers() return elif "finish_conditions_setup" in postvars: self.send_response(301) self.send_header('Location','/mod_scenario/'+scenario_name) self.end_headers() return if "function_to_run_1" in postvars:#if the current page is /function_to_run/scenario name because "function_to_run_1" is the hidden form name #<input type="hidden" name="mod_functions1a" value=""> scenario_name=self.clear_PostData(postvars["function_to_run_1"][0])#get the current scenario name if scenario_name not in scenarioDict: return(-1) if (postvars["menu_number"]!=" "): menu_number=int(self.clear_PostData(postvars["menu_number"][0])) else: return(-1) print "menu_number",menu_number functions_list=[] for i in range(1,menu_number+1): try: left_element="#_"+self.clear_PostData(postvars["select_l"+str(i)][0])+"_#" operator=self.clear_PostData(postvars["select_op"+str(i)][0]) second_operator=self.clear_PostData(postvars["second_op"+str(i)][0]) if operator=="==": operator="=" right_element=self.clear_PostData(postvars["select_r"+str(i)][0]) third_element=self.clear_PostData(postvars["third_element"+str(i)][0]) try:#detect if is a number a=float(right_element) except: right_element="#_"+right_element+"_#" if (third_element!="")&(third_element!=" ")&(second_operator!="")&(second_operator!=" "): try:#detect if is a number a=float(third_element) except: third_element="#_"+third_element+"_#" functions_list.append(left_element+operator+right_element+second_operator+third_element) except: print "error get func menu" try: l="#_"+self.clear_PostData(postvars["select_new_l"][0])+"_#" o=self.clear_PostData(postvars["select_new_o"][0]) if o=="==": o="=" r=self.clear_PostData(postvars["select_new_r"][0]) try:#detect if is a number a=float(r) except: r="#_"+r+"_#" if (l!="#_select_an_element_#")&(r!="#_select_an_element_#"): functions_list.append(l+o+r) except: print "error2 get cond menu" scenarioDict[scenario_name]["functionsToRun"]=functions_list print "functions",functions_list if "condition_add_submit" in postvars: self.send_response(301) self.send_header('Location','/function_to_run/'+scenario_name) self.end_headers() return elif "finish_conditions_setup" in postvars: self.send_response(301) self.send_header('Location','/mod_scenario/'+scenario_name) self.end_headers() return if "login_form" in postvars:#if the current page is /login.html because "login_form" is the hidden form name #<form action="" method="POST"><input type="hidden" name="login_form" value="/login"> pag="" if ((postvars["username_form"]!=" ")&(postvars["password_form"]!=" ")): username=self.clear_PostData(postvars["username_form"][0]) password=self.clear_PostData(postvars["password_form"][0]) if (username in usersDict.keys()): #if the username exist if usersDict[username]["pw"]==password : #if the password is correct user_active_time_dict[self.client_address[0]]=[username,datetime.datetime.today().minute+(datetime.datetime.today().hour)*60 ] print "user ip is:",self.client_address[0] print user_active_time_dict print "user :"+username+"logged succesfully" #pag="successfully logged" self.send_response(301) self.send_header('Location','/') self.end_headers() return else: print "error user :"+username+"cant't log because of wrong password" errorQueue.put("error user :"+username+"cant't log because of wrong password" ) #pag="wrong password" self.send_response(301) self.send_header('Location','/gui/password_error.html') self.end_headers() return else: print "error an user tried to log in with a wrong username" errorQueue.put("error an user tried to log in with a wrong username" ) self.send_response(301) self.send_header('Location','/gui/user_error.html') self.end_headers() return #pag="wrong username" if "new_user_form" in postvars:#if the current page is /create_user.html because "new_user_form" is the hidden form name # <form action="" method="POST"><input type="hidden" name="new_user_form" value=""> pag="" if ((postvars["create_user_form"]!=" ")&(postvars["create_password_form"]!=" ")&(postvars["repeat_password_form"]!=" ")): username=self.clear_PostData(postvars["create_user_form"][0]) password=self.clear_PostData(postvars["create_password_form"][0]) repeated_password=self.clear_PostData(postvars["repeat_password_form"][0]) mail=self.clear_PostData(postvars["create_mail_form"][0]) if (password!=repeated_password): #wrong password entered message="error the two passwords entered are not the same, please retype" print message errorQueue.put(message ) cgi_name="gui/new_user.py" namespace={} web_page="" execfile(cgi_name,locals(),namespace) #execute external script /gui/pag_creator.py web_page=namespace["web_page"] self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(web_page) return if (internet_connection!=1): # no internet connection message="error internet connection lost while creating onos online user, please connect onos center to internet" print message errorQueue.put(message) cgi_name="gui/new_user.py" namespace={} web_page="" execfile(cgi_name,locals(),namespace) #execute external script /gui/pag_creator.py web_page=namespace["web_page"] self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(web_page) return if (username not in usersDict.keys()): #if the username does not alredy exist in the local dictionary site_query=onos_online_site_url+"create_new_onos_user.php" params = {'username':username, 'onos_key':onos_online_key,"user_pass":password,"onos_password":onos_online_password} try : f=url_request_manager.request_encode_body('POST',site_query,params,timeout=Timeout(total=20)) result=f.data print result except Exception, e : message="server online query to create new user failed,please check connection and retry"+" e:"+str(e.args) print message errorQueue.put(message ) cgi_name="gui/new_user.py" namespace={} web_page="" execfile(cgi_name,locals(),namespace) #execute external script /gui/pag_creator.py web_page=namespace["web_page"] self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(web_page) return if (result.find("syntax error")!=-1)or (result.find("error_")!=-1): message="error in the server answer while creating onos online user, please retry" print message errorQueue.put(message ) cgi_name="gui/new_user.py" namespace={} web_page="" execfile(cgi_name,locals(),namespace) #execute external script /gui/pag_creator.py web_page=namespace["web_page"] self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(web_page) return if (result.find("#_onos_online_user_created")!=-1): #the username was created in the online server usersDict[username]={"pw":password,"mail_control_password":password,"priority":0,"user_mail":mail} message="username created in the online server and in the onos server" print message errorQueue.put(message ) cgi_name="gui/new_user.py" namespace={} web_page="" execfile(cgi_name,locals(),namespace) #execute external script /gui/pag_creator.py web_page=namespace["web_page"] self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(web_page) else: #username already used on online server message="error the username is already used in the online server,please choose another username and retry,result:"+result print message errorQueue.put(message ) cgi_name="gui/new_user.py" namespace={} web_page="" execfile(cgi_name,locals(),namespace) #execute external script /gui/pag_creator.py web_page=namespace["web_page"] self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(web_page) return else: message="error the username is already used in the onosCenter,please choose another username and retry" print message errorQueue.put(message ) cgi_name="gui/new_user.py" namespace={} web_page="" execfile(cgi_name,locals(),namespace) #execute external script /gui/pag_creator.py web_page=namespace["web_page"] self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(web_page) return if "post0" in postvars: print "received post0:" print postvars["post0"][0] # print the first post variable if (data_to_update==100): #updateJson( object_dict,zoneDict) updateDir() data_to_update=0 else: postvars = {} #a timeout class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): # i don't know if usefull to close client timout connections
[docs] print "class RequestHandler executed()" def setup(self):
[docs] BaseHTTPServer.BaseHTTPRequestHandler.setup(self) self.request.settimeout(30) def finish_request(self, request, client_address): print "finish_request() executed" request.settimeout(30) # "super" can not be used because BaseServer is not created from object BaseHTTPServer.HTTPServer.finish_request(self, request, client_address) #another timeout #class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):# i don't know if usefull to close client timout # def __init__(self, request, client_address, server): # BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, request, client_address, server) # print "classsee eseguitaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" def onlineServerSync():
[docs] print "onlineServerSync() excuted" global onlineServerSyncThreadIsrunning global online_first_contact global online_usersDict global force_online_sync_users global online_zone_dict global online_object_dict result="" while (exit==0): #if exit ==1 then close the service onlineServerSyncThreadIsrunning=1 # try: # urllib2.urlopen("http://www.google.com") # except: # print "no internet connection" # errorQueue.put("no internet connection" ) #time.sleep(30) #wait 60 seconds # return try: object_tmp_dict=transform_object_to_dict(object_dict) except Exception, e : print "error executing transform_object_to_dict()"+" e:"+str(e.args) errorQueue.put("error executing transform_object_to_dict()"+" e:"+str(e.args) ) if (online_first_contact==1) : zone_json_dictionary=json.dumps(zoneDict) object_json_dictionary=json.dumps(object_tmp_dict) #site_query=onos_online_site_url+"create_new_onos_center.php" #params = urllib.urlencode({'onos_key': onos_online_key, 'pass':onos_online_password,'hw_fw_version':router_hardware_fw_version}) #f = urllib.urlopen(site_query, params) #print f.read() #banana check the answer to see if the database was created #update all objects and zones site_query=onos_online_site_url+"db_sync_with_onos.php" params = {'onos_key': onos_online_key, 'onos_password':onos_online_password,"zone_sync":"1","zone_dict":zone_json_dictionary,"obj_sync":"all","obj_dict":object_json_dictionary} try : #f = urllib2.urlopen(site_query, params,timeout = 5) f=url_request_manager.request_encode_body('POST',site_query,params,timeout=Timeout(total=20)) result=f.data print result online_first_contact=0 online_object_dict=object_json_dictionary online_zone_dict=zone_json_dictionary except Exception, e : print "first online contact failed" +" e:"+str(e.args) errorQueue.put("first online contact failed"+" e:"+str(e.args) ) continue if (result.find("syntax error")!=-1)or (result.find("error_")!=-1): online_object_dict="" online_zone_dict="" online_first_contact=1 #time.sleep(online_server_delay) #onlineServerSyncThreadIsrunning=0 #return continue #if (cmp(online_usersDict,online_synced_user_dict))!=0 : #the dictionaries are different banana, to get this value from the server if (force_online_sync_users==1): #create a copy of all the local users in the online db print "i create the remote users" site_query=onos_online_site_url+"create_new_onos_user.php" for a in online_usersDict.keys(): # for each local username params = {'onos_key': onos_online_key, 'onos_password':onos_online_password,"username":a,"user_pass":online_usersDict[a]["pw"]} try: #f = urllib2.urlopen(site_query, params,timeout = 5) f=url_request_manager.request_encode_body('POST',site_query,params,timeout=Timeout(total=20)) result=f.data print result force_online_sync_users=0 except Exception, e : print "error creating online user "+" e:"+str(e.args) errorQueue.put( "error creating online user "+" e:"+str(e.args)) if (result.find("syntax error")!=-1)or (result.find("error_")!=-1): force_online_sync_users=1 object_json_dictionary=json.dumps(object_tmp_dict) if (object_json_dictionary!=online_object_dict): #the dictionaries are different print "i sync the remote object dict" #print "object_json_dictionary:"+object_json_dictionary site_query=onos_online_site_url+"db_sync_with_onos.php" params = {'onos_key': onos_online_key, 'onos_password':onos_online_password,"zone_sync":"0","obj_sync":"all","obj_dict":object_json_dictionary} try: #f = urllib2.urlopen(site_query, params,timeout = 5) #result=f.read() f=url_request_manager.request_encode_body('POST',site_query,params,timeout=Timeout(total=20)) result=f.data print result online_object_dict=object_json_dictionary except Exception, e : print "error in the remote object update"+" e:"+str(e.args) errorQueue.put("error in the remote object update"+" e:"+str(e.args) ) online_object_dict="" continue if (result.find("syntax error")!=-1)or (result.find("error_")!=-1): online_object_dict="" continue zone_json_dictionary=json.dumps(zoneDict) #print "cmp zone----------------------------------------",cmp(zone_json_dictionary,online_zone_dict) if (zone_json_dictionary!=online_zone_dict) : #the dictionaries are different banana, to get this value from the server print "i sync the remote zone dict" site_query=onos_online_site_url+"db_sync_with_onos.php" params = {'onos_key': onos_online_key, 'onos_password':onos_online_password,"zone_sync":"1","zone_dict":zone_json_dictionary,"obj_sync":"0"} try: #f = urllib2.urlopen(site_query, params,timeout = 5) #result=f.read() f=url_request_manager.request_encode_body('POST',site_query,params,timeout=Timeout(total=20)) result=f.data print result online_zone_dict=zone_json_dictionary #banana, to get this value from the server except Exception, e : print "error in the remote object update"+" e:"+str(e.args) errorQueue.put("error in the remote object update"+" e:"+str(e.args) ) online_zone_dict="" continue if (result.find("syntax error")!=-1)or (result.find("error_")!=-1): online_zone_dict="" continue #time_sync=datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S") # '2015-08-19-09-15-18' time to allow the server detect when the onos center is online site_query=onos_online_site_url+"get_sync_messages.php" params = {'onos_key': onos_online_key, 'onos_password': onos_online_password,'hw_fw_version':router_hardware_fw_version} try: #f = urllib2.urlopen(site_query, params,timeout = 5) #sync_message=f.read() f=url_request_manager.request_encode_body('POST',site_query,params,timeout=Timeout(total=20)) result=f.data sync_message=result print sync_message except Exception, e : print "error contacting the online server to get sync message"+" e:"+str(e.args) errorQueue.put( "error contacting the online server to get sync message"+" e:"+str(e.args)) onlineServerSyncThreadIsrunning=0 return() #message example : # '#start@#_@onosuser#_@obj_ch#_@obj1#_@objstatus_to_set#_#stop@" message for online obj changed to objstatus_to_set try: ###json_filtered_msg=re.match(r'#_cmd_.+?_cmd_#',sync_message).group(1) #re.search('#_cmd_(.+?)_cmd_#',sync_message).group(1) #json_filtered_msg=sync_message.partition("#_cmd_")[2].partition("_cmd_#")[0] json_filtered_msg=re.search('#_cmd_(.+?)_cmd_#',sync_message).group(1) print "filtered sync_message :"+json_filtered_msg cmd_list=json.loads(json_filtered_msg) print "json_cmd_list:",cmd_list for a in cmd_list : #iterate the list cmd_split=a.split("#_@") #split using #_@ as delimiter print "cmd_split",cmd_split username=cmd_split[1] if username not in usersDict.keys(): print "error online username not in local users Dict" errorQueue.put( "error online username not in local users Dict") continue cmd_code=cmd_split[2] print "online username:"+username print "cmd code="+cmd_code if cmd_code=="obj_ch": obj_name=cmd_split[3] status_to_set=cmd_split[4] priority=usersDict[username]["priority"] priorityCmdQueue.put( {"cmd":"setSts","webObjectName":obj_name,"status_to_set":status_to_set,"write_to_hw":1,"priority":priority,"user":username,"mail_report_list":[] }) except Exception, e : print "sync_message decoding error,sync_message:"+sync_message+" e:"+str(e.args) errorQueue.put( "sync_message decoding error,sync_message"+sync_message+" e:"+str(e.args) ) onlineServerSyncThreadIsrunning=0 return() onlineServerSyncThreadIsrunning=0 return() def mailOutputHandler():
[docs] global errorQueue global mailOutputHandler_is_running mailOutputHandler_is_running=1 print "mailOutputHandler thread executed" while not mailQueue.empty(): #until there are no more mail to send mail_to_send = mailQueue.get() #mailQueue.task_done() mail_address=mail_to_send["mail_address"] mailText=mail_to_send["mailText"] mailSubject=mail_to_send["mailSubject"] mail_sent=sendMail(mail_address,mailText,mailSubject,onos_mail_conf,smtplib,string) if mail_sent!=1 : #mail error , onos was not able to send the mail and will try again print "error cant send mail" errorQueue.put("error cant send mail" ) errorQueue.put(mail_sent) mailQueue.put(mail_to_send) #read the mail to the queue for further try #mailQueue.put({"mail_address":mail_address,"mailText":mailText,"mailSubject":mailSubject}) time.sleep(mail_retry_timeout) # wait before retry...to not overuse the cpu mailOutputHandler_is_running=0 return def mailCheckThread():
[docs] print "mailCheckThread() excuted" global mailCheckThreadIsrunning mailCheckThreadIsrunning=1 if (exit==0): #if exit ==1 then close the webserver #time.sleep(1) #wait try: mailList=receiveMail(onos_mail_conf,imaplib,email) #a list of list where the data are (msg_sender,msg_subject,msg_text) except Exception, e: print "error in mailagent"+str(e.args) errorQueue.put("error in mailagent"+str(e.args)) mailList=-1 if mailList==-1: print "error mailagent , wrong username/password or no internet connection" errorQueue.put( "error mailagent , wrong username/password or no internet connection,i disable the mail service") print "i disable the mail service" enable_mail_service=0 return() if len(mailList)>0: #there are mails for rx_mail in mailList: #print "rx mail=",rx_mail m_sender=rx_mail[0] m_subject=rx_mail[1] m_text=rx_mail[2] rx_mail_lines=m_text.splitlines() #split by lines #answer_mail=[] mailText="" #answer mail text mailSubject="onos_report" #answer mail subject for l in rx_mail_lines: #for each line there will be a command... l=l.strip()#remove start and end spaces onos_usr="onos_mail_guest" usr_onos_mail_pw=usersDict[onos_usr]["mail_control_password"] cmd_type="" cmd_argument="" priority="" log_enable=0 scenario_enable="" status="" # example : onos=cmd:so,arg:button1_RouterGL0000,st:1, note the end "," must be used if 1: tmp_split=l.split(",") for t_arg in tmp_split: if (t_arg.find(u"usr:"))!=-1: onos_usr=t_arg.split(u":")[1] #get onos_usr from "usr:onos_usr" if (t_arg.find(u"pw:"))!=-1: usr_onos_mail_pw=t_arg.split(u":")[1] #get onos_pw from "pw:onos_pw" if (t_arg.find(u"cmd:"))!=-1: cmd_type=t_arg.split(u":")[1] if (t_arg.find(u"st:"))!=-1: status=t_arg.split(u":")[1] if (t_arg.find(u"arg:"))!=-1: cmd_argument=t_arg.split(u":")[1] if (t_arg.find(u"priority:"))!=-1: priority=t_arg.split(u":")[1] if onos_usr not in usersDict.keys() : print "error mail user not in user list" errorQueue.put( "error mail user not in user list" ) mailText=mailText+compose_error_mail("wrong_username") continue if compareText(usr_onos_mail_pw,usersDict[onos_usr]["mail_control_password"])!=1 : print "error mail user password not correct" errorQueue.put( "error mail user password not correct" ) mailText=mailText+compose_error_mail("wrong_password") continue if compareText(onos_usr,onos_usr)==1: #if the username is the default mail one.. if m_sender not in mail_whiteList : print "error mail not in mail list" errorQueue.put("error mail not in mail list" ) mailText=mailText+compose_error_mail("white_list") continue if accept_only_from_white_list==1: if m_sender not in mail_whiteList : print "error mail not in mail list" errorQueue.put( "error mail not in mail list" ) mailText=mailText+compose_error_mail("white_list") continue else: print "mail parsing error" errorQueue.put("mail parsing error" ) mailText=mailText+compose_error_mail("parse") continue if (len(priority)==0): priority=usersDict[onos_usr]["priority"] #print "priority set to :",priority if compareText(cmd_type,u"so"): #if the cmd type is set object.. if (len(cmd_argument)>0)&(len(status)>0): #the arguments lenghts are ok if cmd_argument in object_dict: #the object exist obj_previous_status=object_dict[cmd_argument].getStatus() if (object_dict[cmd_argument].validateStatusToSetObj(status)==1 ): #if the status is ok and type is output print "check priority" if object_dict[cmd_argument].checkRequiredPriority(priority)==1: #check priority print "priority ok" #check permission if object_dict[cmd_argument].checkPermissions(onos_usr,"x",priority):#check if user has execution to obj print "permission ok ,i write to obj" mailText=mailText+"O.N.O.S. received the mail :"+l+" and is processing it ," priorityCmdQueue.put( {"cmd":"setSts","webObjectName":cmd_argument,"status_to_set":status,"write_to_hw":1,"priority":priority,"user":"onos_usr","mail_report_list":[m_sender] }) continue else: #permission error mailText=mailText+compose_error_mail("so_permissions",cmd_argument) continue else: print "error mail , user priority not sufficent to change the obj status" errorQueue.put("error mail , user priority not sufficent to change the obj status" ) mailText=mailText+compose_error_mail("so_priority",cmd_argument) continue else: print "error mail ,object type not compatible with status passed " errorQueue.put("error mail ,object type not compatible with status passed " ) mailText=mailText+compose_error_mail("so_value",cmd_argument) continue else: print "error mail, can't found the argument in the dictionary " errorQueue.put("error mail, can't found the argument in the dictionary " ) mailText=mailText+compose_error_mail("so_obj_not_exist",cmd_argument) continue else: print "error mail invalid arg len" errorQueue.put("error mail invalid arg len" ) continue else: #not a know cmdtype print "unknow mail cmd" continue print "send mail.."+mailText mailQueue.put({"mail_address":m_sender,"mailText":mailText,"mailSubject":mailSubject}) else:#no mail received #time.sleep(mail_check_frequency) mailCheckThreadIsrunning=0 return() #time.sleep(mail_check_frequency) mailCheckThreadIsrunning=0 return() def hardwareHandlerThread(): #check the nodes status and update the webobjects values
[docs] global mailCheckThreadIsrunning global last_pin_read_time global last_mail_sync_time global last_server_sync_time global last_error_check_time read_pin=1 #banana #time.sleep(5) #wait for webserver to startup print "hardwareHandlerThread() executed" #if (exit==0): #if exit ==1 then close the webserver #print time.time() #print "last_mail_sync_time",last_mail_sync_time #print "last_server_sync_time",last_server_sync_time #print "last_pin_read_time",last_pin_read_time #print "diff last_mail_sync_time",time.time()-last_mail_sync_time #print "diff last_server_sync_time",time.time()-last_server_sync_time #print "diff last_pin_read_time",time.time()-last_pin_read_time last_node_check=0 last_internet_check=0 while (exit==0): time.sleep(1.5)#to save cpu load if ( (time.time()-last_internet_check) >5 ): #EVERY 5 SECONDS last_internet_check=time.time() internet_connection=0 try: urllib2.urlopen("http://www.google.com") internet_connection=1 except Exception, e: print "no internet connection 0"+" e:"+str(e.args) #errorQueue.put("no internet connection 0"+" e:"+str(e.args) ) internet_connection=0 if ( (time.time()-last_node_check) >2 ): #EVERY 2 SECONDS print "threads:",len(threading.enumerate()) print "check nodeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" last_node_check=time.time() #banana try... for a in nodeDict.keys(): if a==router_sn: #skip the router node continue if nodeDict[a].getNodeTimeout()=="never": #never timeout continue print "nodecheck:"+a #print "last_node_sync:"+str(nodeDict[a].getLastNodeSync()) #print "time_now:"+str(time.time()) print "difference=:"+str(time.time()-nodeDict[a].getLastNodeSync()) if ( (time.time()-nodeDict[a].getLastNodeSync() )>nodeDict[a].getNodeTimeout() ) : #the node is not connected anymore if nodeDict[a].getNodeActivity()==0: #if the node was already inactive nodeDict[a].updateLastNodeSync(time.time()-99999) #set this to prevent the overflow of the variable continue #skip nodeDict[a].setNodeActivity(0) #set the node as inactive print "the node:"+a+" IS NOT CONNECTED ANYMORE,did you disconnected it?" errorQueue.put( "The node:"+a+" IS NOT CONNECTED ANYMORE,did you disconnected it?"+"at:" +getErrorTimeString()) for b in object_dict.keys(): if object_dict[b].getHwNodeSerialNumber()==a : #if the web object is from the node a then disactive it #object_dict[b].setStatus("inactive") priorityCmdQueue.put( {"cmd":"setSts","webObjectName":b,"status_to_set":"inactive","write_to_hw":0,"user":"onos_node","priority":99,"mail_report_list":[]}) else:#now the node is connected if nodeDict[a].getNodeActivity()==0: #the node was not connected but now it is nodeDict[a].setNodeActivity(1) #set the node as active print "node:"+a+" returned active" for b in object_dict.keys(): print "object_dict[b].getHwNodeSerialNumber():"+str(object_dict[b].getHwNodeSerialNumber()) if object_dict[b].getHwNodeSerialNumber()==a : #if the web object is from the node a then reactive it print "webobject:"+b+"returned active" prev_s=object_dict[b].getPreviousStatus() current_s=object_dict[b].getStatus() if ((current_s=="inactive") or (current_s=="onoswait") ): # prev_s=object_dict[b].getStartStatus() #if the current status is "inactive" set it to the previous status print "the new status will be:"+str(prev_s) priorityCmdQueue.put( {"cmd":"setSts","webObjectName":b,"status_to_set":prev_s,"write_to_hw":1,"user":"onos_node","priority":99,"mail_report_list":[]}) #set the web_object to the status before the disconnection #nodeDict[a].updateLastNodeSync(time.time()) if (online_server_enable==1)&(internet_connection==1): if (onlineServerSyncThreadIsrunning==0)&((time.time()-last_server_sync_time)>online_server_delay): last_server_sync_time=time.time() print "i started the online server sync service" try: w4 = threading.Thread(target=onlineServerSync) w4.daemon = True #make the thread a daemon thread w4.start() except Exception, e : print "error executing onlineServerSync()"+" e:"+str(e.args) errorQueue.put( "error executing onlineServerSync()"+" e:"+str(e.args)) # time.sleep(0.3) #don't remove this or else the router became instable #the mail check will run only if the onlineServerSync is not running if (enable_mail_service==1)&(internet_connection==1)&(onlineServerSyncThreadIsrunning==0): if (mailCheckThreadIsrunning==0)&((time.time()-last_mail_sync_time)>mail_check_frequency): last_mail_sync_time=time.time() try: w3 = threading.Thread(target=mailCheckThread) w3.daemon = True #make the thread a daemon thread w3.start() except Exception, e : print "error executing mailCheckThread()"+" e:"+str(e.args) errorQueue.put("error executing mailCheckThread()"+" e:"+str(e.args) ) #continue #time.sleep(0.2) if (read_pin>0)&((time.time()-last_pin_read_time)>router_read_pin_frequency): #execute every n seconds last_pin_read_time=time.time() #time.sleep(0.2) #try: #read local onosCenter pins (the router pin) try: read_pin=read_pin+hardware.read_router_pins() # if hardware.read_router_pins() is -1 for two times it will go to <0 except Exception, e : print "error executing hardware.read_router_pins()"+" e:"+str(e.args) errorQueue.put( "error executing hardware.read_router_pins()"+" e:"+str(e.args)) if (mail_error_log_enable==1): if ( ( (time.time()-last_error_check_time)>error_log_mail_frequency) ): last_error_check_time=time.time() try: error_text="" while not errorQueue.empty(): error_text =error_text+";;;\n"+str(errorQueue.get()) #errorQueue.task_done() if (len (error_text) > 0): mailQueue.put({"mail_address":mail_where_to_send_errors,"mailText":error_text,"mailSubject":"onos_errors_report"}) except Exception, e: print "error in the error mail log of hardwareHandlerThread !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! "+" e:"+str(e.args) print error_text errorQueue.put("error in the error mail log of hardwareHandlerThread "+" e:"+str(e.args)) if ( mailQueue.empty()==0 )&( mailOutputHandler_is_running==0)&(internet_connection==1)&(enable_mail_output_service==1): #start the mail output thread if needed #print "mailOutputHandler_is_running=",mailOutputHandler_is_running #print "i execute mailOutputHandler thread ddddddddddddddddddddDDDDDDDDDDDDDDDDDDDdddddddddddDDDDDDDDDDDDDDDDdd " try: send_mail = threading.Thread(target=mailOutputHandler) send_mail.daemon = True #make the thread a daemon thread send_mail.start() except Exception, e: print "error in the mail send of onosBusThread "+" e:"+str(e.args) errorQueue.put("error in the mail send of onosBusThread "+" e:"+str(e.args)+str(threading.active_count())) #print "mailOutputHandler_is_running=",mailOutputHandler_is_running def executeQueueFunction(dataExchanged):
[docs] if ((dataExchanged["cmd"])=="setNodePin"): try: node_sn=dataExchanged["node_sn"] pin_number=dataExchanged["pinNumber"] pin_status=dataExchanged["status_to_set"] write_hw_enable=dataExchanged["write_to_hw"] mail_list_to_report_to=dataExchanged["mail_report_list"] setNodePin(node_sn,pin_number,pin_status,write_hw_enable) except Exception, e : print "error in the setNodePin of onosBusThread "+" e:"+str(e.args) errorQueue.put("error in the setNodePin of onosBusThread "+" e:"+str(e.args)) return(-1) if (dataExchanged["cmd"]=="setSts"): try: objName=dataExchanged["webObjectName"] status_to_set=dataExchanged["status_to_set"] write_hw_enable=dataExchanged["write_to_hw"] usr="onos_sys" priority=0 mail_list_to_report_to=[] if "mail_report_list" in dataExchanged.keys(): mail_list_to_report_to=dataExchanged["mail_report_list"] if "user" in dataExchanged.keys(): usr=dataExchanged["user"] if "priority" in dataExchanged.keys(): priority=dataExchanged["priority"] changeWebObjectStatus(objName,status_to_set,write_hw_enable,usr,priority,mail_list_to_report_to) except Exception, e: print "error in the setSts of onosBusThread "+" e:"+str(e.args) errorQueue.put("error in the setSts of onosBusThread: name:"+str(objName)+",st:"+str(status_to_set)+",wr_en:"+str(write_hw_enable)+",usr:"+usr+",priority:"+str(priority)+" e:"+str(e.args)) if (dataExchanged["cmd"]=="scen_check"): try: scenarioName=dataExchanged["scenarioName"] checkwebObjectScenarios(scenarioName) except Exception, e: print "error in the scen_check of onosBusThread ,scenario_name:"+str(scenarioName)+" e:"+str(e.args) errorQueue.put("error in the scen_check of onosBusThread ,scenario_name:"+str(scenarioName)+" e:"+str(e.args)) print "dataExchanged = : ", dataExchanged return() def onosBusThread():
[docs] global internet_connection time.sleep(5) #wait for webserver to startup while (exit==0): #if exit ==1 then close the webserver time.sleep(0.03) #wait until layerExchangeDataQueue has some element try: while not priorityCmdQueue.empty(): #this has priority over the other layer #if not priorityCmdQueue.empty(): executeQueueFunction(priorityCmdQueue.get()) while not layerExchangeDataQueue.empty(): #if not layerExchangeDataQueue.empty(): while not priorityCmdQueue.empty(): #this has priority over the other layer #if not priorityCmdQueue.empty(): executeQueueFunction(priorityCmdQueue.get()) executeQueueFunction(layerExchangeDataQueue.get()) #layerExchangeDataQueue.task_done() #here starts the less important part ,executed only when there is nothing in layerExchangeDataQueue try: old_minutes=object_dict["minutes"].getStatus() except Exception, e: print "error in the minutes update of onosBusThread "+" e:"+str(e.args) errorQueue.put("error in the minutes update of onosBusThread "+" e:"+str(e.args)) old_minutes=0 #time_objects_handler if (old_minutes!=datetime.datetime.today().minute): #each minute check try: changeWebObjectStatus("minutes",datetime.datetime.today().minute,0) changeWebObjectStatus("dayTime",datetime.datetime.today().minute+(datetime.datetime.today().hour)*60,0) old_hours=object_dict["hours"].getStatus() old_day=object_dict["day"].getStatus() old_month=object_dict["month"].getStatus() old_year=object_dict["year"].getStatus() old_dayTime=object_dict["dayTime"].getStatus() #hours of the day expressed in minutes if (old_hours!=datetime.datetime.today().hour): #os.system('''ntpd -q -p 0.openwrt.pool.ntp.org''') #update from online time with lock_bash_cmd: subprocess.check_output('''ntpd -q -p 0.openwrt.pool.ntp.org''', shell=True,close_fds=True) changeWebObjectStatus("hours",datetime.datetime.today().hour,0) if (old_day!=datetime.datetime.today().day): changeWebObjectStatus("day",datetime.datetime.today().day,0) if (old_month!=datetime.datetime.today().month): changeWebObjectStatus("month",datetime.datetime.today().month,0) if (old_year!=datetime.datetime.today().year): changeWebObjectStatus("year",datetime.datetime.today().year,0) except Exception, e: print "error in the time_objects_handler of onosBusThread "+" e:"+str(e.args) errorQueue.put("error in the time_objects_handler of onosBusThread"+" e:"+str(e.args)) global check_log_len_time if log_enable==1 : if ((old_dayTime-check_log_len_time)>10): #each 10 minutes make a check, # for u in user_active_time_dict.keys(): #check the user login timout check_log_len_time=old_dayTime print "check_log_len_time " error_phrase="error" if os.path.getsize(log_name)>1000000: #if log size > 1 megabyte then save the errors and delete it print "i clear the onos log" #os.system('''grep -B5 -A5 -P '^'''+error_phrase+'''$' '''+log_name+'''>>'''+error_log_name) #save the 5 line prev and after the line with an error with lock_bash_cmd: subprocess.check_output('''grep -B5 -A5 -P '^'''+error_phrase+'''$' '''+log_name+'''>>'''+error_log_name, shell=True,close_fds=True) #grep -B5 -A5 -P '^5$' filename #os.system('''echo " " >'''+log_name) #clear the file with lock_bash_cmd: subprocess.check_output('''echo " " >'''+log_name, shell=True,close_fds=True) except Exception, e: print "main error in onosBusThread() "+" e:"+str(e.args) errorQueue.put("main error in onosBusThread()"+" e:"+str(e.args)) def nodeTcpServer():
[docs] while (exit==0): #if exit ==1 then close the webserver wait_because_node_is_talking=0 time.sleep(0.2) try: # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # sock.setsockopt(socket.IPPROTO_TCP,socket.TCP_NODELAY, True) #disable_nagle_algorithm'): #http://pydoc.net/Python/mrs-mapreduce/0.9/mrs.http/ https://aboutsimon.com/index.html%3Fp=85.html server_address = (onos_center_internal_ip, service_webserver_port) #stored in globalVar.py print >>sys.stderr, 'starting up on %s port %s' % server_address sock.bind(server_address) sock.listen(1) # Listen for incoming connections node_ip="" while (exit==0): time.sleep(0.1) wait_because_node_is_talking=0 # Wait for a connection sock.settimeout(480) # print >>sys.stderr, 'waiting for a connection' try: connection, client_address = sock.accept() node_ip=client_address[0] print "nodeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",node_ip except Exception, e : print "timeout in receiving!!!",e try: connection.close() print "connection closed" except: print "connection alredy closed" print "error connection, client_address = sock.accept() in nodeTcpServer()"+str(e.args) errorQueue.put("error connection, client_address = sock.accept() in nodeTcpServer()"+"at:"+getErrorTimeString()) else: # if the try was executed without errors received_message="" try: #print >>sys.stderr, 'connection from', client_address # Receive the data in small chunks and retransmit it wait_because_node_is_talking=1 while (exit==0): data = connection.recv(1024) #accept data till 1024 bytes received_message=received_message+data # print >>sys.stderr, 'received "%s"' % data if data: connection.settimeout(2.0) # print >>sys.stderr, 'sending data back to the client' msg=received_message if data.find("_#]")!=-1: # if the message is completed close the connection print "end line received!!!! ----------------------------------------------------jjuyjytrty" print "received_message:"+received_message #example: "pinsetup?node_sn=ProminiA0001&fw=4.85_#]" if received_message.startswith("pinsetup?") : node_sn=re.search('sn=(.+?)&',received_message).group(1) node_fw=re.search('&fw=(.+?)_#',received_message).group(1) print "node_sn"+node_sn print "node_fw"+node_fw print "nodeipfffffffffffffffffffffffffffffffffddddddd",node_ip msg=createNewNode(node_sn,node_ip,node_fw)+"_#]" connection.sendall(msg) connection.close() wait_because_node_is_talking=0 break if received_message.startswith("n_sync?") : node_sn=re.search('sn=(.+?)&',received_message).group(1) node_fw=re.search('&fw=(.+?)_#',received_message).group(1) print "node_sn"+node_sn print "node_fw"+node_fw print "nodeipfffffffffffffffffffffffffffffffffddddddd",node_ip connection.sendall('ok') connection.close() msg=createNewNode(node_sn,node_ip,node_fw)+"_#]" #i call createNewNode just to update the node ip ... wait_because_node_is_talking=0 break connection.sendall(data) connection.close() wait_because_node_is_talking=0 break else: print >>sys.stderr, 'no more data from', client_address connection.close() wait_because_node_is_talking=0 break except Exception, e : print "error tcp connection",e finally: try: connection.close() except: print "connection not created2" try: # Clean up the connection, close() is always called, even in the event of an error. connection.close() except: print "connection not created3" except Exception, e : print "error tcp server thread",e errorQueue.put("error tcp server thread"+" e:"+str(e.args) ) finally: try: connection.close() except: print "connection not created 4" def run_while_true(server_class=BaseHTTPServer.HTTPServer,
[docs] handler_class=RequestHandler): """ This assumes that keep_running() is a function of no arguments which is tested initially and after each request. If its return value is true, the server continues. """ server_address = ('', gui_webserver_port) httpd = server_class(server_address, MyHandler) while exit==0: #if exit ==1 then close the webserver #main loop of the webserver print "main webserver " try: httpd.handle_request() except Exception, e: print "something went wrong on main Webserver handler "+" e:"+str(e.args) errorQueue.put("something went wrong on main Webserver handler "+" e:"+str(e.args) ) def main():
[docs] global exit try: #server = HTTPServer(('', 80), MyHandler) print 'started httpserver...' bus = threading.Thread(target=onosBusThread) bus.daemon = True #make the thread a daemon thread bus.start() w2 = threading.Thread(target=nodeTcpServer) w2.daemon = True #make the thread a daemon thread w2.start() w1 = threading.Thread(target=hardwareHandlerThread) w1.daemon = True #make the thread a daemon thread w1.start() run_while_true() except KeyboardInterrupt: #updateJson(object_dict,zoneDict) print '^C received, shutting down server' hardware.close() exit=1 server.socket.close() if __name__ == '__main__':
main()