Process Incoming SMS Messages
Route: POST /api/sms/receive
Functionality:
Extract gas level data from SMS.
Identify and link the SMS to the appropriate sensor and client.
Store gas reading and update relevant statuses.
Service Layer (
services/smsService.js):
// javascript
import { db } from '@/lib/db';
export async function processIncomingSMS(fromNumber, body) {
const sensor = await db.sensor.findFirst({
where: { phone_number: fromNumber },
});
if (!sensor) return { error: 'Sensor not found' };
const client = await db.client.findFirst({
where: { sensor_phone_number: fromNumber },
});
const gasLevel = parseInt(body, 10);
let status = 'Normal';
if (gasLevel <= 20) status = 'Low';
else if (gasLevel > 80) status = 'High';
await db.gasReading.upsert({
where: { sensor_id: sensor.id },
update: { gas_level: gasLevel, status, last_updated: new Date() },
create: {
sensor_id: sensor.id,
client_id: client?.id || null,
gas_level: gasLevel,
status,
location: { lat: 0, lng: 0 },
},
});
return { success: true };
}
Last updated