LAPI-298: Update to exit, to log in logs directory and to be able to send GPS

This commit is contained in:
2019-09-25 14:02:03 +03:00
parent 37d906aacd
commit ea2e0168d3
7 changed files with 133 additions and 59 deletions

View File

@ -25,6 +25,9 @@ class Asset {
this._processConfigs();
this.startTime = +new Date();
this.pttEndSuccessfully = false;
this.assetProps = {};
utils.writeLog(`Creating asset ${id}`)
// Do async work: Init asset.
async.waterfall([
@ -35,9 +38,9 @@ class Asset {
this._moveToChannel.bind(this),
],
(err, result) => {
this._log('Finish init');
utils.writeLog(`Asset ${this.id} was successfully initialized`)
if (err) {
this._log('Init failed:');
utils.writeLog(`Asset ${this.id} was not successfully initialized`)
console.log(err)
return;
}
@ -47,10 +50,6 @@ class Asset {
});
}
_log(msg) {
log(this.assetProps ? (this.assetProps.name + ' - ' + this.id) : (this.id), msg);
}
_processConfigs() {
let apiConfig = this.configs.api;
@ -72,12 +71,11 @@ class Asset {
}
_getDataFromApi(callback) {
Request.get(
this.apiEndpoint + '/asset/' + this.id,
{},
(error, response, body) => {
console.log('get data from ghub', error)
utils.writeLog(`Get informations about asset ${this.id}`)
if (!error && (response.statusCode === 200 || response.statusCode === 201)) {
let bodyObj = JSON.parse(body);
@ -117,7 +115,7 @@ class Asset {
if (!this.groupId) {
return callback('No talk group assigned to ' + this.id);
}
utils.writeLog(`Informations about asset ${this.id} received`)
return callback();
} else {
return callback(error);
@ -147,8 +145,7 @@ class Asset {
return callback();
});
hub.on('connect', () => {
this._log('Hub connected? ' + hub.connected)
this._log('Connected to hub.');
utils.writeLog(`Asset ${this.id} connected to HUB`)
this._sendArs();
});
@ -166,11 +163,9 @@ class Asset {
}
_sendArs() {
let hub = this.hub;
if (hub && hub.connected) {
this._log('Sending ars event')
utils.writeLog(`Asset ${this.id} sending ARS`)
hub.emit('ars', JSON.stringify({
ars: true,
userAgent: 'android',
@ -201,7 +196,7 @@ class Asset {
{},
(error, response, body) => {
if (!error && (response.statusCode === 200 || response.statusCode === 201)) {
this._log('Registered')
utils.writeLog(`Asset ${this.id} audio registered`);
return callback();
} else {
return callback(error);
@ -233,6 +228,7 @@ class Asset {
scan_group_ids: null
}
));
utils.writeLog(`Asset ${this.id} mmonitoring group ${this.groupId}`)
return callback();
} else {
return callback('Cannot send group-monitoring: Hub not connected');
@ -245,14 +241,18 @@ class Asset {
}
_start() {
if(!this.configs.settings.stay_only_connected) {
if(this.configs.settings.send_voice) {
this._makePtt(() => {
if(this.pttEndSuccessfully) {
this._verifyRecorder();
}
});
}
if(this.configs.settings.send_gps) {
console.log('send gps')
this._sendGPS();
}
}
_verifyRecorder(callback) {
@ -280,14 +280,30 @@ class Asset {
latest = e;
}
})
console.log(chalk.green(`Report found id: ${latest.id} | description: ${latest.description}`));
console.log(chalk.green(`[RECORDER] Record found(${latest.id}) for asset ${this.id} | description: ${latest.description}`));
utils.writeLog(`[RECORDER] Record found(${latest.id}) for asset ${this.id} | description: ${latest.description}`)
} else {
console.log(chalk.yellow(`Report for unit: ${this.id} not found`));
console.log(chalk.yellow(`[RECORDER] for asset ${this.id} not found`));
}
} else {
console.log('Error:', error);
utils.writeLog(`[RECORDER] Error ${error}`);
throw error;
}
// DEBUG
// console.log('this.id', this.id)
// console.log('Math.max(...this.configs.assets.ids', Math.max(...this.configs.assets.ids))
// console.log('this.id === Math.max(...this.configs.assets.ids', this.id === Math.max(...this.configs.assets.ids))
if(this.id === Math.max(...this.configs.assets.ids)) {
setTimeout(() => {
utils.writeLog('STOP')
.then(() => {
process.exit(0);
});
}, 10000);
}
}
);
}
@ -343,7 +359,6 @@ class Asset {
// Send ptt-release on voice end.
voiceStream.on('end', () => {
this._log('Voice end.');
this.pttEndSuccessfully = true;
setTimeout(() => {
this._sendPttRelease();
@ -410,8 +425,48 @@ class Asset {
})
}
_sendGPS(callback) {
console.log('_sendGPS')
let hub = this.hub;
if (hub && hub.connected) {
let lat = 46.217802;
let lng = 24.776126;
setInterval(() => {
var new_lat = this._randomCoordinates(lat);
var new_lng = this._randomCoordinates(lng);
hub.emit('gps', JSON.stringify(
{
unix_time: 1467126677000,
asset_id: this.assetProps.id,
asset_sip_id: this.assetProps.sip_id,
speed_kmh: 16,
lat: new_lat,
lng: new_lng,
accuracy: 20.3,
activity_type: "driving",
activity_confidence: 90
}
));
lat = new_lat;
lng = new_lng;
console.log('_sendGPS | lat:', lat, ' | lng:', lng)
}, this.configs.settings.gps_report_interval);
}
}
_randomCoordinates(coordinate) {
if(Math.round(Math.random()) === 0) {
return parseFloat(parseFloat(coordinate) - parseFloat((Math.random() * (0.01 - 0.005) + 0.005).toFixed(4))).toFixed(6);
} else {
return parseFloat(parseFloat(coordinate) + parseFloat((Math.random() * (0.01 - 0.005) + 0.005).toFixed(4))).toFixed(6);
}
}
_sendPttPress(callback) {
this._log('Sending ptt-press...' + '| priority: ' + this.assetProps.priority + ' | Group: ' + this.groupId);
let hub = this.hub;
if (hub && hub.connected) {
@ -420,8 +475,7 @@ class Asset {
if (data.asset_id != this.id) {
return;
}
this._log('Received ptt-accept');
utils.writeLog(`Asset ${this.id} sending PTT-PRESS to group ${this.groupId}`)
hub.removeListener('ptt-deny', pttDenyHandler);
callback(true);
};
@ -432,8 +486,7 @@ class Asset {
if (data.asset_id != this.id) {
return;
}
this._log('Received ptt-deny');
utils.writeLog(`Asset ${this.id} received PTT-DENY`);
hub.removeListener('ptt-accept', pttAcceptHandler);
callback(false);
};
@ -460,7 +513,7 @@ class Asset {
let hub = this.hub;
if (hub && hub.connected) {
this._log('Sending ptt-release..');
utils.writeLog(`Asset ${this.id} sending PTT-RELEASE to group ${this.groupId}`);
hub.emit('ptt-release', JSON.stringify(
{
destination_group_id: this.groupId,

View File

@ -6,7 +6,7 @@ var NodeCodecs = require('mumble-client-codecs-node');
var fs = require('fs');
var execSync = require('child_process').execSync;
var currentPath = require('path').dirname(require.main.filename);
const utils = require('./utils');
const OpusEncoder = require('node-opus').OpusEncoder;
class Mumble {
@ -29,7 +29,7 @@ class Mumble {
var path = currentPath + '/certs/' + id + '-cert.pem';
if (!fs.existsSync(path)) {
console.log(id, 'Creating certificates...');
utils.writeLog(`Creating certificates for asset ${id}`)
try {
var code = execSync(currentPath + '/createCerts.sh ' + id);
} catch (e) {
@ -37,7 +37,7 @@ class Mumble {
}
return callback(true);
} else {
console.log(id, 'Certificates already created.');
utils.writeLog(`Certificates for asset ${id} already created`);
return callback(true);
}
}
@ -47,15 +47,15 @@ class Mumble {
// If ca does not exist create them.
var rootPath = currentPath + '/certs/root-cert.pem';
if (!fs.existsSync(rootPath)) {
console.log(id, ' - Creating CA certificates...')
try {
execSync('./createCA.sh');
} catch(e) {
utils.writeLog(`Creating certificates for Mumble`);
try { execSync('./createCA.sh'); }
catch(e) {
utils.writeLog(`Could not crete Mumble certificates. Error:${e}`)
throw 'Could not crete CA certificates. ' + e;
}
} else {
utils.writeLog(`Certificates for Mumble already created`);
}
console.log(id,' - CA certificates ok.')
var reconnect = inject(function(){
var args = slice.call(arguments);

View File

@ -1,7 +1,9 @@
const Asset = require('./asset');
const Request = require('request');
const async = require('async');
const utils = require('./utils');
const fs = require('fs');
const path = require('path');
class Simulator {
@ -18,14 +20,14 @@ class Simulator {
this.apiEndpoint += '://' + this.configs.api.host + (this.configs.api.port ? (':' + this.configs.api.port) : '');
async.waterfall([
this.unregisterAsstes.bind(this)
this._manageLogs.bind(this),
this._unregisterAsstes.bind(this)
],
(err, result) => {
if(err) {
console.log(err)
return;
}
this._start();
});
@ -33,19 +35,32 @@ class Simulator {
_start() {
this.assetIds.forEach(id => {
console.log('Creating asset', id, '...');
this.assets[id] = new Asset(id, this.configs);
});
}
unregisterAsstes(callback) {
_manageLogs(callback) {
fs.readdir('logs', (err, files) => {
if (err) throw err;
for (const file of files) {
fs.unlinkSync(path.join('logs', file), err => {
if (err) throw err;
});
}
fs.openSync('./logs/simulator-log', 'w');
utils.writeLog('START');
});
return callback();
}
_unregisterAsstes(callback) {
let url = this.apiEndpoint + '/audio/un-register/[' + this.assetIds + ']/';
console.log('url', url)
Request.post(
url,
{},
(error, response, body) => {
if (!error && (response.statusCode === 200 || response.statusCode === 201)) {
utils.writeLog(`Unregister assets: ${this.assetIds}`)
return callback();
} else {
return callback(error);

View File

@ -1,5 +1,11 @@
const fs = require('fs');
const moment = require('moment');
module.exports.log = function(actor, message) {
console.log((new Date()).toISOString() + ' ' + actor + ': '+ message);
module.exports.writeLog = async (value) => {
return new Promise(async (resolve, reject) => {
await fs.writeFile('./logs/simulator-log', `[${moment().format('YYYY-MM-DD HH:mm:ss')}] ${value}\n`, {'flag':'a'}, function(err) {
if (err) { reject(err); }
else { resolve(); }
});
});
}