Skip to content

Commit

Permalink
Merge branch 'main' into prod-lambda
Browse files Browse the repository at this point in the history
  • Loading branch information
Fruittips committed Nov 25, 2023
2 parents 4f4c682 + fe6386f commit c232965
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 57 deletions.
41 changes: 22 additions & 19 deletions fire-cloud/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,26 +109,15 @@ async function connectAndSubscribe() {

//invoke lambda function to calculate fire probability and update database
const rowId = data[0].id;
await invokeAnalytics(rowId, temperature, flameSensorValue);

// START publish to flame presence topic to tune freq flow
/*
1. get the fire probablity from the database
2. validate and check if the fire probability is above threshold -> timestamp
3. publish to flame presence topic
*/
const { data: fireData, error: fireErr } = await supabase
.from("firecloud")
.select("fire_probability, node_id")
.eq("id", rowId);
const lambdaRes = await invokeAnalytics(rowId, temperature, flameSensorValue);

const nodeId = lambdaRes.node_id;
const fireProbability = fireData.fire_probability;

if (fireErr) {
console.error(fireErr);
if (fireProbability === null) {
console.log("lambda function failed to calculate fire probability");
return;
}
const nodeId = fireData[0].node_id;
const fireProbability = fireData[0].fire_probability;

await validateAndPublishFireMessage(nodeId, fireProbability);
});
}
Expand All @@ -138,7 +127,7 @@ async function validateAndPublishFireMessage(nodeId, fireProbability) {
const fireProbabilityThreshold = 0.3;

if (fireProbability > fireProbabilityThreshold) {
if (fireStatuses[nodeId] === 0) await publishMessage(FLAME_PRESENCE_TOPIC, { status: 1 });
if (fireStatuses[nodeId] === 0) await updateAndPublishFireMessage(FLAME_PRESENCE_TOPIC, 1);
fireStatuses[nodeId] = 1;
}

Expand All @@ -153,14 +142,28 @@ async function validateAndPublishFireMessage(nodeId, fireProbability) {

// if status has been 0 for more than 5 minutes -> there is no more fire -> publish status 0
if (timeDiffInMinutes > 5) {
await publishMessage(FLAME_PRESENCE_TOPIC, { status: 0 });
await updateAndPublishFireMessage(FLAME_PRESENCE_TOPIC, 0);
fireStatuses[nodeId] = 0;
noFireDurations[nodeId] = null;
}
}
}
}

async function updateAndPublishFireMessage(topic, status) {
const hasFire = status === 1;
const { error } = await supabase
.from("fire_status")
.update({ has_fire: hasFire, timestamp: new Date().toISOString() })
.eq("id", 1);
if (error) {
console.error(error);
return;
}

await publishMessage(topic, { status: status });
}

async function publishMessage(topic, message) {
const messageJson = JSON.stringify(message);
const messageBuffer = Buffer.from(messageJson);
Expand Down
36 changes: 0 additions & 36 deletions lambda/lambda_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,11 @@
import numpy as np
import os
from supabase import create_client, Client
import redis

REDIS_ENDPOINT = os.environ.get("REDIS_ENDPOINT")
SUPABASE_URL = os.environ.get("SUPABASE_URL")
SUPABASE_KEY = os.environ.get("SUPABASE_KEY")

supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
try:
redisClient = redis.from_url(REDIS_ENDPOINT, decode_responses=True)
except Exception as e:
print(f"Error connecting to redis: {e}")

PAST_RECORDS_DURATION = 120 # in minutes

def lambda_handler(event, context):
Expand Down Expand Up @@ -62,7 +55,6 @@ def lambda_handler(event, context):
'body': json.dumps({
'fire_probability': fire_probability,
'r_value': r_value,
'redis_val': test_redis(redisClient)
})
})

Expand Down Expand Up @@ -111,34 +103,6 @@ def get_r_value(temp_arr, humidity_arr):
r_actual = r_corrcoef[0][1]
return r_actual

# ================== Redis helper functions ==================
# def set_timestamp(nodeId: str):
# key = f"node_{nodeId}_timestamp"
# five_minutes = 60 * 5
# redisClient.set(key, "1")
# redisClient.expire(key, five_minutes)

# def set_flag(nodeId: str):
# key = f"node_{nodeId}_flag"
# redisClient.set(key, "1")

# def get_flag(nodeId: str):
# key = f"node_{nodeId}_flag"
# # return None if does not exists
# return redisClient.get(key)

# def get_timestamp(nodeId: str):
# key = f"node_{nodeId}_timestamp"
# # return None if does not exists
# return redisClient.get(key)

def test_redis(redisClient):
key = "test"
redisClient.set(key, "1")
res = redisClient.get(key)
redisClient.delete(key)
return res

# #TODO: DONT PUSH THIS REMOVE IT BEFORE PUSHING
# if __name__ == "__main__":
# lambda_handler({
Expand Down
4 changes: 2 additions & 2 deletions node.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,12 +132,12 @@ async def __listen_to_flame_presence(self):
if len(flame_presence_data) > 0:
flame_presence = self.__decode_json_data(self.flame_presence_characteristic.read())
print("Flame presence characteristic value:",flame_presence)
if flame_presence["status"] == "1":
if flame_presence["status"] == 1:
print("Flame detected. Increasing sampling interval and clock frequency.")
self.sampling_interval = _SAMPLING_INTERVAL_HIGH
machine.freq(_FREQ_HIGH)
print(f"Sampling interval: {self.sampling_interval} seconds", f"Clock frequency: {machine.freq()}")
elif flame_presence["status"] == "0":
elif flame_presence["status"] == 0:
print("No flame detected. Decreasing sampling interval and clock frequency.")
self.sampling_interval = _SAMPLING_INTERVAL_LOW
machine.freq(_FREQ_LOW)
Expand Down

0 comments on commit c232965

Please sign in to comment.