def deviceInterval(devAddr): if request.method == "POST": try: dt = request.get_json() interval = dt["interval"] db = Mongo.get_db() col = db["downlink_mac"] col.update({"devAddr": devAddr}, { "$set": { "interval": { "commandType": "interval", "commandId": 2, "value": interval, "dateCreated": datetime.now(), "status": "pending" } } }, upsert=True) except Exception: return jsonify(msg="Bad Gateway"), 501 return jsonify(msg="ok"), 200 if request.method == "GET": try: db = Mongo.get_db() col = db["downlink_mac"] downlink_mac = list(col.find({"devAddr": devAddr})) if len(downlink_mac): if downlink_mac[0]['interval']: return jsonify(interval=downlink_mac[0]['interval']), 200 return jsonify(interval=20), 200 except Exception: return jsonify(msg="Bad Gateway"), 501
def gateways(appId): if request.method == "GET": db = Mongo.get_db() col = db["gateways"] gateways = list(col.find({"appId": appId}, {'_id': 0})) return jsonify(gateways=gateways), 200 if request.method == "POST": try: db = Mongo.get_db() col = db["gateways"] dt = request.get_json() dt["appId"] = appId dt["ownerId"] = get_jwt_identity() dt["dateCreated"] = datetime.now() if col.insert_one(dt).acknowledged: col = db["applications"] if col.update_one({ "appId": appId }, { "$push": { "gateways": dt["gwId"] } }, upsert=True).modified_count: return jsonify(msg="ok"), 200 else: return jsonify(msg="Bad Gateway"), 501 else: return jsonify(msg="Bad Gateway"), 501 except Exception as e: return jsonify(msg="Bad Gateway"), 501
def getProfile(userId): if request.method == "GET": if not userId: return "Bad Call", 400 db = Mongo.get_db() col = db["profile"] profile = list(col.find({"username": userId}, {'_id': 0})) if len(profile): return jsonify(profile=profile[0]), 200 return "Not found", 404 if request.method == "POST": data = request.get_json() if not ("autoActions" in data.keys() and "autoActionsTimePeriod" in data.keys()): return "Bad Call", 400 db = Mongo.get_db() col = db["profile"] if col.update_one({ "username": userId }, { "$set": { "autoActions": data["autoActions"], "autoActionsTimePeriod": data["autoActionsTimePeriod"] } }, upsert=True).acknowledged: return jsonify(msg="ok"), 200 else: return jsonify(msg="Bad Gateway"), 501
def setting_communications(): try: print("before first request") cwd = os.path.dirname(os.path.abspath(__file__)) Configuration(os.path.join(cwd, 'config/config.json')) config = Configuration.get() db = Mongo() pub = Publisher(config["AMQP"]) mqttc = Mongo.get_mqttc() threading.Thread(target=mqttc_keep_alive, args=(mqttc, )).start() except Exception as e: print("log", str(e))
def saveRating(data): try: db = Mongo.get_db() return db["ratings"].insert_one(data).acknowledged except Exception as e: print("log e") return False
def getData(devAddr): db = Mongo.get_db() col = db["device_raw_data"] sensor_data = list( col.find({ "devAddr": devAddr, "msgType": "04" }, {"_id": 0})) return jsonify(data=sensor_data), 200
def action(gwId): if request.method == "POST": # TODO: check the owner of this gw with get_jwt_identity() at the db first data = request.get_json() idx = findIndexOfActuator(data) print(idx) mqttc = Mongo.get_mqttc() dl = '{"actuator": %s, "actuatorCode": %s, "time": %s}' % ( data["action"], idx, data["actionTime"]) mqttc.publish('atlas/%s/action' % gwId, dl) return jsonify(msg="ok"), 200
def getStatus(devAddr): db = Mongo.get_db() col = db["device_raw_data"] status = list( col.find({ "devAddr": devAddr, "msgType": "04" }, { "_id": 0 }).sort([("date", -1)]).limit(1)) return jsonify(status=status), 200
def changePassword(userId): data = request.get_json() if not ("password" in data.keys()): return "Bad Call", 400 data["password"] = hashlib.md5(data["password"].encode()).hexdigest() db = Mongo.get_db() col = db["auth"] col.update({"username": userId}, {"$set": {"password": data["password"]}}) # if not col.find(data).count(): # return "Not Found", 404 # access_token = create_access_token(identity=data["username"], expires_delta=timedelta(days=30)) # return jsonify(access_token=access_token, identity=data["username"]), 200 return jsonify(data="okk"), 200
def applications(): # verify_jwt_in_request() if request.method == "GET": db = Mongo.get_db() col = db["applications"] applications = list( col.find({"ownerId": get_jwt_identity()}, {'_id': 0})) return jsonify(applications=applications), 200 if request.method == "POST": try: dt = request.get_json() dt["hasAppKey"] = False if dt["appKey"] == "" else True dt["ownerId"] = get_jwt_identity() dt["dateCreated"] = datetime.now() dt["devices"] = [] dt["appId"] = random_md5like_hash(6) db = Mongo.get_db() col = db["applications"] if col.insert_one(dt).acknowledged: return jsonify(msg="ok"), 200 else: return jsonify(msg="Bad Gateway"), 501 except Exception: return jsonify(msg="Bad Gateway"), 501
def authenticate(): data = request.get_json() try: if not ("password" in data.keys() and "username" in data.keys()): return "Bad Call", 400 data["password"] = hashlib.md5(data["password"].encode()).hexdigest() db = Mongo.get_db() col = db["auth"] if not col.find(data).count(): return jsonify(msg="not found"), 404 access_token = create_access_token(identity=data["username"], expires_delta=timedelta(days=30)) return jsonify(access_token=access_token, identity=data["username"]), 200 except: return jsonify(msg="bad gateway"), 500
def deviceTxPower(devAddr): if request.method == "POST": try: dt = request.get_json() txPower = dt["txPower"] db = Mongo.get_db() col = db["downlink_mac"] col.update({"devAddr": devAddr}, { "$set": { "txPower": { "commandType": "txPower", "commandId": 4, "value": txPower, "dateCreated": datetime.now(), "status": "pending" } } }, upsert=True) except Exception: return jsonify(msg="Bad Gateway"), 501 return jsonify(msg="ok"), 200
def notifiations(destId): if request.method == "GET": params = list(request.args.keys()) if 'nPerPage' not in params: return jsonify(msg="Bad Request"), 401 else: nPerPage = int(request.args.get('nPerPage')) if 'directionNext' in params: nextPage = True else: nextPage = False if 'startId' in params: startId = request.args.get('startId') else: startId = False db = Mongo.get_db() col = db["notifications"] total_documents = list( col.aggregate([{ "$match": { "dest": destId } }, { "$count": "total_documents" }])) if len(total_documents): total_documents = total_documents[0]["total_documents"] else: return jsonify(msg="Not Found"), 404 if startId: if nextPage: results = list( col.find({ "dest": destId, "time": { "$lt": int(startId) } }, { "_id": 0 }).sort("_id", -1).limit(nPerPage)) else: results = list( col.find({ "dest": destId, "time": { "$gt": int(startId) } }, { "_id": 0 }).sort("_id", 1).limit(nPerPage)) results.sort(key=lambda x: x["time"], reverse=True) # pagination with time is wrong. In the future i will have to select a starting point of a unique # ascending index. (not an ObjectId though because its not a json serializable type else: results = list( col.find({ "dest": destId }, { "_id": 0 }).sort("_id", -1).limit(nPerPage)) return jsonify(data=results, count=total_documents, msg="OK"), 200 if request.method == "POST": try: dt = request.get_json() if not all(item in dt.keys() for item in ['msgBody', 'source']): return jsonify(msg="Bad Request"), 401 db = Mongo.get_db() col = db["notifications"] if col.insert_one({ "msgBody": dt["msgBody"], "date": datetime.now(), "time": int(datetime.timestamp(datetime.now())), "dest": destId, "source": dt["source"] }).acknowledged: return jsonify(msg="ok"), 200 else: return jsonify(msg="Bad Gateway"), 501 except Exception: return jsonify(msg="Bad Gateway"), 501
def getDevicesByOwner(ownerId): db = Mongo.get_db() col = db["devices"] devices = list(col.find({"ownerId": ownerId}, {'_id': 0})) return jsonify(devices=devices), 200
@jwt.invalid_token_loader def my_invalid_token_loader(token): return jsonify({"msg": "Invalid JWT token"}), 422 # if i want to make a custom return for get_jwt_identity # @jwt.user_identity_loader # def user_identity_lookup(user): # return user['id'] def mqttc_keep_alive(mqttc): while 1: mqttc.publish('atlas/keep_alive', "heartbeat [atlas api]") time.sleep(30) if __name__ == "__main__": try: cwd = os.path.dirname(os.path.abspath(__file__)) Configuration(os.path.join(cwd, 'config/config.json')) config = Configuration.get() db = Mongo() pub = Publisher(config["AMQP"]) mqttc = Mongo.get_mqttc() mqttc.publish('atlas/system', "start of api") threading.Thread(target=mqttc_keep_alive, args=(mqttc,)).start() except Exception as e: raise SystemExit("Error while setting communications: {}".format(str(e))) application.run(debug=config["DEBUG"])