def verifyRules(): data = readJSON() status = data['status'] rules = data['rules'] ts = time.localtime(time.time()) h = ts.tm_hour m = ts.tm_min pw = ts.tm_wday week = [1,2,3,4,5,6,0] w = week[pw] for rule in rules: ammountTriggers = 1 verified = 0 triggers = [] ruleKeys = [] for key in rule.keys(): ruleKeys.append(key) if 'triggers' in ruleKeys: ammountTriggers = len(rule['triggers']) triggers = rule['triggers'] else: triggers.append(rule['trigger']) for trigger in triggers: #Verify device to device value = "" if '>' in str(trigger['value']): id = trigger['value'].split('>')[0] param = trigger['value'].split('>')[1] value = status[id][param] else: value = trigger['value'] #Verify operators if int(trigger['operator']) == 1 and str(status[trigger['id']][trigger['param']]) == str(value): verified+=1 elif int(trigger['operator']) == 2 and status[trigger['id']][trigger['param']] < value: verified+=1 elif int(trigger['operator']) == 3 and status[trigger['id']][trigger['param']] > value: verified+=1 elif int(trigger['operator']) == 4 and h == int(value.split(':')[0]) and m == int(value.split(':')[1]): if len(value.split(':')) == 3: if str(w) in value.split(':')[2]: verified+=1 else: verified+=1 #Update targets if needed if verified == ammountTriggers: for target in rule['targets']: data['status'][target['id']][target['param']] = target['value'] publish.single("device/"+target['id'], json.dumps(data['status'][target['id']]), hostname="192.168.19.92") writeJSON(data)
def rules(process = "", id = -1): config = readConfig() domain = config['domain'] if process == 'edit': if id != -1: data = readJSON() return render_template('panel/edit_rules.html', ruleID=id) else: return render_template('panel/edit_rules.html', ruleID=id) elif process == 'json': if id != -1: data = readJSON() return render_template('panel/json_rules.html', ruleID=id) else: return render_template('panel/json_rules.html', ruleID=id) else: return render_template('panel/rules.html', domain=domain)
def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) #Get the data payload = json.loads(msg.payload) id = payload['id'] param = payload['param'] value = payload['value'] intent = payload['intent'] if intent == 'execute': data = readJSON(); data['status'][id][param] = value; writeJSON(data) publish.single("device/"+id, json.dumps(data['status'][id]), hostname="192.168.19.92") elif intent == 'rules': data = readJSON(); data['status'][id][param] = value; writeJSON(data) verifyRules() elif intent == 'request': publish.single("device/"+id, json.dumps(data['status'][id]), hostname="192.168.19.92")
def updatestates(): #Get JSON data = readJSON() alive = data['alive'] # Get te actual timestamp ts = int(time.time()*1000) for device in alive: if False: #ts - int(alive[device]['timestamp']) > deviceAliveTimeout: data['status'][device]['online'] = False else: data['status'][device]['online'] = True #Save the new data writeJSON(data)
def devices(process = "", id = ""): config = readConfig() domain = config['domain'] if process == 'edit': if id != '': data = readJSON() devices = data['devices'] #Find the device device = {} for d in devices: if id == d['id']: device = d break deviceString=json.dumps(device) return render_template('panel/edit_device.html', deviceString=deviceString, deviceID=id) else: return render_template('panel/edit_device.html', deviceID=id) else: return render_template('panel/devices.html', domain=domain)
def smarthome(): #Get all data body = request.json print(body) #Get the agent agent = request.headers['User-Agent'] #Verify special agents if '+http://www.google.com/bot.html' in agent: agent = 'google'; elif agent == 'OpenAuth': agent = 'google'; #Get the access_token tokenClient = request.headers['authorization'].split(' ')[1] data = readJSON() token = readToken() if tokenClient == token[agent]['access_token']['value']: #Anlalyze the inputs inputs = body['inputs'] requestId = body['requestId'] for input in inputs: if input['intent'] == 'action.devices.SYNC': print('Intent SYNC') obj = {} obj['requestId'] = requestId obj['payload'] = {} obj['payload']['agentUserId'] = '123' obj['payload']['devices'] = data['devices'] response = app.response_class( response=json.dumps(obj), status=200, mimetype='application/json' ) return response elif input['intent'] == 'action.devices.QUERY': updatestates() data = readJSON() obj = {} obj['requestId'] = requestId obj['payload'] = {} obj['payload']['devices'] = data['status'] response = app.response_class( response=json.dumps(obj), status=200, mimetype='application/json' ) return response elif input['intent'] == 'action.devices.EXECUTE': #Response obj = {} obj['requestId'] = requestId obj['payload'] = {} obj['payload']['commands'] = [] obj['payload']['commands'].append({}) obj['payload']['commands'][0]['ids'] = [] obj['payload']['commands'][0]['status'] = 'SUCCESS' obj['payload']['commands'][0]['states'] = {} #Get ans analyze data data = readJSON() #Only the first input and the first command n = 0 for command in input['payload']['commands']: devices = command['devices'] executions = command['execution'] for device in devices: deviceId = device['id'] obj['payload']['commands'][n]['ids'].append(deviceId) deviceParams = executions[0]['params'] deviceParamsKeys = deviceParams.keys() for key in deviceParamsKeys: data['status'][deviceId][key] = deviceParams[key] publish.single("device/"+deviceId, json.dumps(data['status'][deviceId]), hostname="192.168.19.92") obj['payload']['commands'][n]['states'] = data['status'] n += 1 writeJSON(data) response = app.response_class( response=json.dumps(obj), status=200, mimetype='application/json' ) return response elif input['intent'] == 'action.devices.DISCONNECT': return 'Ok' else: print('Intent desconocido') else: print('Token incorrecto') return "A"
def token(): agent = request.headers['User-Agent'] #Verify special agents if '+http://www.google.com/bot.html' in agent: agent = 'google'; elif agent == 'OpenAuth': agent = 'google'; grantType = request.form.get('grant_type') client_id = request.form.get('client_id') client_secret = request.form.get('client_secret') code = '' if grantType == 'authorization_code': code = request.form.get('code') else: code = request.form.get('refresh_token') #Get the tokens and ids from DDBB data = readJSON() token = readToken() obj = {} #Verify the code if code == token[agent][grantType]['value']: #Tokens lifetime secondsInDay = 86400; #Create a new token access_token = tokenGenerator(agent, 'access_token') #Compose the response JSON obj['token_type'] = 'bearer' obj['expires_in'] = secondsInDay if grantType == 'authorization_code': #Create a new token refresh_token = tokenGenerator(agent, 'refresh_token') obj['access_token'] = access_token obj['refresh_token'] = refresh_token elif grantType == 'refresh_token': obj['access_token'] = access_token obj['refresh_token'] = code #Clear authorization_code if autoAuthentication is not permited if agent == 'google': data = readJSON() token[agent]['authorization_code']['value'] = random.randrange(1000000000) writeJSON(data) ## TODO: #Create an alert on the status register #Response back response = app.response_class( response=json.dumps(obj), status=200, mimetype='application/json' ) return response else: #Response back obj['error'] = 'invalid_grant' response = app.response_class( response=json.dumps(obj), status=200, mimetype='application/json' ) return response
def front(operation, segment = "", value = ''): #Log in doesn't require token if operation == 'login': if segment == 'user': config = readConfig() user = request.headers['user'] password = request.headers['pass'] cipher_suite = Fernet(str.encode(config['key'][2:len(config['key'])])) plain_text = cipher_suite.decrypt(str.encode(config['pass'][2:len(config['pass'])])) responseData = {} if user == config['user'] and plain_text == str.encode(password): #Generate the token chars = 'abcdefghijklmnopqrstuvwyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' token = '' i = 0 while i < 40: token += random.choice(chars) i += 1 #Saved the new token config = readConfig(); config['token'] = { 'front': token } writeConfig(config) #Prepare the response responseData = { 'status': 'in', 'user': user, 'token': token } else: #Prepare the response responseData = { 'status': 'fail' } elif segment == 'token': config = readConfig() user = request.headers['user'] token = request.headers['token'] if user == config['user'] and token == config['token']['front']: responseData = { 'status': 'in' } else: responseData = { 'status': 'fail' } elif segment == 'googleSync': print(responseURL) config = readConfig() user = request.headers['user'] password = request.headers['pass'] cipher_suite = Fernet(str.encode(config['key'][2:len(config['key'])])) plain_text = cipher_suite.decrypt(str.encode(config['pass'][2:len(config['pass'])])) responseData = {} if user == config['user'] and plain_text == str.encode(password): return responseURL else: return "fail" response = app.response_class( response=json.dumps(responseData), status=200, mimetype='application/json' ) return response #Operations not related with login else: #Verify the user token token = request.headers['authorization'].split(' ')[1] savedToken = readConfig()['token']['front']; if token == savedToken: #Read data data = {} if operation == 'read': if 'token' in segment: dataTmp = readToken() data = { "client_id": dataTmp["google"]["client_id"], "client_secret": dataTmp["google"]["client_secret"], } else: data = readJSON() #Get the requested data if segment != '': for p in segment.split('>'): data = data[p] response = app.response_class( response=json.dumps(data), status=200, mimetype='application/json' ) return response #Save simple data #Write data elif operation == 'write': data = {} if 'token' in segment: data = readToken() data["google"]["client_id"] = json.loads(value)['client_id'] data["google"]["client_secret"] = json.loads(value)['client_secret'] writeToken(data) else: data = readJSON() segments = segment.split('>') #Esto es una ñapa, pero ahora mismo no se cómo solucionarlo if len(segments) == 1: data[segment] = json.loads(value) elif len(segments) == 2: data[segments[0]][segments[1]] = json.loads(value) elif len(segments) == 3: data[segments[0]][segments[1]][segments[2]] = json.loads(value) writeJSON(data) response = app.response_class( response=json.dumps(data), status=200, mimetype='application/json' ) return response #Special operations elif operation == 'device': data = readJSON() if segment == 'update' or segment == 'create': incommingData = json.loads(value) deviceID = incommingData['devices']['id'] #Updating device or create device if segment == 'update': temp_devices = []; for device in data['devices']: if device['id'] == incommingData['devices']['id']: temp_devices.append(incommingData['devices']) else: temp_devices.append(device) data['devices'] = temp_devices else: data['devices'].append(incommingData['devices']) #Update alive data['alive'][deviceID] = incommingData['alive'] #Update status if not deviceID in data['status'].keys(): data['status'][deviceID] = {} #Create dummy status using selected traits with open('paramByTrait.json', 'r') as f: paramByTrait = json.load(f) for trait in incommingData['devices']['traits']: for paramKey in paramByTrait[trait].keys(): data['status'][deviceID][paramKey] = paramByTrait[trait][paramKey] data['status'][deviceID]['online'] = True elif segment == 'delete': temp_devices = []; for device in data['devices']: if device['id'] != value: temp_devices.append(device) data['devices'] = temp_devices # Delete status status = data['status'] del status[value] data['status'] = status # Delete alive alive = data['alive'] del alive[value] data['alive'] = alive writeJSON(data) response = app.response_class( response=json.dumps(data), status=200, mimetype='application/json' ) return response #Special operations elif operation == 'rule': data = readJSON() if segment == 'update': incommingData = json.loads(value) data['rules'][int(incommingData['n'])] = incommingData['rule'] if segment == 'create': incommingData = json.loads(value) data['rules'].append(incommingData['rule']) elif segment == 'delete': temp_rules = data['rules'] del temp_rules[int(value)] data['rules'] = temp_rules writeJSON(data) response = app.response_class( response=json.dumps(data), status=200, mimetype='application/json' ) return response else: return 'Bad token'