Skip to content

Commit

Permalink
feat: simulation time is now dynamic
Browse files Browse the repository at this point in the history
  • Loading branch information
llVitell committed Aug 7, 2024
1 parent a16e5f4 commit 73e68ca
Show file tree
Hide file tree
Showing 17 changed files with 474 additions and 84 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"dependencies": {
"@prisma/client": "5.2.0",
"debug": "4.3.4",
"fastify": "^4.28.1",
"firebase-admin": "11.10.1",
"mqtt": "5.0.4",
"node-cron": "3.0.2",
Expand Down
323 changes: 323 additions & 0 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion src/@types/global.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable no-var */
declare global {
// eslint-disable-next-line no-var
var __io__: import('socket.io').Server
var __SIMULATION_TIME__: number
}

export {}
4 changes: 3 additions & 1 deletion src/@types/route.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
interface Route {
sub: (client: import('mqtt').MqttClient) => void
type: 'mqtt' | 'http'
sub?: (client: import('mqtt').MqttClient) => void
init?: (app: FastifyInstance) => void
SUB_TOPIC: string
}
155 changes: 80 additions & 75 deletions src/jobs/fakePub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ const clientPublish = <T>({
cb?.()
}

global.__SIMULATION_TIME__ = 10

const updateData = (client: MqttClient) => {
const pubDebug = debug(`${MAIN_TOPIC}:Mqtt:demo:pub`)

Expand All @@ -50,83 +52,86 @@ const updateData = (client: MqttClient) => {
return
}

cron.schedule('*/30 * * * * *', async (): Promise<void> => {
pubDebug(`Job started at: ${new Date().toISOString()}`)
cron.schedule(
`*/${global.__SIMULATION_TIME__} * * * * *`,
async (): Promise<void> => {
pubDebug(`Job started at: ${new Date().toISOString()}`)

const { id, moduleId, sensorId } = DEMO_CLIENT
const currentIsoTime = new Date().toISOString()
const { id, moduleId, sensorId } = DEMO_CLIENT
const currentIsoTime = new Date().toISOString()

pubDebug(`Publishing messages at: ${currentIsoTime}`)
clientPublish({
client,
value: randomInInterval(200, 450),
id,
moduleId,
sensorId,
topic: 'aq',
cb: () => {
clientPublish({
client,
value: parseFloat(randomInInterval(500, 800)),
id,
moduleId,
sensorId,
topic: 'co2',
cb: () => {
clientPublish({
client,
value: randomInInterval(1, 20),
id,
moduleId,
sensorId,
topic: 'humidity',
cb: () => {
clientPublish({
client,
value: randomInInterval(40, 70),
id,
moduleId,
sensorId,
topic: 'pm2.5',
cb: () => {
clientPublish({
client,
value: 998,
id,
moduleId,
sensorId,
topic: 'pressure',
cb: () => {
clientPublish({
client,
value: randomInInterval(23, 27, 1),
id,
moduleId,
sensorId,
topic: 'temperature',
cb: () => {
clientPublish({
client,
value: currentIsoTime,
id,
moduleId,
sensorId,
topic: 'date',
demo: true
})
}
})
}
})
}
})
}
})
}
})
}
})
})
pubDebug(`Publishing messages at: ${currentIsoTime}`)
clientPublish({
client,
value: randomInInterval(200, 450),
id,
moduleId,
sensorId,
topic: 'aq',
cb: () => {
clientPublish({
client,
value: parseFloat(randomInInterval(500, 800)),
id,
moduleId,
sensorId,
topic: 'co2',
cb: () => {
clientPublish({
client,
value: randomInInterval(1, 20),
id,
moduleId,
sensorId,
topic: 'humidity',
cb: () => {
clientPublish({
client,
value: randomInInterval(40, 70),
id,
moduleId,
sensorId,
topic: 'pm2.5',
cb: () => {
clientPublish({
client,
value: 998,
id,
moduleId,
sensorId,
topic: 'pressure',
cb: () => {
clientPublish({
client,
value: randomInInterval(23, 27, 1),
id,
moduleId,
sensorId,
topic: 'temperature',
cb: () => {
clientPublish({
client,
value: currentIsoTime,
id,
moduleId,
sensorId,
topic: 'date',
demo: true
})
}
})
}
})
}
})
}
})
}
})
}
})
}
)
}

export { updateData }
11 changes: 7 additions & 4 deletions src/network/mqtt/router.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { MqttClient } from 'mqtt'

import { FastifyInstance } from 'fastify'
import * as Routes from './routes'

const applyRoutes = (client: MqttClient) => {
;(Object.keys(Routes) as (keyof typeof Routes)[]).forEach(route => {
Routes[route].sub(client)
const applyRoutes = (client: MqttClient, app: FastifyInstance) => {
;(Object.keys(Routes) as (keyof typeof Routes)[]).forEach(routeKey => {
const route = Routes[routeKey] as Route

if (route.type === 'mqtt' && route.sub) route.sub(client)
else if (route.type === 'http' && route.init) route.init(app)
})
}

Expand Down
1 change: 1 addition & 0 deletions src/network/mqtt/routes/aq.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ const sub = (client: MqttClient) => {
}

const aq: Route = {
type: 'mqtt',
sub,
SUB_TOPIC
}
Expand Down
1 change: 1 addition & 0 deletions src/network/mqtt/routes/co2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ const sub = (client: MqttClient) => {
}

const co2: Route = {
type: 'mqtt',
sub,
SUB_TOPIC
}
Expand Down
1 change: 1 addition & 0 deletions src/network/mqtt/routes/date.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ const sub = (client: MqttClient) => {
}

const date: Route = {
type: 'mqtt',
sub,
SUB_TOPIC
}
Expand Down
1 change: 1 addition & 0 deletions src/network/mqtt/routes/humidity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const sub = (client: MqttClient) => {
}

const humidity: Route = {
type: 'mqtt',
sub,
SUB_TOPIC
}
Expand Down
1 change: 1 addition & 0 deletions src/network/mqtt/routes/photo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ const sub = (client: MqttClient) => {
}

const receivePhoto: Route = {
type: 'mqtt',
sub,
SUB_TOPIC
}
Expand Down
1 change: 1 addition & 0 deletions src/network/mqtt/routes/pm2.5.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const sub = (client: MqttClient) => {

// eslint-disable-next-line camelcase
const pm2_5: Route = {
type: 'mqtt',
sub,
SUB_TOPIC
}
Expand Down
1 change: 1 addition & 0 deletions src/network/mqtt/routes/pressure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const sub = (client: MqttClient) => {
}

const pressure: Route = {
type: 'mqtt',
sub,
SUB_TOPIC
}
Expand Down
43 changes: 43 additions & 0 deletions src/network/mqtt/routes/simulationTIme.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import debug from 'debug'
import { FastifyInstance } from 'fastify'
import { MAIN_TOPIC } from 'utils'

const TOPIC = 'simulationTIme'
const SUB_TOPIC = `${MAIN_TOPIC}/${TOPIC}`

const updateSimulationTime = (app: FastifyInstance) => {
const simDebug = debug('simulation:time:update')

app.post<{ Params: { time: number } }>(
'/simulationTime/:time',
async (req, reply) => {
const {
headers: { authorization },
params: { time }
} = req

if (authorization !== process.env.API_KEY)
return reply.status(401).send({ message: 'Unauthorized' })

if (isNaN(Number(time)))
return reply.status(400).send({ message: 'Time is not a number' })

global.__SIMULATION_TIME__ = time * 1000
simDebug(
`Updated simulation time: ${new Date(
global.__SIMULATION_TIME__
).toISOString()}`
)

return { message: 'Simulation time updated', newTime: `${time}s` }
}
)
}

const simulationTime: Route = {
type: 'http',
init: updateSimulationTime,
SUB_TOPIC
}

export { simulationTime }
1 change: 1 addition & 0 deletions src/network/mqtt/routes/temperature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ const sub = (client: MqttClient) => {
}

const temperature: Route = {
type: 'mqtt',
sub,
SUB_TOPIC
}
Expand Down
7 changes: 4 additions & 3 deletions src/network/mqtt/server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { connect, type IClientOptions, type MqttClient } from 'mqtt'
import { Debugger } from 'debug'

import fastify from 'fastify'
declare global {
// eslint-disable-next-line no-var
var __mqttClient__: MqttClient
Expand Down Expand Up @@ -36,8 +36,9 @@ const getClient = (d?: Debugger) => {

const start = async (d: Debugger) => {
const { applyRoutes } = await import('./router')

applyRoutes(getClient(d))
const app = fastify()
// updateSimulationTime(app)
applyRoutes(getClient(d), app)
}

const stop = async () => {
Expand Down
3 changes: 3 additions & 0 deletions src/network/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { dbConnection, firebaseConnection } from 'database'
import { MAIN_TOPIC } from 'utils'
import { getClient, start as startMqtt } from './mqtt'
import { socketConnection } from './socket'
import { updateData } from 'jobs/fakePub'

const namespace = `${MAIN_TOPIC}:Mqtt:Server`
const serverDebug = debug(namespace)
Expand All @@ -15,6 +16,8 @@ const start = async () => {
await dbConnection(serverDebug).connect()
})

updateData(getClient(serverDebug))

if (process.env.NODE_ENV !== 'local') {
const jobs = await import('../jobs')

Expand Down

0 comments on commit 73e68ca

Please sign in to comment.