def login(): try: if not request.is_json: raise APImissingParameter(400, "Missing json object in request") print("we are in login") username = request.json.get('username', None) password = request.json.get('password', None) if not username: raise APImissingParameter(400, "Missing username parameter in payload") if not password: raise APImissingParameter(400, "Missing password parameter in payload") user = None if current_app.config['TESTING']: print("Running in TESTING mode") user = conn_test.run_query_result_many(c_queries.GET_USER, (username, )) else: conn = db(current_app.config['APP_DATABASE']) user = conn.run_query_result_many(c_queries.GET_USER, (username, )) if len(user) == 1: access_token = create_access_token(identity=user) decoded_token = decode_token(access_token) # Get values from token to be stored jti = decoded_token['jti'] # unique identifier token_type = decoded_token['type'] #user_id = decoded_token[username] expires = datetime.fromtimestamp(decoded_token['exp']) # Store in database try: conn = db(current_app.config['APP_DATABASE']) token_id = conn.run_query_non_result( c_queries.ADD_TOKEN, (jti, token_type, username, expires)) except APIsqlError as e: token_id = conn.run_query_non_result( c_queries.UPDATE_TOKEN, (jti, token_type, expires, username)) msg = {'msg': 'Success', 'data': access_token} return jsonify(msg), 200 except APIexception as e: abort(e.code, description=e.msg) return jsonify({ 'msg': "Failed", 'data': { 'error': "Bad username or password" } }), 401
def get_temp(): if (not request.is_json or not 'sensor' in request.json or not 'start_date' in request.json or not 'end_date' in request.json): raise APImissingParameter(400, name="Bad request", description="Missing parameters in request") sensor_id = request.json.get('sensor', None) sensor_id_checked = None if (isinstance(sensor_id, list)): sensor_id_checked = int(sensor_id[0]) else: sensor_id_checked = int(sensor_id) start_date = request.json.get('start_date', None) end_date = request.json.get('end_date', None) conn = db(current_app.config['APP_DATABASE']) lst = conn.run_query_result_many(c_queries.GET_TEMP, (start_date, end_date)) check_id = lambda x: x[1] == sensor_id_checked result = [row for row in lst if check_id(row)] msg = {'msg': 'Success', 'data': result} return jsonify(msg), 200
def setup_temp(): if (not request.is_json or request.json['name'] or request.json['folder'] or request.json['postition'] or request.json['unit'] or request.json['comment']): raise APImissingParameter(400, "Missing parameters in request") name = request.json.get('name', None) folder = request.json.get('folder', None) position = request.json.get('position', None) unit = request.json.get('unit', None) comment = request.json.get('comment', None) str_date = datetime.now().date() str_time = datetime.now().time() date = ' '.join(str_date, str_time) conn = db(current_app.config['APP_DATABASE']) return_id = db.run_query_non_result( c_queries.CREATE_SENSOR, (name, folder, position, unit, date, comment)) if return_id != id: raise APIreturnError( 404, name='Not found', msg='Return Id from the sql database is not correct') return jsonify(return_id), 200
def read_temp(sensor): if sensor == None or sensor == '': raise APImissingParameter(400, "Missing parameters in request") print(c_queries.GET_SENSOR) conn = db(current_app.config['APP_DATABASE']) sensor = db.run_query_result_many(c_queries.GET_SENSOR, (sensor, )) device_file = sensor[2] + '/w1_slave' reg_confirm = re.compile('YES') reg_temp = re.compile('t=(\d+)') temp_c = None temp_f = None with device_file as f: lines = f.readlines() measure_confirm = reg_confirm.match(lines) if measure_confirm: measure_temp = reg_temp.match(lines) temp_c = float(measure_temp[1] / 1000.0) temp_f = temp_c * 9.0 / 5.0 + 32.0 if sensor[4] == 'C' or sensor[4] == 'c': msg = {'Sensor': sensor, 'Temperature': temp_c} return jsonify(msg), 200 elif sensor[4] == 'F' or sensor[4] == 'f': msg = {'Sensor': sensor, 'Temperature': temp_f} return jsonify(msg), 200 else: abort(404, name="Not found", msg="Sensor setting has an unknown unit")
def logout(): try: username = get_jwt_identity()[0][3] # Remove token from database conn = db(current_app.config['APP_DATABASE']) token_id = conn.run_query_non_result(c_queries.DELETE_TOKEN, (username, )) msg = {'msg': 'Success'} return jsonify(msg), 200 except APIexception as e: abort(e.code, description=e.msg)
def create_tables(self) -> db: if self.testing: self.conn = db(self.database, memory=True) self.conn.mitigate_database(self.queries.CREATE_TABLE_TEMP) self.conn.mitigate_database(self.queries.CREATE_TABLE_SENSOR) self.conn.mitigate_database(self.queries.CREATE_TABLE_USER) self.conn.mitigate_database(self.queries.CREATE_TABLE_TOKENLIST) values = ('test_first', 'test_second', 'test', 'test') self.conn.run_query_non_result(self.queries.INSERT_TEST_USER, values) else: self.conn = db(self.database) self.conn.mitigate_database(self.queries.CREATE_TABLE_TEMP) self.conn.mitigate_database(self.queries.CREATE_TABLE_SENSOR) self.conn.mitigate_database(self.queries.CREATE_TABLE_USER) self.conn.mitigate_database(self.queries.CREATE_TABLE_TOKENLIST) #try: #values = ('test', 'test', 'test', 'test') #self.conn.run_query_non_result(self.queries.INSERT_TEST_USER, values) #except APIsqlError as e: # print("Test user already exist") return self.conn
def delete_temp(id): if id == None or id == '': raise APImissingParameter(400, "Missing parameters in request") conn = db(current_app.config['APP_DATABASE']) last_row = conn.run_query_non_result(c_queries.DELETE_TEMP, (id, )) if not isinstance(last_row, int) or last_row == -1: raise APIreturnError( 404, name='Not found', description='Return Id from the sql database is not correct') msg = {'msg': 'Success' if last_row == 0 else 'Failed', 'data': id} return jsonify(msg), 200
def get_all_sensor(): sensors = None if current_app.config['TESTING']: sensors = conn_test.run_query_result_many(c_queries.GET_SENSOR_ALL) else: conn = db(current_app.config['APP_DATABASE']) sensors = conn.run_query_result_many(c_queries.GET_SENSOR_ALL) if not isinstance(sensors, list): raise APIreturnError(404, name='Not found', msg='Sensor from the sql database is not correct') return jsonify({'msg': 'Success', 'data': sensors}), 200
def get_temp(): if (not request.is_json or request.json['sensor'] or request.json['start_date'] or request.json['end_date']): raise APImissingParameter(400, "Missing parameters in request") sensor_id = request.json.get('sensor', None) start_date = request.json.get('start_date', None) end_date = request.json.get('end_date', None) print(c_queries.GET_TEMP) conn = db(current_app.config['APP_DATABASE']) lst = db.run_query_result_many(c_queries.GET_TEMP, (start_date, end_date)) result = [(lambda x: x[1] == sensor_id)(row) for row in lst] return jsonify(result), 200
def add_sensor(): if (not request.is_json or not 'name' in request.json or not 'folder' in request.json or not 'position' in request.json or not 'unit' in request.json or not 'comment' in request.json): raise APImissingParameter( 400, name="Bad request", msg="Missing parameters in request - {}".format(request.json)) name = request.json.get('name', None) folder = request.json.get('folder', None) position = request.json.get('position', None) unit = request.json.get('unit', None) comment = request.json.get('comment', None) date = datetime.now().strftime('%Y:%m:%d %H:%M:%S') reg_unit = re.compile('^[c|C|f|F]') match = reg_unit.match(unit) if match == None: raise APImissingParameter( 400, name="Bad request", msg="Unit has to be F or C representing Farenheit or Celsius") return_id = None if current_app.config['TESTING']: return_id = conn_test.run_query_non_result( c_queries.CREATE_SENSOR, (name, folder, position, match[0], date, comment)) else: conn = db(current_app.config['APP_DATABASE']) return_id = conn.run_query_non_result( c_queries.CREATE_SENSOR, (name, folder, position, match[0], date, comment)) if not isinstance(return_id, int): raise APIreturnError( 404, name='Not found', msg='Return Id from the sql database is not correct') return jsonify({'msg': 'Success', 'data': return_id}), 201
def delete_temp(id): if id == None or id == '': raise APImissingParameter(400, "Missing parameters in request") print(c_queries.DELETE_TEMP) conn = db(current_app.config['APP_DATABASE']) return_id = db.run_query_non_result(c_queries.DELETE_TEMP, (id, )) if return_id != id: raise APIreturnError( 404, name='Not found', msg='Return Id from the sql database is not correct') return jsonify(return_id), 200 # current_user = get_jwt_identity() # logged_in_as=current_user
def get_sensor(id): if id == None: raise APImissingParameter(400, name="Bad request", msg="Missing sensor id request") sensor = None if current_app.config['TESTING']: sensor = conn_test.run_query_result_many(c_queries.GET_SENSOR, (str(id), )) else: conn = db(current_app.config['APP_DATABASE']) sensor = conn.run_query_result_many(c_queries.GET_SENSOR, (str(id), )) if not isinstance(sensor, list): raise APIreturnError(404, name='Not found', msg='Sensor from the sql database is not correct') return jsonify({'msg': 'Success', 'data': sensor}), 200
def delete_sensor(id): if id == None: raise APImissingParameter(400, name="Bad request", msg="Missing sensor id request") sensor_id = None if current_app.config['TESTING']: sensor_id = conn_test.run_query_non_result(c_queries.DELETE_SENSOR, (str(id), )) else: conn = db(current_app.config['APP_DATABASE']) sensor_id = conn.run_query_non_result(c_queries.DELETE_SENSOR, (str(id), )) if not isinstance(sensor_id, int): raise APIreturnError(404, name="Not found", msg="Sensor id from SQL database is not valid") return jsonify({'msg': 'Success', 'data': sensor_id}), 200
def read_temp(id): if id == None or id == '': raise APImissingParameter(400, name="Bad request", msg="Missing parameters in request") try: sensor = None if current_app.config['TESTING']: # Return a mocked temperature value sensor = conn_test.run_query_result_many(c_queries.GET_SENSOR, (id, )) msg = { 'msg': 'Success', 'data': { 'sensor': sensor[0], 'temperature': 26.54 } } return jsonify(msg), 200 else: # Read temperature value from DS18B20 conn = db(current_app.config['APP_DATABASE']) sensors = conn.run_query_result_many(c_queries.GET_SENSOR, (id, )) sensor = sensors[0] device_file = c_folders.BASE_DIR + sensor[2] + '/w1_slave' reg_confirm = re.compile('YES') reg_temp = re.compile('t=(\d+)') temp_c = None temp_f = None try: # NB with device_file as f: -> Does not work f = open(device_file, 'r') lines = f.readlines() f.close() measure_confirm = reg_confirm.search(lines[0]) print(measure_confirm) if measure_confirm: measure_temp = reg_temp.search(lines[1]) print(measure_temp[1]) temp_c = float(measure_temp[1]) / 1000.0 temp_f = temp_c * 9.0 / 5.0 + 32.0 except OSError: APIonewireError( 500, "Hardware error", "Could not open/read file: {}".format(device_file)) if sensor[4] == 'C' or sensor[4] == 'c': msg = { 'msg': 'Success', 'data': { 'sensor': sensor, 'temperature': temp_c } } return jsonify(msg), 200 elif sensor[4] == 'F' or sensor[4] == 'f': msg = { 'msg': 'Success', 'data': { 'sensor': sensor, 'temperature': temp_f } } return jsonify(msg), 200 else: APIreturnError(404, name="Not found", msg="Sensor setting has an unknown unit") except APIexception as e: if not name in e: e.name = "General fault" if not msg in e: e.msg = "Server error - {}".format(e.description()) abort(404, e)