def count(): """ Infinite loop executed by this daemon. In every iteration the daemon gets the files which are not sended to the target machine and send it to the target machine marking it as sended in the configuration file. The daemon will turn on the wifi if needed. """ while 1: frequency = int(utils.getConfiguration('frequency_scp')) powermode = int(utils.getConfiguration('powermode')) if(powermode == 2 or powermode == 3): turnWifiOn() try: ssh = createSSHClient(address, port, user, password) scp = SCPClient(ssh.get_transport()) except: utils.log(log_path, "Error trying connect with the destiny device.") yapdi.Daemon().kill() exit() try: datafiles = getFilesToSend() for datafile in datafiles: scp.put(samples_path+datafile, directory) createBackup(datafile) mark_as_send(datafile) utils.log(log_path, "File " + datafile + " sended to " + address) if(powermode == 2 or powermode == 3): turnWifiOff() time.sleep(frequency * 3600) except: utils.log(log_path, "Error sending the files.") time.sleep(frequency * 3600)
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 ip_configuration(): """ This method detect if the ip of the device changed since the last exection. If the IP is the same the method will finish, else the method will save the new IP, change the host name and the domain in the device and change the static links in the html files in order to keep the web page available inside the VUT university network. """ ip = "localhost" newip = "localhost" time.sleep(5) #Wait for get IP try: newip = subprocess.Popen(["hostname", "-I"], stdout=subprocess.PIPE).communicate()[0].split() newip = newip[0] except: print "I couldn't get IP" try: with open("./config/ip", 'r') as ipfile: ip = ipfile.read().strip() ipfile.close() if (newip != ip): utils.log(log_path,"IP changed. New ip is " + newip) system('echo "'+ newip +'" > ./config/ip') newDomain = web_maker.changeDeviceDomain(newip) utils.log(log_path, "Device domain changed to: " + newDomain) except: system('echo "'+ newip +'" > ./config/ip') utils.log(log_path, "Ip file doesn't exist, generating one.") web_maker.changeDeviceDomain(newip) utils.log(log_path, "Device domain changed to: " + utils.getConfiguration("domain"))
def checkup(self): colorarray = ['', '', '', '', ''] """ Method for full system check up - unfinished """ # if device is on if True: #self.setLedOn(0,'g') colorarray[0] = 'g' # if device is connected to Internet try: response = urllib2.urlopen('http://www.google.com', timeout=1) #self.setLedOn(1,'g') colorarray[1] = 'g' except urllib2.URLError as err: #self.setLedOff(1) colorarray[1] = '' # if device can communicate with servers try: conf = utils.getConfiguration('BaseURL') base = conf['path'] try: serialNumber = utils.getSerialNumber() except Exception, e: utils.log("Microchip: ") utils.log(str(e)) except: utils.log("Microchip: Unknown Error") appurl = base + "/api/v1/en/planthive/get-device-command/" + str( serialNumber) response = urllib2.urlopen(appurl, timeout=1) #self.setLedOn(2,'g') colorarray[2] = 'g'
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 : if confs['option_snapshot_vflip'] == 'True': self.option_snapshot_vflip = True if confs['option_snapshot_hflip'] == 'True': self.option_snapshot_hflip = True print("Camera initialized - configuration found") self.isOn = bool(self.getInRam()['camera_is_on'])
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): 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.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): 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 get_arguments(): """ Read the configuration files and get the actual values of the configurations. The configuration this sensor use are: * Error: stored in "sensor_error" configuration file. * Frequency: stored in "frequency_temp" configuration file. * Number of samples: stored in "file_size" configuration file. """ global frequency global number_samples global error error = int(utils.getConfiguration("sensor_error")) frequency = int(utils.getConfiguration("frequency_temp")) number_samples = int(utils.getConfiguration("file_size")) if (frequency == 0) : frequency = 10 if (number_samples == 0) : number_samples = 120 utils.log(log_path,"Get arguments: Frequency "+ str(frequency) +" and Number Samples " + str(number_samples) + " and Error: " + str(error))
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): confs = utils.getConfiguration(self.name) if confs != None: 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("Moisturemeter initialized - configuration found") else: # newConfs = [('channel',None)] # utils.setConfiguration(self.name,newConfs) print( "Moisturemeter initialized - Warning: configuration not found")
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): 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): 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 mark_as_send(file_name): """ Write the chosen file in the sendedFiles configuration file marking it as read if the data file is full. :param file_name: name of the file to mark as send. :type file_name: string """ file_size = int(utils.getConfiguration('file_size')) with open(samples_path+file_name) as datafile: samples_in_file = enumerate(datafile) datafile.close() if(samples_in_file >= file_size): with open("./config/sendedFiles", 'a+') as file: file.write(file_name+"\n") file.close
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 __init__(self): confs = utils.getConfiguration(self.name) print("Hygrometer initialized - configuration found") sensor = Si7021(SMBus(1))
def __init__(self): confs = utils.getConfiguration('PCA_PWM_frequency') frequency = confs['value'] self.pwm = Adafruit_PCA9685.PCA9685() self.pwm.set_pwm_freq(frequency) print("ExecutePWM initialized")
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")
def __init__(self): confs = utils.getConfiguration(self.name) print("WaterLevel initialized - configuration found") sensor = proximity.VL6180X(0)