Example #1
0
def add_sensor_value(sensor_type):
    temp_reading = request.get_json()
    if "timestamp" not in temp_reading:
        return bad_request("timestamp attribute missing")
    if "sensor" not in temp_reading:
        return bad_request("sensor attribute missing")
    if "value" not in temp_reading:
        return bad_request("value attribute missing")
    if "next_update" not in temp_reading:
        return bad_request("next_update attribute missing")
    sensor_id = temp_reading["sensor"].replace(":", "")
    sensor = Sensor.get_by_id(sensor_id)
    if sensor is not None and sensor.sensor_type != sensor_type:
        return bad_request("Sensor is already registered as another type")
    if sensor is None:
        sensor = Sensor.create(id=sensor_id, name=sensor_id, sensor_type=sensor_type)
    sensor.next_update = datetime.utcfromtimestamp(
        temp_reading["timestamp"] + temp_reading["next_update"]
    )
    db.session.commit()
    reading = Reading(
        sensor=sensor_id,
        timestamp=datetime.utcfromtimestamp(temp_reading["timestamp"]),
        value=temp_reading["value"] * 100,
    )
    db.session.add(reading)
    db.session.commit()

    return jsonify({"message": "thanks"}), 201
Example #2
0
def get_sensor_log(sensor_id):
    sensor = Sensor.get_by_id(sensor_id)
    if sensor is None:
        return not_found("Sensor not found")
    rows = LogRow.get_by_sensor_id(sensor_id)
    res = []
    for row in rows:
        res.append(row.to_json())
    return jsonify(res), 200
Example #3
0
def update_sensor(sensor_id):
    sensor = Sensor.get_by_id(sensor_id)
    if sensor is None:
        return not_found("Sensor not found")
    name_change = next(c for c in request.get_json() if {
        "op": "replace",
        "path": "/name"
    }.items() <= c.items())
    if name_change is not None and "value" in name_change:
        sensor.name = name_change["value"]
        db.session.commit()
        return jsonify(sensor.to_json()), 200
    return bad_request("Not able to parse any patch changes")
Example #4
0
def add_sensor_log(sensor_id):
    sensor = Sensor.get_by_id(sensor_id)
    if sensor is None:
        return not_found("Sensor not found")
    log_request = request.get_json()
    if "timestamp" not in log_request:
        return bad_request("timestamp attribute missing")
    if "message" not in log_request:
        return bad_request("message attribute missing")
    if len(log_request["message"]) > 256:
        return bad_request("message attribute too long, max is 256")
    LogRow.create(
        sensor_id=sensor_id,
        timestamp=datetime.utcfromtimestamp(log_request["timestamp"]),
        message=log_request["message"],
    )
    return jsonify({"message": "thanks"}), 201
Example #5
0
def get_sensor(sensor_id):
    sensor = Sensor.get_by_id(sensor_id)
    if sensor is None:
        return not_found("Sensor not found")
    return jsonify(sensor.to_json()), 200