Compare commits
22 Commits
540becee46
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 84a9ce3f4c | |||
| 6fe3050c1c | |||
| 70c534c204 | |||
| a619733a08 | |||
| ba54730f2f | |||
| 20b7691b8b | |||
| e2d1c4f681 | |||
| 5c55b915e1 | |||
| 677ee6325f | |||
| 4edef06212 | |||
| e2ffbc5435 | |||
| 7d8d6ed2b9 | |||
| 205ee1f0e5 | |||
| 13e3287fd7 | |||
| c09b3b9a13 | |||
| b521c32ade | |||
| 4a582f4889 | |||
| d39def8dfa | |||
| d4e31ab688 | |||
| fd0eb59f24 | |||
| 75832125e2 | |||
| bd52094c5f |
182
app.js
182
app.js
@ -1,7 +1,7 @@
|
|||||||
require("dotenv").config({ path: ".env" });
|
require("dotenv").config({ path: ".env" });
|
||||||
require("events").EventEmitter.prototype._maxListeners = 30;
|
require("events").EventEmitter.prototype._maxListeners = 30;
|
||||||
const morgan = require("morgan");
|
const morgan = require("morgan");
|
||||||
// start for gps-tracking
|
|
||||||
const net = require("net");
|
const net = require("net");
|
||||||
const dgram = require("dgram");
|
const dgram = require("dgram");
|
||||||
const crc = require("crc");
|
const crc = require("crc");
|
||||||
@ -13,36 +13,23 @@ const VhcModels = require("./models/VhcModels");
|
|||||||
const LibMail = require("./library/LibMail");
|
const LibMail = require("./library/LibMail");
|
||||||
const LibHelper = require("./library/LibHelper");
|
const LibHelper = require("./library/LibHelper");
|
||||||
const nanoid = require("nanoid").nanoid;
|
const nanoid = require("nanoid").nanoid;
|
||||||
// end for gps-tracking
|
|
||||||
|
|
||||||
// start for normal http request
|
|
||||||
const express = require("express");
|
const express = require("express");
|
||||||
// const LibBullAdapter = require('./library/LibBullAdapter');
|
|
||||||
const routes = require("./routes/routes");
|
const routes = require("./routes/routes");
|
||||||
// const routes = require('./routes/routes_without_scheduler');
|
|
||||||
const app = express();
|
const app = express();
|
||||||
// end for normal http request
|
|
||||||
|
|
||||||
// start for logging
|
|
||||||
const LibWinston = require("./library/LibWinston");
|
const LibWinston = require("./library/LibWinston");
|
||||||
|
|
||||||
const logName = "libUdp";
|
const logName = "libUdp";
|
||||||
const Logger = LibWinston.initialize(logName);
|
const Logger = LibWinston.initialize(logName);
|
||||||
// end for logging
|
|
||||||
|
|
||||||
// start commit / log message from gps
|
|
||||||
async function commitMessage(now, logDevice) {
|
async function commitMessage(now, logDevice) {
|
||||||
try {
|
try {
|
||||||
// don't log
|
|
||||||
if (!logDevice.original_hex) {
|
if (!logDevice.original_hex) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
// in the future don't log to db if device_id not found in vhc
|
|
||||||
const vhc = await VhcModels.getVhcByDeviceId(logDevice.device_id);
|
const vhc = await VhcModels.getVhcByDeviceId(logDevice.device_id);
|
||||||
const lastTrack = await GpsTracksModels.get2LastLocByDeviceId(logDevice.device_id);
|
const lastTrack = await GpsTracksModels.get2LastLocByDeviceId(logDevice.device_id);
|
||||||
|
|
||||||
if (["heartbeat", "alarm"].includes(logDevice.action)) {
|
if (["heartbeat", "alarm"].includes(logDevice.action)) {
|
||||||
// set engine stts moving,idling,stopped
|
|
||||||
if (logDevice.ignition == GpsTracksModels.STTS_IGNITION_HIGH) {
|
if (logDevice.ignition == GpsTracksModels.STTS_IGNITION_HIGH) {
|
||||||
if (logDevice.speed) {
|
if (logDevice.speed) {
|
||||||
logDevice.stts_engine = GpsTracksModels.STTS_EN_MOVING;
|
logDevice.stts_engine = GpsTracksModels.STTS_EN_MOVING;
|
||||||
@ -60,9 +47,8 @@ async function commitMessage(now, logDevice) {
|
|||||||
logDevice.stts_engine = GpsTracksModels.STTS_EN_STOPING;
|
logDevice.stts_engine = GpsTracksModels.STTS_EN_STOPING;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// get last ignition, stts_engine, stts_alarm, stts_charge, stts_acc, stts_volt, stts_switch
|
|
||||||
if (["location"].includes(logDevice.action)) {
|
if (["location"].includes(logDevice.action)) {
|
||||||
// get last ignition
|
|
||||||
const lastHeartbeatOrAlarm = await GpsTracksModels.get2LastHeartbeatOrAlarm(logDevice.device_id);
|
const lastHeartbeatOrAlarm = await GpsTracksModels.get2LastHeartbeatOrAlarm(logDevice.device_id);
|
||||||
if (lastHeartbeatOrAlarm.length > 0) {
|
if (lastHeartbeatOrAlarm.length > 0) {
|
||||||
logDevice.ignition = lastHeartbeatOrAlarm[0].ignition;
|
logDevice.ignition = lastHeartbeatOrAlarm[0].ignition;
|
||||||
@ -73,7 +59,7 @@ async function commitMessage(now, logDevice) {
|
|||||||
logDevice.stts_gps = lastHeartbeatOrAlarm[0].stts_gps;
|
logDevice.stts_gps = lastHeartbeatOrAlarm[0].stts_gps;
|
||||||
logDevice.stts_gsm = lastHeartbeatOrAlarm[0].stts_gsm;
|
logDevice.stts_gsm = lastHeartbeatOrAlarm[0].stts_gsm;
|
||||||
}
|
}
|
||||||
// set engine stts moving,idling,stopped
|
|
||||||
if (logDevice.ignition == GpsTracksModels.STTS_IGNITION_HIGH) {
|
if (logDevice.ignition == GpsTracksModels.STTS_IGNITION_HIGH) {
|
||||||
if (logDevice.speed) {
|
if (logDevice.speed) {
|
||||||
logDevice.stts_engine = GpsTracksModels.STTS_EN_MOVING;
|
logDevice.stts_engine = GpsTracksModels.STTS_EN_MOVING;
|
||||||
@ -87,11 +73,10 @@ async function commitMessage(now, logDevice) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// get stts_alarm, stts_charge, stts_acc, stts_volt, stts_switch
|
|
||||||
} else {
|
} else {
|
||||||
logDevice.stts_engine = GpsTracksModels.STTS_EN_STOPING;
|
logDevice.stts_engine = GpsTracksModels.STTS_EN_STOPING;
|
||||||
}
|
}
|
||||||
logDevice.stts_oil_electricity = lastHeartbeatOrAlarm[0].stts_oil_electricity;
|
logDevice.stts_oil_electricity = lastHeartbeatOrAlarm[0]?.stts_oil_electricity ?? 0;
|
||||||
logDevice.stts_alarm = lastHeartbeatOrAlarm[0].stts_alarm;
|
logDevice.stts_alarm = lastHeartbeatOrAlarm[0].stts_alarm;
|
||||||
logDevice.stts_charge = lastHeartbeatOrAlarm[0].stts_charge;
|
logDevice.stts_charge = lastHeartbeatOrAlarm[0].stts_charge;
|
||||||
logDevice.stts_acc = lastHeartbeatOrAlarm[0].stts_acc;
|
logDevice.stts_acc = lastHeartbeatOrAlarm[0].stts_acc;
|
||||||
@ -99,7 +84,6 @@ async function commitMessage(now, logDevice) {
|
|||||||
logDevice.stts_switch = lastHeartbeatOrAlarm[0].stts_switch;
|
logDevice.stts_switch = lastHeartbeatOrAlarm[0].stts_switch;
|
||||||
}
|
}
|
||||||
|
|
||||||
// sekarang heartbeat diinject data lokasi juga dari lokasi terakhir
|
|
||||||
if (["heartbeat"].includes(logDevice.action)) {
|
if (["heartbeat"].includes(logDevice.action)) {
|
||||||
if (lastTrack.length > 0) {
|
if (lastTrack.length > 0) {
|
||||||
logDevice.latitude = lastTrack[0].latitude;
|
logDevice.latitude = lastTrack[0].latitude;
|
||||||
@ -115,12 +99,6 @@ async function commitMessage(now, logDevice) {
|
|||||||
logDevice.pos_type_gps = lastTrack[0].pos_type_gps;
|
logDevice.pos_type_gps = lastTrack[0].pos_type_gps;
|
||||||
logDevice.is_pos_gps = lastTrack[0].is_pos_gps;
|
logDevice.is_pos_gps = lastTrack[0].is_pos_gps;
|
||||||
|
|
||||||
// jika gapengen dimunculin di last movement
|
|
||||||
// logDevice.crt = lastTrack[0].crt;
|
|
||||||
// logDevice.crt_format = lastTrack[0].crt_format;
|
|
||||||
// logDevice.crt_d = lastTrack[0].crt_d;
|
|
||||||
// logDevice.crt_d_format = lastTrack[0].crt_d_format;
|
|
||||||
// jika pengen di munculin di last movement
|
|
||||||
logDevice.crt = now;
|
logDevice.crt = now;
|
||||||
logDevice.crt_format = moment.unix(now).format("YYYY-MM-DD HH:mm:ss");
|
logDevice.crt_format = moment.unix(now).format("YYYY-MM-DD HH:mm:ss");
|
||||||
logDevice.crt_d = now;
|
logDevice.crt_d = now;
|
||||||
@ -128,35 +106,80 @@ async function commitMessage(now, logDevice) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// count milleage
|
// ================= UPDATE SUM MILEAGE DARI t_vehicle ====================
|
||||||
if (logDevice.latitude != null && logDevice.longitude != null && lastTrack.length > 0) {
|
if (logDevice.latitude != null && logDevice.longitude != null && lastTrack.length > 0) {
|
||||||
const distance = LibHelper.haversineGreatCircleDistance(lastTrack[0].latitude, lastTrack[0].longitude, logDevice.latitude, logDevice.longitude, LibHelper.EARTH_RADIUS_KM);
|
const distance = LibHelper.haversineGreatCircleDistance(lastTrack[0].latitude, lastTrack[0].longitude, logDevice.latitude, logDevice.longitude, LibHelper.EARTH_RADIUS_KM);
|
||||||
|
|
||||||
const distance_km = LibHelper.kmToKm(distance, 100000000);
|
const distance_km = LibHelper.kmToKm(distance, 100000000);
|
||||||
// console.log(`GPS TRACKER UP LOCATION => device_id:${logDevice.device_id} vhc_id:${(vhc[0]) ? vhc[0].vid : 0}, distance_km:${distance_km}`);
|
|
||||||
// validasi jika lebih dari 3km, ga disimpan
|
|
||||||
if (distance_km >= 3) {
|
if (distance_km >= 3) {
|
||||||
GpsTracksModels.bundleCreate2(logDevice, logDevice); // jika tidak disimpan malah jadi bug, jadi akan update lokasi terus dengan kalkulasi jarak sebelumnya jadi makan lama makin lebar, mending disimpen terus milleagenya jadi 0 aja
|
GpsTracksModels.bundleCreate2(logDevice, logDevice);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
logDevice.pre_milleage = distance_km;
|
logDevice.pre_milleage = distance_km;
|
||||||
logDevice.sum_milleage = (lastTrack[0].sum_milleage + logDevice.pre_milleage).toFixed(8);
|
|
||||||
|
// 1. Hitung sum_milleage dari log sebelumnya
|
||||||
|
const logBaseMileage = lastTrack[0]?.sum_milleage ?? 0;
|
||||||
|
logDevice.sum_milleage = (logBaseMileage + logDevice.pre_milleage).toFixed(8);
|
||||||
|
|
||||||
|
// 2. Hitung vhc_milleage dari master vehicle
|
||||||
if (vhc.length > 0) {
|
if (vhc.length > 0) {
|
||||||
logDevice.vhc_id = vhc[0] ? vhc[0].vid : 0;
|
const vhcBaseMileage = vhc[0]?.sum_milleage ?? 0;
|
||||||
if (lastTrack[0].vhc_id == logDevice.vhc_id) {
|
logDevice.vhc_id = vhc[0]?.vid ?? 0;
|
||||||
logDevice.vhc_milleage = (lastTrack[0].vhc_milleage + logDevice.pre_milleage).toFixed(8);
|
logDevice.vhc_milleage = (vhcBaseMileage + logDevice.pre_milleage).toFixed(8);
|
||||||
} else {
|
|
||||||
logDevice.vhc_milleage = (vhc[0] ? vhc[0].sum_milleage : 0 + logDevice.pre_milleage).toFixed(8);
|
VhcModels.update(logDevice.vhc_id, {
|
||||||
}
|
sum_milleage: logDevice.vhc_milleage,
|
||||||
VhcModels.update(vhc[0] ? vhc[0].vid : 0, { sum_milleage: logDevice.vhc_milleage });
|
});
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// truck zoning spawn
|
// 4. Simpan ke DB
|
||||||
|
GpsTracksModels.bundleCreate2(logDevice, logDevice);
|
||||||
|
}
|
||||||
|
|
||||||
|
// V1
|
||||||
|
// if (logDevice.latitude != null && logDevice.longitude != null && lastTrack.length > 0) {
|
||||||
|
// const distance = LibHelper.haversineGreatCircleDistance(lastTrack[0].latitude, lastTrack[0].longitude, logDevice.latitude, logDevice.longitude, LibHelper.EARTH_RADIUS_KM);
|
||||||
|
// const distance_km = LibHelper.kmToKm(distance, 100000000);
|
||||||
|
|
||||||
|
// if (distance_km >= 3) {
|
||||||
|
// GpsTracksModels.bundleCreate2(logDevice, logDevice);
|
||||||
|
// return false;
|
||||||
|
// }
|
||||||
|
// logDevice.pre_milleage = distance_km;
|
||||||
|
// logDevice.sum_milleage = (lastTrack[0].sum_milleage + logDevice.pre_milleage).toFixed(8);
|
||||||
|
// if (vhc.length > 0) {
|
||||||
|
// logDevice.vhc_id = vhc[0] ? vhc[0].vid : 0;
|
||||||
|
// if (lastTrack[0].vhc_id == logDevice.vhc_id) {
|
||||||
|
// logDevice.vhc_milleage = (lastTrack[0].vhc_milleage + logDevice.pre_milleage).toFixed(8);
|
||||||
|
// } else {
|
||||||
|
// logDevice.vhc_milleage = (vhc[0] ? vhc[0].sum_milleage : 0 + logDevice.pre_milleage).toFixed(8);
|
||||||
|
// }
|
||||||
|
// VhcModels.update(vhc[0] ? vhc[0].vid : 0, { sum_milleage: logDevice.vhc_milleage });
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// if (logDevice.latitude != null && logDevice.longitude != null && lastTrack.length > 0) {
|
||||||
|
// const distance = LibHelper.haversineGreatCircleDistance(lastTrack[0].latitude, lastTrack[0].longitude, logDevice.latitude, logDevice.longitude, LibHelper.EARTH_RADIUS_KM);
|
||||||
|
// const distance_km = LibHelper.kmToKm(distance, 100000000);
|
||||||
|
|
||||||
|
// if (distance_km >= 3) {
|
||||||
|
// GpsTracksModels.bundleCreate2(logDevice, logDevice);
|
||||||
|
// return false;
|
||||||
|
// }
|
||||||
|
// logDevice.pre_milleage = distance_km;
|
||||||
|
// logDevice.sum_milleage = (lastTrack[0].sum_milleage + logDevice.pre_milleage).toFixed(8);
|
||||||
|
// if (vhc.length > 0) {
|
||||||
|
// logDevice.vhc_id = vhc[0].vid;
|
||||||
|
// const increment = parseFloat(logDevice.pre_milleage || 0);
|
||||||
|
|
||||||
|
// await VhcModels.incrementMileage(vhc[0].vid, increment);
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
if (logDevice.latitude != null && logDevice.longitude != null) {
|
if (logDevice.latitude != null && logDevice.longitude != null) {
|
||||||
// && vhc.length > 0
|
|
||||||
// log tracking
|
|
||||||
const currTrack = await GpsTracksModels.bundleCreate2(logDevice, logDevice);
|
const currTrack = await GpsTracksModels.bundleCreate2(logDevice, logDevice);
|
||||||
// console.log('GT06 HAS LOCATION AND CHECK ZONE');
|
|
||||||
const inCircle = await ZoneModels.getInCircle(logDevice.latitude, logDevice.longitude);
|
const inCircle = await ZoneModels.getInCircle(logDevice.latitude, logDevice.longitude);
|
||||||
const inShape = await ZoneModels.getInShape(logDevice.latitude, logDevice.longitude);
|
const inShape = await ZoneModels.getInShape(logDevice.latitude, logDevice.longitude);
|
||||||
const insideSpawnZone = [];
|
const insideSpawnZone = [];
|
||||||
@ -215,7 +238,6 @@ async function commitMessage(now, logDevice) {
|
|||||||
da_name: vhc[0] ? vhc[0].da_name : 0 || "",
|
da_name: vhc[0] ? vhc[0].da_name : 0 || "",
|
||||||
da_phone: "+" + (vhc[0] ? vhc[0].da_phone_code : 0 || "") + (vhc[0] ? vhc[0].da_phone : 0 || ""),
|
da_phone: "+" + (vhc[0] ? vhc[0].da_phone_code : 0 || "") + (vhc[0] ? vhc[0].da_phone : 0 || ""),
|
||||||
};
|
};
|
||||||
// LibMail.sendVhcSpawnZoneMail(`${(vhc[0]) ? vhc[0].nopol1 : 0 || ''}${(vhc[0]) ? vhc[0].nopol2 : 0 || ''}${(vhc[0]) ? vhc[0].nopol3 : 0 || ''} entering zone ${mailData.z_name}`, mailData.pic_mail, mailData);
|
|
||||||
|
|
||||||
if (logDevice.device_id === "0865784052395871") console.log(1234567890);
|
if (logDevice.device_id === "0865784052395871") console.log(1234567890);
|
||||||
GpsTracksModels.create2SpawnZone({
|
GpsTracksModels.create2SpawnZone({
|
||||||
@ -238,16 +260,13 @@ async function commitMessage(now, logDevice) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// log tracking
|
|
||||||
GpsTracksModels.bundleCreate2(logDevice, logDevice);
|
GpsTracksModels.bundleCreate2(logDevice, logDevice);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// end commit / log message from gps
|
|
||||||
|
|
||||||
// start for gps-tracking TCP ONLY
|
|
||||||
const devices = [];
|
const devices = [];
|
||||||
const netConn = require("./config/netConn");
|
const netConn = require("./config/netConn");
|
||||||
/**
|
/**
|
||||||
@ -259,9 +278,6 @@ net.createServer(
|
|||||||
allowHalfOpen: true,
|
allowHalfOpen: true,
|
||||||
},
|
},
|
||||||
function (c) {
|
function (c) {
|
||||||
// c mean connection
|
|
||||||
|
|
||||||
// save connections
|
|
||||||
c.id = nanoid();
|
c.id = nanoid();
|
||||||
|
|
||||||
c.pipe(c);
|
c.pipe(c);
|
||||||
@ -269,7 +285,6 @@ net.createServer(
|
|||||||
c.on("data", async (buffer_req) => {
|
c.on("data", async (buffer_req) => {
|
||||||
const now = moment().unix();
|
const now = moment().unix();
|
||||||
const me = LibDevice.identifyProtocolFromBuffer(buffer_req);
|
const me = LibDevice.identifyProtocolFromBuffer(buffer_req);
|
||||||
// console.log('app ', buffer_req);
|
|
||||||
|
|
||||||
const logDevice = {
|
const logDevice = {
|
||||||
original_hex: me.ori_string,
|
original_hex: me.ori_string,
|
||||||
@ -308,7 +323,6 @@ net.createServer(
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (me.protocol_name == "gt06") {
|
if (me.protocol_name == "gt06") {
|
||||||
// const act = LibDevice.gt06Action(me, device.device_id || null);
|
|
||||||
let dvc_id = devices[c.id];
|
let dvc_id = devices[c.id];
|
||||||
const act = LibDevice.gt06Action(me, dvc_id || null);
|
const act = LibDevice.gt06Action(me, dvc_id || null);
|
||||||
|
|
||||||
@ -338,19 +352,35 @@ net.createServer(
|
|||||||
logDevice.pos_type_gps = Number(act.gps_data.realtime_dif_gps) === 0 ? GpsTracksModels.STTS_POS_TYPE_GPS_RLTM : GpsTracksModels.STTS_POS_TYPE_GPS_DIFF;
|
logDevice.pos_type_gps = Number(act.gps_data.realtime_dif_gps) === 0 ? GpsTracksModels.STTS_POS_TYPE_GPS_RLTM : GpsTracksModels.STTS_POS_TYPE_GPS_DIFF;
|
||||||
logDevice.is_pos_gps = Number(act.gps_data.positioning_gps) ? GpsTracksModels.STTS_IS_POS_GPS_HAS : GpsTracksModels.STTS_IS_POS_GPS_NOT;
|
logDevice.is_pos_gps = Number(act.gps_data.positioning_gps) ? GpsTracksModels.STTS_IS_POS_GPS_HAS : GpsTracksModels.STTS_IS_POS_GPS_NOT;
|
||||||
|
|
||||||
logDevice.crt = moment(act.gps_data.date).unix();
|
// logDevice.crt = moment(act.gps_data.date).unix();
|
||||||
logDevice.crt_format = moment(act.gps_data.date).format("YYYY-MM-DD HH:mm:ss");
|
// logDevice.crt_format = moment(act.gps_data.date).format("YYYY-MM-DD HH:mm:ss");
|
||||||
logDevice.crt_d = moment(act.gps_data.date).unix();
|
// logDevice.crt_d = moment(act.gps_data.date).unix();
|
||||||
logDevice.crt_d_format = moment(act.gps_data.date).format("YYYY-MM-DD HH:mm:ss");
|
// logDevice.crt_d_format = moment(act.gps_data.date).format("YYYY-MM-DD HH:mm:ss");
|
||||||
|
|
||||||
|
let deviceTime = moment(act.gps_data.date).unix();
|
||||||
|
let now = moment().unix();
|
||||||
|
let diff = Math.abs(deviceTime - now);
|
||||||
|
|
||||||
|
// Jika beda waktu terlalu besar (> 300 detik atau 5 menit), pakai waktu server
|
||||||
|
if (diff > 300) {
|
||||||
|
console.warn(`[WAKTU TIDAK VALID] Device ${logDevice.device_id} mengirim waktu tidak sinkron, pakai waktu server.`);
|
||||||
|
deviceTime = now;
|
||||||
|
}
|
||||||
|
|
||||||
|
logDevice.crt = deviceTime;
|
||||||
|
logDevice.crt_format = moment.unix(deviceTime).format("YYYY-MM-DD HH:mm:ss");
|
||||||
|
logDevice.crt_d = deviceTime;
|
||||||
|
logDevice.crt_d_format = moment.unix(deviceTime).format("YYYY-MM-DD HH:mm:ss");
|
||||||
|
logDevice.crt_device_raw = moment(act.gps_data.date).unix(); // waktu asli dari device (sebelum validasi)
|
||||||
} else if (act.action_type == "heartbeat") {
|
} else if (act.action_type == "heartbeat") {
|
||||||
logDevice.action = act.action_type;
|
logDevice.action = act.action_type;
|
||||||
logDevice.device_id = act.device_id;
|
logDevice.device_id = act.device_id;
|
||||||
|
|
||||||
logDevice.ignition = Number(act.stts_data.terminal_info.acc) ? GpsTracksModels.STTS_IGNITION_HIGH : GpsTracksModels.STTS_IGNITION_LOW;
|
logDevice.ignition = Number(act.stts_data.terminal_info.acc) ? GpsTracksModels.STTS_IGNITION_HIGH : GpsTracksModels.STTS_IGNITION_LOW;
|
||||||
logDevice.stts_gps = act.stts_data.terminal_info.gps_tracking ? GpsTracksModels.STTS_GPS_ON : GpsTracksModels.STTS_GPS_OFF; // 1=>on, 2=>off
|
logDevice.stts_gps = act.stts_data.terminal_info.gps_tracking ? GpsTracksModels.STTS_GPS_ON : GpsTracksModels.STTS_GPS_OFF;
|
||||||
logDevice.stts_gsm = Number(act.stts_data.gsm_signal_strength) + 1; // 1=>no signal, n>1=>get signal
|
logDevice.stts_gsm = Number(act.stts_data.gsm_signal_strength) + 1;
|
||||||
|
|
||||||
logDevice.stts_oil_electricity = Number(act.stts_data.terminal_info.oil_electricity) === 0 ? GpsTracksModels.STTS_OIL_ELECTRIC_ON : GpsTracksModels.STTS_OIL_ELECTRIC_OFF; // 1=>on, 2=>off
|
logDevice.stts_oil_electricity = Number(act.stts_data.terminal_info.oil_electricity) === 0 ? GpsTracksModels.STTS_OIL_ELECTRIC_ON : GpsTracksModels.STTS_OIL_ELECTRIC_OFF;
|
||||||
|
|
||||||
let stts_alarm = Number(act.stts_data.terminal_info.stts);
|
let stts_alarm = Number(act.stts_data.terminal_info.stts);
|
||||||
if (stts_alarm == 0) {
|
if (stts_alarm == 0) {
|
||||||
@ -391,10 +421,10 @@ net.createServer(
|
|||||||
logDevice.is_pos_gps = Number(act.gps_data.positioning_gps) ? GpsTracksModels.STTS_IS_POS_GPS_HAS : GpsTracksModels.STTS_IS_POS_GPS_NOT;
|
logDevice.is_pos_gps = Number(act.gps_data.positioning_gps) ? GpsTracksModels.STTS_IS_POS_GPS_HAS : GpsTracksModels.STTS_IS_POS_GPS_NOT;
|
||||||
|
|
||||||
logDevice.ignition = Number(act.stts_data.terminal_info.acc) ? GpsTracksModels.STTS_IGNITION_HIGH : GpsTracksModels.STTS_IGNITION_LOW;
|
logDevice.ignition = Number(act.stts_data.terminal_info.acc) ? GpsTracksModels.STTS_IGNITION_HIGH : GpsTracksModels.STTS_IGNITION_LOW;
|
||||||
logDevice.stts_gps = act.stts_data.terminal_info.gps_tracking ? GpsTracksModels.STTS_GPS_ON : GpsTracksModels.STTS_GPS_OFF; // 1=>on, 2=>off
|
logDevice.stts_gps = act.stts_data.terminal_info.gps_tracking ? GpsTracksModels.STTS_GPS_ON : GpsTracksModels.STTS_GPS_OFF;
|
||||||
logDevice.stts_gsm = Number(act.stts_data.gsm_signal_strength) + 1; // 1=>no signal, n>1=>get signal
|
logDevice.stts_gsm = Number(act.stts_data.gsm_signal_strength) + 1;
|
||||||
|
|
||||||
logDevice.stts_oil_electricity = Number(act.stts_data.terminal_info.oil_electricity) === 0 ? GpsTracksModels.STTS_OIL_ELECTRIC_ON : GpsTracksModels.STTS_OIL_ELECTRIC_OFF; // 1=>on, 2=>off
|
logDevice.stts_oil_electricity = Number(act.stts_data.terminal_info.oil_electricity) === 0 ? GpsTracksModels.STTS_OIL_ELECTRIC_ON : GpsTracksModels.STTS_OIL_ELECTRIC_OFF;
|
||||||
|
|
||||||
let stts_alarm = Number(act.stts_data.terminal_info.stts);
|
let stts_alarm = Number(act.stts_data.terminal_info.stts);
|
||||||
if (stts_alarm == 0) {
|
if (stts_alarm == 0) {
|
||||||
@ -422,9 +452,7 @@ net.createServer(
|
|||||||
if (typeof act.buffer_resp != "undefined") {
|
if (typeof act.buffer_resp != "undefined") {
|
||||||
c.write(act.buffer_resp);
|
c.write(act.buffer_resp);
|
||||||
}
|
}
|
||||||
}
|
} else {
|
||||||
// act.action_type == 'other'
|
|
||||||
else {
|
|
||||||
logDevice.action = act.action_type;
|
logDevice.action = act.action_type;
|
||||||
logDevice.device_id = act.device_id;
|
logDevice.device_id = act.device_id;
|
||||||
}
|
}
|
||||||
@ -435,7 +463,6 @@ net.createServer(
|
|||||||
c.on("end", () => {});
|
c.on("end", () => {});
|
||||||
c.on("close", () => {});
|
c.on("close", () => {});
|
||||||
|
|
||||||
// unused
|
|
||||||
c.on("drain", (a) => {
|
c.on("drain", (a) => {
|
||||||
console.log("client drain", a);
|
console.log("client drain", a);
|
||||||
});
|
});
|
||||||
@ -452,41 +479,27 @@ net.createServer(
|
|||||||
console.log("client timeout", a);
|
console.log("client timeout", a);
|
||||||
});
|
});
|
||||||
|
|
||||||
// not work for gps tracker
|
|
||||||
// https://stackoverflow.com/questions/17245881/how-do-i-debug-error-econnreset-in-node-js
|
|
||||||
// c.write("<?xml version=\"1.0\"?>\n");
|
|
||||||
// c.write("<!DOCTYPE cross-domain-policy SYSTEM \"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd\">\n");
|
|
||||||
// c.write("<cross-domain-policy>\n");
|
|
||||||
// c.write("<allow-access-from domain=\"*\" to-ports=\"*\"/>\n");
|
|
||||||
// c.write("</cross-domain-policy>\n");
|
|
||||||
// c.end();
|
|
||||||
|
|
||||||
c.pipe(c);
|
c.pipe(c);
|
||||||
}
|
}
|
||||||
).listen(process.env.PORT, () => {
|
).listen(process.env.PORT, () => {
|
||||||
console.log("Server gps tracker running at port " + process.env.PORT);
|
console.log("Server gps tracker running at port " + process.env.PORT);
|
||||||
});
|
});
|
||||||
// end for gps-tracking TCP ONLY
|
|
||||||
|
|
||||||
// start for normal http request
|
|
||||||
app.use(morgan("combined"));
|
app.use(morgan("combined"));
|
||||||
app.use(express.json({ limit: "10mb" })); // parsing application/json
|
app.use(express.json({ limit: "10mb" }));
|
||||||
app.use(express.urlencoded({ extended: true, limit: "10mb" })); // parsing application/x-www-form-urlencoded
|
app.use(express.urlencoded({ extended: true, limit: "10mb" }));
|
||||||
app.use(async function (req, res, next) {
|
app.use(async function (req, res, next) {
|
||||||
// set control allowed headers
|
|
||||||
res.header("Access-Control-Allow-Origin", "*");
|
res.header("Access-Control-Allow-Origin", "*");
|
||||||
res.header("Access-Control-Allow-Methods", "OPTIONS,GET,HEAD,PUT,PATCH,POST,DELETE");
|
res.header("Access-Control-Allow-Methods", "OPTIONS,GET,HEAD,PUT,PATCH,POST,DELETE");
|
||||||
res.header("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type, X-Requested-With, Range, x-api-key, x-forwarded-for");
|
res.header("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type, X-Requested-With, Range, x-api-key, x-forwarded-for");
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
// app.use(process.env.PATH_URL + '/bull/monitor', LibBullAdapter.getRouter());
|
|
||||||
routes.use(app);
|
routes.use(app);
|
||||||
app.listen(process.env.PORT_EXPRESS, () => {
|
app.listen(process.env.PORT_EXPRESS, () => {
|
||||||
console.log("Express server running at port " + process.env.PORT_EXPRESS);
|
console.log("Express server running at port " + process.env.PORT_EXPRESS);
|
||||||
});
|
});
|
||||||
// end for normal http request
|
|
||||||
|
|
||||||
// start for gps-tracking UDP ONLY
|
|
||||||
const udp = dgram.createSocket("udp4");
|
const udp = dgram.createSocket("udp4");
|
||||||
|
|
||||||
const devices1 = [];
|
const devices1 = [];
|
||||||
@ -567,4 +580,3 @@ udp.on("listening", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
udp.bind(process.env.PORT_UDP);
|
udp.bind(process.env.PORT_UDP);
|
||||||
// end for gps-tracking UDP ONLY
|
|
||||||
|
|||||||
570
app.js_BU20250626
Normal file
570
app.js_BU20250626
Normal file
@ -0,0 +1,570 @@
|
|||||||
|
require("dotenv").config({ path: ".env" });
|
||||||
|
require("events").EventEmitter.prototype._maxListeners = 30;
|
||||||
|
const morgan = require("morgan");
|
||||||
|
// start for gps-tracking
|
||||||
|
const net = require("net");
|
||||||
|
const dgram = require("dgram");
|
||||||
|
const crc = require("crc");
|
||||||
|
const moment = require("moment");
|
||||||
|
const LibDevice = require("./library/LibDevice");
|
||||||
|
const GpsTracksModels = require("./models/GpsTracksModels");
|
||||||
|
const ZoneModels = require("./models/ZoneModels");
|
||||||
|
const VhcModels = require("./models/VhcModels");
|
||||||
|
const LibMail = require("./library/LibMail");
|
||||||
|
const LibHelper = require("./library/LibHelper");
|
||||||
|
const nanoid = require("nanoid").nanoid;
|
||||||
|
// end for gps-tracking
|
||||||
|
|
||||||
|
// start for normal http request
|
||||||
|
const express = require("express");
|
||||||
|
// const LibBullAdapter = require('./library/LibBullAdapter');
|
||||||
|
const routes = require("./routes/routes");
|
||||||
|
// const routes = require('./routes/routes_without_scheduler');
|
||||||
|
const app = express();
|
||||||
|
// end for normal http request
|
||||||
|
|
||||||
|
// start for logging
|
||||||
|
const LibWinston = require("./library/LibWinston");
|
||||||
|
|
||||||
|
const logName = "libUdp";
|
||||||
|
const Logger = LibWinston.initialize(logName);
|
||||||
|
// end for logging
|
||||||
|
|
||||||
|
// start commit / log message from gps
|
||||||
|
async function commitMessage(now, logDevice) {
|
||||||
|
try {
|
||||||
|
// don't log
|
||||||
|
if (!logDevice.original_hex) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// in the future don't log to db if device_id not found in vhc
|
||||||
|
const vhc = await VhcModels.getVhcByDeviceId(logDevice.device_id);
|
||||||
|
const lastTrack = await GpsTracksModels.get2LastLocByDeviceId(logDevice.device_id);
|
||||||
|
|
||||||
|
if (["heartbeat", "alarm"].includes(logDevice.action)) {
|
||||||
|
// set engine stts moving,idling,stopped
|
||||||
|
if (logDevice.ignition == GpsTracksModels.STTS_IGNITION_HIGH) {
|
||||||
|
if (logDevice.speed) {
|
||||||
|
logDevice.stts_engine = GpsTracksModels.STTS_EN_MOVING;
|
||||||
|
} else {
|
||||||
|
if (lastTrack.length > 0) {
|
||||||
|
const checkLastHeartbeat = await GpsTracksModels.getLastHeartbeatToDeterminIdling(logDevice.device_id, lastTrack[0].crt, now);
|
||||||
|
if (checkLastHeartbeat.length >= 3) {
|
||||||
|
logDevice.stts_engine = GpsTracksModels.STTS_EN_IDLING;
|
||||||
|
} else {
|
||||||
|
logDevice.stts_engine = lastTrack[0].stts_engine;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
logDevice.stts_engine = GpsTracksModels.STTS_EN_STOPING;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// get last ignition, stts_engine, stts_alarm, stts_charge, stts_acc, stts_volt, stts_switch
|
||||||
|
if (["location"].includes(logDevice.action)) {
|
||||||
|
// get last ignition
|
||||||
|
const lastHeartbeatOrAlarm = await GpsTracksModels.get2LastHeartbeatOrAlarm(logDevice.device_id);
|
||||||
|
if (lastHeartbeatOrAlarm.length > 0) {
|
||||||
|
logDevice.ignition = lastHeartbeatOrAlarm[0].ignition;
|
||||||
|
logDevice.stts_gps = lastHeartbeatOrAlarm[0].stts_gps;
|
||||||
|
logDevice.stts_gsm = lastHeartbeatOrAlarm[0].stts_gsm;
|
||||||
|
} else {
|
||||||
|
logDevice.ignition = lastHeartbeatOrAlarm[0].ignition;
|
||||||
|
logDevice.stts_gps = lastHeartbeatOrAlarm[0].stts_gps;
|
||||||
|
logDevice.stts_gsm = lastHeartbeatOrAlarm[0].stts_gsm;
|
||||||
|
}
|
||||||
|
// set engine stts moving,idling,stopped
|
||||||
|
if (logDevice.ignition == GpsTracksModels.STTS_IGNITION_HIGH) {
|
||||||
|
if (logDevice.speed) {
|
||||||
|
logDevice.stts_engine = GpsTracksModels.STTS_EN_MOVING;
|
||||||
|
} else {
|
||||||
|
if (lastTrack.length > 0) {
|
||||||
|
const checkLastHeartbeat = await GpsTracksModels.getLastHeartbeatToDeterminIdling(logDevice.device_id, lastTrack[0].crt, now);
|
||||||
|
if (checkLastHeartbeat.length >= 3) {
|
||||||
|
logDevice.stts_engine = GpsTracksModels.STTS_EN_IDLING;
|
||||||
|
} else {
|
||||||
|
logDevice.stts_engine = lastTrack[0].stts_engine;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// get stts_alarm, stts_charge, stts_acc, stts_volt, stts_switch
|
||||||
|
} else {
|
||||||
|
logDevice.stts_engine = GpsTracksModels.STTS_EN_STOPING;
|
||||||
|
}
|
||||||
|
logDevice.stts_oil_electricity = lastHeartbeatOrAlarm[0].stts_oil_electricity;
|
||||||
|
logDevice.stts_alarm = lastHeartbeatOrAlarm[0].stts_alarm;
|
||||||
|
logDevice.stts_charge = lastHeartbeatOrAlarm[0].stts_charge;
|
||||||
|
logDevice.stts_acc = lastHeartbeatOrAlarm[0].stts_acc;
|
||||||
|
logDevice.stts_volt = lastHeartbeatOrAlarm[0].stts_volt;
|
||||||
|
logDevice.stts_switch = lastHeartbeatOrAlarm[0].stts_switch;
|
||||||
|
}
|
||||||
|
|
||||||
|
// sekarang heartbeat diinject data lokasi juga dari lokasi terakhir
|
||||||
|
if (["heartbeat"].includes(logDevice.action)) {
|
||||||
|
if (lastTrack.length > 0) {
|
||||||
|
logDevice.latitude = lastTrack[0].latitude;
|
||||||
|
logDevice.longitude = lastTrack[0].longitude;
|
||||||
|
logDevice.speed = lastTrack[0].speed;
|
||||||
|
logDevice.orientation = lastTrack[0].orientation;
|
||||||
|
if (logDevice.latitude) {
|
||||||
|
logDevice.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_NOT;
|
||||||
|
}
|
||||||
|
|
||||||
|
logDevice.length_gps = lastTrack[0].length_gps;
|
||||||
|
logDevice.pos_stlt_gps = lastTrack[0].pos_stlt_gps;
|
||||||
|
logDevice.pos_type_gps = lastTrack[0].pos_type_gps;
|
||||||
|
logDevice.is_pos_gps = lastTrack[0].is_pos_gps;
|
||||||
|
|
||||||
|
// jika gapengen dimunculin di last movement
|
||||||
|
// logDevice.crt = lastTrack[0].crt;
|
||||||
|
// logDevice.crt_format = lastTrack[0].crt_format;
|
||||||
|
// logDevice.crt_d = lastTrack[0].crt_d;
|
||||||
|
// logDevice.crt_d_format = lastTrack[0].crt_d_format;
|
||||||
|
// jika pengen di munculin di last movement
|
||||||
|
logDevice.crt = now;
|
||||||
|
logDevice.crt_format = moment.unix(now).format("YYYY-MM-DD HH:mm:ss");
|
||||||
|
logDevice.crt_d = now;
|
||||||
|
logDevice.crt_d_format = moment.unix(now).format("YYYY-MM-DD HH:mm:ss");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// count milleage
|
||||||
|
if (logDevice.latitude != null && logDevice.longitude != null && lastTrack.length > 0) {
|
||||||
|
const distance = LibHelper.haversineGreatCircleDistance(lastTrack[0].latitude, lastTrack[0].longitude, logDevice.latitude, logDevice.longitude, LibHelper.EARTH_RADIUS_KM);
|
||||||
|
const distance_km = LibHelper.kmToKm(distance, 100000000);
|
||||||
|
// console.log(`GPS TRACKER UP LOCATION => device_id:${logDevice.device_id} vhc_id:${(vhc[0]) ? vhc[0].vid : 0}, distance_km:${distance_km}`);
|
||||||
|
// validasi jika lebih dari 3km, ga disimpan
|
||||||
|
if (distance_km >= 3) {
|
||||||
|
GpsTracksModels.bundleCreate2(logDevice, logDevice); // jika tidak disimpan malah jadi bug, jadi akan update lokasi terus dengan kalkulasi jarak sebelumnya jadi makan lama makin lebar, mending disimpen terus milleagenya jadi 0 aja
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
logDevice.pre_milleage = distance_km;
|
||||||
|
logDevice.sum_milleage = (lastTrack[0].sum_milleage + logDevice.pre_milleage).toFixed(8);
|
||||||
|
if (vhc.length > 0) {
|
||||||
|
logDevice.vhc_id = vhc[0] ? vhc[0].vid : 0;
|
||||||
|
if (lastTrack[0].vhc_id == logDevice.vhc_id) {
|
||||||
|
logDevice.vhc_milleage = (lastTrack[0].vhc_milleage + logDevice.pre_milleage).toFixed(8);
|
||||||
|
} else {
|
||||||
|
logDevice.vhc_milleage = (vhc[0] ? vhc[0].sum_milleage : 0 + logDevice.pre_milleage).toFixed(8);
|
||||||
|
}
|
||||||
|
VhcModels.update(vhc[0] ? vhc[0].vid : 0, { sum_milleage: logDevice.vhc_milleage });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// truck zoning spawn
|
||||||
|
if (logDevice.latitude != null && logDevice.longitude != null) {
|
||||||
|
// && vhc.length > 0
|
||||||
|
// log tracking
|
||||||
|
const currTrack = await GpsTracksModels.bundleCreate2(logDevice, logDevice);
|
||||||
|
// console.log('GT06 HAS LOCATION AND CHECK ZONE');
|
||||||
|
const inCircle = await ZoneModels.getInCircle(logDevice.latitude, logDevice.longitude);
|
||||||
|
const inShape = await ZoneModels.getInShape(logDevice.latitude, logDevice.longitude);
|
||||||
|
const insideSpawnZone = [];
|
||||||
|
for (let zone of inCircle) {
|
||||||
|
insideSpawnZone.push(zone);
|
||||||
|
}
|
||||||
|
for (let zone of inShape) {
|
||||||
|
insideSpawnZone.push(zone);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* get lastSpawn desc index 0, where leave_at = 0
|
||||||
|
* kalo gaada create, dengan isi field enter_at aja, kalo ada didalam zona
|
||||||
|
* kalo ada update, dengan isi field leave_at aja, kalo udah diluar zona
|
||||||
|
*/
|
||||||
|
const lastSpawn = await GpsTracksModels.listSpawnZone({
|
||||||
|
source: GpsTracksModels.SOURCE_GPS_TRACKER,
|
||||||
|
device_id: logDevice.device_id,
|
||||||
|
vhc_id: vhc[0] ? vhc[0].vid : 0,
|
||||||
|
leave_at_d: 0,
|
||||||
|
order_by: "ORDER BY id DESC",
|
||||||
|
limit: 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (lastSpawn.length > 0) {
|
||||||
|
let is_leave_zone = 1;
|
||||||
|
for (const insideZone of insideSpawnZone) {
|
||||||
|
if (insideZone.zid === lastSpawn[0].zone_id) is_leave_zone = 0;
|
||||||
|
}
|
||||||
|
if (is_leave_zone === 1 && lastSpawn[0].device_id == logDevice.device_id) {
|
||||||
|
GpsTracksModels.updt2SpawnZone(
|
||||||
|
{
|
||||||
|
leave_lat: logDevice.latitude,
|
||||||
|
leave_lng: logDevice.longitude,
|
||||||
|
leave_at_d: logDevice.crt_d || now,
|
||||||
|
leave_at_d_format: moment.unix(logDevice.crt_d || now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
leave_at_s: now,
|
||||||
|
leave_at_s_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
updt: now,
|
||||||
|
updt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
},
|
||||||
|
lastSpawn[0].id
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (let zone of insideSpawnZone) {
|
||||||
|
let mailData = {
|
||||||
|
pic_name: zone.pic_name,
|
||||||
|
pic_mail: zone.pic_mail,
|
||||||
|
z_name: zone.name,
|
||||||
|
z_type_name: zone.type_name,
|
||||||
|
z_workflow_name: zone.workflow_type_name,
|
||||||
|
shiptocode: zone.shiptocode,
|
||||||
|
z_fulladdress: zone.fulladdress,
|
||||||
|
v_nopol: (vhc[0] ? vhc[0].nopol1 : 0 || "") + (vhc[0] ? vhc[0].nopol2 : 0 || "") + (vhc[0] ? vhc[0].nopol3 : 0 || ""),
|
||||||
|
da_name: vhc[0] ? vhc[0].da_name : 0 || "",
|
||||||
|
da_phone: "+" + (vhc[0] ? vhc[0].da_phone_code : 0 || "") + (vhc[0] ? vhc[0].da_phone : 0 || ""),
|
||||||
|
};
|
||||||
|
// LibMail.sendVhcSpawnZoneMail(`${(vhc[0]) ? vhc[0].nopol1 : 0 || ''}${(vhc[0]) ? vhc[0].nopol2 : 0 || ''}${(vhc[0]) ? vhc[0].nopol3 : 0 || ''} entering zone ${mailData.z_name}`, mailData.pic_mail, mailData);
|
||||||
|
|
||||||
|
if (logDevice.device_id === "0865784052395871") console.log(1234567890);
|
||||||
|
GpsTracksModels.create2SpawnZone({
|
||||||
|
device_id: logDevice.device_id,
|
||||||
|
master_id: Number(currTrack.result.insertId),
|
||||||
|
enter_lat: logDevice.latitude,
|
||||||
|
enter_lng: logDevice.longitude,
|
||||||
|
enter_at_d: logDevice.crt_d || now,
|
||||||
|
enter_at_d_format: moment.unix(logDevice.crt_d || now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
enter_at_s: now,
|
||||||
|
enter_at_s_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
zone_id: zone.zid,
|
||||||
|
zone_name: zone.name,
|
||||||
|
vhc_id: vhc[0] ? vhc[0].vid : 0,
|
||||||
|
source: GpsTracksModels.SOURCE_GPS_TRACKER,
|
||||||
|
crt: now,
|
||||||
|
crt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
});
|
||||||
|
if (logDevice.device_id === "0865784052395871") console.log("DISINI");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// log tracking
|
||||||
|
GpsTracksModels.bundleCreate2(logDevice, logDevice);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// end commit / log message from gps
|
||||||
|
|
||||||
|
// start for gps-tracking TCP ONLY
|
||||||
|
const devices = [];
|
||||||
|
const netConn = require("./config/netConn");
|
||||||
|
/**
|
||||||
|
* uniquely identify a socket with Node.js
|
||||||
|
* https://stackoverflow.com/questions/6805432/how-to-uniquely-identify-a-socket-with-node-js
|
||||||
|
*/
|
||||||
|
net.createServer(
|
||||||
|
{
|
||||||
|
allowHalfOpen: true,
|
||||||
|
},
|
||||||
|
function (c) {
|
||||||
|
// c mean connection
|
||||||
|
|
||||||
|
// save connections
|
||||||
|
c.id = nanoid();
|
||||||
|
|
||||||
|
c.pipe(c);
|
||||||
|
|
||||||
|
c.on("data", async (buffer_req) => {
|
||||||
|
const now = moment().unix();
|
||||||
|
const me = LibDevice.identifyProtocolFromBuffer(buffer_req);
|
||||||
|
// console.log('app ', buffer_req);
|
||||||
|
|
||||||
|
const logDevice = {
|
||||||
|
original_hex: me.ori_string,
|
||||||
|
protocol: me.protocol_name == "unknown" ? null : me.protocol_name,
|
||||||
|
action: null,
|
||||||
|
device_id: null,
|
||||||
|
latitude: null,
|
||||||
|
longitude: null,
|
||||||
|
speed: null,
|
||||||
|
orientation: 0,
|
||||||
|
ignition: 0,
|
||||||
|
stts_engine: 0,
|
||||||
|
stts_gps: 0,
|
||||||
|
length_gps: 0,
|
||||||
|
pos_stlt_gps: 0,
|
||||||
|
pos_type_gps: 0,
|
||||||
|
is_pos_gps: 0,
|
||||||
|
stts_gsm: 0,
|
||||||
|
stts_oil_electricity: 0,
|
||||||
|
stts_alarm: 0,
|
||||||
|
stts_charge: 0,
|
||||||
|
stts_acc: 0,
|
||||||
|
stts_volt: 0,
|
||||||
|
stts_switch: 0,
|
||||||
|
stts_reverse_geo: 0,
|
||||||
|
pre_milleage: 0,
|
||||||
|
source: GpsTracksModels.SOURCE_GPS_TRACKER,
|
||||||
|
vhc_id: 0,
|
||||||
|
drv_id: 0,
|
||||||
|
crt: now,
|
||||||
|
crt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
crt_d: 0,
|
||||||
|
crt_d_format: null,
|
||||||
|
crt_s: now,
|
||||||
|
crt_s_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
};
|
||||||
|
|
||||||
|
if (me.protocol_name == "gt06") {
|
||||||
|
// const act = LibDevice.gt06Action(me, device.device_id || null);
|
||||||
|
let dvc_id = devices[c.id];
|
||||||
|
const act = LibDevice.gt06Action(me, dvc_id || null);
|
||||||
|
|
||||||
|
if (act.action_type == "login") {
|
||||||
|
logDevice.action = act.action_type;
|
||||||
|
logDevice.device_id = act.device_id;
|
||||||
|
|
||||||
|
devices[c.id] = act.device_id;
|
||||||
|
netConn[act.device_id] = c;
|
||||||
|
if (typeof act.buffer_resp != "undefined") {
|
||||||
|
c.write(act.buffer_resp);
|
||||||
|
}
|
||||||
|
} else if (act.action_type == "location") {
|
||||||
|
logDevice.action = act.action_type;
|
||||||
|
logDevice.device_id = act.device_id;
|
||||||
|
|
||||||
|
logDevice.latitude = act.gps_data.latitude || null;
|
||||||
|
logDevice.longitude = act.gps_data.longitude || null;
|
||||||
|
logDevice.speed = act.gps_data.speed;
|
||||||
|
logDevice.orientation = act.gps_data.orientation;
|
||||||
|
if (logDevice.latitude) {
|
||||||
|
logDevice.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_NOT;
|
||||||
|
}
|
||||||
|
|
||||||
|
logDevice.length_gps = act.gps_data.quantity_pos_satellites_c;
|
||||||
|
logDevice.pos_stlt_gps = act.gps_data.quantity_pos_satellites_b;
|
||||||
|
logDevice.pos_type_gps = Number(act.gps_data.realtime_dif_gps) === 0 ? GpsTracksModels.STTS_POS_TYPE_GPS_RLTM : GpsTracksModels.STTS_POS_TYPE_GPS_DIFF;
|
||||||
|
logDevice.is_pos_gps = Number(act.gps_data.positioning_gps) ? GpsTracksModels.STTS_IS_POS_GPS_HAS : GpsTracksModels.STTS_IS_POS_GPS_NOT;
|
||||||
|
|
||||||
|
logDevice.crt = moment(act.gps_data.date).unix();
|
||||||
|
logDevice.crt_format = moment(act.gps_data.date).format("YYYY-MM-DD HH:mm:ss");
|
||||||
|
logDevice.crt_d = moment(act.gps_data.date).unix();
|
||||||
|
logDevice.crt_d_format = moment(act.gps_data.date).format("YYYY-MM-DD HH:mm:ss");
|
||||||
|
} else if (act.action_type == "heartbeat") {
|
||||||
|
logDevice.action = act.action_type;
|
||||||
|
logDevice.device_id = act.device_id;
|
||||||
|
|
||||||
|
logDevice.ignition = Number(act.stts_data.terminal_info.acc) ? GpsTracksModels.STTS_IGNITION_HIGH : GpsTracksModels.STTS_IGNITION_LOW;
|
||||||
|
logDevice.stts_gps = act.stts_data.terminal_info.gps_tracking ? GpsTracksModels.STTS_GPS_ON : GpsTracksModels.STTS_GPS_OFF; // 1=>on, 2=>off
|
||||||
|
logDevice.stts_gsm = Number(act.stts_data.gsm_signal_strength) + 1; // 1=>no signal, n>1=>get signal
|
||||||
|
|
||||||
|
logDevice.stts_oil_electricity = Number(act.stts_data.terminal_info.oil_electricity) === 0 ? GpsTracksModels.STTS_OIL_ELECTRIC_ON : GpsTracksModels.STTS_OIL_ELECTRIC_OFF; // 1=>on, 2=>off
|
||||||
|
|
||||||
|
let stts_alarm = Number(act.stts_data.terminal_info.stts);
|
||||||
|
if (stts_alarm == 0) {
|
||||||
|
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_NORMAL;
|
||||||
|
} else if (stts_alarm == 1) {
|
||||||
|
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_SHOCK;
|
||||||
|
} else if (stts_alarm == 2) {
|
||||||
|
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_POWER_CUT;
|
||||||
|
} else if (stts_alarm == 3) {
|
||||||
|
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_LOW_BATTERY;
|
||||||
|
} else if (stts_alarm == 4) {
|
||||||
|
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_SOS;
|
||||||
|
}
|
||||||
|
|
||||||
|
logDevice.stts_charge = Number(act.stts_data.terminal_info.charge) ? GpsTracksModels.STTS_CHARGE_ON : GpsTracksModels.STTS_CHARGE_OFF;
|
||||||
|
logDevice.stts_acc = Number(act.stts_data.terminal_info.acc) ? GpsTracksModels.STTS_ACC_HIGH : GpsTracksModels.STTS_ACC_LOW;
|
||||||
|
logDevice.stts_switch = Number(act.stts_data.terminal_info.is_active) ? GpsTracksModels.STTS_SWITCH_ON : GpsTracksModels.STTS_SWITCH_OFF;
|
||||||
|
logDevice.stts_volt = Number(act.stts_data.voltage_level) + 1;
|
||||||
|
|
||||||
|
if (typeof act.buffer_resp != "undefined") {
|
||||||
|
c.write(act.buffer_resp);
|
||||||
|
}
|
||||||
|
} else if (act.action_type == "alarm") {
|
||||||
|
logDevice.action = act.action_type;
|
||||||
|
logDevice.device_id = act.device_id;
|
||||||
|
|
||||||
|
logDevice.latitude = act.gps_data.latitude || null;
|
||||||
|
logDevice.longitude = act.gps_data.longitude || null;
|
||||||
|
logDevice.speed = act.gps_data.speed;
|
||||||
|
logDevice.orientation = act.gps_data.orientation;
|
||||||
|
if (logDevice.latitude) {
|
||||||
|
logDevice.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_NOT;
|
||||||
|
}
|
||||||
|
|
||||||
|
logDevice.length_gps = act.gps_data.quantity_pos_satellites_c;
|
||||||
|
logDevice.pos_stlt_gps = act.gps_data.quantity_pos_satellites_b;
|
||||||
|
logDevice.pos_type_gps = Number(act.gps_data.realtime_dif_gps) === 0 ? GpsTracksModels.STTS_POS_TYPE_GPS_RLTM : GpsTracksModels.STTS_POS_TYPE_GPS_DIFF;
|
||||||
|
logDevice.is_pos_gps = Number(act.gps_data.positioning_gps) ? GpsTracksModels.STTS_IS_POS_GPS_HAS : GpsTracksModels.STTS_IS_POS_GPS_NOT;
|
||||||
|
|
||||||
|
logDevice.ignition = Number(act.stts_data.terminal_info.acc) ? GpsTracksModels.STTS_IGNITION_HIGH : GpsTracksModels.STTS_IGNITION_LOW;
|
||||||
|
logDevice.stts_gps = act.stts_data.terminal_info.gps_tracking ? GpsTracksModels.STTS_GPS_ON : GpsTracksModels.STTS_GPS_OFF; // 1=>on, 2=>off
|
||||||
|
logDevice.stts_gsm = Number(act.stts_data.gsm_signal_strength) + 1; // 1=>no signal, n>1=>get signal
|
||||||
|
|
||||||
|
logDevice.stts_oil_electricity = Number(act.stts_data.terminal_info.oil_electricity) === 0 ? GpsTracksModels.STTS_OIL_ELECTRIC_ON : GpsTracksModels.STTS_OIL_ELECTRIC_OFF; // 1=>on, 2=>off
|
||||||
|
|
||||||
|
let stts_alarm = Number(act.stts_data.terminal_info.stts);
|
||||||
|
if (stts_alarm == 0) {
|
||||||
|
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_NORMAL;
|
||||||
|
} else if (stts_alarm == 1) {
|
||||||
|
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_SHOCK;
|
||||||
|
} else if (stts_alarm == 2) {
|
||||||
|
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_POWER_CUT;
|
||||||
|
} else if (stts_alarm == 3) {
|
||||||
|
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_LOW_BATTERY;
|
||||||
|
} else if (stts_alarm == 4) {
|
||||||
|
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_SOS;
|
||||||
|
}
|
||||||
|
|
||||||
|
logDevice.stts_charge = Number(act.stts_data.terminal_info.charge) ? GpsTracksModels.STTS_CHARGE_ON : GpsTracksModels.STTS_CHARGE_OFF;
|
||||||
|
logDevice.stts_acc = Number(act.stts_data.terminal_info.acc) ? GpsTracksModels.STTS_ACC_HIGH : GpsTracksModels.STTS_ACC_LOW;
|
||||||
|
logDevice.stts_switch = Number(act.stts_data.terminal_info.is_active) ? GpsTracksModels.STTS_SWITCH_ON : GpsTracksModels.STTS_SWITCH_OFF;
|
||||||
|
logDevice.stts_volt = Number(act.stts_data.voltage_level) + 1;
|
||||||
|
|
||||||
|
logDevice.crt = moment(act.gps_data.date).unix();
|
||||||
|
logDevice.crt_format = moment(act.gps_data.date).format("YYYY-MM-DD HH:mm:ss");
|
||||||
|
logDevice.crt_d = moment(act.gps_data.date).unix();
|
||||||
|
logDevice.crt_d_format = moment(act.gps_data.date).format("YYYY-MM-DD HH:mm:ss");
|
||||||
|
|
||||||
|
if (typeof act.buffer_resp != "undefined") {
|
||||||
|
c.write(act.buffer_resp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// act.action_type == 'other'
|
||||||
|
else {
|
||||||
|
logDevice.action = act.action_type;
|
||||||
|
logDevice.device_id = act.device_id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
commitMessage(now, logDevice);
|
||||||
|
});
|
||||||
|
c.on("end", () => {});
|
||||||
|
c.on("close", () => {});
|
||||||
|
|
||||||
|
// unused
|
||||||
|
c.on("drain", (a) => {
|
||||||
|
console.log("client drain", a);
|
||||||
|
});
|
||||||
|
c.on("error", (a) => {
|
||||||
|
console.error("client error", a);
|
||||||
|
});
|
||||||
|
c.on("lookup", (a) => {
|
||||||
|
console.log("client lookup", a);
|
||||||
|
});
|
||||||
|
c.on("ready", (a) => {
|
||||||
|
console.log("client ready", a);
|
||||||
|
});
|
||||||
|
c.on("timeout", (a) => {
|
||||||
|
console.log("client timeout", a);
|
||||||
|
});
|
||||||
|
|
||||||
|
// not work for gps tracker
|
||||||
|
// https://stackoverflow.com/questions/17245881/how-do-i-debug-error-econnreset-in-node-js
|
||||||
|
// c.write("<?xml version=\"1.0\"?>\n");
|
||||||
|
// c.write("<!DOCTYPE cross-domain-policy SYSTEM \"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd\">\n");
|
||||||
|
// c.write("<cross-domain-policy>\n");
|
||||||
|
// c.write("<allow-access-from domain=\"*\" to-ports=\"*\"/>\n");
|
||||||
|
// c.write("</cross-domain-policy>\n");
|
||||||
|
// c.end();
|
||||||
|
|
||||||
|
c.pipe(c);
|
||||||
|
}
|
||||||
|
).listen(process.env.PORT, () => {
|
||||||
|
console.log("Server gps tracker running at port " + process.env.PORT);
|
||||||
|
});
|
||||||
|
// end for gps-tracking TCP ONLY
|
||||||
|
|
||||||
|
// start for normal http request
|
||||||
|
app.use(morgan("combined"));
|
||||||
|
app.use(express.json({ limit: "10mb" })); // parsing application/json
|
||||||
|
app.use(express.urlencoded({ extended: true, limit: "10mb" })); // parsing application/x-www-form-urlencoded
|
||||||
|
app.use(async function (req, res, next) {
|
||||||
|
// set control allowed headers
|
||||||
|
res.header("Access-Control-Allow-Origin", "*");
|
||||||
|
res.header("Access-Control-Allow-Methods", "OPTIONS,GET,HEAD,PUT,PATCH,POST,DELETE");
|
||||||
|
res.header("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type, X-Requested-With, Range, x-api-key, x-forwarded-for");
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
// app.use(process.env.PATH_URL + '/bull/monitor', LibBullAdapter.getRouter());
|
||||||
|
routes.use(app);
|
||||||
|
app.listen(process.env.PORT_EXPRESS, () => {
|
||||||
|
console.log("Express server running at port " + process.env.PORT_EXPRESS);
|
||||||
|
});
|
||||||
|
// end for normal http request
|
||||||
|
|
||||||
|
// start for gps-tracking UDP ONLY
|
||||||
|
const udp = dgram.createSocket("udp4");
|
||||||
|
|
||||||
|
const devices1 = [];
|
||||||
|
udp.on("message", (msg, rinfo) => {
|
||||||
|
const buffer_req = Buffer.from(msg, "utf8");
|
||||||
|
console.log("20203", buffer_req);
|
||||||
|
console.log("20203", rinfo);
|
||||||
|
Logger.log("info", buffer_req.toString("hex"));
|
||||||
|
|
||||||
|
const now = moment().unix();
|
||||||
|
const me = LibDevice.identifyProtocolFromBuffer(buffer_req, { isEelinkCustom: 1 });
|
||||||
|
console.log("port 20203 ", me);
|
||||||
|
|
||||||
|
const logDevice = {
|
||||||
|
original_hex: me.ori_buffer,
|
||||||
|
protocol: me.protocol_name == "unknown" ? null : me.protocol_name,
|
||||||
|
action: null,
|
||||||
|
device_id: null,
|
||||||
|
latitude: null,
|
||||||
|
longitude: null,
|
||||||
|
speed: null,
|
||||||
|
orientation: 0,
|
||||||
|
ignition: 0,
|
||||||
|
stts_engine: 0,
|
||||||
|
stts_gps: 0,
|
||||||
|
length_gps: 0,
|
||||||
|
pos_stlt_gps: 0,
|
||||||
|
pos_type_gps: 0,
|
||||||
|
is_pos_gps: 0,
|
||||||
|
stts_gsm: 0,
|
||||||
|
stts_oil_electricity: 0,
|
||||||
|
stts_alarm: 0,
|
||||||
|
stts_charge: 0,
|
||||||
|
stts_acc: 0,
|
||||||
|
stts_volt: 0,
|
||||||
|
stts_switch: 0,
|
||||||
|
stts_reverse_geo: 0,
|
||||||
|
pre_milleage: 0,
|
||||||
|
source: GpsTracksModels.SOURCE_GPS_TRACKER,
|
||||||
|
crt: now,
|
||||||
|
crt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
crt_d: 0,
|
||||||
|
crt_d_format: null,
|
||||||
|
crt_s: now,
|
||||||
|
crt_s_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
};
|
||||||
|
|
||||||
|
if (me.protocol_name === "eelinkCustom") {
|
||||||
|
let dvc_id = devices1[`${rinfo.address}:${rinfo.port}`];
|
||||||
|
const act = LibDevice.eelinkCustomAction(me, dvc_id || null);
|
||||||
|
console.log("act 20203", act);
|
||||||
|
|
||||||
|
if (act.action_type == "exist_data") {
|
||||||
|
logDevice.action = act.action_type;
|
||||||
|
logDevice.device_id = act.device_id;
|
||||||
|
|
||||||
|
devices1[`${rinfo.address}:${rinfo.port}`] = act.device_id;
|
||||||
|
if (typeof act.buffer_resp != "undefined") {
|
||||||
|
udp.send(act.buffer_resp, 0, act.buffer_resp.length, rinfo.port, rinfo.address, function (err, bytes) {
|
||||||
|
if (err) throw err;
|
||||||
|
console.log("UDP message sent to " + rinfo.address + ":" + rinfo.port);
|
||||||
|
console.log("20203", bytes);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
udp.on("error", (err) => {
|
||||||
|
console.log(`udp error:\n${err.stack}`);
|
||||||
|
udp.close();
|
||||||
|
});
|
||||||
|
udp.on("close", function () {
|
||||||
|
console.log("udp socket is closed !");
|
||||||
|
});
|
||||||
|
udp.on("listening", () => {
|
||||||
|
const address = udp.address();
|
||||||
|
console.log(`udp listening ${address.address}:${address.port}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
udp.bind(process.env.PORT_UDP);
|
||||||
|
// end for gps-tracking UDP ONLY
|
||||||
74
config/dbConnCron.js
Normal file
74
config/dbConnCron.js
Normal file
@ -0,0 +1,74 @@
|
|||||||
|
const mysql = require("mysql2")
|
||||||
|
const pool = mysql.createPool({
|
||||||
|
host: process.env.DBHOST,
|
||||||
|
port: process.env.DBPORT,
|
||||||
|
user: process.env.DBUSER,
|
||||||
|
password: process.env.DBPASSWORD,
|
||||||
|
database: process.env.DATABASE,
|
||||||
|
connectionLimit: 100,
|
||||||
|
multipleStatements: true,
|
||||||
|
// waitForConnections: true,
|
||||||
|
maxIdle: 10, // max idle connections, the default value is the same as `connectionLimit`
|
||||||
|
idleTimeout: 60000, // idle connections timeout, in milliseconds, the default value 60000
|
||||||
|
queueLimit: 50,
|
||||||
|
// enableKeepAlive: true,
|
||||||
|
// keepAliveInitialDelay: 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
const connection = () => {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
pool.getConnection((err, connection) => {
|
||||||
|
if (err) {
|
||||||
|
// Log the error and reject the promise
|
||||||
|
console.error("Error getting connection from pool:", err)
|
||||||
|
return reject(err)
|
||||||
|
}
|
||||||
|
const query = (sql, binding) => {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
connection.query(sql, binding, (err, result) => {
|
||||||
|
if (err) {
|
||||||
|
// Log the query error for debugging
|
||||||
|
console.error("Error executing query:", err, { sql, binding })
|
||||||
|
return reject(err)
|
||||||
|
}
|
||||||
|
resolve(result)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const release = () => {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
if (err) {
|
||||||
|
// Log error in release method if exists
|
||||||
|
console.error("Error during connection release:", err)
|
||||||
|
return reject(err)
|
||||||
|
}
|
||||||
|
resolve(connection.release())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
resolve({
|
||||||
|
query,
|
||||||
|
release,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const query = (sql, binding) => {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
pool.query(sql, binding, (err, result, fields) => {
|
||||||
|
if (err) {
|
||||||
|
// Log the error for debugging
|
||||||
|
console.error("Error executing pooled query:", err, { sql, binding })
|
||||||
|
return reject(err)
|
||||||
|
}
|
||||||
|
resolve(result)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
module.exports = {
|
||||||
|
pool,
|
||||||
|
connection,
|
||||||
|
query,
|
||||||
|
}
|
||||||
@ -2,13 +2,16 @@ require("dotenv").config({ path: require("path").resolve(__dirname, "../.env") }
|
|||||||
|
|
||||||
const mysql = require("mysql");
|
const mysql = require("mysql");
|
||||||
const pool = mysql.createPool({
|
const pool = mysql.createPool({
|
||||||
connectionLimit: process.env.CONNECTIONLIMIT,
|
// connectionLimit: process.env.CONNECTIONLIMIT,
|
||||||
host: process.env.DBHOST,
|
host: process.env.DBHOST,
|
||||||
port: process.env.DBPORT,
|
port: process.env.DBPORT,
|
||||||
user: process.env.DBUSER,
|
user: process.env.DBUSER,
|
||||||
password: process.env.DBPASSWORD,
|
password: process.env.DBPASSWORD,
|
||||||
database: process.env.DATABASE,
|
database: process.env.DATABASE,
|
||||||
acquireTimeout: Number(process.env.ACQRTIMEOUT), // in ms
|
connectionLimit: 10,
|
||||||
|
connectTimeout: 20000,
|
||||||
|
acquireTimeout: 20000,
|
||||||
|
// acquireTimeout: Number(process.env.ACQRTIMEOUT), // in ms
|
||||||
});
|
});
|
||||||
|
|
||||||
pool.getConnection((err, conn) => {
|
pool.getConnection((err, conn) => {
|
||||||
|
|||||||
@ -11,22 +11,19 @@ const VhcModels = require("../models/VhcModels");
|
|||||||
const ZoneModels = require("../models/ZoneModels");
|
const ZoneModels = require("../models/ZoneModels");
|
||||||
const LibHelper = require("../library/LibHelper");
|
const LibHelper = require("../library/LibHelper");
|
||||||
|
|
||||||
// const LibQueueBlastOrder = require('../library/LibQueueBlastOrder');
|
|
||||||
Validator.useLang("en");
|
Validator.useLang("en");
|
||||||
|
|
||||||
const devices = [];
|
const devices = [];
|
||||||
|
|
||||||
async function commitMessage(now, logDevice) {
|
async function commitMessage(now, logDevice) {
|
||||||
try {
|
try {
|
||||||
// don't log
|
|
||||||
if (!logDevice.original_hex) {
|
if (!logDevice.original_hex) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
// in the future don't log to db if device_id not found in vhc
|
|
||||||
const vhc = await VhcModels.getVhcByDeviceId(logDevice.device_id);
|
const vhc = await VhcModels.getVhcByDeviceId(logDevice.device_id);
|
||||||
const lastTrack = await GpsTracksModels.get2LastLocByDeviceId(logDevice.device_id);
|
const lastTrack = await GpsTracksModels.get2LastLocByDeviceId(logDevice.device_id);
|
||||||
if (["heartbeat", "alarm"].includes(logDevice.action)) {
|
if (["heartbeat", "alarm"].includes(logDevice.action)) {
|
||||||
// set engine stts moving,idling,stopped
|
|
||||||
if (logDevice.ignition == GpsTracksModels.STTS_IGNITION_HIGH) {
|
if (logDevice.ignition == GpsTracksModels.STTS_IGNITION_HIGH) {
|
||||||
if (logDevice.speed) {
|
if (logDevice.speed) {
|
||||||
logDevice.stts_engine = GpsTracksModels.STTS_EN_MOVING;
|
logDevice.stts_engine = GpsTracksModels.STTS_EN_MOVING;
|
||||||
@ -44,19 +41,31 @@ async function commitMessage(now, logDevice) {
|
|||||||
logDevice.stts_engine = GpsTracksModels.STTS_EN_STOPING;
|
logDevice.stts_engine = GpsTracksModels.STTS_EN_STOPING;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// get last ignition, stts_engine, stts_alarm, stts_charge, stts_acc, stts_volt, stts_switch
|
|
||||||
if (["location"].includes(logDevice.action)) {
|
if (["location"].includes(logDevice.action)) {
|
||||||
console.log("logDevice:", logDevice);
|
console.log("logDevice:", logDevice);
|
||||||
// get last ignition
|
|
||||||
const lastHeartbeatOrAlarm = await GpsTracksModels.get2LastHeartbeatOrAlarm(logDevice.device_id);
|
const lastHeartbeatOrAlarm = await GpsTracksModels.get2LastHeartbeatOrAlarm(logDevice.device_id);
|
||||||
if (lastHeartbeatOrAlarm.length > 0) {
|
if (lastHeartbeatOrAlarm.length > 0) {
|
||||||
logDevice.ignition = lastHeartbeatOrAlarm[0].ignition;
|
logDevice.ignition = lastHeartbeatOrAlarm[0].ignition;
|
||||||
logDevice.stts_gps = lastHeartbeatOrAlarm[0].stts_gps;
|
logDevice.stts_gps = lastHeartbeatOrAlarm[0].stts_gps;
|
||||||
logDevice.stts_gsm = lastHeartbeatOrAlarm[0].stts_gsm;
|
logDevice.stts_gsm = lastHeartbeatOrAlarm[0].stts_gsm;
|
||||||
|
logDevice.stts_oil_electricity = lastHeartbeatOrAlarm[0].stts_oil_electricity;
|
||||||
|
logDevice.stts_alarm = lastHeartbeatOrAlarm[0].stts_alarm;
|
||||||
|
logDevice.stts_charge = lastHeartbeatOrAlarm[0].stts_charge;
|
||||||
|
logDevice.stts_acc = lastHeartbeatOrAlarm[0].stts_acc;
|
||||||
|
logDevice.stts_volt = lastHeartbeatOrAlarm[0].stts_volt;
|
||||||
|
logDevice.stts_switch = lastHeartbeatOrAlarm[0].stts_switch;
|
||||||
} else {
|
} else {
|
||||||
logDevice.ignition = lastHeartbeatOrAlarm[0].ignition;
|
logDevice.ignition = null;
|
||||||
logDevice.stts_gps = lastHeartbeatOrAlarm[0].stts_gps;
|
logDevice.stts_gps = null;
|
||||||
logDevice.stts_gsm = lastHeartbeatOrAlarm[0].stts_gsm;
|
logDevice.stts_gsm = null;
|
||||||
|
logDevice.stts_oil_electricity = null;
|
||||||
|
logDevice.stts_alarm = null;
|
||||||
|
logDevice.stts_charge = null;
|
||||||
|
logDevice.stts_acc = null;
|
||||||
|
logDevice.stts_volt = null;
|
||||||
|
logDevice.stts_switch = null;
|
||||||
}
|
}
|
||||||
// set engine stts moving,idling,stopped
|
// set engine stts moving,idling,stopped
|
||||||
if (logDevice.ignition == GpsTracksModels.STTS_IGNITION_HIGH) {
|
if (logDevice.ignition == GpsTracksModels.STTS_IGNITION_HIGH) {
|
||||||
@ -127,11 +136,19 @@ async function commitMessage(now, logDevice) {
|
|||||||
logDevice.sum_milleage = (lastTrack[0].sum_milleage + logDevice.pre_milleage).toFixed(8);
|
logDevice.sum_milleage = (lastTrack[0].sum_milleage + logDevice.pre_milleage).toFixed(8);
|
||||||
if (vhc.length > 0) {
|
if (vhc.length > 0) {
|
||||||
logDevice.vhc_id = vhc[0] ? vhc[0].vid : 0;
|
logDevice.vhc_id = vhc[0] ? vhc[0].vid : 0;
|
||||||
if (lastTrack[0].vhc_id == logDevice.vhc_id) {
|
// if (lastTrack[0].vhc_id == logDevice.vhc_id) {
|
||||||
logDevice.vhc_milleage = (lastTrack[0].vhc_milleage + logDevice.pre_milleage).toFixed(8);
|
// logDevice.vhc_milleage = (lastTrack[0].vhc_milleage + logDevice.pre_milleage).toFixed(8);
|
||||||
} else {
|
// } else {
|
||||||
logDevice.vhc_milleage = (vhc[0] ? vhc[0].sum_milleage : 0 + logDevice.pre_milleage).toFixed(8);
|
// logDevice.vhc_milleage = (vhc[0] ? vhc[0].sum_milleage : 0 + logDevice.pre_milleage).toFixed(8);
|
||||||
}
|
// }
|
||||||
|
// if (lastTrack[0].vhc_id == logDevice.vhc_id) {
|
||||||
|
// logDevice.vhc_milleage = (lastTrack[0].vhc_milleage + logDevice.pre_milleage).toFixed(8);
|
||||||
|
// } else {
|
||||||
|
// logDevice.vhc_milleage = ((vhc[0] ? vhc[0].sum_milleage : 0) + logDevice.pre_milleage).toFixed(8);
|
||||||
|
// }
|
||||||
|
// force mileage dari vechile
|
||||||
|
logDevice.vhc_milleage = ((vhc[0]?.sum_milleage || 0) + logDevice.pre_milleage).toFixed(8);
|
||||||
|
|
||||||
VhcModels.update(vhc[0] ? vhc[0].vid : 0, { sum_milleage: logDevice.vhc_milleage });
|
VhcModels.update(vhc[0] ? vhc[0].vid : 0, { sum_milleage: logDevice.vhc_milleage });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -237,10 +254,8 @@ class ListenController {
|
|||||||
try {
|
try {
|
||||||
const c = { id: req.body._id };
|
const c = { id: req.body._id };
|
||||||
let buffer_req = Buffer.from(req.body.data, "base64");
|
let buffer_req = Buffer.from(req.body.data, "base64");
|
||||||
console.log("buffer_req", buffer_req);
|
|
||||||
const now = moment().unix();
|
const now = moment().unix();
|
||||||
const me = LibDevice.identifyProtocolFromBuffer(buffer_req);
|
const me = LibDevice.identifyProtocolFromBuffer(buffer_req);
|
||||||
// console.log('app ', buffer_req);
|
|
||||||
|
|
||||||
const logDevice = {
|
const logDevice = {
|
||||||
original_hex: me.ori_string,
|
original_hex: me.ori_string,
|
||||||
@ -279,23 +294,16 @@ class ListenController {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (me.protocol_name == "gt06") {
|
if (me.protocol_name == "gt06") {
|
||||||
// const act = LibDevice.gt06Action(me, device.device_id || null);
|
|
||||||
let dvc_id = devices[c.id];
|
let dvc_id = devices[c.id];
|
||||||
const act = LibDevice.gt06Action(me, dvc_id || null);
|
const act = LibDevice.gt06Action(me, dvc_id || null);
|
||||||
|
|
||||||
if (act.action_type == "login") {
|
if (act.action_type == "login") {
|
||||||
logDevice.action = act.action_type;
|
logDevice.action = act.action_type;
|
||||||
logDevice.device_id = act.device_id;
|
logDevice.device_id = act.device_id;
|
||||||
|
|
||||||
devices[c.id] = act.device_id;
|
devices[c.id] = act.device_id;
|
||||||
// netConn[act.device_id] = c;
|
|
||||||
if (typeof act.buffer_resp != "undefined") {
|
|
||||||
// c.write(act.buffer_resp);
|
|
||||||
}
|
|
||||||
} else if (act.action_type == "location") {
|
} else if (act.action_type == "location") {
|
||||||
logDevice.action = act.action_type;
|
logDevice.action = act.action_type;
|
||||||
logDevice.device_id = act.device_id;
|
logDevice.device_id = act.device_id;
|
||||||
|
|
||||||
logDevice.latitude = act.gps_data.latitude || null;
|
logDevice.latitude = act.gps_data.latitude || null;
|
||||||
logDevice.longitude = act.gps_data.longitude || null;
|
logDevice.longitude = act.gps_data.longitude || null;
|
||||||
logDevice.speed = act.gps_data.speed;
|
logDevice.speed = act.gps_data.speed;
|
||||||
@ -303,12 +311,10 @@ class ListenController {
|
|||||||
if (logDevice.latitude) {
|
if (logDevice.latitude) {
|
||||||
logDevice.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_NOT;
|
logDevice.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_NOT;
|
||||||
}
|
}
|
||||||
|
|
||||||
logDevice.length_gps = act.gps_data.quantity_pos_satellites_c;
|
logDevice.length_gps = act.gps_data.quantity_pos_satellites_c;
|
||||||
logDevice.pos_stlt_gps = act.gps_data.quantity_pos_satellites_b;
|
logDevice.pos_stlt_gps = act.gps_data.quantity_pos_satellites_b;
|
||||||
logDevice.pos_type_gps = Number(act.gps_data.realtime_dif_gps) === 0 ? GpsTracksModels.STTS_POS_TYPE_GPS_RLTM : GpsTracksModels.STTS_POS_TYPE_GPS_DIFF;
|
logDevice.pos_type_gps = Number(act.gps_data.realtime_dif_gps) === 0 ? GpsTracksModels.STTS_POS_TYPE_GPS_RLTM : GpsTracksModels.STTS_POS_TYPE_GPS_DIFF;
|
||||||
logDevice.is_pos_gps = Number(act.gps_data.positioning_gps) ? GpsTracksModels.STTS_IS_POS_GPS_HAS : GpsTracksModels.STTS_IS_POS_GPS_NOT;
|
logDevice.is_pos_gps = Number(act.gps_data.positioning_gps) ? GpsTracksModels.STTS_IS_POS_GPS_HAS : GpsTracksModels.STTS_IS_POS_GPS_NOT;
|
||||||
|
|
||||||
logDevice.crt = moment(act.gps_data.date).unix();
|
logDevice.crt = moment(act.gps_data.date).unix();
|
||||||
logDevice.crt_format = moment(act.gps_data.date).format("YYYY-MM-DD HH:mm:ss");
|
logDevice.crt_format = moment(act.gps_data.date).format("YYYY-MM-DD HH:mm:ss");
|
||||||
logDevice.crt_d = moment(act.gps_data.date).unix();
|
logDevice.crt_d = moment(act.gps_data.date).unix();
|
||||||
@ -316,38 +322,21 @@ class ListenController {
|
|||||||
} else if (act.action_type == "heartbeat") {
|
} else if (act.action_type == "heartbeat") {
|
||||||
logDevice.action = act.action_type;
|
logDevice.action = act.action_type;
|
||||||
logDevice.device_id = act.device_id;
|
logDevice.device_id = act.device_id;
|
||||||
|
|
||||||
logDevice.ignition = Number(act.stts_data.terminal_info.acc) ? GpsTracksModels.STTS_IGNITION_HIGH : GpsTracksModels.STTS_IGNITION_LOW;
|
logDevice.ignition = Number(act.stts_data.terminal_info.acc) ? GpsTracksModels.STTS_IGNITION_HIGH : GpsTracksModels.STTS_IGNITION_LOW;
|
||||||
logDevice.stts_gps = act.stts_data.terminal_info.gps_tracking ? GpsTracksModels.STTS_GPS_ON : GpsTracksModels.STTS_GPS_OFF; // 1=>on, 2=>off
|
logDevice.stts_gps = act.stts_data.terminal_info.gps_tracking ? GpsTracksModels.STTS_GPS_ON : GpsTracksModels.STTS_GPS_OFF;
|
||||||
logDevice.stts_gsm = Number(act.stts_data.gsm_signal_strength) + 1; // 1=>no signal, n>1=>get signal
|
logDevice.stts_gsm = Number(act.stts_data.gsm_signal_strength) + 1;
|
||||||
|
logDevice.stts_oil_electricity = Number(act.stts_data.terminal_info.oil_electricity) === 0 ? GpsTracksModels.STTS_OIL_ELECTRIC_ON : GpsTracksModels.STTS_OIL_ELECTRIC_OFF;
|
||||||
logDevice.stts_oil_electricity = Number(act.stts_data.terminal_info.oil_electricity) === 0 ? GpsTracksModels.STTS_OIL_ELECTRIC_ON : GpsTracksModels.STTS_OIL_ELECTRIC_OFF; // 1=>on, 2=>off
|
|
||||||
|
|
||||||
let stts_alarm = Number(act.stts_data.terminal_info.stts);
|
let stts_alarm = Number(act.stts_data.terminal_info.stts);
|
||||||
if (stts_alarm == 0) {
|
logDevice.stts_alarm = stts_alarm === 1 ? GpsTracksModels.STTS_ALARM_SHOCK : stts_alarm === 2 ? GpsTracksModels.STTS_ALARM_POWER_CUT : stts_alarm === 3 ? GpsTracksModels.STTS_ALARM_LOW_BATTERY : stts_alarm === 4 ? GpsTracksModels.STTS_ALARM_SOS : GpsTracksModels.STTS_ALARM_NORMAL;
|
||||||
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_NORMAL;
|
|
||||||
} else if (stts_alarm == 1) {
|
|
||||||
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_SHOCK;
|
|
||||||
} else if (stts_alarm == 2) {
|
|
||||||
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_POWER_CUT;
|
|
||||||
} else if (stts_alarm == 3) {
|
|
||||||
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_LOW_BATTERY;
|
|
||||||
} else if (stts_alarm == 4) {
|
|
||||||
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_SOS;
|
|
||||||
}
|
|
||||||
|
|
||||||
logDevice.stts_charge = Number(act.stts_data.terminal_info.charge) ? GpsTracksModels.STTS_CHARGE_ON : GpsTracksModels.STTS_CHARGE_OFF;
|
logDevice.stts_charge = Number(act.stts_data.terminal_info.charge) ? GpsTracksModels.STTS_CHARGE_ON : GpsTracksModels.STTS_CHARGE_OFF;
|
||||||
logDevice.stts_acc = Number(act.stts_data.terminal_info.acc) ? GpsTracksModels.STTS_ACC_HIGH : GpsTracksModels.STTS_ACC_LOW;
|
logDevice.stts_acc = Number(act.stts_data.terminal_info.acc) ? GpsTracksModels.STTS_ACC_HIGH : GpsTracksModels.STTS_ACC_LOW;
|
||||||
logDevice.stts_switch = Number(act.stts_data.terminal_info.is_active) ? GpsTracksModels.STTS_SWITCH_ON : GpsTracksModels.STTS_SWITCH_OFF;
|
logDevice.stts_switch = Number(act.stts_data.terminal_info.is_active) ? GpsTracksModels.STTS_SWITCH_ON : GpsTracksModels.STTS_SWITCH_OFF;
|
||||||
logDevice.stts_volt = Number(act.stts_data.voltage_level) + 1;
|
logDevice.stts_volt = Number(act.stts_data.voltage_level) + 1;
|
||||||
|
|
||||||
if (typeof act.buffer_resp != "undefined") {
|
|
||||||
// c.write(act.buffer_resp);
|
|
||||||
}
|
|
||||||
} else if (act.action_type == "alarm") {
|
} else if (act.action_type == "alarm") {
|
||||||
logDevice.action = act.action_type;
|
logDevice.action = act.action_type;
|
||||||
logDevice.device_id = act.device_id;
|
logDevice.device_id = act.device_id;
|
||||||
|
|
||||||
logDevice.latitude = act.gps_data.latitude || null;
|
logDevice.latitude = act.gps_data.latitude || null;
|
||||||
logDevice.longitude = act.gps_data.longitude || null;
|
logDevice.longitude = act.gps_data.longitude || null;
|
||||||
logDevice.speed = act.gps_data.speed;
|
logDevice.speed = act.gps_data.speed;
|
||||||
@ -355,47 +344,27 @@ class ListenController {
|
|||||||
if (logDevice.latitude) {
|
if (logDevice.latitude) {
|
||||||
logDevice.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_NOT;
|
logDevice.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_NOT;
|
||||||
}
|
}
|
||||||
|
|
||||||
logDevice.length_gps = act.gps_data.quantity_pos_satellites_c;
|
logDevice.length_gps = act.gps_data.quantity_pos_satellites_c;
|
||||||
logDevice.pos_stlt_gps = act.gps_data.quantity_pos_satellites_b;
|
logDevice.pos_stlt_gps = act.gps_data.quantity_pos_satellites_b;
|
||||||
logDevice.pos_type_gps = Number(act.gps_data.realtime_dif_gps) === 0 ? GpsTracksModels.STTS_POS_TYPE_GPS_RLTM : GpsTracksModels.STTS_POS_TYPE_GPS_DIFF;
|
logDevice.pos_type_gps = Number(act.gps_data.realtime_dif_gps) === 0 ? GpsTracksModels.STTS_POS_TYPE_GPS_RLTM : GpsTracksModels.STTS_POS_TYPE_GPS_DIFF;
|
||||||
logDevice.is_pos_gps = Number(act.gps_data.positioning_gps) ? GpsTracksModels.STTS_IS_POS_GPS_HAS : GpsTracksModels.STTS_IS_POS_GPS_NOT;
|
logDevice.is_pos_gps = Number(act.gps_data.positioning_gps) ? GpsTracksModels.STTS_IS_POS_GPS_HAS : GpsTracksModels.STTS_IS_POS_GPS_NOT;
|
||||||
|
|
||||||
logDevice.ignition = Number(act.stts_data.terminal_info.acc) ? GpsTracksModels.STTS_IGNITION_HIGH : GpsTracksModels.STTS_IGNITION_LOW;
|
logDevice.ignition = Number(act.stts_data.terminal_info.acc) ? GpsTracksModels.STTS_IGNITION_HIGH : GpsTracksModels.STTS_IGNITION_LOW;
|
||||||
logDevice.stts_gps = act.stts_data.terminal_info.gps_tracking ? GpsTracksModels.STTS_GPS_ON : GpsTracksModels.STTS_GPS_OFF; // 1=>on, 2=>off
|
logDevice.stts_gps = act.stts_data.terminal_info.gps_tracking ? GpsTracksModels.STTS_GPS_ON : GpsTracksModels.STTS_GPS_OFF;
|
||||||
logDevice.stts_gsm = Number(act.stts_data.gsm_signal_strength) + 1; // 1=>no signal, n>1=>get signal
|
logDevice.stts_gsm = Number(act.stts_data.gsm_signal_strength) + 1;
|
||||||
|
logDevice.stts_oil_electricity = Number(act.stts_data.terminal_info.oil_electricity) === 0 ? GpsTracksModels.STTS_OIL_ELECTRIC_ON : GpsTracksModels.STTS_OIL_ELECTRIC_OFF;
|
||||||
logDevice.stts_oil_electricity = Number(act.stts_data.terminal_info.oil_electricity) === 0 ? GpsTracksModels.STTS_OIL_ELECTRIC_ON : GpsTracksModels.STTS_OIL_ELECTRIC_OFF; // 1=>on, 2=>off
|
|
||||||
|
|
||||||
let stts_alarm = Number(act.stts_data.terminal_info.stts);
|
let stts_alarm = Number(act.stts_data.terminal_info.stts);
|
||||||
if (stts_alarm == 0) {
|
logDevice.stts_alarm = stts_alarm === 1 ? GpsTracksModels.STTS_ALARM_SHOCK : stts_alarm === 2 ? GpsTracksModels.STTS_ALARM_POWER_CUT : stts_alarm === 3 ? GpsTracksModels.STTS_ALARM_LOW_BATTERY : stts_alarm === 4 ? GpsTracksModels.STTS_ALARM_SOS : GpsTracksModels.STTS_ALARM_NORMAL;
|
||||||
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_NORMAL;
|
|
||||||
} else if (stts_alarm == 1) {
|
|
||||||
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_SHOCK;
|
|
||||||
} else if (stts_alarm == 2) {
|
|
||||||
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_POWER_CUT;
|
|
||||||
} else if (stts_alarm == 3) {
|
|
||||||
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_LOW_BATTERY;
|
|
||||||
} else if (stts_alarm == 4) {
|
|
||||||
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_SOS;
|
|
||||||
}
|
|
||||||
|
|
||||||
logDevice.stts_charge = Number(act.stts_data.terminal_info.charge) ? GpsTracksModels.STTS_CHARGE_ON : GpsTracksModels.STTS_CHARGE_OFF;
|
logDevice.stts_charge = Number(act.stts_data.terminal_info.charge) ? GpsTracksModels.STTS_CHARGE_ON : GpsTracksModels.STTS_CHARGE_OFF;
|
||||||
logDevice.stts_acc = Number(act.stts_data.terminal_info.acc) ? GpsTracksModels.STTS_ACC_HIGH : GpsTracksModels.STTS_ACC_LOW;
|
logDevice.stts_acc = Number(act.stts_data.terminal_info.acc) ? GpsTracksModels.STTS_ACC_HIGH : GpsTracksModels.STTS_ACC_LOW;
|
||||||
logDevice.stts_switch = Number(act.stts_data.terminal_info.is_active) ? GpsTracksModels.STTS_SWITCH_ON : GpsTracksModels.STTS_SWITCH_OFF;
|
logDevice.stts_switch = Number(act.stts_data.terminal_info.is_active) ? GpsTracksModels.STTS_SWITCH_ON : GpsTracksModels.STTS_SWITCH_OFF;
|
||||||
logDevice.stts_volt = Number(act.stts_data.voltage_level) + 1;
|
logDevice.stts_volt = Number(act.stts_data.voltage_level) + 1;
|
||||||
|
|
||||||
logDevice.crt = moment(act.gps_data.date).unix();
|
logDevice.crt = moment(act.gps_data.date).unix();
|
||||||
logDevice.crt_format = moment(act.gps_data.date).format("YYYY-MM-DD HH:mm:ss");
|
logDevice.crt_format = moment(act.gps_data.date).format("YYYY-MM-DD HH:mm:ss");
|
||||||
logDevice.crt_d = moment(act.gps_data.date).unix();
|
logDevice.crt_d = moment(act.gps_data.date).unix();
|
||||||
logDevice.crt_d_format = moment(act.gps_data.date).format("YYYY-MM-DD HH:mm:ss");
|
logDevice.crt_d_format = moment(act.gps_data.date).format("YYYY-MM-DD HH:mm:ss");
|
||||||
|
} else {
|
||||||
if (typeof act.buffer_resp != "undefined") {
|
|
||||||
// c.write(act.buffer_resp);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// act.action_type == 'other'
|
|
||||||
else {
|
|
||||||
logDevice.action = act.action_type;
|
logDevice.action = act.action_type;
|
||||||
logDevice.device_id = act.device_id;
|
logDevice.device_id = act.device_id;
|
||||||
}
|
}
|
||||||
|
|||||||
439
controllers/ListenController_bak.js
Normal file
439
controllers/ListenController_bak.js
Normal file
@ -0,0 +1,439 @@
|
|||||||
|
const moment = require("moment");
|
||||||
|
const Validator = require("validatorjs");
|
||||||
|
const Helper = require("../library/LibHelper");
|
||||||
|
const response = require("../config/response");
|
||||||
|
const LibMail = require("../library/LibMail");
|
||||||
|
const LibDevice = require("../library/LibDevice");
|
||||||
|
const DanaModels = require("../models/DanaModels");
|
||||||
|
const GpsTracksModels = require("../models/GpsTracksModels");
|
||||||
|
const { nanoid } = require("nanoid");
|
||||||
|
const VhcModels = require("../models/VhcModels");
|
||||||
|
const ZoneModels = require("../models/ZoneModels");
|
||||||
|
const LibHelper = require("../library/LibHelper");
|
||||||
|
|
||||||
|
// const LibQueueBlastOrder = require('../library/LibQueueBlastOrder');
|
||||||
|
Validator.useLang("en");
|
||||||
|
|
||||||
|
const devices = [];
|
||||||
|
|
||||||
|
async function commitMessage(now, logDevice) {
|
||||||
|
try {
|
||||||
|
// don't log
|
||||||
|
if (!logDevice.original_hex) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// in the future don't log to db if device_id not found in vhc
|
||||||
|
const vhc = await VhcModels.getVhcByDeviceId(logDevice.device_id);
|
||||||
|
const lastTrack = await GpsTracksModels.get2LastLocByDeviceId(logDevice.device_id);
|
||||||
|
if (["heartbeat", "alarm"].includes(logDevice.action)) {
|
||||||
|
// set engine stts moving,idling,stopped
|
||||||
|
if (logDevice.ignition == GpsTracksModels.STTS_IGNITION_HIGH) {
|
||||||
|
if (logDevice.speed) {
|
||||||
|
logDevice.stts_engine = GpsTracksModels.STTS_EN_MOVING;
|
||||||
|
} else {
|
||||||
|
if (lastTrack.length > 0) {
|
||||||
|
const checkLastHeartbeat = await GpsTracksModels.getLastHeartbeatToDeterminIdling(logDevice.device_id, lastTrack[0].crt, now);
|
||||||
|
if (checkLastHeartbeat.length >= 3) {
|
||||||
|
logDevice.stts_engine = GpsTracksModels.STTS_EN_IDLING;
|
||||||
|
} else {
|
||||||
|
logDevice.stts_engine = lastTrack[0].stts_engine;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
logDevice.stts_engine = GpsTracksModels.STTS_EN_STOPING;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// get last ignition, stts_engine, stts_alarm, stts_charge, stts_acc, stts_volt, stts_switch
|
||||||
|
if (["location"].includes(logDevice.action)) {
|
||||||
|
console.log("logDevice:", logDevice);
|
||||||
|
// get last ignition
|
||||||
|
const lastHeartbeatOrAlarm = await GpsTracksModels.get2LastHeartbeatOrAlarm(logDevice.device_id);
|
||||||
|
if (lastHeartbeatOrAlarm.length > 0) {
|
||||||
|
logDevice.ignition = lastHeartbeatOrAlarm[0].ignition;
|
||||||
|
logDevice.stts_gps = lastHeartbeatOrAlarm[0].stts_gps;
|
||||||
|
logDevice.stts_gsm = lastHeartbeatOrAlarm[0].stts_gsm;
|
||||||
|
logDevice.stts_oil_electricity = lastHeartbeatOrAlarm[0].stts_oil_electricity;
|
||||||
|
logDevice.stts_alarm = lastHeartbeatOrAlarm[0].stts_alarm;
|
||||||
|
logDevice.stts_charge = lastHeartbeatOrAlarm[0].stts_charge;
|
||||||
|
logDevice.stts_acc = lastHeartbeatOrAlarm[0].stts_acc;
|
||||||
|
logDevice.stts_volt = lastHeartbeatOrAlarm[0].stts_volt;
|
||||||
|
logDevice.stts_switch = lastHeartbeatOrAlarm[0].stts_switch;
|
||||||
|
} else {
|
||||||
|
logDevice.ignition = null;
|
||||||
|
logDevice.stts_gps = null;
|
||||||
|
logDevice.stts_gsm = null;
|
||||||
|
logDevice.stts_oil_electricity = null;
|
||||||
|
logDevice.stts_alarm = null;
|
||||||
|
logDevice.stts_charge = null;
|
||||||
|
logDevice.stts_acc = null;
|
||||||
|
logDevice.stts_volt = null;
|
||||||
|
logDevice.stts_switch = null;
|
||||||
|
}
|
||||||
|
// set engine stts moving,idling,stopped
|
||||||
|
if (logDevice.ignition == GpsTracksModels.STTS_IGNITION_HIGH) {
|
||||||
|
if (logDevice.speed) {
|
||||||
|
logDevice.stts_engine = GpsTracksModels.STTS_EN_MOVING;
|
||||||
|
} else {
|
||||||
|
if (lastTrack.length > 0) {
|
||||||
|
const checkLastHeartbeat = await GpsTracksModels.getLastHeartbeatToDeterminIdling(logDevice.device_id, lastTrack[0].crt, now);
|
||||||
|
if (checkLastHeartbeat.length >= 3) {
|
||||||
|
logDevice.stts_engine = GpsTracksModels.STTS_EN_IDLING;
|
||||||
|
} else {
|
||||||
|
logDevice.stts_engine = lastTrack[0].stts_engine;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// get stts_alarm, stts_charge, stts_acc, stts_volt, stts_switch
|
||||||
|
} else {
|
||||||
|
logDevice.stts_engine = GpsTracksModels.STTS_EN_STOPING;
|
||||||
|
}
|
||||||
|
logDevice.stts_oil_electricity = lastHeartbeatOrAlarm[0].stts_oil_electricity;
|
||||||
|
logDevice.stts_alarm = lastHeartbeatOrAlarm[0].stts_alarm;
|
||||||
|
logDevice.stts_charge = lastHeartbeatOrAlarm[0].stts_charge;
|
||||||
|
logDevice.stts_acc = lastHeartbeatOrAlarm[0].stts_acc;
|
||||||
|
logDevice.stts_volt = lastHeartbeatOrAlarm[0].stts_volt;
|
||||||
|
logDevice.stts_switch = lastHeartbeatOrAlarm[0].stts_switch;
|
||||||
|
}
|
||||||
|
|
||||||
|
// sekarang heartbeat diinject data lokasi juga dari lokasi terakhir
|
||||||
|
if (["heartbeat"].includes(logDevice.action)) {
|
||||||
|
if (lastTrack.length > 0) {
|
||||||
|
logDevice.latitude = lastTrack[0].latitude;
|
||||||
|
logDevice.longitude = lastTrack[0].longitude;
|
||||||
|
logDevice.speed = lastTrack[0].speed;
|
||||||
|
logDevice.orientation = lastTrack[0].orientation;
|
||||||
|
if (logDevice.latitude) {
|
||||||
|
logDevice.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_NOT;
|
||||||
|
}
|
||||||
|
|
||||||
|
logDevice.length_gps = lastTrack[0].length_gps;
|
||||||
|
logDevice.pos_stlt_gps = lastTrack[0].pos_stlt_gps;
|
||||||
|
logDevice.pos_type_gps = lastTrack[0].pos_type_gps;
|
||||||
|
logDevice.is_pos_gps = lastTrack[0].is_pos_gps;
|
||||||
|
|
||||||
|
// jika gapengen dimunculin di last movement
|
||||||
|
// logDevice.crt = lastTrack[0].crt;
|
||||||
|
// logDevice.crt_format = lastTrack[0].crt_format;
|
||||||
|
// logDevice.crt_d = lastTrack[0].crt_d;
|
||||||
|
// logDevice.crt_d_format = lastTrack[0].crt_d_format;
|
||||||
|
// jika pengen di munculin di last movement
|
||||||
|
logDevice.crt = now;
|
||||||
|
logDevice.crt_format = moment.unix(now).format("YYYY-MM-DD HH:mm:ss");
|
||||||
|
logDevice.crt_d = now;
|
||||||
|
logDevice.crt_d_format = moment.unix(now).format("YYYY-MM-DD HH:mm:ss");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// count milleage
|
||||||
|
if (logDevice.latitude != null && logDevice.longitude != null && lastTrack.length > 0) {
|
||||||
|
const distance = LibHelper.haversineGreatCircleDistance(lastTrack[0].latitude, lastTrack[0].longitude, logDevice.latitude, logDevice.longitude, LibHelper.EARTH_RADIUS_KM);
|
||||||
|
const distance_km = LibHelper.kmToKm(distance, 100000000);
|
||||||
|
// console.log(`GPS TRACKER UP LOCATION => device_id:${logDevice.device_id} vhc_id:${(vhc[0]) ? vhc[0].vid : 0}, distance_km:${distance_km}`);
|
||||||
|
// validasi jika lebih dari 3km, ga disimpan
|
||||||
|
if (distance_km >= 3) {
|
||||||
|
GpsTracksModels.bundleCreate2(logDevice, logDevice); // jika tidak disimpan malah jadi bug, jadi akan update lokasi terus dengan kalkulasi jarak sebelumnya jadi makan lama makin lebar, mending disimpen terus milleagenya jadi 0 aja
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
logDevice.pre_milleage = distance_km;
|
||||||
|
logDevice.sum_milleage = (lastTrack[0].sum_milleage + logDevice.pre_milleage).toFixed(8);
|
||||||
|
if (vhc.length > 0) {
|
||||||
|
logDevice.vhc_id = vhc[0] ? vhc[0].vid : 0;
|
||||||
|
// if (lastTrack[0].vhc_id == logDevice.vhc_id) {
|
||||||
|
// logDevice.vhc_milleage = (lastTrack[0].vhc_milleage + logDevice.pre_milleage).toFixed(8);
|
||||||
|
// } else {
|
||||||
|
// logDevice.vhc_milleage = (vhc[0] ? vhc[0].sum_milleage : 0 + logDevice.pre_milleage).toFixed(8);
|
||||||
|
// }
|
||||||
|
if (lastTrack[0].vhc_id == logDevice.vhc_id) {
|
||||||
|
logDevice.vhc_milleage = (lastTrack[0].vhc_milleage + logDevice.pre_milleage).toFixed(8);
|
||||||
|
} else {
|
||||||
|
logDevice.vhc_milleage = ((vhc[0] ? vhc[0].sum_milleage : 0) + logDevice.pre_milleage).toFixed(8);
|
||||||
|
}
|
||||||
|
|
||||||
|
VhcModels.update(vhc[0] ? vhc[0].vid : 0, { sum_milleage: logDevice.vhc_milleage });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// truck zoning spawn
|
||||||
|
if (logDevice.latitude != null && logDevice.longitude != null) {
|
||||||
|
// && vhc.length > 0
|
||||||
|
// log tracking
|
||||||
|
const currTrack = await GpsTracksModels.bundleCreate2(logDevice, logDevice);
|
||||||
|
// console.log('GT06 HAS LOCATION AND CHECK ZONE');
|
||||||
|
const inCircle = await ZoneModels.getInCircle(logDevice.latitude, logDevice.longitude);
|
||||||
|
const inShape = await ZoneModels.getInShape(logDevice.latitude, logDevice.longitude);
|
||||||
|
const insideSpawnZone = [];
|
||||||
|
for (let zone of inCircle) {
|
||||||
|
insideSpawnZone.push(zone);
|
||||||
|
}
|
||||||
|
for (let zone of inShape) {
|
||||||
|
insideSpawnZone.push(zone);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* get lastSpawn desc index 0, where leave_at = 0
|
||||||
|
* kalo gaada create, dengan isi field enter_at aja, kalo ada didalam zona
|
||||||
|
* kalo ada update, dengan isi field leave_at aja, kalo udah diluar zona
|
||||||
|
*/
|
||||||
|
const lastSpawn = await GpsTracksModels.listSpawnZone({
|
||||||
|
source: GpsTracksModels.SOURCE_GPS_TRACKER,
|
||||||
|
device_id: logDevice.device_id,
|
||||||
|
vhc_id: vhc[0] ? vhc[0].vid : 0,
|
||||||
|
leave_at_d: 0,
|
||||||
|
order_by: "ORDER BY id DESC",
|
||||||
|
limit: 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (lastSpawn.length > 0) {
|
||||||
|
let is_leave_zone = 1;
|
||||||
|
for (const insideZone of insideSpawnZone) {
|
||||||
|
if (insideZone.zid === lastSpawn[0].zone_id) is_leave_zone = 0;
|
||||||
|
}
|
||||||
|
if (is_leave_zone === 1 && lastSpawn[0].device_id == logDevice.device_id) {
|
||||||
|
GpsTracksModels.updt2SpawnZone(
|
||||||
|
{
|
||||||
|
leave_lat: logDevice.latitude,
|
||||||
|
leave_lng: logDevice.longitude,
|
||||||
|
leave_at_d: logDevice.crt_d || now,
|
||||||
|
leave_at_d_format: moment.unix(logDevice.crt_d || now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
leave_at_s: now,
|
||||||
|
leave_at_s_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
updt: now,
|
||||||
|
updt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
},
|
||||||
|
lastSpawn[0].id
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (let zone of insideSpawnZone) {
|
||||||
|
let mailData = {
|
||||||
|
pic_name: zone.pic_name,
|
||||||
|
pic_mail: zone.pic_mail,
|
||||||
|
z_name: zone.name,
|
||||||
|
z_type_name: zone.type_name,
|
||||||
|
z_workflow_name: zone.workflow_type_name,
|
||||||
|
shiptocode: zone.shiptocode,
|
||||||
|
z_fulladdress: zone.fulladdress,
|
||||||
|
v_nopol: (vhc[0] ? vhc[0].nopol1 : 0 || "") + (vhc[0] ? vhc[0].nopol2 : 0 || "") + (vhc[0] ? vhc[0].nopol3 : 0 || ""),
|
||||||
|
da_name: vhc[0] ? vhc[0].da_name : 0 || "",
|
||||||
|
da_phone: "+" + (vhc[0] ? vhc[0].da_phone_code : 0 || "") + (vhc[0] ? vhc[0].da_phone : 0 || ""),
|
||||||
|
};
|
||||||
|
// LibMail.sendVhcSpawnZoneMail(`${(vhc[0]) ? vhc[0].nopol1 : 0 || ''}${(vhc[0]) ? vhc[0].nopol2 : 0 || ''}${(vhc[0]) ? vhc[0].nopol3 : 0 || ''} entering zone ${mailData.z_name}`, mailData.pic_mail, mailData);
|
||||||
|
|
||||||
|
if (logDevice.device_id === "0865784052395871") console.log(1234567890);
|
||||||
|
GpsTracksModels.create2SpawnZone({
|
||||||
|
device_id: logDevice.device_id,
|
||||||
|
master_id: Number(currTrack.result.insertId),
|
||||||
|
enter_lat: logDevice.latitude,
|
||||||
|
enter_lng: logDevice.longitude,
|
||||||
|
enter_at_d: logDevice.crt_d || now,
|
||||||
|
enter_at_d_format: moment.unix(logDevice.crt_d || now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
enter_at_s: now,
|
||||||
|
enter_at_s_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
zone_id: zone.zid,
|
||||||
|
zone_name: zone.name,
|
||||||
|
vhc_id: vhc[0] ? vhc[0].vid : 0,
|
||||||
|
source: GpsTracksModels.SOURCE_GPS_TRACKER,
|
||||||
|
crt: now,
|
||||||
|
crt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
});
|
||||||
|
if (logDevice.device_id === "0865784052395871") console.log("DISINI");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// log tracking
|
||||||
|
GpsTracksModels.bundleCreate2(logDevice, logDevice);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ListenController {
|
||||||
|
async gps(req, res) {
|
||||||
|
let apiRes = {};
|
||||||
|
try {
|
||||||
|
const c = { id: req.body._id };
|
||||||
|
let buffer_req = Buffer.from(req.body.data, "base64");
|
||||||
|
console.log("buffer_req", buffer_req);
|
||||||
|
const now = moment().unix();
|
||||||
|
const me = LibDevice.identifyProtocolFromBuffer(buffer_req);
|
||||||
|
// console.log('app ', buffer_req);
|
||||||
|
|
||||||
|
const logDevice = {
|
||||||
|
original_hex: me.ori_string,
|
||||||
|
protocol: me.protocol_name == "unknown" ? null : me.protocol_name,
|
||||||
|
action: null,
|
||||||
|
device_id: null,
|
||||||
|
latitude: null,
|
||||||
|
longitude: null,
|
||||||
|
speed: null,
|
||||||
|
orientation: 0,
|
||||||
|
ignition: 0,
|
||||||
|
stts_engine: 0,
|
||||||
|
stts_gps: 0,
|
||||||
|
length_gps: 0,
|
||||||
|
pos_stlt_gps: 0,
|
||||||
|
pos_type_gps: 0,
|
||||||
|
is_pos_gps: 0,
|
||||||
|
stts_gsm: 0,
|
||||||
|
stts_oil_electricity: 0,
|
||||||
|
stts_alarm: 0,
|
||||||
|
stts_charge: 0,
|
||||||
|
stts_acc: 0,
|
||||||
|
stts_volt: 0,
|
||||||
|
stts_switch: 0,
|
||||||
|
stts_reverse_geo: 0,
|
||||||
|
pre_milleage: 0,
|
||||||
|
source: GpsTracksModels.SOURCE_GPS_TRACKER,
|
||||||
|
vhc_id: 0,
|
||||||
|
drv_id: 0,
|
||||||
|
crt: now,
|
||||||
|
crt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
crt_d: 0,
|
||||||
|
crt_d_format: null,
|
||||||
|
crt_s: now,
|
||||||
|
crt_s_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
};
|
||||||
|
|
||||||
|
if (me.protocol_name == "gt06") {
|
||||||
|
// const act = LibDevice.gt06Action(me, device.device_id || null);
|
||||||
|
let dvc_id = devices[c.id];
|
||||||
|
const act = LibDevice.gt06Action(me, dvc_id || null);
|
||||||
|
|
||||||
|
if (act.action_type == "login") {
|
||||||
|
logDevice.action = act.action_type;
|
||||||
|
logDevice.device_id = act.device_id;
|
||||||
|
|
||||||
|
devices[c.id] = act.device_id;
|
||||||
|
// netConn[act.device_id] = c;
|
||||||
|
if (typeof act.buffer_resp != "undefined") {
|
||||||
|
// c.write(act.buffer_resp);
|
||||||
|
}
|
||||||
|
} else if (act.action_type == "location") {
|
||||||
|
logDevice.action = act.action_type;
|
||||||
|
logDevice.device_id = act.device_id;
|
||||||
|
|
||||||
|
logDevice.latitude = act.gps_data.latitude || null;
|
||||||
|
logDevice.longitude = act.gps_data.longitude || null;
|
||||||
|
logDevice.speed = act.gps_data.speed;
|
||||||
|
logDevice.orientation = act.gps_data.orientation;
|
||||||
|
if (logDevice.latitude) {
|
||||||
|
logDevice.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_NOT;
|
||||||
|
}
|
||||||
|
|
||||||
|
logDevice.length_gps = act.gps_data.quantity_pos_satellites_c;
|
||||||
|
logDevice.pos_stlt_gps = act.gps_data.quantity_pos_satellites_b;
|
||||||
|
logDevice.pos_type_gps = Number(act.gps_data.realtime_dif_gps) === 0 ? GpsTracksModels.STTS_POS_TYPE_GPS_RLTM : GpsTracksModels.STTS_POS_TYPE_GPS_DIFF;
|
||||||
|
logDevice.is_pos_gps = Number(act.gps_data.positioning_gps) ? GpsTracksModels.STTS_IS_POS_GPS_HAS : GpsTracksModels.STTS_IS_POS_GPS_NOT;
|
||||||
|
|
||||||
|
logDevice.crt = moment(act.gps_data.date).unix();
|
||||||
|
logDevice.crt_format = moment(act.gps_data.date).format("YYYY-MM-DD HH:mm:ss");
|
||||||
|
logDevice.crt_d = moment(act.gps_data.date).unix();
|
||||||
|
logDevice.crt_d_format = moment(act.gps_data.date).format("YYYY-MM-DD HH:mm:ss");
|
||||||
|
} else if (act.action_type == "heartbeat") {
|
||||||
|
logDevice.action = act.action_type;
|
||||||
|
logDevice.device_id = act.device_id;
|
||||||
|
|
||||||
|
logDevice.ignition = Number(act.stts_data.terminal_info.acc) ? GpsTracksModels.STTS_IGNITION_HIGH : GpsTracksModels.STTS_IGNITION_LOW;
|
||||||
|
logDevice.stts_gps = act.stts_data.terminal_info.gps_tracking ? GpsTracksModels.STTS_GPS_ON : GpsTracksModels.STTS_GPS_OFF; // 1=>on, 2=>off
|
||||||
|
logDevice.stts_gsm = Number(act.stts_data.gsm_signal_strength) + 1; // 1=>no signal, n>1=>get signal
|
||||||
|
|
||||||
|
logDevice.stts_oil_electricity = Number(act.stts_data.terminal_info.oil_electricity) === 0 ? GpsTracksModels.STTS_OIL_ELECTRIC_ON : GpsTracksModels.STTS_OIL_ELECTRIC_OFF; // 1=>on, 2=>off
|
||||||
|
|
||||||
|
let stts_alarm = Number(act.stts_data.terminal_info.stts);
|
||||||
|
if (stts_alarm == 0) {
|
||||||
|
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_NORMAL;
|
||||||
|
} else if (stts_alarm == 1) {
|
||||||
|
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_SHOCK;
|
||||||
|
} else if (stts_alarm == 2) {
|
||||||
|
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_POWER_CUT;
|
||||||
|
} else if (stts_alarm == 3) {
|
||||||
|
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_LOW_BATTERY;
|
||||||
|
} else if (stts_alarm == 4) {
|
||||||
|
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_SOS;
|
||||||
|
}
|
||||||
|
|
||||||
|
logDevice.stts_charge = Number(act.stts_data.terminal_info.charge) ? GpsTracksModels.STTS_CHARGE_ON : GpsTracksModels.STTS_CHARGE_OFF;
|
||||||
|
logDevice.stts_acc = Number(act.stts_data.terminal_info.acc) ? GpsTracksModels.STTS_ACC_HIGH : GpsTracksModels.STTS_ACC_LOW;
|
||||||
|
logDevice.stts_switch = Number(act.stts_data.terminal_info.is_active) ? GpsTracksModels.STTS_SWITCH_ON : GpsTracksModels.STTS_SWITCH_OFF;
|
||||||
|
logDevice.stts_volt = Number(act.stts_data.voltage_level) + 1;
|
||||||
|
|
||||||
|
if (typeof act.buffer_resp != "undefined") {
|
||||||
|
// c.write(act.buffer_resp);
|
||||||
|
}
|
||||||
|
} else if (act.action_type == "alarm") {
|
||||||
|
logDevice.action = act.action_type;
|
||||||
|
logDevice.device_id = act.device_id;
|
||||||
|
|
||||||
|
logDevice.latitude = act.gps_data.latitude || null;
|
||||||
|
logDevice.longitude = act.gps_data.longitude || null;
|
||||||
|
logDevice.speed = act.gps_data.speed;
|
||||||
|
logDevice.orientation = act.gps_data.orientation;
|
||||||
|
if (logDevice.latitude) {
|
||||||
|
logDevice.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_NOT;
|
||||||
|
}
|
||||||
|
|
||||||
|
logDevice.length_gps = act.gps_data.quantity_pos_satellites_c;
|
||||||
|
logDevice.pos_stlt_gps = act.gps_data.quantity_pos_satellites_b;
|
||||||
|
logDevice.pos_type_gps = Number(act.gps_data.realtime_dif_gps) === 0 ? GpsTracksModels.STTS_POS_TYPE_GPS_RLTM : GpsTracksModels.STTS_POS_TYPE_GPS_DIFF;
|
||||||
|
logDevice.is_pos_gps = Number(act.gps_data.positioning_gps) ? GpsTracksModels.STTS_IS_POS_GPS_HAS : GpsTracksModels.STTS_IS_POS_GPS_NOT;
|
||||||
|
|
||||||
|
logDevice.ignition = Number(act.stts_data.terminal_info.acc) ? GpsTracksModels.STTS_IGNITION_HIGH : GpsTracksModels.STTS_IGNITION_LOW;
|
||||||
|
logDevice.stts_gps = act.stts_data.terminal_info.gps_tracking ? GpsTracksModels.STTS_GPS_ON : GpsTracksModels.STTS_GPS_OFF; // 1=>on, 2=>off
|
||||||
|
logDevice.stts_gsm = Number(act.stts_data.gsm_signal_strength) + 1; // 1=>no signal, n>1=>get signal
|
||||||
|
|
||||||
|
logDevice.stts_oil_electricity = Number(act.stts_data.terminal_info.oil_electricity) === 0 ? GpsTracksModels.STTS_OIL_ELECTRIC_ON : GpsTracksModels.STTS_OIL_ELECTRIC_OFF; // 1=>on, 2=>off
|
||||||
|
|
||||||
|
let stts_alarm = Number(act.stts_data.terminal_info.stts);
|
||||||
|
if (stts_alarm == 0) {
|
||||||
|
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_NORMAL;
|
||||||
|
} else if (stts_alarm == 1) {
|
||||||
|
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_SHOCK;
|
||||||
|
} else if (stts_alarm == 2) {
|
||||||
|
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_POWER_CUT;
|
||||||
|
} else if (stts_alarm == 3) {
|
||||||
|
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_LOW_BATTERY;
|
||||||
|
} else if (stts_alarm == 4) {
|
||||||
|
logDevice.stts_alarm = GpsTracksModels.STTS_ALARM_SOS;
|
||||||
|
}
|
||||||
|
|
||||||
|
logDevice.stts_charge = Number(act.stts_data.terminal_info.charge) ? GpsTracksModels.STTS_CHARGE_ON : GpsTracksModels.STTS_CHARGE_OFF;
|
||||||
|
logDevice.stts_acc = Number(act.stts_data.terminal_info.acc) ? GpsTracksModels.STTS_ACC_HIGH : GpsTracksModels.STTS_ACC_LOW;
|
||||||
|
logDevice.stts_switch = Number(act.stts_data.terminal_info.is_active) ? GpsTracksModels.STTS_SWITCH_ON : GpsTracksModels.STTS_SWITCH_OFF;
|
||||||
|
logDevice.stts_volt = Number(act.stts_data.voltage_level) + 1;
|
||||||
|
|
||||||
|
logDevice.crt = moment(act.gps_data.date).unix();
|
||||||
|
logDevice.crt_format = moment(act.gps_data.date).format("YYYY-MM-DD HH:mm:ss");
|
||||||
|
logDevice.crt_d = moment(act.gps_data.date).unix();
|
||||||
|
logDevice.crt_d_format = moment(act.gps_data.date).format("YYYY-MM-DD HH:mm:ss");
|
||||||
|
|
||||||
|
if (typeof act.buffer_resp != "undefined") {
|
||||||
|
// c.write(act.buffer_resp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// act.action_type == 'other'
|
||||||
|
else {
|
||||||
|
logDevice.action = act.action_type;
|
||||||
|
logDevice.device_id = act.device_id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await commitMessage(now, logDevice);
|
||||||
|
|
||||||
|
apiRes = JSON.parse(JSON.stringify(response[200]));
|
||||||
|
apiRes.meta.message = "success";
|
||||||
|
apiRes.data = logDevice;
|
||||||
|
return res.status(200).json(apiRes);
|
||||||
|
} catch (e) {
|
||||||
|
console.log("error", e);
|
||||||
|
apiRes = JSON.parse(JSON.stringify(response[500]));
|
||||||
|
apiRes.meta.message += Helper.setErrMsg(": " + e.message);
|
||||||
|
return res.status(500).json(apiRes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const object = new ListenController();
|
||||||
|
|
||||||
|
module.exports = object;
|
||||||
@ -1,40 +1,58 @@
|
|||||||
require("dotenv").config({ path: "../.env" });
|
require("dotenv").config({ path: "../.env" })
|
||||||
const LibWinston = require("../library/LibWinston");
|
const LibWinston = require("../library/LibWinston")
|
||||||
const moment = require("moment");
|
const moment = require("moment")
|
||||||
const axios = require("axios").default;
|
const axios = require("axios").default
|
||||||
const url = require("url");
|
const url = require("url")
|
||||||
const request = require("../config/request");
|
const request = require("../config/request")
|
||||||
const GpsTracksModels = require("../models/GpsTracksModels");
|
const GpsTracksModels = require("../models/GpsTracksModels")
|
||||||
const RegionModels = require("../models/RegionModels");
|
const RegionModels = require("../models/RegionModels")
|
||||||
const { stringify } = require("flatted");
|
const { stringify } = require("flatted")
|
||||||
|
|
||||||
const schedulerName = process.env.REDIS_SCHEDULER_REVERSE_GEO;
|
const schedulerName = process.env.REDIS_SCHEDULER_REVERSE_GEO
|
||||||
const Logger = LibWinston.initialize(schedulerName);
|
const Logger = LibWinston.initialize(schedulerName)
|
||||||
|
|
||||||
const go = async () => {
|
const go = async () => {
|
||||||
try {
|
try {
|
||||||
Logger.log("info", `${schedulerName} running: ${moment().format("YYYY-MM-DD HH:mm:ss")}`);
|
Logger.log("info", `${schedulerName} running: ${moment().format("YYYY-MM-DD HH:mm:ss")}`)
|
||||||
// (async function() {
|
// (async function() {
|
||||||
try {
|
try {
|
||||||
let loop = process.env.SCHEDULE_REVERSE_GEO_MAX_LOOP;
|
let loop = process.env.SCHEDULE_REVERSE_GEO_MAX_LOOP
|
||||||
for (let x = 0; x < loop; x++) {
|
for (let x = 0; x < loop; x++) {
|
||||||
// let tracks = [];
|
const axInstance = axios.create({
|
||||||
let tracks = await GpsTracksModels.get2ForReverseGeo(1);
|
proxy: {
|
||||||
for (let i = 0; i < tracks.length; i++) {
|
host: process.env.PROXY_URL,
|
||||||
console.log("tracks[i] :", tracks[i].id, tracks[i].device_id, tracks[i].latitude, tracks[i].longitude);
|
port: Number(process.env.PROXY_PORT),
|
||||||
let now = moment().unix();
|
},
|
||||||
let updtData = {};
|
timeout: 15_000,
|
||||||
let respReverseGeo = null;
|
// headers: { "User-Agent": "movana-fleet-management/1.0 (emirsyafmun@gmail.com)" },
|
||||||
try {
|
})
|
||||||
const sameAddr = await GpsTracksModels.select2Address(tracks[i].latitude, tracks[i].longitude);
|
const urlBase = request.osm_reverse_geo.urlFull
|
||||||
|
|
||||||
|
// let tracks = [];
|
||||||
|
let tracks = await GpsTracksModels.get2ForReverseGeo(10)
|
||||||
|
|
||||||
|
function processTrack(track, i) {
|
||||||
|
return (async () => {
|
||||||
|
console.log("track:", track.id, track.device_id, track.latitude, track.longitude)
|
||||||
|
let now = moment().unix()
|
||||||
|
let updtData = {}
|
||||||
|
let respReverseGeo = null
|
||||||
|
|
||||||
|
const params = new url.URLSearchParams({
|
||||||
|
lat: track.latitude,
|
||||||
|
lon: track.longitude,
|
||||||
|
format: "geojson",
|
||||||
|
})
|
||||||
|
|
||||||
|
try {
|
||||||
|
const sameAddr = await GpsTracksModels.select2Address(track.latitude, track.longitude)
|
||||||
if (sameAddr.length > 0) {
|
if (sameAddr.length > 0) {
|
||||||
let addrData = {
|
let addrData = {
|
||||||
device_id: tracks[i].device_id,
|
device_id: track.device_id,
|
||||||
master_id: tracks[i].id,
|
master_id: track.id,
|
||||||
type: sameAddr[0].type,
|
type: sameAddr[0].type,
|
||||||
lat: tracks[i].latitude,
|
lat: track.latitude,
|
||||||
lng: tracks[i].longitude,
|
lng: track.longitude,
|
||||||
country_id: sameAddr[0].country_id,
|
country_id: sameAddr[0].country_id,
|
||||||
country_code: sameAddr[0].country_code,
|
country_code: sameAddr[0].country_code,
|
||||||
country_text: sameAddr[0].country_text,
|
country_text: sameAddr[0].country_text,
|
||||||
@ -54,68 +72,45 @@ const go = async () => {
|
|||||||
log_reverse_geo: sameAddr[0].log_reverse_geo,
|
log_reverse_geo: sameAddr[0].log_reverse_geo,
|
||||||
crt: now,
|
crt: now,
|
||||||
crt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
crt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
};
|
}
|
||||||
GpsTracksModels.create2Address(addrData);
|
GpsTracksModels.create2Address(addrData)
|
||||||
updtData.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_SC;
|
updtData.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_SC
|
||||||
await GpsTracksModels.update2(tracks[i].id, updtData);
|
await GpsTracksModels.update2(track.id, updtData)
|
||||||
continue;
|
console.log("skip same address:", track.id)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
let params = new url.URLSearchParams({
|
const resp = await axInstance.get(`${urlBase}?${params.toString()}`, {
|
||||||
lat: tracks[i].latitude,
|
headers: { "User-Agent": `movana-fleet-management-` + i },
|
||||||
lon: tracks[i].longitude,
|
})
|
||||||
format: "geojson",
|
const respData = resp.data || {}
|
||||||
});
|
if (resp.status === 200) {
|
||||||
//const axInstance = axios.create()
|
console.log("SUCCESS respReverseGeo:", track.id)
|
||||||
const axInstance = axios.create({
|
|
||||||
proxy: {
|
|
||||||
host: process.env.PROXY_URL,
|
|
||||||
port: process.env.PROXY_PORT,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
axios.defaults.timeout = 10000;
|
|
||||||
axios.defaults.crossDomain = true;
|
|
||||||
// respReverseGeo = await axios({
|
|
||||||
// url: request.osm_reverse_geo.urlFull,
|
|
||||||
// method: request.osm_reverse_geo.method,
|
|
||||||
// params: params,
|
|
||||||
// responseType: 'json',
|
|
||||||
// });
|
|
||||||
// respReverseGeo = await axInstance.get(request.osm_reverse_geo.urlFull + "?" + params.toString(), {
|
|
||||||
// timeout: 10000,
|
|
||||||
// });
|
|
||||||
respReverseGeo = await axInstance.get(request.osm_reverse_geo.urlFull + "?" + params.toString(), {
|
|
||||||
timeout: 10000,
|
|
||||||
headers: {
|
|
||||||
"User-Agent": "movana-fleet-management/1.0 (emirsyafmun@gmail.com)",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
console.log("respReverseGeo: ", respReverseGeo.data || null);
|
|
||||||
let respData = respReverseGeo.data || {};
|
|
||||||
if (respReverseGeo.status == 200) {
|
|
||||||
if (respData.features.length < 1) {
|
if (respData.features.length < 1) {
|
||||||
GpsTracksModels.create2Address({
|
GpsTracksModels.create2Address({
|
||||||
device_id: tracks[i].device_id,
|
device_id: track.device_id,
|
||||||
master_id: tracks[i].id,
|
master_id: track.id,
|
||||||
lat: tracks[i].latitude,
|
lat: track.latitude,
|
||||||
lng: tracks[i].longitude,
|
lng: track.longitude,
|
||||||
stts_reverse_geo: GpsTracksModels.STTS_REVERSE_GEO_LOST,
|
stts_reverse_geo: GpsTracksModels.STTS_REVERSE_GEO_LOST,
|
||||||
log_reverse_geo: JSON.stringify(respData),
|
log_reverse_geo: JSON.stringify(respData),
|
||||||
crt: now,
|
crt: now,
|
||||||
crt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
crt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
});
|
})
|
||||||
updtData.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_LOST;
|
updtData.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_LOST
|
||||||
await GpsTracksModels.update2(tracks[i].id, updtData);
|
await GpsTracksModels.update2(track.id, updtData)
|
||||||
} else {
|
} else {
|
||||||
let respAddr = respData.features[0].properties.address;
|
let respAddr = respData.features[0].properties.address
|
||||||
let addrData = {
|
let addrData = {
|
||||||
device_id: tracks[i].device_id,
|
device_id: track.device_id,
|
||||||
master_id: tracks[i].id,
|
master_id: track.id,
|
||||||
lat: tracks[i].latitude,
|
lat: track.latitude,
|
||||||
lng: tracks[i].longitude,
|
lng: track.longitude,
|
||||||
country_id: GpsTracksModels.DEFAULT_COUNTRY_ID,
|
country_id: GpsTracksModels.DEFAULT_COUNTRY_ID,
|
||||||
country_code: respAddr.country_code,
|
country_code: respAddr.country_code,
|
||||||
country_text: respAddr.country ? respAddr.country.toUpperCase() : respAddr.country || null,
|
country_text: respAddr.country
|
||||||
|
? respAddr.country.toUpperCase()
|
||||||
|
: respAddr.country || null,
|
||||||
state_id: null,
|
state_id: null,
|
||||||
city_id: null,
|
city_id: null,
|
||||||
district_id: null,
|
district_id: null,
|
||||||
@ -123,40 +118,57 @@ const go = async () => {
|
|||||||
postcode: respAddr.postcode,
|
postcode: respAddr.postcode,
|
||||||
fulladdress: encodeURIComponent(respData.features[0].properties.display_name),
|
fulladdress: encodeURIComponent(respData.features[0].properties.display_name),
|
||||||
stts_reverse_geo: GpsTracksModels.STTS_REVERSE_GEO_SC,
|
stts_reverse_geo: GpsTracksModels.STTS_REVERSE_GEO_SC,
|
||||||
log_reverse_geo: respData.features[0].properties ? JSON.stringify(respData.features[0].properties) : null,
|
log_reverse_geo: respData.features[0].properties
|
||||||
|
? JSON.stringify(respData.features[0].properties)
|
||||||
|
: null,
|
||||||
crt: now,
|
crt: now,
|
||||||
crt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
crt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
};
|
}
|
||||||
if (respAddr.state || respAddr.city) {
|
if (respAddr.state || respAddr.city) {
|
||||||
addrData.state_text = respAddr.region || respAddr.state || respAddr.state_district || respAddr.county || respAddr.city || "";
|
addrData.state_text =
|
||||||
addrData.state_text = addrData.state_text ? addrData.state_text.toUpperCase() : addrData.state_text || null;
|
respAddr.region ||
|
||||||
addrData.state_text = addrData.state_text || null;
|
respAddr.state ||
|
||||||
|
respAddr.state_district ||
|
||||||
|
respAddr.county ||
|
||||||
|
respAddr.city ||
|
||||||
|
""
|
||||||
|
addrData.state_text = addrData.state_text
|
||||||
|
? addrData.state_text.toUpperCase()
|
||||||
|
: addrData.state_text || null
|
||||||
|
addrData.state_text = addrData.state_text || null
|
||||||
}
|
}
|
||||||
if (respAddr.city_district || respAddr.city) {
|
if (respAddr.city_district || respAddr.city) {
|
||||||
addrData.city_text = respAddr.city_district || respAddr.city || "";
|
addrData.city_text = respAddr.city_district || respAddr.city || ""
|
||||||
addrData.city_text = addrData.city_text ? addrData.city_text.toUpperCase() : addrData.city_text || null;
|
addrData.city_text = addrData.city_text
|
||||||
addrData.city_text = addrData.city_text || null;
|
? addrData.city_text.toUpperCase()
|
||||||
|
: addrData.city_text || null
|
||||||
|
addrData.city_text = addrData.city_text || null
|
||||||
}
|
}
|
||||||
if (respAddr.suburb || respAddr.subdistrict) {
|
if (respAddr.suburb || respAddr.subdistrict) {
|
||||||
addrData.district_text = respAddr.suburb || respAddr.subdistrict || respAddr.subdivision || "";
|
addrData.district_text =
|
||||||
addrData.district_text = addrData.district_text ? addrData.district_text.toUpperCase() : addrData.district_text || null;
|
respAddr.suburb || respAddr.subdistrict || respAddr.subdivision || ""
|
||||||
addrData.district_text = addrData.district_text || null;
|
addrData.district_text = addrData.district_text
|
||||||
|
? addrData.district_text.toUpperCase()
|
||||||
|
: addrData.district_text || null
|
||||||
|
addrData.district_text = addrData.district_text || null
|
||||||
}
|
}
|
||||||
if (respAddr.village) {
|
if (respAddr.village) {
|
||||||
addrData.village_text = respAddr.village || respAddr.neighbourhood || "";
|
addrData.village_text = respAddr.village || respAddr.neighbourhood || ""
|
||||||
addrData.village_text = addrData.village_text ? addrData.village_text.toUpperCase() : addrData.village_text || null;
|
addrData.village_text = addrData.village_text
|
||||||
addrData.village_text = addrData.village_text || null;
|
? addrData.village_text.toUpperCase()
|
||||||
|
: addrData.village_text || null
|
||||||
|
addrData.village_text = addrData.village_text || null
|
||||||
}
|
}
|
||||||
if (respAddr.amenity || respAddr.road || respAddr.city_block) {
|
if (respAddr.amenity || respAddr.road || respAddr.city_block) {
|
||||||
addrData.streets = "";
|
addrData.streets = ""
|
||||||
addrData.streets += respAddr.amenity ? respAddr.amenity + ", " : "";
|
addrData.streets += respAddr.amenity ? respAddr.amenity + ", " : ""
|
||||||
addrData.streets += respAddr.road ? respAddr.road + ", " : "";
|
addrData.streets += respAddr.road ? respAddr.road + ", " : ""
|
||||||
addrData.streets += respAddr.house_number ? respAddr.house_number + ", " : "";
|
addrData.streets += respAddr.house_number ? respAddr.house_number + ", " : ""
|
||||||
addrData.streets += respAddr.house_name ? respAddr.house_name + ", " : "";
|
addrData.streets += respAddr.house_name ? respAddr.house_name + ", " : ""
|
||||||
addrData.streets += respAddr.city_block ? respAddr.city_block + ", " : "";
|
addrData.streets += respAddr.city_block ? respAddr.city_block + ", " : ""
|
||||||
addrData.streets += addrData.streets || null;
|
addrData.streets += addrData.streets || null
|
||||||
if (addrData.streets) {
|
if (addrData.streets) {
|
||||||
addrData.streets = encodeURIComponent(addrData.streets.slice(0, -2));
|
addrData.streets = encodeURIComponent(addrData.streets.slice(0, -2))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -165,119 +177,420 @@ const go = async () => {
|
|||||||
nmKotamadyaKel: addrData.city_text,
|
nmKotamadyaKel: addrData.city_text,
|
||||||
nmKecamatanKel: addrData.district_text,
|
nmKecamatanKel: addrData.district_text,
|
||||||
nmKelurahan: addrData.village_text,
|
nmKelurahan: addrData.village_text,
|
||||||
});
|
})
|
||||||
if (byAll.length > 1) {
|
if (byAll.length > 1) {
|
||||||
addrData.state_id = byAll[0].kodeProv;
|
addrData.state_id = byAll[0].kodeProv
|
||||||
addrData.city_id = byAll[0].kodeKab;
|
addrData.city_id = byAll[0].kodeKab
|
||||||
addrData.district_id = byAll[0].kodeKec;
|
addrData.district_id = byAll[0].kodeKec
|
||||||
addrData.village_id = byAll[0].kodeKel;
|
addrData.village_id = byAll[0].kodeKel
|
||||||
}
|
}
|
||||||
|
|
||||||
let byKel = await RegionModels.whereLike({
|
let byKel = await RegionModels.whereLike({
|
||||||
nmKelurahan: addrData.village_text,
|
nmKelurahan: addrData.village_text,
|
||||||
});
|
})
|
||||||
if (byAll.length < 1 && byKel.length > 0) {
|
if (byAll.length < 1 && byKel.length > 0) {
|
||||||
addrData.state_id = byKel[0].kodeProv;
|
addrData.state_id = byKel[0].kodeProv
|
||||||
addrData.city_id = byKel[0].kodeKab;
|
addrData.city_id = byKel[0].kodeKab
|
||||||
addrData.district_id = byKel[0].kodeKec;
|
addrData.district_id = byKel[0].kodeKec
|
||||||
addrData.village_id = byKel[0].kodeKel;
|
addrData.village_id = byKel[0].kodeKel
|
||||||
}
|
}
|
||||||
|
|
||||||
if (addrData.state_id === null) {
|
if (addrData.state_id === null) {
|
||||||
let byPr = await RegionModels.whereLike({ nmProvinsiKel: addrData.state_text });
|
let byPr = await RegionModels.whereLike({ nmProvinsiKel: addrData.state_text })
|
||||||
if (byPr.length > 0) {
|
if (byPr.length > 0) {
|
||||||
addrData.state_id = byPr[0].kodeProv;
|
addrData.state_id = byPr[0].kodeProv
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (addrData.state_id !== null && addrData.city_id === null) {
|
if (addrData.state_id !== null && addrData.city_id === null) {
|
||||||
let byKt = await RegionModels.whereLike({ nmKotamadyaKel: addrData.city_text });
|
let byKt = await RegionModels.whereLike({ nmKotamadyaKel: addrData.city_text })
|
||||||
if (byKt.length > 0) {
|
if (byKt.length > 0) {
|
||||||
addrData.city_id = byKt[0].kodeKab;
|
addrData.city_id = byKt[0].kodeKab
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (addrData.state_id !== null && addrData.city_id !== null && addrData.district_id === null) {
|
if (
|
||||||
let byKc = await RegionModels.whereLike({ nmKecamatanKel: addrData.district_text });
|
addrData.state_id !== null &&
|
||||||
|
addrData.city_id !== null &&
|
||||||
|
addrData.district_id === null
|
||||||
|
) {
|
||||||
|
let byKc = await RegionModels.whereLike({
|
||||||
|
nmKecamatanKel: addrData.district_text,
|
||||||
|
})
|
||||||
if (byKc.length > 0) {
|
if (byKc.length > 0) {
|
||||||
addrData.district_id = byKc[0].kodeKec;
|
addrData.district_id = byKc[0].kodeKec
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (addrData.state_id !== null && addrData.city_id !== null && addrData.district_id !== null && addrData.village_id === null) {
|
if (
|
||||||
let byKl = await RegionModels.whereLike({ nmKelurahan: addrData.village_text });
|
addrData.state_id !== null &&
|
||||||
|
addrData.city_id !== null &&
|
||||||
|
addrData.district_id !== null &&
|
||||||
|
addrData.village_id === null
|
||||||
|
) {
|
||||||
|
let byKl = await RegionModels.whereLike({ nmKelurahan: addrData.village_text })
|
||||||
if (byKl.length > 0) {
|
if (byKl.length > 0) {
|
||||||
addrData.village_id = byKl[0].kodeKel;
|
addrData.village_id = byKl[0].kodeKel
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
GpsTracksModels.create2Address(addrData).catch((e) => {
|
GpsTracksModels.create2Address(addrData).catch((e) => {
|
||||||
Logger.log("error", `${schedulerName} running_error: ${JSON.stringify(e, Object.getOwnPropertyNames(e))}`);
|
Logger.log(
|
||||||
});
|
"error",
|
||||||
updtData.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_SC;
|
`${schedulerName} running_error: ${JSON.stringify(
|
||||||
await GpsTracksModels.update2(tracks[i].id, updtData);
|
e,
|
||||||
|
Object.getOwnPropertyNames(e)
|
||||||
|
)}`
|
||||||
|
)
|
||||||
|
})
|
||||||
|
updtData.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_SC
|
||||||
|
await GpsTracksModels.update2(track.id, updtData)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
console.log("FAILED respReverseGeo:", resp.status, resp.statusText)
|
||||||
GpsTracksModels.create2Address({
|
GpsTracksModels.create2Address({
|
||||||
device_id: tracks[i].device_id,
|
device_id: track.device_id,
|
||||||
master_id: tracks[i].id,
|
master_id: track.id,
|
||||||
lat: tracks[i].latitude,
|
lat: track.latitude,
|
||||||
lng: tracks[i].longitude,
|
lng: track.longitude,
|
||||||
stts_reverse_geo: GpsTracksModels.STTS_REVERSE_GEO_ER,
|
stts_reverse_geo: GpsTracksModels.STTS_REVERSE_GEO_ER,
|
||||||
log_reverse_geo: JSON.stringify(respData),
|
log_reverse_geo: JSON.stringify(respData),
|
||||||
crt: now,
|
crt: now,
|
||||||
crt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
crt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
});
|
})
|
||||||
updtData.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_ER;
|
updtData.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_ER
|
||||||
await GpsTracksModels.update2(tracks[i].id, updtData);
|
await GpsTracksModels.update2(track.id, updtData)
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
let respData = {};
|
console.log("FAILED reverse geo for track", track.id, e.message)
|
||||||
|
let respData = {}
|
||||||
if (respReverseGeo) {
|
if (respReverseGeo) {
|
||||||
if (respReverseGeo.status != 200) {
|
if (respReverseGeo.status != 200) {
|
||||||
respData.data = respReverseGeo.data;
|
respData.data = respReverseGeo.data
|
||||||
} else {
|
} else {
|
||||||
respData.msg = e.message;
|
respData.msg = e.message
|
||||||
}
|
}
|
||||||
} else if (typeof e.response != "undefined") {
|
} else if (typeof e.response != "undefined") {
|
||||||
respData.data = e.response;
|
respData.data = e.response
|
||||||
} else {
|
} else {
|
||||||
respData.msg = e.message;
|
respData.msg = e.message
|
||||||
}
|
}
|
||||||
GpsTracksModels.create2Address({
|
GpsTracksModels.create2Address({
|
||||||
device_id: tracks[i].device_id,
|
device_id: track.device_id,
|
||||||
master_id: tracks[i].id,
|
master_id: track.id,
|
||||||
lat: tracks[i].latitude,
|
lat: track.latitude,
|
||||||
lng: tracks[i].longitude,
|
lng: track.longitude,
|
||||||
stts_reverse_geo: GpsTracksModels.STTS_REVERSE_GEO_ER,
|
stts_reverse_geo: GpsTracksModels.STTS_REVERSE_GEO_ER,
|
||||||
// log_reverse_geo: JSON.stringify(respData.data),
|
// log_reverse_geo: JSON.stringify(respData.data),
|
||||||
log_reverse_geo: stringify(respData.data),
|
log_reverse_geo: stringify(respData.data),
|
||||||
crt: now,
|
crt: now,
|
||||||
crt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
crt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
});
|
})
|
||||||
updtData.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_ER;
|
updtData.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_ER
|
||||||
await GpsTracksModels.update2(tracks[i].id, updtData);
|
await GpsTracksModels.update2(track.id, updtData)
|
||||||
}
|
}
|
||||||
|
})()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await Promise.allSettled(tracks.map(processTrack))
|
||||||
|
|
||||||
|
// for (let i = 0; i < tracks.length; i++) {
|
||||||
|
// const track = tracks[i]
|
||||||
|
// console.log("tracks[i] :", track.id, track.device_id, track.latitude, track.longitude)
|
||||||
|
// let now = moment().unix()
|
||||||
|
// let updtData = {}
|
||||||
|
// let respReverseGeo = null
|
||||||
|
// try {
|
||||||
|
// const sameAddr = await GpsTracksModels.select2Address(track.latitude, track.longitude)
|
||||||
|
|
||||||
|
// if (sameAddr.length > 0) {
|
||||||
|
// let addrData = {
|
||||||
|
// device_id: track.device_id,
|
||||||
|
// master_id: track.id,
|
||||||
|
// type: sameAddr[0].type,
|
||||||
|
// lat: track.latitude,
|
||||||
|
// lng: track.longitude,
|
||||||
|
// country_id: sameAddr[0].country_id,
|
||||||
|
// country_code: sameAddr[0].country_code,
|
||||||
|
// country_text: sameAddr[0].country_text,
|
||||||
|
// state_id: sameAddr[0].state_id,
|
||||||
|
// state_text: sameAddr[0].state_text,
|
||||||
|
// city_id: sameAddr[0].city_id,
|
||||||
|
// city_text: sameAddr[0].city_text,
|
||||||
|
// district_id: sameAddr[0].district_id,
|
||||||
|
// district_text: sameAddr[0].district_text,
|
||||||
|
// village_id: sameAddr[0].village_id,
|
||||||
|
// village_text: sameAddr[0].village_text,
|
||||||
|
// postcode: sameAddr[0].postcode,
|
||||||
|
// streets: sameAddr[0].streets,
|
||||||
|
// fulladdress: encodeURIComponent(decodeURIComponent(sameAddr[0].fulladdress)),
|
||||||
|
// type_reverse_geo: sameAddr[0].type_reverse_geo,
|
||||||
|
// stts_reverse_geo: GpsTracksModels.STTS_REVERSE_GEO_SC,
|
||||||
|
// log_reverse_geo: sameAddr[0].log_reverse_geo,
|
||||||
|
// crt: now,
|
||||||
|
// crt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
// }
|
||||||
|
// GpsTracksModels.create2Address(addrData)
|
||||||
|
// updtData.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_SC
|
||||||
|
// await GpsTracksModels.update2(track.id, updtData)
|
||||||
|
// continue
|
||||||
|
// }
|
||||||
|
|
||||||
|
// let params = new url.URLSearchParams({
|
||||||
|
// lat: track.latitude,
|
||||||
|
// lon: track.longitude,
|
||||||
|
// format: "geojson",
|
||||||
|
// })
|
||||||
|
// //const axInstance = axios.create()
|
||||||
|
// const axInstance = axios.create({
|
||||||
|
// proxy: {
|
||||||
|
// host: process.env.PROXY_URL,
|
||||||
|
// port: process.env.PROXY_PORT,
|
||||||
|
// },
|
||||||
|
// })
|
||||||
|
// axios.defaults.timeout = 10000
|
||||||
|
// axios.defaults.crossDomain = true
|
||||||
|
// // respReverseGeo = await axios({
|
||||||
|
// // url: request.osm_reverse_geo.urlFull,
|
||||||
|
// // method: request.osm_reverse_geo.method,
|
||||||
|
// // params: params,
|
||||||
|
// // responseType: 'json',
|
||||||
|
// // });
|
||||||
|
// // respReverseGeo = await axInstance.get(request.osm_reverse_geo.urlFull + "?" + params.toString(), {
|
||||||
|
// // timeout: 10000,
|
||||||
|
// // });
|
||||||
|
// respReverseGeo = await axInstance.get(
|
||||||
|
// request.osm_reverse_geo.urlFull + "?" + params.toString(),
|
||||||
|
// {
|
||||||
|
// timeout: 10000,
|
||||||
|
// headers: {
|
||||||
|
// "User-Agent": "movana-fleet-management/1.0 (emirsyafmun@gmail.com)",
|
||||||
|
// },
|
||||||
|
// }
|
||||||
|
// )
|
||||||
|
// let respData = respReverseGeo.data || {}
|
||||||
|
// if (respReverseGeo.status == 200) {
|
||||||
|
// console.log("respReverseGeo: ", respData || "null")
|
||||||
|
// if (respData.features.length < 1) {
|
||||||
|
// GpsTracksModels.create2Address({
|
||||||
|
// device_id: track.device_id,
|
||||||
|
// master_id: track.id,
|
||||||
|
// lat: track.latitude,
|
||||||
|
// lng: track.longitude,
|
||||||
|
// stts_reverse_geo: GpsTracksModels.STTS_REVERSE_GEO_LOST,
|
||||||
|
// log_reverse_geo: JSON.stringify(respData),
|
||||||
|
// crt: now,
|
||||||
|
// crt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
// })
|
||||||
|
// updtData.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_LOST
|
||||||
|
// await GpsTracksModels.update2(track.id, updtData)
|
||||||
|
// } else {
|
||||||
|
// let respAddr = respData.features[0].properties.address
|
||||||
|
// let addrData = {
|
||||||
|
// device_id: track.device_id,
|
||||||
|
// master_id: track.id,
|
||||||
|
// lat: track.latitude,
|
||||||
|
// lng: track.longitude,
|
||||||
|
// country_id: GpsTracksModels.DEFAULT_COUNTRY_ID,
|
||||||
|
// country_code: respAddr.country_code,
|
||||||
|
// country_text: respAddr.country
|
||||||
|
// ? respAddr.country.toUpperCase()
|
||||||
|
// : respAddr.country || null,
|
||||||
|
// state_id: null,
|
||||||
|
// city_id: null,
|
||||||
|
// district_id: null,
|
||||||
|
// village_id: null,
|
||||||
|
// postcode: respAddr.postcode,
|
||||||
|
// fulladdress: encodeURIComponent(respData.features[0].properties.display_name),
|
||||||
|
// stts_reverse_geo: GpsTracksModels.STTS_REVERSE_GEO_SC,
|
||||||
|
// log_reverse_geo: respData.features[0].properties
|
||||||
|
// ? JSON.stringify(respData.features[0].properties)
|
||||||
|
// : null,
|
||||||
|
// crt: now,
|
||||||
|
// crt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
// }
|
||||||
|
// if (respAddr.state || respAddr.city) {
|
||||||
|
// addrData.state_text =
|
||||||
|
// respAddr.region ||
|
||||||
|
// respAddr.state ||
|
||||||
|
// respAddr.state_district ||
|
||||||
|
// respAddr.county ||
|
||||||
|
// respAddr.city ||
|
||||||
|
// ""
|
||||||
|
// addrData.state_text = addrData.state_text
|
||||||
|
// ? addrData.state_text.toUpperCase()
|
||||||
|
// : addrData.state_text || null
|
||||||
|
// addrData.state_text = addrData.state_text || null
|
||||||
|
// }
|
||||||
|
// if (respAddr.city_district || respAddr.city) {
|
||||||
|
// addrData.city_text = respAddr.city_district || respAddr.city || ""
|
||||||
|
// addrData.city_text = addrData.city_text
|
||||||
|
// ? addrData.city_text.toUpperCase()
|
||||||
|
// : addrData.city_text || null
|
||||||
|
// addrData.city_text = addrData.city_text || null
|
||||||
|
// }
|
||||||
|
// if (respAddr.suburb || respAddr.subdistrict) {
|
||||||
|
// addrData.district_text =
|
||||||
|
// respAddr.suburb || respAddr.subdistrict || respAddr.subdivision || ""
|
||||||
|
// addrData.district_text = addrData.district_text
|
||||||
|
// ? addrData.district_text.toUpperCase()
|
||||||
|
// : addrData.district_text || null
|
||||||
|
// addrData.district_text = addrData.district_text || null
|
||||||
|
// }
|
||||||
|
// if (respAddr.village) {
|
||||||
|
// addrData.village_text = respAddr.village || respAddr.neighbourhood || ""
|
||||||
|
// addrData.village_text = addrData.village_text
|
||||||
|
// ? addrData.village_text.toUpperCase()
|
||||||
|
// : addrData.village_text || null
|
||||||
|
// addrData.village_text = addrData.village_text || null
|
||||||
|
// }
|
||||||
|
// if (respAddr.amenity || respAddr.road || respAddr.city_block) {
|
||||||
|
// addrData.streets = ""
|
||||||
|
// addrData.streets += respAddr.amenity ? respAddr.amenity + ", " : ""
|
||||||
|
// addrData.streets += respAddr.road ? respAddr.road + ", " : ""
|
||||||
|
// addrData.streets += respAddr.house_number ? respAddr.house_number + ", " : ""
|
||||||
|
// addrData.streets += respAddr.house_name ? respAddr.house_name + ", " : ""
|
||||||
|
// addrData.streets += respAddr.city_block ? respAddr.city_block + ", " : ""
|
||||||
|
// addrData.streets += addrData.streets || null
|
||||||
|
// if (addrData.streets) {
|
||||||
|
// addrData.streets = encodeURIComponent(addrData.streets.slice(0, -2))
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// let byAll = await RegionModels.whereLike({
|
||||||
|
// nmProvinsiKel: addrData.state_text,
|
||||||
|
// nmKotamadyaKel: addrData.city_text,
|
||||||
|
// nmKecamatanKel: addrData.district_text,
|
||||||
|
// nmKelurahan: addrData.village_text,
|
||||||
|
// })
|
||||||
|
// if (byAll.length > 1) {
|
||||||
|
// addrData.state_id = byAll[0].kodeProv
|
||||||
|
// addrData.city_id = byAll[0].kodeKab
|
||||||
|
// addrData.district_id = byAll[0].kodeKec
|
||||||
|
// addrData.village_id = byAll[0].kodeKel
|
||||||
|
// }
|
||||||
|
|
||||||
|
// let byKel = await RegionModels.whereLike({
|
||||||
|
// nmKelurahan: addrData.village_text,
|
||||||
|
// })
|
||||||
|
// if (byAll.length < 1 && byKel.length > 0) {
|
||||||
|
// addrData.state_id = byKel[0].kodeProv
|
||||||
|
// addrData.city_id = byKel[0].kodeKab
|
||||||
|
// addrData.district_id = byKel[0].kodeKec
|
||||||
|
// addrData.village_id = byKel[0].kodeKel
|
||||||
|
// }
|
||||||
|
|
||||||
|
// if (addrData.state_id === null) {
|
||||||
|
// let byPr = await RegionModels.whereLike({ nmProvinsiKel: addrData.state_text })
|
||||||
|
// if (byPr.length > 0) {
|
||||||
|
// addrData.state_id = byPr[0].kodeProv
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// if (addrData.state_id !== null && addrData.city_id === null) {
|
||||||
|
// let byKt = await RegionModels.whereLike({ nmKotamadyaKel: addrData.city_text })
|
||||||
|
// if (byKt.length > 0) {
|
||||||
|
// addrData.city_id = byKt[0].kodeKab
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// if (
|
||||||
|
// addrData.state_id !== null &&
|
||||||
|
// addrData.city_id !== null &&
|
||||||
|
// addrData.district_id === null
|
||||||
|
// ) {
|
||||||
|
// let byKc = await RegionModels.whereLike({ nmKecamatanKel: addrData.district_text })
|
||||||
|
// if (byKc.length > 0) {
|
||||||
|
// addrData.district_id = byKc[0].kodeKec
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// if (
|
||||||
|
// addrData.state_id !== null &&
|
||||||
|
// addrData.city_id !== null &&
|
||||||
|
// addrData.district_id !== null &&
|
||||||
|
// addrData.village_id === null
|
||||||
|
// ) {
|
||||||
|
// let byKl = await RegionModels.whereLike({ nmKelurahan: addrData.village_text })
|
||||||
|
// if (byKl.length > 0) {
|
||||||
|
// addrData.village_id = byKl[0].kodeKel
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// GpsTracksModels.create2Address(addrData).catch((e) => {
|
||||||
|
// Logger.log(
|
||||||
|
// "error",
|
||||||
|
// `${schedulerName} running_error: ${JSON.stringify(
|
||||||
|
// e,
|
||||||
|
// Object.getOwnPropertyNames(e)
|
||||||
|
// )}`
|
||||||
|
// )
|
||||||
|
// })
|
||||||
|
// updtData.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_SC
|
||||||
|
// await GpsTracksModels.update2(track.id, updtData)
|
||||||
|
// }
|
||||||
|
// } else {
|
||||||
|
// console.log("FAILED respReverseGeo: ", respReverseGeo)
|
||||||
|
// GpsTracksModels.create2Address({
|
||||||
|
// device_id: track.device_id,
|
||||||
|
// master_id: track.id,
|
||||||
|
// lat: track.latitude,
|
||||||
|
// lng: track.longitude,
|
||||||
|
// stts_reverse_geo: GpsTracksModels.STTS_REVERSE_GEO_ER,
|
||||||
|
// log_reverse_geo: JSON.stringify(respData),
|
||||||
|
// crt: now,
|
||||||
|
// crt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
// })
|
||||||
|
// updtData.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_ER
|
||||||
|
// await GpsTracksModels.update2(track.id, updtData)
|
||||||
|
// }
|
||||||
|
// } catch (e) {
|
||||||
|
// let respData = {}
|
||||||
|
// if (respReverseGeo) {
|
||||||
|
// if (respReverseGeo.status != 200) {
|
||||||
|
// respData.data = respReverseGeo.data
|
||||||
|
// } else {
|
||||||
|
// respData.msg = e.message
|
||||||
|
// }
|
||||||
|
// } else if (typeof e.response != "undefined") {
|
||||||
|
// respData.data = e.response
|
||||||
|
// } else {
|
||||||
|
// respData.msg = e.message
|
||||||
|
// }
|
||||||
|
// GpsTracksModels.create2Address({
|
||||||
|
// device_id: tracks[i].device_id,
|
||||||
|
// master_id: tracks[i].id,
|
||||||
|
// lat: tracks[i].latitude,
|
||||||
|
// lng: tracks[i].longitude,
|
||||||
|
// stts_reverse_geo: GpsTracksModels.STTS_REVERSE_GEO_ER,
|
||||||
|
// // log_reverse_geo: JSON.stringify(respData.data),
|
||||||
|
// log_reverse_geo: stringify(respData.data),
|
||||||
|
// crt: now,
|
||||||
|
// crt_format: moment.unix(now).format("YYYY-MM-DD HH:mm:ss"),
|
||||||
|
// })
|
||||||
|
// updtData.stts_reverse_geo = GpsTracksModels.STTS_REVERSE_GEO_ER
|
||||||
|
// await GpsTracksModels.update2(tracks[i].id, updtData)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e)
|
||||||
Logger.log("error", `${schedulerName} error: ${JSON.stringify(e)}`);
|
Logger.log("error", `${schedulerName} error: ${JSON.stringify(e)}`)
|
||||||
}
|
}
|
||||||
// })();
|
// })();
|
||||||
|
|
||||||
Logger.log("info", `${schedulerName} success do reverse geocoding ${moment().format("YYYY-MM-DD HH:mm:ss")}`);
|
Logger.log("info", `${schedulerName} success do reverse geocoding ${moment().format("YYYY-MM-DD HH:mm:ss")}`)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
Logger.log("error", `${schedulerName} error: ${JSON.stringify(e)}`);
|
Logger.log("error", `${schedulerName} error: ${JSON.stringify(e)}`)
|
||||||
|
}
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
return true;
|
|
||||||
};
|
|
||||||
|
|
||||||
const index = async () => {
|
const index = async () => {
|
||||||
while (1 == 1) {
|
while (1 == 1) {
|
||||||
await go();
|
await go()
|
||||||
await new Promise((r) => setTimeout(r, 300));
|
await new Promise((r) => setTimeout(r, 1000))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
|
||||||
index();
|
index()
|
||||||
|
|||||||
274
cron/TripsWorker.js
Normal file
274
cron/TripsWorker.js
Normal file
@ -0,0 +1,274 @@
|
|||||||
|
const path = require("path")
|
||||||
|
require("dotenv").config({ path: path.resolve(__dirname, "../.env") })
|
||||||
|
|
||||||
|
const cron = require("node-cron")
|
||||||
|
const db = require("../config/dbConnCron")
|
||||||
|
const moment = require("moment")
|
||||||
|
const TIMEFIX = 25200
|
||||||
|
|
||||||
|
cron.schedule("0 0 * * * *", job)
|
||||||
|
cron.schedule("*/5 * * * *", tripGrouping)
|
||||||
|
// job()
|
||||||
|
// tripGrouping()
|
||||||
|
|
||||||
|
async function job() {
|
||||||
|
console.log("Monthly table job executed:", moment().format("YYYY-MM-DD HH:mm:ss"))
|
||||||
|
const currentDate = moment()
|
||||||
|
const lasYearDate = currentDate.clone().subtract(1, "years")
|
||||||
|
const databaseName = process.env.DATABASE
|
||||||
|
|
||||||
|
for (let i = 0; i <= 14; i++) {
|
||||||
|
const targetMonth = lasYearDate.clone().add(i, "months")
|
||||||
|
const yy = targetMonth.format("YY") // Two-digit year
|
||||||
|
const mm = targetMonth.format("MM") // Two-digit month
|
||||||
|
const tableName = `tracks_${yy}${mm}`
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Check if table exists
|
||||||
|
console.log(`Checking existence of table '${tableName}'...`)
|
||||||
|
const checkQuery = `
|
||||||
|
SELECT TABLE_NAME
|
||||||
|
FROM information_schema.TABLES
|
||||||
|
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?
|
||||||
|
`
|
||||||
|
const checkParams = [databaseName, tableName]
|
||||||
|
const existenceResult = await db.query(checkQuery, checkParams)
|
||||||
|
|
||||||
|
if (existenceResult.length === 0) {
|
||||||
|
// Table does not exist; create it
|
||||||
|
const createQuery = `
|
||||||
|
CREATE TABLE ${tableName} (
|
||||||
|
id bigint NOT NULL AUTO_INCREMENT,
|
||||||
|
original_hex text,
|
||||||
|
protocol enum('gt06','tk119','smartphone') DEFAULT NULL,
|
||||||
|
action enum('login','heartbeat','location','alarm','other') DEFAULT NULL,
|
||||||
|
device_id varchar(16) DEFAULT NULL,
|
||||||
|
latitude double DEFAULT NULL,
|
||||||
|
longitude double DEFAULT NULL,
|
||||||
|
speed int DEFAULT NULL COMMENT 'km/h',
|
||||||
|
orientation int NOT NULL DEFAULT '0' COMMENT 'in 360 degrees',
|
||||||
|
ignition int NOT NULL DEFAULT '0' COMMENT 'pengapian. 1=>on, 2=>off, 3=>acc_low, 4=>acc_high',
|
||||||
|
stts_engine int NOT NULL DEFAULT '0' COMMENT '1=>idling, 2=>moving, 3=>stopping',
|
||||||
|
stts_gps int NOT NULL DEFAULT '0' COMMENT '1=>on, 2=>off',
|
||||||
|
length_gps int NOT NULL DEFAULT '0' COMMENT 'length of GPS information,',
|
||||||
|
pos_stlt_gps int NOT NULL DEFAULT '0' COMMENT 'quantity of positioning satellites',
|
||||||
|
pos_type_gps int NOT NULL DEFAULT '0' COMMENT 'GPS real-time/differential positioning. 1=>diff_positioning,2=>realtime_positioning',
|
||||||
|
is_pos_gps int NOT NULL DEFAULT '0' COMMENT 'GPS having been positioning or not. 1=>not,2=>positioning',
|
||||||
|
stts_gsm int NOT NULL DEFAULT '0' COMMENT '1=>no signal, 2=>extremely weak signal 3=>very weak signal, 4=>good signal, 5=>strong signal',
|
||||||
|
stts_oil_electricity int NOT NULL DEFAULT '0' COMMENT '1=>on, 2=>off',
|
||||||
|
stts_alarm int NOT NULL DEFAULT '0' COMMENT '1=>normal,2=>shock,3=>power_cut,4=>low_battery,5=>sos',
|
||||||
|
stts_charge int NOT NULL DEFAULT '0' COMMENT '1=>off,2=>on',
|
||||||
|
stts_acc int NOT NULL DEFAULT '0' COMMENT '1=>low,2=>high',
|
||||||
|
stts_volt int NOT NULL DEFAULT '0' COMMENT '1=>shutdown,2=>extreme_low_battery,3=>very_low_batter,4=>low_battery,5=>medium,6=>high,7=>very_high',
|
||||||
|
stts_switch int NOT NULL DEFAULT '0' COMMENT '1=>off, 2=>on',
|
||||||
|
stts_reverse_geo int NOT NULL DEFAULT '0' COMMENT '1=>success, 2=>not, 3=>error, 4=>lost',
|
||||||
|
pre_milleage double NOT NULL DEFAULT '0' COMMENT 'in km. distance from prev to now',
|
||||||
|
sum_milleage double NOT NULL DEFAULT '0' COMMENT 'in km. summary device milleage. calculated based on this device',
|
||||||
|
vhc_milleage double NOT NULL DEFAULT '0' COMMENT 'in km. summary vhc milleage. calculated based on vhc, every change vhc this will get last milleage on that vhc',
|
||||||
|
drv_milleage double NOT NULL DEFAULT '0' COMMENT 'in km. summary drv milleage. calculated based on drv, every change drv this will get last milleage on that drv',
|
||||||
|
vhc_id int NOT NULL DEFAULT '0',
|
||||||
|
drv_id int NOT NULL DEFAULT '0',
|
||||||
|
source int NOT NULL DEFAULT '1' COMMENT '1=>gps_tracker, 2=>smartphone',
|
||||||
|
crt int NOT NULL,
|
||||||
|
crt_format datetime NOT NULL,
|
||||||
|
crt_d int NOT NULL DEFAULT '0' COMMENT 'from device/terminal',
|
||||||
|
crt_d_format datetime DEFAULT NULL,
|
||||||
|
crt_s int NOT NULL DEFAULT '0' COMMENT 'from server (receive time)',
|
||||||
|
crt_s_format datetime DEFAULT NULL,
|
||||||
|
crt_device_raw bigint DEFAULT '0' COMMENT 'device raw time',
|
||||||
|
daily_trip_id int unsigned DEFAULT NULL,
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
KEY tracks_device_id (device_id),
|
||||||
|
KEY tracks_vhc_id (vhc_id),
|
||||||
|
KEY tracks_drv_id (drv_id),
|
||||||
|
KEY idx_crt_d (crt_d),
|
||||||
|
KEY idx_vhc_crt_d (vhc_id,crt_d),
|
||||||
|
KEY idx_vhc_id_engine (vhc_id,stts_engine),
|
||||||
|
KEY idx_vhc_lat_long_crt (vhc_id,latitude,longitude,crt),
|
||||||
|
KEY idx_geo_stts_id (stts_reverse_geo,latitude,longitude,id),
|
||||||
|
KEY idx_gps_valid_geo (latitude,longitude,stts_reverse_geo),
|
||||||
|
KEY idx_gps_order (id),
|
||||||
|
KEY t_gps_tracks_latitude_IDX (latitude,longitude,vhc_id,crt_d,action) USING BTREE,
|
||||||
|
KEY t_gps_tracks_crt_s_IDX (crt_s,action) USING BTREE,
|
||||||
|
KEY t_gps_tracks_stts_reverse_geo_IDX (stts_reverse_geo,action,id,latitude,longitude) USING BTREE
|
||||||
|
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4;
|
||||||
|
`
|
||||||
|
const createParams = [] // No parameters for this CREATE statement
|
||||||
|
await db.query(createQuery, createParams)
|
||||||
|
console.log(`Table '${tableName}' created successfully.`)
|
||||||
|
} else {
|
||||||
|
console.log(`Table '${tableName}' already exists.`)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Error processing table '${tableName}':`, error.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// drop tables older than 12 months
|
||||||
|
const dropMonth = currentDate.clone().subtract(13, "months")
|
||||||
|
const dropYy = dropMonth.format("YY")
|
||||||
|
const dropMm = dropMonth.format("MM")
|
||||||
|
const dropTableName = `tracks_${dropYy}${dropMm}`
|
||||||
|
|
||||||
|
try {
|
||||||
|
const dropQuery = `DROP TABLE IF EXISTS ${dropTableName}`
|
||||||
|
await db.query(dropQuery, [])
|
||||||
|
console.log(`Table '${dropTableName}' dropped successfully (if it existed).`)
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Error dropping table '${dropTableName}':`, error.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
// insert prev data
|
||||||
|
for (let i = 0; i <= 12; i++) {
|
||||||
|
const histMonth = lasYearDate.clone().add(i, "months")
|
||||||
|
const histYy = histMonth.format("YY")
|
||||||
|
const histMm = histMonth.format("MM")
|
||||||
|
const histTableName = `tracks_${histYy}${histMm}`
|
||||||
|
console.log(`Processing history insertion for table '${histTableName}'...`)
|
||||||
|
|
||||||
|
try {
|
||||||
|
// const q1 = `SELECT count(*) jmlData FROM ${histTableName}`
|
||||||
|
// const r1 = await db.query(q1)
|
||||||
|
// const jmlData = r1[0].jmlData
|
||||||
|
// if (jmlData == 0) {
|
||||||
|
const startOfMonth = histMonth.clone().startOf("month").unix() - TIMEFIX
|
||||||
|
const endOfMonth = histMonth.clone().endOf("month").unix() - TIMEFIX
|
||||||
|
console.log(
|
||||||
|
`Inserting data into history table '${histTableName}' for records from ${startOfMonth} to ${endOfMonth}`
|
||||||
|
)
|
||||||
|
|
||||||
|
const q2 = `
|
||||||
|
INSERT INTO ${histTableName}
|
||||||
|
SELECT *, null FROM t_gps_tracks a
|
||||||
|
WHERE
|
||||||
|
crt_d < ? AND crt_d >= ?
|
||||||
|
and action = 'location'
|
||||||
|
and not exists (
|
||||||
|
select 1 from ${histTableName} b
|
||||||
|
where b.id = a.id
|
||||||
|
)
|
||||||
|
`
|
||||||
|
const d2 = [endOfMonth, startOfMonth]
|
||||||
|
const r2 = await db.query(q2, d2)
|
||||||
|
console.log(`Inserted ${r2.affectedRows} rows into '${histTableName}'`)
|
||||||
|
// } else {
|
||||||
|
// console.log(`Table '${histTableName}' already has data (${jmlData} rows). Skipping insertion.`)
|
||||||
|
// }
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Error inserting data into history table '${histTableName}':`, error.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log("Monthly table job completed.")
|
||||||
|
}
|
||||||
|
|
||||||
|
async function tripGrouping() {
|
||||||
|
console.log("Trip grouping job executed:", moment().format("YYYY-MM-DD HH:mm:ss"))
|
||||||
|
for (let i = 0; i <= 1; i++) {
|
||||||
|
const lastMonth = moment().subtract(1, "months")
|
||||||
|
const histMonth = lastMonth.clone().add(i, "months")
|
||||||
|
const histYy = histMonth.format("YY")
|
||||||
|
const histMm = histMonth.format("MM")
|
||||||
|
const histTableName = `tracks_${histYy}${histMm}`
|
||||||
|
console.log(`Processing history insertion for table '${histTableName}'...`)
|
||||||
|
|
||||||
|
try {
|
||||||
|
console.time(`Trip grouping for ${histTableName}`)
|
||||||
|
const startOfMonth = histMonth.clone().startOf("month").unix() - TIMEFIX
|
||||||
|
const endOfMonth = histMonth.clone().endOf("month").unix() - TIMEFIX
|
||||||
|
|
||||||
|
const q2 = `
|
||||||
|
insert into trips
|
||||||
|
(id,name,nopol1,vhc_id,mileage,start,finish,startMileage,finishMileage,startLoc,finishLoc,pool_code,dc_code,row_count)
|
||||||
|
WITH
|
||||||
|
gaps AS (
|
||||||
|
SELECT
|
||||||
|
-- previous gap since previous row > 1 hour (3600s)
|
||||||
|
CASE
|
||||||
|
WHEN (crt_d - LAG(crt_d, 1, NULL) OVER (PARTITION BY vhc_id ORDER BY crt_d)) > 3600
|
||||||
|
THEN 1 ELSE 0
|
||||||
|
END AS isStop,
|
||||||
|
t.*
|
||||||
|
FROM ${histTableName} t
|
||||||
|
WHERE
|
||||||
|
t.latitude IS NOT NULL
|
||||||
|
AND t.longitude IS NOT NULL
|
||||||
|
AND t.action = 'location'
|
||||||
|
AND t.crt_d BETWEEN ? AND ?
|
||||||
|
)
|
||||||
|
, trips AS (
|
||||||
|
SELECT
|
||||||
|
-- mark the start of a trip when ignition=4 and previous ignition <> 4
|
||||||
|
CASE
|
||||||
|
WHEN ignition = 4
|
||||||
|
AND LAG(ignition, 1, 0) OVER (PARTITION BY vhc_id ORDER BY crt_d) <> 4
|
||||||
|
or LAG(isStop, 1, 0) over (PARTITION BY vhc_id ORDER BY crt_d) = 1
|
||||||
|
THEN 1 ELSE 0
|
||||||
|
END AS trip_start,
|
||||||
|
g.*
|
||||||
|
FROM gaps g
|
||||||
|
)
|
||||||
|
, numbered AS (
|
||||||
|
SELECT
|
||||||
|
*,
|
||||||
|
-- assign a trip_id by cumulative sum of trip_start
|
||||||
|
SUM(trip_start) OVER (PARTITION BY vhc_id ORDER BY crt_d) AS trip_id
|
||||||
|
FROM trips
|
||||||
|
where
|
||||||
|
ignition = 4
|
||||||
|
and isStop = 0
|
||||||
|
),
|
||||||
|
agg AS (
|
||||||
|
SELECT
|
||||||
|
v.id,
|
||||||
|
v.name,
|
||||||
|
v.nopol1,
|
||||||
|
vhc_id,
|
||||||
|
ROW_NUMBER() OVER (PARTITION BY v.id ORDER BY MIN(a.crt_d)) AS trip_id,
|
||||||
|
SUM(pre_milleage) AS mileage,
|
||||||
|
MIN(a.crt_d) AS start,
|
||||||
|
MAX(a.crt_d) AS finish,
|
||||||
|
MIN(a.vhc_milleage) AS startMileage,
|
||||||
|
MAX(a.vhc_milleage) AS finishMileage,
|
||||||
|
(SELECT fulladdress FROM t_gps_tracks_address WHERE master_id = MIN(a.id) LIMIT 1) AS startLoc,
|
||||||
|
(SELECT fulladdress FROM t_gps_tracks_address WHERE master_id = MAX(a.id) LIMIT 1) AS finishLoc,
|
||||||
|
COUNT(*) AS row_count
|
||||||
|
FROM t_vehicles v
|
||||||
|
LEFT JOIN numbered a ON a.vhc_id = v.id
|
||||||
|
WHERE
|
||||||
|
v.dlt is null and trip_id != 0
|
||||||
|
GROUP BY v.id, a.trip_id
|
||||||
|
HAVING COUNT(*) > 1
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
agg.id,name,nopol1,vhc_id,mileage,start,finish,startMileage,finishMileage,startLoc,finishLoc,
|
||||||
|
tvd.pool_code, tvd.dc_code,
|
||||||
|
row_count
|
||||||
|
FROM agg agg
|
||||||
|
join t_vehicles_detail tvd on tvd.vid = agg.id
|
||||||
|
ORDER BY agg.id, trip_id
|
||||||
|
ON DUPLICATE KEY UPDATE
|
||||||
|
mileage = values(mileage),
|
||||||
|
start = values(start),
|
||||||
|
finish = values(finish),
|
||||||
|
startMileage = values(startMileage),
|
||||||
|
finishMileage = values(finishMileage),
|
||||||
|
startLoc = values(startLoc),
|
||||||
|
finishLoc = values(finishLoc),
|
||||||
|
row_count = values(row_count)
|
||||||
|
`
|
||||||
|
const d2 = [startOfMonth, endOfMonth]
|
||||||
|
const r2 = await db.query(q2, d2)
|
||||||
|
console.log(`Inserted ${r2.affectedRows} rows into 'trips' table from '${histTableName}'`)
|
||||||
|
console.timeEnd(`Trip grouping for ${histTableName}`)
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Error inserting data into history table '${histTableName}':`, error.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log("Trip grouping job completed.")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep the process running
|
||||||
|
// console.log("Cron scheduler ")
|
||||||
|
process.on("SIGINT", () => {
|
||||||
|
console.log("Stopping cron scheduler...")
|
||||||
|
process.exit(0)
|
||||||
|
})
|
||||||
@ -1,5 +1,8 @@
|
|||||||
const LibHelper = require("./LibHelper");
|
const LibHelper = require("./LibHelper");
|
||||||
|
|
||||||
|
// Menyimpan status per device untuk mendeteksi cache
|
||||||
|
const deviceStates = {};
|
||||||
|
|
||||||
class LibDevice {
|
class LibDevice {
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
@ -21,199 +24,110 @@ class LibDevice {
|
|||||||
ori_string: data,
|
ori_string: data,
|
||||||
};
|
};
|
||||||
|
|
||||||
// eelinkCustom
|
|
||||||
if (opts.isEelinkCustom) {
|
if (opts.isEelinkCustom) {
|
||||||
me.protocol_name = "eelinkCustom";
|
me.protocol_name = "eelinkCustom";
|
||||||
|
me.field0 = data.slice(0, 2);
|
||||||
me.field0 = data.slice(0, 2); // system status flag
|
me.field1 = data.slice(2, 18);
|
||||||
me.field1 = data.slice(2, 18); // IMEI
|
me.field2 = data.slice(18, 34);
|
||||||
me.field2 = data.slice(18, 34); // IMSI
|
me.field3 = data.slice(34, 42);
|
||||||
me.field3 = data.slice(34, 42); // Time
|
me.field4 = data.slice(42, 58);
|
||||||
me.field4 = data.slice(42, 58); // Location
|
me.field5 = data.slice(58, 62);
|
||||||
me.field5 = data.slice(58, 62); // Altitude
|
me.field6 = data.slice(62, 66);
|
||||||
me.field6 = data.slice(62, 66); // Heading
|
me.field7 = data.slice(66, 68);
|
||||||
me.field7 = data.slice(66, 68); // Velocity
|
me.field8 = data.slice(68, 70);
|
||||||
me.field8 = data.slice(68, 70); // Power Input Voltage
|
me.field9 = data.slice(70, 72);
|
||||||
me.field9 = data.slice(70, 72); // GPIO Status
|
me.field10 = data.slice(72, 74);
|
||||||
me.field10 = data.slice(72, 74); // Time Seconds
|
me.field11 = data.slice(74, 76);
|
||||||
me.field11 = data.slice(74, 76); // RSSI
|
me.field12 = data.slice(76, 78);
|
||||||
me.field12 = data.slice(76, 78); // Sequence Counter
|
me.field13 = data.slice(78, 80);
|
||||||
me.field13 = data.slice(78, 80); // Vendor ID
|
me.field14 = data.slice(80, 82);
|
||||||
me.field14 = data.slice(80, 82); // GPS Satellites
|
me.field15 = data.slice(82, 90);
|
||||||
me.field15 = data.slice(82, 90); // Accumulators
|
|
||||||
|
|
||||||
me.ori_string = data;
|
me.ori_string = data;
|
||||||
}
|
} else if (data.slice(0, 4) == "7878" || data.slice(0, 4) == "7979") {
|
||||||
// gt06
|
|
||||||
else if (data.slice(0, 4) == "7878" || data.slice(0, 4) == "7979") {
|
|
||||||
me.protocol_name = "gt06";
|
me.protocol_name = "gt06";
|
||||||
|
|
||||||
me.start = data.slice(0, 4);
|
me.start = data.slice(0, 4);
|
||||||
me.length = parseInt(data.slice(4, 6), 16);
|
me.length = parseInt(data.slice(4, 6), 16);
|
||||||
me.protocol_id = data.slice(6, 8);
|
me.protocol_id = data.slice(6, 8);
|
||||||
me.serial_number = data.slice(-12, -8);
|
me.serial_number = data.slice(-12, -8);
|
||||||
me.error_check = data.slice(-8, -4);
|
me.error_check = data.slice(-8, -4);
|
||||||
me.finish = data.slice(-4); // data.substr(6 + me.length * 2, 4);
|
me.finish = data.slice(-4);
|
||||||
|
|
||||||
if (me.finish != "0d0a") {
|
if (me.finish != "0d0a") {
|
||||||
throw "finish code incorrect!";
|
throw "finish code incorrect!";
|
||||||
}
|
}
|
||||||
|
|
||||||
me.ori_string = data;
|
me.ori_string = data;
|
||||||
}
|
} else if (data.slice(0, 4) == "6868") {
|
||||||
// gt02a
|
|
||||||
else if (data.slice(0, 4) == "6868") {
|
|
||||||
me.protocol_name = "gt02a";
|
me.protocol_name = "gt02a";
|
||||||
}
|
} else if (data.slice(0, 4) == "6767") {
|
||||||
// tk103
|
|
||||||
// else if (data.indexOf("B")) {
|
|
||||||
// me.protocol_name = 'tk103';
|
|
||||||
// }
|
|
||||||
// eelink
|
|
||||||
else if (data.slice(0, 4) == "6767") {
|
|
||||||
me.protocol_name = "eelink";
|
me.protocol_name = "eelink";
|
||||||
|
|
||||||
me.start = data.slice(0, 4);
|
me.start = data.slice(0, 4);
|
||||||
me.pid = data.slice(4, 6);
|
me.pid = data.slice(4, 6);
|
||||||
me.size = parseInt(data.slice(6, 10), 16);
|
me.size = parseInt(data.slice(6, 10), 16);
|
||||||
me.sequence = parseInt(data.slice(10, 4), 16);
|
me.sequence = parseInt(data.slice(10, 4), 16);
|
||||||
|
|
||||||
me.ori_string = data;
|
me.ori_string = data;
|
||||||
}
|
} else {
|
||||||
// unknown
|
|
||||||
else {
|
|
||||||
me.protocol_name = "unknown";
|
me.protocol_name = "unknown";
|
||||||
}
|
}
|
||||||
|
|
||||||
return me;
|
return me;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* @param {Object} me
|
|
||||||
* @param {String} device_id
|
|
||||||
* @returns
|
|
||||||
* must return at least => act.cmd,act.action_type,act.device_id
|
|
||||||
*/
|
|
||||||
static gt06Action(me, device_id = null) {
|
static gt06Action(me, device_id = null) {
|
||||||
const act = {};
|
const act = {};
|
||||||
|
|
||||||
// Login message
|
|
||||||
if (me.protocol_id == "01") {
|
if (me.protocol_id == "01") {
|
||||||
act.action_type = "login";
|
act.action_type = "login";
|
||||||
|
|
||||||
act.cmd = "login_request";
|
act.cmd = "login_request";
|
||||||
act.action = "login_request";
|
act.action = "login_request";
|
||||||
act.device_id = me.ori_string.slice(8).slice(0, 16).padStart(16, "0");
|
act.device_id = me.ori_string.slice(8).slice(0, 16).padStart(16, "0");
|
||||||
|
|
||||||
act.buffer_resp = LibDevice.gt06AuthorizeResp(me);
|
act.buffer_resp = LibDevice.gt06AuthorizeResp(me);
|
||||||
}
|
} else if (me.protocol_id == "12" || me.protocol_id == "a0") {
|
||||||
// Location data
|
|
||||||
else if (me.protocol_id == "12" || me.protocol_id == "a0") {
|
|
||||||
act.action_type = "location";
|
act.action_type = "location";
|
||||||
|
|
||||||
act.cmd = "ping";
|
act.cmd = "ping";
|
||||||
act.action = "ping";
|
act.action = "ping";
|
||||||
act.device_id = device_id; // because device_id only sent when login
|
act.device_id = device_id;
|
||||||
|
|
||||||
// content data
|
|
||||||
// me.ori_string.slice(8).slice(0, 52); // me.ori_string.substr(8, me.length * 2);
|
|
||||||
|
|
||||||
// gps information
|
|
||||||
act.gps_string = me.ori_string.slice(8).slice(0, 36);
|
act.gps_string = me.ori_string.slice(8).slice(0, 36);
|
||||||
act.gps_data = LibDevice.gt06ParseLocation(me, act.gps_string);
|
act.gps_data = LibDevice.gt06ParseLocation(me, act.gps_string);
|
||||||
// if (!act.gps_data) {
|
|
||||||
// //Something bad happened
|
|
||||||
// _this.do_log('GPS Data can\'t be parsed. Discarding packet...');
|
|
||||||
// return false;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// lbs information
|
|
||||||
act.lbs_string = me.ori_string.slice(8).slice(36, 52);
|
act.lbs_string = me.ori_string.slice(8).slice(36, 52);
|
||||||
act.lbs_data = LibDevice.gt06ParseLbs(me, act.lbs_string);
|
act.lbs_data = LibDevice.gt06ParseLbs(me, act.lbs_string);
|
||||||
}
|
|
||||||
// Status information
|
|
||||||
else if (me.protocol_id == "13") {
|
|
||||||
act.action_type = "heartbeat";
|
|
||||||
|
|
||||||
|
// ==== Tambahan Deteksi Data Cache ====
|
||||||
|
try {
|
||||||
|
const gpsTime = new Date(act.gps_data?.date || "");
|
||||||
|
const now = new Date();
|
||||||
|
const timeDiff = Math.abs(now.getTime() - gpsTime.getTime()) / 1000;
|
||||||
|
const serialNum = parseInt(me.serial_number, 16);
|
||||||
|
const lastState = deviceStates[device_id] || {};
|
||||||
|
let isSerialBurst = false;
|
||||||
|
if (lastState.last_serial != null && lastState.last_time != null) {
|
||||||
|
const interval = (Date.now() - lastState.last_time) / 1000;
|
||||||
|
isSerialBurst = serialNum === lastState.last_serial + 1 && interval < 2;
|
||||||
|
}
|
||||||
|
act.is_cached = timeDiff > 30 || isSerialBurst;
|
||||||
|
deviceStates[device_id] = {
|
||||||
|
last_serial: serialNum,
|
||||||
|
last_time: Date.now(),
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
act.is_cached = false;
|
||||||
|
}
|
||||||
|
} else if (me.protocol_id == "13") {
|
||||||
|
act.action_type = "heartbeat";
|
||||||
act.cmd = "heartbeat";
|
act.cmd = "heartbeat";
|
||||||
act.action = "heartbeat";
|
act.action = "heartbeat";
|
||||||
act.device_id = device_id; // because device_id only sent when login
|
act.device_id = device_id;
|
||||||
|
|
||||||
// status information
|
|
||||||
act.stts_string = me.ori_string.slice(8).slice(0, 10);
|
act.stts_string = me.ori_string.slice(8).slice(0, 10);
|
||||||
act.stts_data = LibDevice.gt06ParseHeartbeat(me, act.stts_string);
|
act.stts_data = LibDevice.gt06ParseHeartbeat(me, act.stts_string);
|
||||||
|
|
||||||
act.buffer_resp = LibDevice.gt06HeartbeatResp(me);
|
act.buffer_resp = LibDevice.gt06HeartbeatResp(me);
|
||||||
}
|
|
||||||
// String information
|
|
||||||
else if (me.protocol_id == "15") {
|
|
||||||
// act.action_type = 'other'; // 'heartbeat';
|
|
||||||
// act.cmd = 'other'; // 'heartbeat';
|
|
||||||
// act.action = 'other'; // 'heartbeat';
|
|
||||||
// act.device_id = ''; // device_id; // because device_id only sent when login
|
|
||||||
|
|
||||||
act.action_type = "heartbeat";
|
|
||||||
|
|
||||||
act.cmd = "heartbeat";
|
|
||||||
act.action = "heartbeat";
|
|
||||||
act.device_id = device_id; // because device_id only sent when login
|
|
||||||
|
|
||||||
// status information
|
|
||||||
act.stts_string = me.ori_string.slice(8).slice(0, 10);
|
|
||||||
act.stts_data = LibDevice.gt06ParseHeartbeat(me, act.stts_string);
|
|
||||||
|
|
||||||
act.buffer_resp = LibDevice.gt06HeartbeatResp(me);
|
|
||||||
}
|
|
||||||
// Alarm data
|
|
||||||
else if (me.protocol_id == "16" || me.protocol_id == "18") {
|
|
||||||
act.action_type = "alarm";
|
|
||||||
|
|
||||||
act.cmd = "alarm";
|
|
||||||
act.action = "alarm";
|
|
||||||
act.device_id = device_id; // because device_id only sent when login
|
|
||||||
|
|
||||||
// content data
|
|
||||||
// me.ori_string.slice(8).slice(0, 64); // me.ori_string.substr(8, me.length * 2);
|
|
||||||
|
|
||||||
// gps information
|
|
||||||
act.gps_string = me.ori_string.slice(8).slice(0, 36);
|
|
||||||
act.gps_data = LibDevice.gt06ParseLocation(me, act.gps_string);
|
|
||||||
|
|
||||||
// lbs information
|
|
||||||
act.lbs_string = me.ori_string.slice(8).slice(36, 54);
|
|
||||||
act.lbs_data = LibDevice.gt06ParseLbs(me, act.lbs_string);
|
|
||||||
|
|
||||||
// status information
|
|
||||||
act.stts_string = me.ori_string.slice(8).slice(54, 64);
|
|
||||||
act.stts_data = LibDevice.gt06ParseStatusAlarm(me, act.stts_string);
|
|
||||||
|
|
||||||
act.buffer_resp = LibDevice.gt06AlarmResp(me);
|
|
||||||
}
|
|
||||||
// GPS, query address information by phone number
|
|
||||||
else if (me.protocol_id == "1A") {
|
|
||||||
act.action_type = "other";
|
|
||||||
|
|
||||||
act.cmd = "other";
|
|
||||||
act.action = "other";
|
|
||||||
act.device_id = "";
|
|
||||||
}
|
|
||||||
// Command information sent by the server to the terminal
|
|
||||||
else if (me.protocol_id == "80") {
|
|
||||||
act.action_type = "other";
|
|
||||||
|
|
||||||
act.cmd = "other";
|
|
||||||
act.action = "other";
|
|
||||||
act.device_id = "";
|
|
||||||
} else {
|
} else {
|
||||||
act.action_type = "other";
|
act.action_type = "other";
|
||||||
|
|
||||||
act.cmd = "other";
|
act.cmd = "other";
|
||||||
act.action = "other";
|
act.action = "other";
|
||||||
act.device_id = "";
|
act.device_id = device_id || "";
|
||||||
|
}
|
||||||
|
return act;
|
||||||
}
|
}
|
||||||
|
|
||||||
return act;
|
static gt06AuthorizeResp(me) {
|
||||||
|
return Buffer.from("787805010001d9dc0d0a", "hex");
|
||||||
}
|
}
|
||||||
|
|
||||||
static gt06AuthorizeResp(me) {
|
static gt06AuthorizeResp(me) {
|
||||||
|
|||||||
579
library/LibDevice.js_BU20250626
Normal file
579
library/LibDevice.js_BU20250626
Normal file
@ -0,0 +1,579 @@
|
|||||||
|
const LibHelper = require("./LibHelper");
|
||||||
|
|
||||||
|
class LibDevice {
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param {Buffer} buffer
|
||||||
|
* @param {Object} opts
|
||||||
|
* @returns {Object} me
|
||||||
|
* must return at least => obj.protocol_name
|
||||||
|
*/
|
||||||
|
static identifyProtocolFromBuffer(buffer, opts = {}) {
|
||||||
|
let ori_hex_str = "";
|
||||||
|
if (typeof opts.skip_buffer != "undefined" && opts.skip_buffer === true) {
|
||||||
|
ori_hex_str = buffer;
|
||||||
|
} else {
|
||||||
|
ori_hex_str = buffer.toString("hex"); // 16
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = ori_hex_str;
|
||||||
|
const me = {
|
||||||
|
ori_string: data,
|
||||||
|
};
|
||||||
|
|
||||||
|
// eelinkCustom
|
||||||
|
if (opts.isEelinkCustom) {
|
||||||
|
me.protocol_name = "eelinkCustom";
|
||||||
|
|
||||||
|
me.field0 = data.slice(0, 2); // system status flag
|
||||||
|
me.field1 = data.slice(2, 18); // IMEI
|
||||||
|
me.field2 = data.slice(18, 34); // IMSI
|
||||||
|
me.field3 = data.slice(34, 42); // Time
|
||||||
|
me.field4 = data.slice(42, 58); // Location
|
||||||
|
me.field5 = data.slice(58, 62); // Altitude
|
||||||
|
me.field6 = data.slice(62, 66); // Heading
|
||||||
|
me.field7 = data.slice(66, 68); // Velocity
|
||||||
|
me.field8 = data.slice(68, 70); // Power Input Voltage
|
||||||
|
me.field9 = data.slice(70, 72); // GPIO Status
|
||||||
|
me.field10 = data.slice(72, 74); // Time Seconds
|
||||||
|
me.field11 = data.slice(74, 76); // RSSI
|
||||||
|
me.field12 = data.slice(76, 78); // Sequence Counter
|
||||||
|
me.field13 = data.slice(78, 80); // Vendor ID
|
||||||
|
me.field14 = data.slice(80, 82); // GPS Satellites
|
||||||
|
me.field15 = data.slice(82, 90); // Accumulators
|
||||||
|
|
||||||
|
me.ori_string = data;
|
||||||
|
}
|
||||||
|
// gt06
|
||||||
|
else if (data.slice(0, 4) == "7878" || data.slice(0, 4) == "7979") {
|
||||||
|
me.protocol_name = "gt06";
|
||||||
|
|
||||||
|
me.start = data.slice(0, 4);
|
||||||
|
me.length = parseInt(data.slice(4, 6), 16);
|
||||||
|
me.protocol_id = data.slice(6, 8);
|
||||||
|
me.serial_number = data.slice(-12, -8);
|
||||||
|
me.error_check = data.slice(-8, -4);
|
||||||
|
me.finish = data.slice(-4); // data.substr(6 + me.length * 2, 4);
|
||||||
|
|
||||||
|
if (me.finish != "0d0a") {
|
||||||
|
throw "finish code incorrect!";
|
||||||
|
}
|
||||||
|
|
||||||
|
me.ori_string = data;
|
||||||
|
}
|
||||||
|
// gt02a
|
||||||
|
else if (data.slice(0, 4) == "6868") {
|
||||||
|
me.protocol_name = "gt02a";
|
||||||
|
}
|
||||||
|
// tk103
|
||||||
|
// else if (data.indexOf("B")) {
|
||||||
|
// me.protocol_name = 'tk103';
|
||||||
|
// }
|
||||||
|
// eelink
|
||||||
|
else if (data.slice(0, 4) == "6767") {
|
||||||
|
me.protocol_name = "eelink";
|
||||||
|
|
||||||
|
me.start = data.slice(0, 4);
|
||||||
|
me.pid = data.slice(4, 6);
|
||||||
|
me.size = parseInt(data.slice(6, 10), 16);
|
||||||
|
me.sequence = parseInt(data.slice(10, 4), 16);
|
||||||
|
|
||||||
|
me.ori_string = data;
|
||||||
|
}
|
||||||
|
// unknown
|
||||||
|
else {
|
||||||
|
me.protocol_name = "unknown";
|
||||||
|
}
|
||||||
|
|
||||||
|
return me;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param {Object} me
|
||||||
|
* @param {String} device_id
|
||||||
|
* @returns
|
||||||
|
* must return at least => act.cmd,act.action_type,act.device_id
|
||||||
|
*/
|
||||||
|
static gt06Action(me, device_id = null) {
|
||||||
|
const act = {};
|
||||||
|
|
||||||
|
// Login message
|
||||||
|
if (me.protocol_id == "01") {
|
||||||
|
act.action_type = "login";
|
||||||
|
|
||||||
|
act.cmd = "login_request";
|
||||||
|
act.action = "login_request";
|
||||||
|
act.device_id = me.ori_string.slice(8).slice(0, 16).padStart(16, "0");
|
||||||
|
|
||||||
|
act.buffer_resp = LibDevice.gt06AuthorizeResp(me);
|
||||||
|
}
|
||||||
|
// Location data
|
||||||
|
else if (me.protocol_id == "12" || me.protocol_id == "a0") {
|
||||||
|
act.action_type = "location";
|
||||||
|
|
||||||
|
act.cmd = "ping";
|
||||||
|
act.action = "ping";
|
||||||
|
act.device_id = device_id; // because device_id only sent when login
|
||||||
|
|
||||||
|
// content data
|
||||||
|
// me.ori_string.slice(8).slice(0, 52); // me.ori_string.substr(8, me.length * 2);
|
||||||
|
|
||||||
|
// gps information
|
||||||
|
act.gps_string = me.ori_string.slice(8).slice(0, 36);
|
||||||
|
act.gps_data = LibDevice.gt06ParseLocation(me, act.gps_string);
|
||||||
|
// if (!act.gps_data) {
|
||||||
|
// //Something bad happened
|
||||||
|
// _this.do_log('GPS Data can\'t be parsed. Discarding packet...');
|
||||||
|
// return false;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// lbs information
|
||||||
|
act.lbs_string = me.ori_string.slice(8).slice(36, 52);
|
||||||
|
act.lbs_data = LibDevice.gt06ParseLbs(me, act.lbs_string);
|
||||||
|
}
|
||||||
|
// Status information
|
||||||
|
else if (me.protocol_id == "13") {
|
||||||
|
act.action_type = "heartbeat";
|
||||||
|
|
||||||
|
act.cmd = "heartbeat";
|
||||||
|
act.action = "heartbeat";
|
||||||
|
act.device_id = device_id; // because device_id only sent when login
|
||||||
|
|
||||||
|
// status information
|
||||||
|
act.stts_string = me.ori_string.slice(8).slice(0, 10);
|
||||||
|
act.stts_data = LibDevice.gt06ParseHeartbeat(me, act.stts_string);
|
||||||
|
|
||||||
|
act.buffer_resp = LibDevice.gt06HeartbeatResp(me);
|
||||||
|
}
|
||||||
|
// String information
|
||||||
|
else if (me.protocol_id == "15") {
|
||||||
|
// act.action_type = 'other'; // 'heartbeat';
|
||||||
|
// act.cmd = 'other'; // 'heartbeat';
|
||||||
|
// act.action = 'other'; // 'heartbeat';
|
||||||
|
// act.device_id = ''; // device_id; // because device_id only sent when login
|
||||||
|
|
||||||
|
act.action_type = "heartbeat";
|
||||||
|
|
||||||
|
act.cmd = "heartbeat";
|
||||||
|
act.action = "heartbeat";
|
||||||
|
act.device_id = device_id; // because device_id only sent when login
|
||||||
|
|
||||||
|
// status information
|
||||||
|
act.stts_string = me.ori_string.slice(8).slice(0, 10);
|
||||||
|
act.stts_data = LibDevice.gt06ParseHeartbeat(me, act.stts_string);
|
||||||
|
|
||||||
|
act.buffer_resp = LibDevice.gt06HeartbeatResp(me);
|
||||||
|
}
|
||||||
|
// Alarm data
|
||||||
|
else if (me.protocol_id == "16" || me.protocol_id == "18") {
|
||||||
|
act.action_type = "alarm";
|
||||||
|
|
||||||
|
act.cmd = "alarm";
|
||||||
|
act.action = "alarm";
|
||||||
|
act.device_id = device_id; // because device_id only sent when login
|
||||||
|
|
||||||
|
// content data
|
||||||
|
// me.ori_string.slice(8).slice(0, 64); // me.ori_string.substr(8, me.length * 2);
|
||||||
|
|
||||||
|
// gps information
|
||||||
|
act.gps_string = me.ori_string.slice(8).slice(0, 36);
|
||||||
|
act.gps_data = LibDevice.gt06ParseLocation(me, act.gps_string);
|
||||||
|
|
||||||
|
// lbs information
|
||||||
|
act.lbs_string = me.ori_string.slice(8).slice(36, 54);
|
||||||
|
act.lbs_data = LibDevice.gt06ParseLbs(me, act.lbs_string);
|
||||||
|
|
||||||
|
// status information
|
||||||
|
act.stts_string = me.ori_string.slice(8).slice(54, 64);
|
||||||
|
act.stts_data = LibDevice.gt06ParseStatusAlarm(me, act.stts_string);
|
||||||
|
|
||||||
|
act.buffer_resp = LibDevice.gt06AlarmResp(me);
|
||||||
|
}
|
||||||
|
// GPS, query address information by phone number
|
||||||
|
else if (me.protocol_id == "1A") {
|
||||||
|
act.action_type = "other";
|
||||||
|
|
||||||
|
act.cmd = "other";
|
||||||
|
act.action = "other";
|
||||||
|
act.device_id = "";
|
||||||
|
}
|
||||||
|
// Command information sent by the server to the terminal
|
||||||
|
else if (me.protocol_id == "80") {
|
||||||
|
act.action_type = "other";
|
||||||
|
|
||||||
|
act.cmd = "other";
|
||||||
|
act.action = "other";
|
||||||
|
act.device_id = "";
|
||||||
|
} else {
|
||||||
|
act.action_type = "other";
|
||||||
|
|
||||||
|
act.cmd = "other";
|
||||||
|
act.action = "other";
|
||||||
|
act.device_id = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
return act;
|
||||||
|
}
|
||||||
|
|
||||||
|
static gt06AuthorizeResp(me) {
|
||||||
|
return Buffer.from("787805010001d9dc0d0a", "hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
static gt06ParseLocation(me, gps_string = null) {
|
||||||
|
if (!gps_string) {
|
||||||
|
gps_string = me.ori_string.slice(8).slice(0, 36);
|
||||||
|
}
|
||||||
|
|
||||||
|
let year = (parseInt(gps_string.slice(0, 2), 16) + "").padStart(2, 0);
|
||||||
|
year = "20" + year;
|
||||||
|
let month = (parseInt(gps_string.slice(2, 4), 16) + "").padStart(2, 0);
|
||||||
|
let day = (parseInt(gps_string.slice(4, 6), 16) + "").padStart(2, 0);
|
||||||
|
let hour = (parseInt(gps_string.slice(6, 8), 16) + "").padStart(2, 0);
|
||||||
|
let minute = (parseInt(gps_string.slice(8, 10), 16) + "").padStart(2, 0);
|
||||||
|
let second = (parseInt(gps_string.slice(10, 12), 16) + "").padStart(2, 0);
|
||||||
|
|
||||||
|
let ob1 = LibHelper.hex2bin(gps_string.slice(32, 34)); // orientation_byte1
|
||||||
|
let ob1_bit7 = ob1.slice(0, 1);
|
||||||
|
let ob1_bit6 = ob1.slice(1, 2);
|
||||||
|
let ob1_bit5 = ob1.slice(2, 3); // 0 (realtime GPS) or differential positioning
|
||||||
|
let ob1_bit4 = ob1.slice(3, 4); // 1 (GPS has been positioned)
|
||||||
|
let ob1_bit3 = ob1.slice(4, 5); // 0 (east longitude) || 1 (west longitude)
|
||||||
|
let ob1_bit2 = ob1.slice(5, 6); // 1 (north latitude) || 0 (south latitude)
|
||||||
|
let ob1_bit1 = ob1.slice(6, 7);
|
||||||
|
let ob1_bit0 = ob1.slice(7, 8);
|
||||||
|
let ob2 = LibHelper.hex2bin(gps_string.slice(34, 36)); // orientation_byte2
|
||||||
|
// let ob2_bit7 = ob2.slice(0, 1);
|
||||||
|
// let ob2_bit6 = ob2.slice(1, 2);
|
||||||
|
// let ob2_bit5 = ob2.slice(2, 3);
|
||||||
|
// let ob2_bit4 = ob2.slice(3, 4);
|
||||||
|
// let ob2_bit3 = ob2.slice(4, 5);
|
||||||
|
// let ob2_bit2 = ob2.slice(5, 6);
|
||||||
|
// let ob2_bit1 = ob2.slice(6, 7);
|
||||||
|
// let ob2_bit0 = ob2.slice(7, 8);
|
||||||
|
|
||||||
|
let lat_wind = ""; // wind direction N,S
|
||||||
|
let lng_wind = ""; // wind direction W,E
|
||||||
|
if (ob1_bit3 == 1) {
|
||||||
|
lng_wind = "W";
|
||||||
|
}
|
||||||
|
if (ob1_bit3 == 0) {
|
||||||
|
lng_wind = "E";
|
||||||
|
}
|
||||||
|
if (ob1_bit2 == 1) {
|
||||||
|
lat_wind = "N";
|
||||||
|
}
|
||||||
|
if (ob1_bit2 == 0) {
|
||||||
|
lat_wind = "S";
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
date_raw: gps_string.slice(0, 12),
|
||||||
|
date: `${year}-${month}-${day} ${hour}:${minute}:${second}`,
|
||||||
|
quantity_pos_satellites_raw: gps_string.slice(12, 14),
|
||||||
|
quantity_pos_satellites_c: parseInt(gps_string.slice(12, 13), 16), // length of gps information
|
||||||
|
quantity_pos_satellites_b: parseInt(gps_string.slice(13, 14), 16), // number of positioning satellites
|
||||||
|
realtime_dif_gps: ob1_bit5, // 0 (realtime GPS) or differential positioning
|
||||||
|
positioning_gps: ob1_bit6, // 1 (GPS has been positioned)
|
||||||
|
latitude_raw: gps_string.slice(14, 22),
|
||||||
|
longitude_raw: gps_string.slice(22, 30),
|
||||||
|
lat_wind_direction: lat_wind,
|
||||||
|
lng_wind_direction: lng_wind,
|
||||||
|
latitude: LibDevice.gt06Hex2DMM(gps_string.slice(14, 22), lat_wind),
|
||||||
|
longitude: LibDevice.gt06Hex2DMM(gps_string.slice(22, 30), lng_wind),
|
||||||
|
speed: parseInt(gps_string.slice(30, 32), 16), // km/h
|
||||||
|
orientation_raw: gps_string.slice(32, 36),
|
||||||
|
orientation: parseInt(`${ob1_bit1}${ob1_bit0}${ob2}`, 2), // -360 ~ 360 derajat
|
||||||
|
};
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// more accurate
|
||||||
|
static gt06Hex2DMM(hex, direction) {
|
||||||
|
hex = parseInt(hex, 16);
|
||||||
|
// convert hexadecimal to Degrees Minutes.m (DMM)
|
||||||
|
let a = parseInt(hex, 10); // to decimal values
|
||||||
|
let b = a / 30000.0;
|
||||||
|
let degrees = b / 60;
|
||||||
|
let minutes = b % 60;
|
||||||
|
// convert DMM to Decimal Degrees (DD)
|
||||||
|
// let d = minutes / 60
|
||||||
|
// let dd = degrees + d
|
||||||
|
// add - follow wind direction
|
||||||
|
if (direction == "S" || direction == "W" || direction == "s" || direction == "w") {
|
||||||
|
degrees = degrees * -1;
|
||||||
|
}
|
||||||
|
return degrees;
|
||||||
|
}
|
||||||
|
// ga akurat
|
||||||
|
static gt06Hex2DMM1(hex, direction) {
|
||||||
|
hex = parseInt(hex, 16);
|
||||||
|
// convert hexadecimal to Degrees Minutes.m (DMM)
|
||||||
|
let a = parseInt(hex, 10); // to decimal values
|
||||||
|
let b = a / 30000.0;
|
||||||
|
let degrees = b / 60;
|
||||||
|
let minutes = b % 60;
|
||||||
|
// convert DMM to Decimal Degrees (DD)
|
||||||
|
let d = minutes / 60;
|
||||||
|
let dd = degrees + d;
|
||||||
|
// add - follow wind direction
|
||||||
|
if (direction == "S" || direction == "W" || direction == "s" || direction == "w") {
|
||||||
|
dd = dd * -1;
|
||||||
|
}
|
||||||
|
return dd;
|
||||||
|
}
|
||||||
|
|
||||||
|
static gt06HeartbeatResp(me) {
|
||||||
|
return Buffer.from("787805130001d9dc0d0a", "hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
static gt06ParseHeartbeat(me, stts_string) {
|
||||||
|
if (!stts_string) {
|
||||||
|
stts_string = me.ori_string.slice(8).slice(0, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
let terminal_info_raw = stts_string.slice(0, 2);
|
||||||
|
let tib1 = LibHelper.hex2bin(terminal_info_raw); // terminal_info_byte1
|
||||||
|
let tib1_bit7 = tib1.slice(0, 1);
|
||||||
|
let tib1_bit6 = tib1.slice(1, 2);
|
||||||
|
let tib1_bit5 = tib1.slice(2, 3);
|
||||||
|
let tib1_bit4 = tib1.slice(3, 4);
|
||||||
|
let tib1_bit3 = tib1.slice(4, 5);
|
||||||
|
let tib1_bit2 = tib1.slice(5, 6);
|
||||||
|
let tib1_bit1 = tib1.slice(6, 7);
|
||||||
|
let tib1_bit0 = tib1.slice(7, 8);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 0: No Power (shutdown)
|
||||||
|
* 1: Extremely Low Battery (not enough for calling or sending text messages, etc.)
|
||||||
|
* 2: Very Low Battery (Low Battery Alarm)
|
||||||
|
* 3: Low Battery (can be used normally)
|
||||||
|
* 4: Medium
|
||||||
|
* 5: High
|
||||||
|
* 6: Very High
|
||||||
|
*/
|
||||||
|
let voltage_level = stts_string.slice(2, 4);
|
||||||
|
|
||||||
|
let gsm_signal_strength = stts_string.slice(4, 6);
|
||||||
|
|
||||||
|
let alarm_stts = stts_string.slice(6, 8); // former bit: terminal alarm status (suitable for alarm packet and electronic fence project)
|
||||||
|
let language = stts_string.slice(8, 10); // latter bit: the current language used in the terminal
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
terminal_info_raw: terminal_info_raw,
|
||||||
|
terminal_info_byte: tib1,
|
||||||
|
terminal_info: {
|
||||||
|
oil_electricity: tib1_bit7, // 1: oil and electricity disconnected, 0: gas oil and electricity connected
|
||||||
|
gps_tracking: tib1_bit6, // 1: GPS tracking is on, 0: GPS tracking is off
|
||||||
|
stts: `${tib1_bit5}${tib1_bit4}${tib1_bit3}`, // 100: SOS, 011: Low Battery Alarm, 010: Power Cut Alarm, 001: Shock Alarm, 000: Normal
|
||||||
|
charge: tib1_bit2, // 1: Charge On, 0: Charge Off
|
||||||
|
acc: tib1_bit1, // 1: ACC high, 0: ACC Low
|
||||||
|
is_active: tib1_bit0, // 1: Activated, 0: Deactivated
|
||||||
|
},
|
||||||
|
voltage_level,
|
||||||
|
gsm_signal_strength, // 0x00: no signal; 0x01: extremely weak signal; 0x02: very weak signal; 0x03: good signal; 0x04: strong signal.
|
||||||
|
alarm_stts, // 0x00: normal, 0x01: SOS, 0x02: Power Cut Alarm, 0x03: Shock Alarm, 0x04: Fence In Alarm, 0x05: Fence Out Alarm
|
||||||
|
language, // 0x01: Chinese, 0x02: English
|
||||||
|
};
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
static gt06ParseLbs(me, lbs_string) {
|
||||||
|
let mcc_raw = null,
|
||||||
|
mcc = null, // mobile country code
|
||||||
|
mnc_raw = null,
|
||||||
|
mnc = null, // mobile network code
|
||||||
|
lac_raw = null,
|
||||||
|
lac = null, // location area code
|
||||||
|
cellID_raw = null,
|
||||||
|
cellID = null, // cell tower id
|
||||||
|
lbs_length_raw = null,
|
||||||
|
lbs_length = null;
|
||||||
|
|
||||||
|
// from location
|
||||||
|
if (lbs_string.length == 16) {
|
||||||
|
mcc_raw = lbs_string.slice(0, 4);
|
||||||
|
mnc_raw = lbs_string.slice(4, 6);
|
||||||
|
lac_raw = lbs_string.slice(6, 10);
|
||||||
|
cellID_raw = lbs_string.slice(10, 16);
|
||||||
|
}
|
||||||
|
// from alarm
|
||||||
|
else if (lbs_string.length == 18) {
|
||||||
|
lbs_length_raw = lbs_string.slice(0, 2);
|
||||||
|
mcc_raw = lbs_string.slice(2, 6);
|
||||||
|
mnc_raw = lbs_string.slice(6, 8);
|
||||||
|
lac_raw = lbs_string.slice(8, 12);
|
||||||
|
cellID_raw = lbs_string.slice(12, 18);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lbs_length_raw) {
|
||||||
|
lbs_length = parseInt(lbs_length_raw, 16);
|
||||||
|
}
|
||||||
|
if (mnc_raw && mcc_raw && lac_raw && cellID_raw) {
|
||||||
|
mnc = parseInt(mnc_raw, 16);
|
||||||
|
mcc = parseInt(mcc_raw, 16);
|
||||||
|
lac = parseInt(lac_raw, 16);
|
||||||
|
cellID = parseInt(cellID_raw, 16);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
lbs_length_raw,
|
||||||
|
lbs_length,
|
||||||
|
mcc_raw,
|
||||||
|
mcc,
|
||||||
|
mnc_raw,
|
||||||
|
mnc,
|
||||||
|
lac_raw,
|
||||||
|
lac,
|
||||||
|
cellID_raw,
|
||||||
|
cellID,
|
||||||
|
};
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
static gt06ParseStatusAlarm(me, stts_string) {
|
||||||
|
if (!stts_string) {
|
||||||
|
stts_string = me.ori_string.slice(8).slice(54, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
let terminal_info_raw = stts_string.slice(0, 2);
|
||||||
|
let tib1 = LibHelper.hex2bin(terminal_info_raw); // terminal_info_byte1
|
||||||
|
let tib1_bit7 = tib1.slice(0, 1);
|
||||||
|
let tib1_bit6 = tib1.slice(1, 2);
|
||||||
|
let tib1_bit5 = tib1.slice(2, 3);
|
||||||
|
let tib1_bit4 = tib1.slice(3, 4);
|
||||||
|
let tib1_bit3 = tib1.slice(4, 5);
|
||||||
|
let tib1_bit2 = tib1.slice(5, 6);
|
||||||
|
let tib1_bit1 = tib1.slice(6, 7);
|
||||||
|
let tib1_bit0 = tib1.slice(7, 8);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 0: No Power (shutdown)
|
||||||
|
* 1: Extremely Low Battery (not enough for calling or sending text messages, etc.)
|
||||||
|
* 2: Very Low Battery (Low Battery Alarm)
|
||||||
|
* 3: Low Battery (can be used normally)
|
||||||
|
* 4: Medium
|
||||||
|
* 5: High
|
||||||
|
* 6: Very High
|
||||||
|
*/
|
||||||
|
let voltage_level = stts_string.slice(2, 4);
|
||||||
|
|
||||||
|
let gsm_signal_strength = stts_string.slice(4, 6);
|
||||||
|
|
||||||
|
let alarm_stts = stts_string.slice(6, 8); // former bit: terminal alarm status (suitable for alarm packet and electronic fence project)
|
||||||
|
let language = stts_string.slice(8, 10); // latter bit: the current language used in the terminal
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
terminal_info_raw: terminal_info_raw,
|
||||||
|
terminal_info_byte: tib1,
|
||||||
|
terminal_info: {
|
||||||
|
oil_electricity: tib1_bit7, // 1: oil and electricity disconnected, 0: gas oil and electricity connected
|
||||||
|
gps_tracking: tib1_bit6, // 1: GPS tracking is on, 0: GPS tracking is off
|
||||||
|
stts: `${tib1_bit5}${tib1_bit4}${tib1_bit3}`, // 100: SOS, 011: Low Battery Alarm, 010: Power Cut Alarm, 001: Shock Alarm, 000: Normal
|
||||||
|
charge: tib1_bit2, // 1: Charge On, 0: Charge Off
|
||||||
|
acc: tib1_bit1, // 1: ACC high, 0: ACC Low
|
||||||
|
is_active: tib1_bit0, // 1: Activated, 0: Deactivated
|
||||||
|
},
|
||||||
|
voltage_level,
|
||||||
|
gsm_signal_strength, // 0x00: no signal; 0x01: extremely weak signal; 0x02: very weak signal; 0x03: good signal; 0x04: strong signal.
|
||||||
|
alarm_stts, // 0x00: normal, 0x01: SOS, 0x02: Power Cut Alarm, 0x03: Shock Alarm, 0x04: Fence In Alarm, 0x05: Fence Out Alarm
|
||||||
|
language, // 0x01: Chinese, 0x02: English
|
||||||
|
};
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
static gt06AlarmResp(me) {
|
||||||
|
return Buffer.from("787805160001d9dc0d0a", "hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
static eelinkCustomAction(me, device_id = null) {
|
||||||
|
const act = {
|
||||||
|
device_id: me.field1,
|
||||||
|
action_type: "exist_data",
|
||||||
|
cmd: "exist_data",
|
||||||
|
};
|
||||||
|
|
||||||
|
if (me.field3 == "60000000" || me.field3 == "00000000") {
|
||||||
|
act.action_type = "no_data_since_hardware_reset";
|
||||||
|
act.cmd = "no_data_since_hardware_reset";
|
||||||
|
|
||||||
|
// act.buffer_resp = Buffer.from('LOAD');
|
||||||
|
// act.buffer_resp = 'LOAD';
|
||||||
|
// act.buffer_resp = Buffer.from(`6767${me.field0}000A0001${me.field1}01`, 'hex');
|
||||||
|
// act.buffer_resp = `6767${me.field0}000A0001${me.field1}01`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (act.action_type !== "exist_data") return act;
|
||||||
|
|
||||||
|
act.flag = me.field0;
|
||||||
|
act.imsi = me.field2; // International Mobile Subscriber Identifier
|
||||||
|
|
||||||
|
act.time_string = me.field3;
|
||||||
|
const time_data = {};
|
||||||
|
time_data.year = "20" + (parseInt(me.field3.slice(0, 1), 16) + 10);
|
||||||
|
time_data.month = "" + parseInt(me.field3.slice(1, 2), 16);
|
||||||
|
if (time_data.month.length === 1) {
|
||||||
|
time_data.month = "0" + time_data.month;
|
||||||
|
}
|
||||||
|
time_data.day = "" + parseInt(me.field3.slice(2, 4), 16);
|
||||||
|
if (time_data.day.length === 1) {
|
||||||
|
time_data.day = "0" + time_data.day;
|
||||||
|
}
|
||||||
|
time_data.hour = "" + parseInt(me.field3.slice(4, 6), 16);
|
||||||
|
if (time_data.hour.length === 1) {
|
||||||
|
time_data.hour = "0" + time_data.hour;
|
||||||
|
}
|
||||||
|
time_data.minute = "" + parseInt(me.field3.slice(6, 8), 16);
|
||||||
|
if (time_data.minute.length === 1) {
|
||||||
|
time_data.minute = "0" + time_data.minute;
|
||||||
|
}
|
||||||
|
act.time_data = time_data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* north => -9000000 to +9000000, can 1 or 2 digits of degree
|
||||||
|
* west => -18000000 to +18000000, usually 3 digits degree
|
||||||
|
*/
|
||||||
|
act.location_string = me.field4;
|
||||||
|
// original value is expressed as signed hex value, so we must to conversion to decimal
|
||||||
|
// using two complement
|
||||||
|
let north = ~parseInt(me.field4.slice(0, 8), 16);
|
||||||
|
let west = ~parseInt(me.field4.slice(8, 16), 16);
|
||||||
|
// add magnitude
|
||||||
|
north = north * -1 + 1;
|
||||||
|
west = west * -1 + 1;
|
||||||
|
// convert to string
|
||||||
|
north += "";
|
||||||
|
west += "";
|
||||||
|
// remove - from string at first and save to temporary variable
|
||||||
|
let signedNorth = "";
|
||||||
|
if (north.indexOf("-") === 0) {
|
||||||
|
north = north.slice(1);
|
||||||
|
signedNorth = "-";
|
||||||
|
}
|
||||||
|
let signedWest = "";
|
||||||
|
if (west.indexOf("-") === 0) {
|
||||||
|
west = west.slice(1);
|
||||||
|
signedWest = "-";
|
||||||
|
}
|
||||||
|
// separate DDM => Degree Decimal Minutes
|
||||||
|
let northDegree = north.slice(0, 1);
|
||||||
|
let northDecimalMinute = north.slice(1, 7);
|
||||||
|
if (north.length === 8) {
|
||||||
|
northDegree = north.slice(0, 2);
|
||||||
|
northDecimalMinute = north.slice(2, 7);
|
||||||
|
}
|
||||||
|
let westDegree = west.slice(0, 3);
|
||||||
|
let westDecimalMinute = west.slice(3, 7);
|
||||||
|
// convert DDM to DD (Decimal Degrees)
|
||||||
|
act.latitude = "" + signedNorth + northDegree + "." + ("" + northDecimalMinute / 60).replace(".", "");
|
||||||
|
act.longitude = "" + signedWest + westDegree + "." + ("" + westDecimalMinute / 60).replace(".", "");
|
||||||
|
|
||||||
|
return act;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = LibDevice;
|
||||||
File diff suppressed because it is too large
Load Diff
@ -1,7 +1,6 @@
|
|||||||
const db = require(`../config/dbMysqlConn`);
|
const db = require(`../config/dbMysqlConn`);
|
||||||
|
|
||||||
class VhcModels {
|
class VhcModels {
|
||||||
|
|
||||||
static STTS_ACTIVE = 1;
|
static STTS_ACTIVE = 1;
|
||||||
static STTS_INACTIVE = 2;
|
static STTS_INACTIVE = 2;
|
||||||
|
|
||||||
@ -11,13 +10,13 @@ class VhcModels {
|
|||||||
static async getVhcByDeviceId(device_id) {
|
static async getVhcByDeviceId(device_id) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
let params = [];
|
let params = [];
|
||||||
let query = 'SELECT';
|
let query = "SELECT";
|
||||||
query += ' v.id as vid,v.nopol1,v.nopol2,v.nopol3,v.sum_milleage,vd.speed_limit';
|
query += " v.id as vid,v.nopol1,v.nopol2,v.nopol3,v.sum_milleage,vd.speed_limit";
|
||||||
query += ' ,da.fullname as da_name,da.phone as da_phone,da.phone_code as da_phone_code';
|
query += " ,da.fullname as da_name,da.phone as da_phone,da.phone_code as da_phone_code";
|
||||||
query += ' FROM t_vehicles AS v';
|
query += " FROM t_vehicles AS v";
|
||||||
query += ' INNER JOIN t_vehicles_detail AS vd ON v.id = vd.vid';
|
query += " INNER JOIN t_vehicles_detail AS vd ON v.id = vd.vid";
|
||||||
query += ' LEFT JOIN t_drivers AS da ON v.a_did = da.id';
|
query += " LEFT JOIN t_drivers AS da ON v.a_did = da.id";
|
||||||
query += ' WHERE v.dlt is null AND v.status = ? AND v.device_id = ?';
|
query += " WHERE v.dlt is null AND v.status = ? AND v.device_id = ?";
|
||||||
params.push(VhcModels.STTS_ACTIVE, device_id);
|
params.push(VhcModels.STTS_ACTIVE, device_id);
|
||||||
db.query(query, params, function (err, resp) {
|
db.query(query, params, function (err, resp) {
|
||||||
if (err) {
|
if (err) {
|
||||||
@ -33,16 +32,16 @@ class VhcModels {
|
|||||||
static async getVhcById(id) {
|
static async getVhcById(id) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
let params = [];
|
let params = [];
|
||||||
let query = 'SELECT';
|
let query = "SELECT";
|
||||||
query += ' v.id as vid,v.nopol1,v.nopol2,v.nopol3,v.sum_milleage,vd.speed_limit';
|
query += " v.id as vid,v.nopol1,v.nopol2,v.nopol3,v.sum_milleage,vd.speed_limit";
|
||||||
query += ' ,da.fullname as da_name,da.phone as da_phone,da.phone_code as da_phone_code';
|
query += " ,da.fullname as da_name,da.phone as da_phone,da.phone_code as da_phone_code";
|
||||||
query += ' ,v.is_in_ord,v.ord_id,v.ord_code,v.ord_ids';
|
query += " ,v.is_in_ord,v.ord_id,v.ord_code,v.ord_ids";
|
||||||
query += ' FROM t_vehicles AS v';
|
query += " FROM t_vehicles AS v";
|
||||||
query += ' INNER JOIN t_vehicles_detail AS vd ON v.id = vd.vid';
|
query += " INNER JOIN t_vehicles_detail AS vd ON v.id = vd.vid";
|
||||||
query += ' LEFT JOIN t_drivers AS da ON v.a_did = da.id';
|
query += " LEFT JOIN t_drivers AS da ON v.a_did = da.id";
|
||||||
// query += ' WHERE v.dlt is null AND v.status = ? AND v.id = ?';
|
// query += ' WHERE v.dlt is null AND v.status = ? AND v.id = ?';
|
||||||
query += ' WHERE v.dlt is null AND v.id = ?';
|
query += " WHERE v.dlt is null AND v.id = ?";
|
||||||
query += ' LIMIT 1';
|
query += " LIMIT 1";
|
||||||
params.push(id);
|
params.push(id);
|
||||||
db.query(query, params, function (err, resp) {
|
db.query(query, params, function (err, resp) {
|
||||||
if (err) {
|
if (err) {
|
||||||
@ -91,11 +90,22 @@ class VhcModels {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
static async incrementMileage(vhc_id, add_km) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const query = `
|
||||||
|
UPDATE t_vehicles
|
||||||
|
SET sum_milleage = COALESCE(sum_milleage, 0) + ?
|
||||||
|
WHERE id = ? AND dlt IS NULL
|
||||||
|
`;
|
||||||
|
db.query(query, [add_km, vhc_id], (err, result) => {
|
||||||
|
if (err) return reject(err);
|
||||||
|
resolve(result);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = VhcModels;
|
module.exports = VhcModels;
|
||||||
@ -2,7 +2,7 @@
|
|||||||
"name": "fs",
|
"name": "fs",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "index.js",
|
"main": "app.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "echo \"Error: no test specified\" && exit 1",
|
"test": "echo \"Error: no test specified\" && exit 1",
|
||||||
"start": "node app.js",
|
"start": "node app.js",
|
||||||
@ -35,7 +35,9 @@
|
|||||||
"moment": "^2.29.1",
|
"moment": "^2.29.1",
|
||||||
"morgan": "^1.10.0",
|
"morgan": "^1.10.0",
|
||||||
"mysql": "^2.18.1",
|
"mysql": "^2.18.1",
|
||||||
|
"mysql2": "^3.15.1",
|
||||||
"nanoid": "^3.3.1",
|
"nanoid": "^3.3.1",
|
||||||
|
"node-cron": "^4.2.1",
|
||||||
"nodemailer": "^6.7.2",
|
"nodemailer": "^6.7.2",
|
||||||
"path": "^0.12.7",
|
"path": "^0.12.7",
|
||||||
"udp-packet": "^2.0.0",
|
"udp-packet": "^2.0.0",
|
||||||
|
|||||||
4163
pnpm-lock.yaml
generated
Normal file
4163
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
@ -1,50 +1,48 @@
|
|||||||
const WorkerController = require('../controllers/WorkerController');
|
const WorkerController = require("../controllers/WorkerController");
|
||||||
const ZoneController = require('../controllers/ZoneController');
|
const ZoneController = require("../controllers/ZoneController");
|
||||||
const DummyController = require('../controllers/DummyController');
|
const DummyController = require("../controllers/DummyController");
|
||||||
const OrderController = require('../controllers/OrderController');
|
const OrderController = require("../controllers/OrderController");
|
||||||
const ListenController = require("../controllers/ListenController");
|
const ListenController = require("../controllers/ListenController");
|
||||||
|
|
||||||
const ServiceDriverRoute = require('./ServiceDriverRoute');
|
const ServiceDriverRoute = require("./ServiceDriverRoute");
|
||||||
|
|
||||||
const { PATH_URL } = process.env;
|
const { PATH_URL } = process.env;
|
||||||
|
|
||||||
exports.use = function (app) {
|
exports.use = function (app) {
|
||||||
|
|
||||||
// app.all('/*', DummyController.logging);
|
// app.all('/*', DummyController.logging);
|
||||||
|
|
||||||
// queue
|
// queue
|
||||||
app.post(PATH_URL + '/workers/add', WorkerController.add);
|
app.post(PATH_URL + "/workers/add", WorkerController.add);
|
||||||
app.get(PATH_URL + '/workers/getJobs', WorkerController.getJobs);
|
app.get(PATH_URL + "/workers/getJobs", WorkerController.getJobs);
|
||||||
app.get(PATH_URL + '/workers/getRepeatableJobs', WorkerController.getRepeatableJobs);
|
app.get(PATH_URL + "/workers/getRepeatableJobs", WorkerController.getRepeatableJobs);
|
||||||
app.post(PATH_URL + '/workers/resume', WorkerController.resume);
|
app.post(PATH_URL + "/workers/resume", WorkerController.resume);
|
||||||
app.post(PATH_URL + '/workers/pause', WorkerController.pause);
|
app.post(PATH_URL + "/workers/pause", WorkerController.pause);
|
||||||
app.post(PATH_URL + '/workers/drain', WorkerController.drain);
|
app.post(PATH_URL + "/workers/drain", WorkerController.drain);
|
||||||
app.post(PATH_URL + '/workers/obliterate', WorkerController.obliterate);
|
app.post(PATH_URL + "/workers/obliterate", WorkerController.obliterate);
|
||||||
// workers
|
// workers
|
||||||
app.post(PATH_URL + '/workers/start', WorkerController.start);
|
app.post(PATH_URL + "/workers/start", WorkerController.start);
|
||||||
app.post(PATH_URL + '/workers/shutdown', WorkerController.shutdown);
|
app.post(PATH_URL + "/workers/shutdown", WorkerController.shutdown);
|
||||||
// process workers via request
|
// process workers via request
|
||||||
app.post(PATH_URL + '/workers/revgeo', WorkerController.revgeo);
|
app.post(PATH_URL + "/workers/revgeo", WorkerController.revgeo);
|
||||||
|
|
||||||
// zoning
|
// zoning
|
||||||
app.get(PATH_URL + '/zone/nearest', ZoneController.nearest);
|
app.get(PATH_URL + "/zone/nearest", ZoneController.nearest);
|
||||||
app.get(PATH_URL + '/zone/in_circle', ZoneController.inCircle);
|
app.get(PATH_URL + "/zone/in_circle", ZoneController.inCircle);
|
||||||
app.get(PATH_URL + '/zone/in_shape', ZoneController.inShape);
|
app.get(PATH_URL + "/zone/in_shape", ZoneController.inShape);
|
||||||
|
|
||||||
// order
|
// order
|
||||||
app.post(PATH_URL + '/order/create', OrderController.createOrder);
|
app.post(PATH_URL + "/order/create", OrderController.createOrder);
|
||||||
app.post(PATH_URL + '/order/email_to_vendor', OrderController.emailToVendor);
|
app.post(PATH_URL + "/order/email_to_vendor", OrderController.emailToVendor);
|
||||||
app.post(PATH_URL + '/order/email_vendor_acc_order', OrderController.emailVdrAccOrder);
|
app.post(PATH_URL + "/order/email_vendor_acc_order", OrderController.emailVdrAccOrder);
|
||||||
app.post(PATH_URL + '/order/delay_blast_order', OrderController.delayBlastOrder);
|
app.post(PATH_URL + "/order/delay_blast_order", OrderController.delayBlastOrder);
|
||||||
app.post(PATH_URL + '/order/finance_info_tf_pocket', OrderController.sendFinanceInfoTfPocket);
|
app.post(PATH_URL + "/order/finance_info_tf_pocket", OrderController.sendFinanceInfoTfPocket);
|
||||||
app.post(PATH_URL + '/order/finance_info_dana_amount', OrderController.sendFinanceInfoDanaAmount);
|
app.post(PATH_URL + "/order/finance_info_dana_amount", OrderController.sendFinanceInfoDanaAmount);
|
||||||
|
|
||||||
// dummy
|
// dummy
|
||||||
app.get(PATH_URL + '/dummy/distance', DummyController.distance);
|
app.get(PATH_URL + "/dummy/distance", DummyController.distance);
|
||||||
app.post(PATH_URL + '/dummy/send_email', DummyController.sendEmail);
|
app.post(PATH_URL + "/dummy/send_email", DummyController.sendEmail);
|
||||||
|
|
||||||
// LISTEN
|
// LISTEN
|
||||||
app.post(PATH_URL + "/listen/gps", ListenController.gps);
|
app.post(PATH_URL + "/listen/gps", ListenController.gps);
|
||||||
ServiceDriverRoute.routesConfig(app);
|
ServiceDriverRoute.routesConfig(app);
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user