def changeDeviceDomain(newip): """ Change the device name in the /etc/hostname and in /etc/hosts. The device domain is generated with the actual ip in order to get a domain in the FIT faculty of VUT university. :param newip: The new ip the function will use for generate the new domain. :type domain: string. """ domain = ".fit.vutbr.cz" hostname = "dhcpr" machine_number = "000" ip = newip.split('.') if (int(ip[3]) == 179): hostname = "dhcps" elif (int(ip[3]) == 178): hostname = "dhcpr" if ( int(ip[3]) < 10 ): machine_number = "00"+ip[3] elif (int(ip[3]) < 100): machine_number = "0"+ip[3] elif (int(ip[3]) < 1000): machine_number = ip[3] make_pages(hostname+machine_number+domain) utils.setConfiguration("domain", hostname+machine_number+domain) system('sudo echo "' +hostname+machine_number+ '" > /etc/hostname') system('sudo echo -e "' +newip+ '\t' +hostname+machine_number+domain +'\t'+ hostname+machine_number+'\n" >> /etc/hosts') system('sudo /etc/init.d/hostname.sh') system('sudo reboot')
def do_GET(self): """ Handles HTTP GET request. The paths of the webpage are: * / with the home page * /configuration private part of the web, it is needed a session for enter in the page. * /login The allow file types of the files requested to this server are: * JavaScript * html * css """ if self.path=="/": global samples_show if (samples_show == 0): samples_show = int(utils.getConfiguration("samples_show")) if( samples_show == 0 ): samples_show = 20 utils.setConfiguration("samples_show", samples_show) create_web(samples_show) self.path="web/html/web.html" if self.path=="/configuration": if (cookie_storage.check_session(self.headers)): self.path = configuration_path else: self.path = "web/html/login.html" if self.path=="/login": self.path="web/html/login.html" try: #Check the file extension required and #set the right mime type sendReply = False if self.path.endswith(".html"): mimetype='text/html' sendReply = True if self.path.endswith(".js"): mimetype='application/javascript' sendReply = True if self.path.endswith(".css"): mimetype='text/css' sendReply = True if sendReply == True: #Open the static file requested and send it f = open(curdir + sep + self.path) self.send_response(200) self.send_header('Content-type',mimetype) self.end_headers() self.wfile.write(f.read()) f.close() return except IOError: self.send_error(404,'File Not Found: %s' % self.path)
def __init__(self): confs = utils.getConfiguration(self.name) if confs != None : self.channel = int(confs['channel']) print("Phmeter initialized - configuration found") else: newConfs = [('channel',None)] utils.setConfiguration(self.name,newConfs) print("Phmeter initialized - Warning: new configuration")
def __init__(self): confs = utils.getConfiguration(self.name) if confs != None: self.pin = int(confs['pin']) self.sensor = confs['sensor'] print("Thermometer initialized - configuration found") else: newConfs = [('pin', None), ('sensor', None)] utils.setConfiguration(self.name, newConfs) print("Thermometer initialized - Warning: new configuration")
def __init__(self): confs = utils.getConfiguration(self.name) if confs != None: self.pin_red = int(confs['pin_red']) self.pin_blue = int(confs['pin_blue']) print("LedController initialized - configuration found") else: newConfs = [('pin_red', None), ('pin_blue', None)] utils.setConfiguration(self.name, newConfs) print("LedController initialized - Warning: new configuration")
def __init__(self): self.dimmer = dimmerController.DimmerController() confs = utils.getConfiguration(self.name) if confs != None: self.channel = int(confs['channel']) print("AirPumpController initialized - configuration found") else: newConfs = [('channel', None)] utils.setConfiguration(self.name, newConfs) print("AirPumpController initialized - Warning: new configuration")
def __init__(self): confs = utils.getConfiguration(self.name) if confs != None: self.serialNumber = str(confs['serial_number']) print("AquaThermometer initialized - configuration found") else: serialNumber = self.detectSerialNumber() self.serialNumber = serialNumber newConfs = [('serial_number', str(serialNumber))] utils.setConfiguration(self.name, newConfs) print("AquaThermometer initialized - Warning: new configuration")
def __init__(self): # LED strip configuration: LED_COUNT = 5 # Number of LED pixels. #LED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!). #LED_PIN = 10 # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0). LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz) LED_DMA = 10 # DMA channel to use for generating signal (try 10) LED_BRIGHTNESS = 80 # Set to 0 for darkest and 255 for brightest LED_INVERT = False # True to invert the signal (when using NPN transistor level shift) LED_CHANNEL = 0 # set to '1' for GPIOs 13, 19, 41, 45 or 53 confs = utils.getConfiguration(self.name) if confs != None: self.channel = confs['channel'] if self.channel != 'None': self.channel = int(self.channel) else: self.channel = False print("FrontLED initialized - configuration found") else: self.channel = 18 newConfs = [('channel', None)] utils.setConfiguration(self.name, newConfs) print("FrontLED initialized - Warning: new configuration") if self.channel != False: #from neopixel import * import neopixel # Create NeoPixel object with appropriate configuration. self.strip = neopixel.Adafruit_NeoPixel(LED_COUNT, self.channel, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL) # Intialize the library (must be called once before other functions). self.strip.begin() print("LED Strip initialized") else: self.dimmer = ExecutePWM.ExecutePWM() confs = utils.getConfiguration(self.name) if confs != None: self.channel_0 = int(confs['channel_0']) self.channel_1 = int(confs['channel_1']) self.channel_2 = int(confs['channel_2']) self.channel_3 = int(confs['channel_3']) self.channel_4 = int(confs['channel_4']) print("Old IndicatorPanel initialized - configuration found") else: newConfs = [('channel_0', None), ('channel_1', None), ('channel_2', None), ('channel_3', None), ('channel_4', None)] utils.setConfiguration(self.name, newConfs) print( "Old IndicatorPanel initialized - Warning: new configuration" )
def __init__(self): confs = utils.getConfiguration(self.name) if confs != None: try: self.pin_0 = int(confs['pin_0']) self.pin_1 = int(confs['pin_1']) except: print("Notice: some of the Relay pins are not set") print("Relay initialized - configuration found") else: newConfs = [('pin_0', None), ('pin_1', None)] utils.setConfiguration(self.name, newConfs) print("Relay initialized - Warning: new configuration")
def __init__(self): self.ex_pwm = pwmController.ExecutePWM() confs = utils.getConfiguration(self.name) if confs != None: self.channel_r = int(confs['channel_red']) self.channel_b = int(confs['channel_blue']) self.channel_w = int(confs['channel_white']) self.channel_f = int(confs['channel_farred']) print("LedController initialized - configuration found") else: newConfs = [('channel_r', None), ('channel_b', None), ('channel_w', None), ('channel_f', None)] utils.setConfiguration(self.name, newConfs) print("LedController initialized - Warning: new configuration")
def __init__(self): confs = utils.getConfiguration(self.name) if confs != None : try: self.pin_0 = int(confs['pin_0']) self.pin_1 = int(confs['pin_1']) self.pin_2 = int(confs['pin_2']) self.pin_3 = int(confs['pin_3']) except: print("Notice: some of the Fan pins are not used") print("FanController initialized - configuration found") else: newConfs = [('pin_0',None),('pin_1',None),('pin_2',None),('pin_3',None)] utils.setConfiguration(self.name,newConfs) print("FanController initialized - Warning: new configuration")
def __init__(self): self.ex_pwm = pwmController.ExecutePWM() confs = utils.getConfiguration(self.name) if confs != None : self.channel_w1 = int(confs['channel_w1']) self.channel_w2 = int(confs['channel_w2']) self.channel_b = int(confs['channel_b']) self.channel_r1 = int(confs['channel_r1']) self.channel_r2 = int(confs['channel_r2']) self.channel_fr = int(confs['channel_fr']) print("LedController initialized - configuration found") else: newConfs = [('channel_r1',None),('channel_r2',None),('channel_b',None),('channel_w1',None),('channel_w2',None),('channel_fr',None)] utils.setConfiguration(self.name,newConfs) print("LedController initialized - Warning: new configuration")
def __init__(self): self.dimmer = dimmerController.DimmerController() confs = utils.getConfiguration(self.name) if confs != None: self.channel_0 = int(confs['channel_0']) self.channel_1 = int(confs['channel_1']) self.channel_2 = int(confs['channel_2']) self.channel_3 = int(confs['channel_3']) self.channel_4 = int(confs['channel_4']) print("IndicatorPanel initialized - configuration found") else: newConfs = [('channel_0', None), ('channel_1', None), ('channel_2', None), ('channel_3', None), ('channel_4', None)] utils.setConfiguration(self.name, newConfs) print("IndicatorPanel initialized - Warning: new configuration")
def __init__(self): confs = utils.getConfiguration(self.name) if confs != None: try: self.controller_name = str(confs['controller_name']) self.controller_id = int(confs['controller_id']) except: print("Notice: some of the Water Pump pins are not used") print("WaterPumpController initialized - configuration found") else: newConfs = [('controller_name', None), ('controller_id', None)] utils.setConfiguration(self.name, newConfs) print( "WaterPumpController initialized - Warning: new configuration") if self.controller_name.upper() == 'relay'.upper(): self.controller = Relay.Relay()
def __init__(self): self.ex_pwm = pwmController.ExecutePWM() confs = utils.getConfiguration(self.name) if confs != None : try: self.channel_front = int(confs['channel_front']) self.channel_back = int(confs['channel_back']) self.channel_led = int(confs['channel_led']) self.fan_on_timeout_min = float(confs['fan_on_timeout_min']) self.fan_off_timeout_min = float(confs['fan_off_timeout_min']) except: print("Notice: some of the Fan channels are not used") print("FanController initialized - configuration found") else: newConfs = [('channel_front',None),('channel_back',None),('channel_led',None),('fan_on_timeout_min',1),('fan_off_timeout_min',5)] utils.setConfiguration(self.name,newConfs) print("Fan Object initialized - Warning: new configuration")
def temperature_configuration(): """ Check if the configurations of the temperature daemon exists. If there is no configuration file it will create a new ones with default values. After that the methon will wake up the temperature daemon. """ try: with open("./config/frequency_temp", 'r') as tempfile: frequency = tempfile.next().strip() tempfile.close() except: frequency = 10 utils.log(log_path, "Temperature isn't set up. Creating default configuration file. Default Frequency 10 minutes.") utils.setConfiguration("frequency_temp", frequency) try: with open("./config/file_size", 'r') as sizefile: size = sizefile.next().strip() sizefile.close() except: size = 120 utils.log(log_path, "File size isn't set up. Creating default configuration file. Default file size is 120 samples.") utils.setConfiguration("file_size", size) system('sudo python tempdaemon.py start &') utils.log(log_path, "Temperature daemon started. Frequency " + str(frequency) + "min and file size "+ str(size) + " samples.")
def powerMode_configuration(): """ This method detect the actual power saving mode in the configuration files and set up the right power saving mode. By default, if the configuration doesn't exist the first power saving mode will be enabled. """ powermode = 0 try: with open("./config/powermode", 'r') as powermodefile: powermode = int(powermodefile.read().strip()) powermodefile.close() if( powermode == 0): #execute script system("sudo pmnormal") #start server system("sudo python server.py &") elif( powermode == 1): #execute script system("sudo pm1") #start server system("sudo python server.py &") elif( powermode == 2): if(utils.crontab_exist()): if(isPowermode2_on()): system("sudo pm2") else: system("sudo pm1") else: utils.log(log_path, "Crontab doesn't exist. Changing to power mode 1.") utils.setConfiguration("powermode", 1) system("pm1") elif( powermode == 3): if(utils.crontab_exist()): if(isPowermode2_on()): system("sudo pm2") else: system("sudo pm1") else: utils.log(log_path, "Crontab doesn't exist. Changing to power mode 1.") utils.setConfiguration("powermode", 1) system("pm1") except: utils.log(log_path, "Power mode config file doesn't exist. Creating one and switching to power mode 1.") utils.setConfiguration("powermode", 1) system("pm1")
def do_POST(self): """ Handles the HTTP POST request. The POST endpoints are: * /login When a post is made to login the server check if the hashes of the login data matchs the hashes of the user and password stored in the server. If the data match the server create a session with a cookie which still alive for 1200 seconds. Else the server will redirect to a error page. * /configuration First the server will check if the data type is correct, then it will check if the values are in the permited ranges and after that it will change the configuration. This endpoint change the number of samples shown in the home page, the frequency of the temperature sensor and the size of the dara files stored in the device. * /scp After check the session and the data type the server will set the scp target address and start the scp daemon. If the checkbox is mark, the server will store the configuration of the scp. * /pmnormal handles post to set power saving mode normal First the server will check if the session is ok, then it will set up the normal power saving mode. * /pm1 handles post to set power saving mode 1 First the server will check if the session is ok, then it will set up the first power saving mode. * /pm2_multiple handles post to set power saving mode 2 in the advanced formulary. After check the session and the data the server will set up the second power mode and will write the crontab which fits the schedule created by the user. * /pm2_one handles post to set power saving mode 2 with one interval for all days. After check the session and the data the server will set up the second power mode and will write the crontab which fits the schedule created by the user. * /pm2_eachday handles post to set power saving mode 2 with one different every day. After check the session and the data the server will set up the second power mode and will write the crontab which fits the schedule created by the user. * /pm3_multiple handles post to set power saving mode 3 in the advanced formulary. After check the session and the data the server will set up the third power mode and will write the crontab which fits the schedule created by the user. * /pm3_one post to set power saving mode 3 with one interval for all days. After check the session and the data the server will set up the third power mode and will write the crontab which fits the schedule created by the user. * /pm3_eachday handles post to set power saving mode 3 with one different every day. After check the session and the data the server will set up the third power mode and will write the crontab which fits the schedule created by the user. """ global configuration_path if(self.path == '/login'): print "[Login Post]" form = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], }) login = form["login"].value.strip() password = form["password"].value.strip() if(utils.check_login(login, password)): #Cookie creation c = Cookie.SimpleCookie() hash_object = hashlib.md5(str(datetime.now()).encode()) c['cookietemp'] = str(hash_object.hexdigest()) c['cookietemp']['domain'] = utils.getConfiguration("domain") c['cookietemp']['expires'] = 1200 c['cookietemp']['path'] = "/" c['cookietemp']['httponly'] = "true" cookie_storage.store_cookie(c) self.send_response(200) self.send_header('Content-type','text/html') self.send_header('Set-Cookie', c.output(attrs=['path', 'expires'], header="Cookie:")) self.end_headers() f = open(curdir + sep + "web/html/configuration.html") self.wfile.write(f.read()) f.close() else: self.answerPost(curdir + sep + "web/html/login-fail.html", 200) if(self.path == '/configuration'): global samples_show isDataCorrect = True print "[Configuration Post]" form = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], }) #Session check if (cookie_storage.check_session(self.headers)): #Data validation if not re.match("^[0-9]+$", form["samples"].value): self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200) elif not re.match("^[0-9]+$", form["frequency"].value): self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200) elif not re.match("^[0-9]+$", form["websamples"].value): self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200) elif not re.match("^([0-9]+|-[0-9]+)$", form["error"].value): self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200) else: if( utils.isInt( form["websamples"].value ) and int( form["websamples"].value ) > 0 ): samples_show = int(form["websamples"].value) utils.setConfiguration("samples_show" , samples_show) else: isDataCorrect = False if( utils.isInt( form["error"].value )): utils.setConfiguration("sensor_error" , int(form["error"].value)) else: isDataCorrect = False if( utils.isInt( form["samples"].value ) and int( form["samples"].value ) > 0 ): utils.setConfiguration("file_size" , int(form["samples"].value)) else: isDataCorrect = False if( utils.isInt( form["frequency"].value ) and int( form["frequency"].value ) > 0 ): frequency = int(form["frequency"].value) utils.setConfiguration("frequency_temp" , frequency) else: isDataCorrect = False if( isDataCorrect ): self.answerPost(curdir + sep + "web/html/configuration-changed.html", 200) else: self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200) else: self.answerPost(curdir + sep + "web/html/session-fail.html", 200) if(self.path == '/scp'): #Session check if (cookie_storage.check_session(self.headers)): global store_data isDataCorrect = False print "[SCP Post]" form = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], }) if 'check' in form: store_data = True else: store_data = False #Data validation if utils.isInt(form["scpfrequency"].value) and utils.isInt(form["port"].value) and form["scp"].value and form["user"].value and form["directory"].value and form["password"].value: isDataCorrect = True utils.setConfiguration("frequency_scp", form["scpfrequency"].value) #Store data if user wants. if store_data: with file("./config/scp",'w+') as scpfile: scpfile.write(form["user"].value+"\n") scpfile.write(form["scp"].value+"\n") scpfile.write(form["directory"].value+"\n") scpfile.write(form["port"].value+"\n") scpfile.write(form["password"].value+"\n") scpfile.close() else: system("sudo rm ./config/scp") #Create scp task. #TODO encriptar datos que se pasan al script (?) p = subprocess.Popen(["python", "scpdaemon.py", "start", form["scp"].value, form["user"].value, form["port"].value, form["directory"].value], stdin=PIPE, stdout=PIPE) print p.communicate(form["password"].value) #TODO check that is correct, subprocess.check~ #Redirect to configuration. if( isDataCorrect ): self.answerPost(curdir + sep + "web/html/configuration-changed.html", 200) else: self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200) else: self.answerPost(curdir + sep + "web/html/session-fail.html", 200) if(self.path == '/pmnormal'): #Session check if (cookie_storage.check_session(self.headers)): #TODO eliminar datos de otros modos, overclock etc. print "[Power mode normal Post]" self.setPowerSavingModeNormal() utils.setConfiguration("powermode", "0") self.answerPost(curdir + sep + "web/html/configuration-changed.html", 200) else: self.answerPost(curdir + sep + "web/html/session-fail.html", 200) if(self.path == '/pm1'): #Session check if (cookie_storage.check_session(self.headers)): #TODO pmnormal.sh -> wifi activado, con underclock, eliminar datos que generen los otros modos etc print "[Power mode 1 Post]" self.setPowerSavingMode1() utils.setConfiguration("powermode", "1") self.answerPost(curdir + sep + "web/html/configuration-changed.html", 200) else: self.answerPost(curdir + sep + "web/html/session-fail.html", 200) if(self.path == '/pm2_multiple'): if (cookie_storage.check_session(self.headers)): configuration_path = './web/html/configuration_mode2.html' #TODO elimnar datos de los otros modos print "[Power mode 2 Post: Multiple intervals]" #Post form recover form = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], }) if(utils.validateInterval_multiple(form)): utils.create_crontab(form, True) utils.setConfiguration("powermode", "2") self.answerPost(curdir + sep + "web/html/configuration-changed.html", 200) else: self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200) else: self.answerPost(curdir + sep + "web/html/session-fail.html", 200) if(self.path == '/pm2_one'): if(cookie_storage.check_session(self.headers)): configuration_path = './web/html/configuration_mode2.html' print "[Power mode 2 Post: One interval]" #Post form recover form = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], }) #validation if(utils.validateInterval(form["start"].value, form["end"].value)): monday = tuesday = wednesday = thursday = friday = saturday = sunday = (int(form["start"].value),int(form["end"].value)) utils.write_crontab([monday, tuesday, wednesday, thursday, friday, saturday, sunday], False) utils.setConfiguration("powermode", "2") self.answerPost(curdir + sep + "web/html/configuration-changed.html",200) else: self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200) else: self.answerPost(curdir + sep + "web/html/session-fail.html", 200) if(self.path == '/pm2_eachday'): if (cookie_storage.check_session(self.headers)): configuration_path = './web/html/configuration_mode2.html' print "[Power mode 2 Post: Multiple intervals]" #Post form recover form = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], }) if(utils.validateInterval_eachDay(form)): utils.create_crontab(form, False) utils.setConfiguration("powermode", "2") self.answerPost(curdir + sep + "web/html/configuration-changed.html", 200) else: self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200) else: self.answerPost(curdir + sep + "web/html/session-fail.html", 200) if(self.path == '/pm3'): configuration_path = './web/html/configuration_mode3.html' print "[Power mode 3 Post]" utils.setConfiguration("powermode", "3")