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

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

View File

@ -12,23 +12,17 @@ use_secure = true
accept_untrusted_certs = true accept_untrusted_certs = true
[settings] [settings]
stay_only_connected = false send_voice = true
send_gps = false
gps_report_interval = 1000 # The interval in which the GPS is sent
[assets] [assets]
#ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] # ids = [1947]
# ids = [51] ids = [1947,1957]
# ids = [15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44, # ids = [1947,1957,1967]
# 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101,
# 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205
# ]
# ids = [1957]
# ids = [1949, 1950]
ids = [1947,1957,1967]
# ids = [1947,1957,1967,1977,1987,1997,2007,2017,2027,2037,2047,2057,2067,2077,2087,2097,2107,2117,2127,2137]
# ids = [1947,1957,1967,1977,1987,1997,2007,2017,2027,2037] # colinde 0-10 # ids = [1947,1957,1967,1977,1987,1997,2007,2017,2027,2037] # colinde 0-10
# ids = [2047,2057,2067,2077,2087,2097,2107,2117,2127,2137] # colinde 11-20 # ids = [2047,2057,2067,2077,2087,2097,2107,2117,2127,2137] # colinde 11-20
# ids = [1947,1957,1967,1977,1987,1997,2007,2017,2027,2037,2047,2057,2067,2077,2087,2097,2107,2117,2127,2137] colinde 0-20
# audio-test-100 1947 colinde # audio-test-100 1947 colinde
# audio-test-110 1957 colinde2 # audio-test-110 1957 colinde2

5
package-lock.json generated
View File

@ -647,6 +647,11 @@
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz",
"integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=" "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ="
}, },
"moment": {
"version": "2.24.0",
"resolved": "https://registry.npmjs.org/moment/-/moment-2.24.0.tgz",
"integrity": "sha512-bV7f+6l2QigeBBZSM/6yTNq4P2fNpSWj/0e7jQcy87A8e7o2nAfP/34/2ky5Vw4B9S446EtIhodAzkFCcR4dQg=="
},
"ms": { "ms": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",

View File

@ -14,6 +14,7 @@
"config": "^1.30.0", "config": "^1.30.0",
"lame": "^1.2.4", "lame": "^1.2.4",
"libsamplerate.js": "^1.0.0", "libsamplerate.js": "^1.0.0",
"moment": "^2.24.0",
"mumble-client": "^1.1.1", "mumble-client": "^1.1.1",
"mumble-client-codecs-node": "0.0.1", "mumble-client-codecs-node": "0.0.1",
"reconnect-core": "^1.3.0", "reconnect-core": "^1.3.0",

View File

@ -25,6 +25,9 @@ class Asset {
this._processConfigs(); this._processConfigs();
this.startTime = +new Date(); this.startTime = +new Date();
this.pttEndSuccessfully = false; this.pttEndSuccessfully = false;
this.assetProps = {};
utils.writeLog(`Creating asset ${id}`)
// Do async work: Init asset. // Do async work: Init asset.
async.waterfall([ async.waterfall([
@ -35,9 +38,9 @@ class Asset {
this._moveToChannel.bind(this), this._moveToChannel.bind(this),
], ],
(err, result) => { (err, result) => {
this._log('Finish init'); utils.writeLog(`Asset ${this.id} was successfully initialized`)
if (err) { if (err) {
this._log('Init failed:'); utils.writeLog(`Asset ${this.id} was not successfully initialized`)
console.log(err) console.log(err)
return; return;
} }
@ -47,10 +50,6 @@ class Asset {
}); });
} }
_log(msg) {
log(this.assetProps ? (this.assetProps.name + ' - ' + this.id) : (this.id), msg);
}
_processConfigs() { _processConfigs() {
let apiConfig = this.configs.api; let apiConfig = this.configs.api;
@ -72,12 +71,11 @@ class Asset {
} }
_getDataFromApi(callback) { _getDataFromApi(callback) {
Request.get( Request.get(
this.apiEndpoint + '/asset/' + this.id, this.apiEndpoint + '/asset/' + this.id,
{}, {},
(error, response, body) => { (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)) { if (!error && (response.statusCode === 200 || response.statusCode === 201)) {
let bodyObj = JSON.parse(body); let bodyObj = JSON.parse(body);
@ -117,7 +115,7 @@ class Asset {
if (!this.groupId) { if (!this.groupId) {
return callback('No talk group assigned to ' + this.id); return callback('No talk group assigned to ' + this.id);
} }
utils.writeLog(`Informations about asset ${this.id} received`)
return callback(); return callback();
} else { } else {
return callback(error); return callback(error);
@ -147,8 +145,7 @@ class Asset {
return callback(); return callback();
}); });
hub.on('connect', () => { hub.on('connect', () => {
this._log('Hub connected? ' + hub.connected) utils.writeLog(`Asset ${this.id} connected to HUB`)
this._log('Connected to hub.');
this._sendArs(); this._sendArs();
}); });
@ -166,11 +163,9 @@ class Asset {
} }
_sendArs() { _sendArs() {
let hub = this.hub; let hub = this.hub;
if (hub && hub.connected) { if (hub && hub.connected) {
utils.writeLog(`Asset ${this.id} sending ARS`)
this._log('Sending ars event')
hub.emit('ars', JSON.stringify({ hub.emit('ars', JSON.stringify({
ars: true, ars: true,
userAgent: 'android', userAgent: 'android',
@ -201,7 +196,7 @@ class Asset {
{}, {},
(error, response, body) => { (error, response, body) => {
if (!error && (response.statusCode === 200 || response.statusCode === 201)) { if (!error && (response.statusCode === 200 || response.statusCode === 201)) {
this._log('Registered') utils.writeLog(`Asset ${this.id} audio registered`);
return callback(); return callback();
} else { } else {
return callback(error); return callback(error);
@ -233,6 +228,7 @@ class Asset {
scan_group_ids: null scan_group_ids: null
} }
)); ));
utils.writeLog(`Asset ${this.id} mmonitoring group ${this.groupId}`)
return callback(); return callback();
} else { } else {
return callback('Cannot send group-monitoring: Hub not connected'); return callback('Cannot send group-monitoring: Hub not connected');
@ -245,14 +241,18 @@ class Asset {
} }
_start() { _start() {
if(this.configs.settings.send_voice) {
if(!this.configs.settings.stay_only_connected) {
this._makePtt(() => { this._makePtt(() => {
if(this.pttEndSuccessfully) { if(this.pttEndSuccessfully) {
this._verifyRecorder(); this._verifyRecorder();
} }
}); });
} }
if(this.configs.settings.send_gps) {
console.log('send gps')
this._sendGPS();
}
} }
_verifyRecorder(callback) { _verifyRecorder(callback) {
@ -280,14 +280,30 @@ class Asset {
latest = e; latest = e;
} }
}) })
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(`[RECORDER] for asset ${this.id} not found`));
}
} else {
utils.writeLog(`[RECORDER] Error ${error}`);
throw error;
}
console.log(chalk.green(`Report found id: ${latest.id} | description: ${latest.description}`)); // DEBUG
} else { // console.log('this.id', this.id)
console.log(chalk.yellow(`Report for unit: ${this.id} not found`)); // 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))
} else {
console.log('Error:', error); 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. // Send ptt-release on voice end.
voiceStream.on('end', () => { voiceStream.on('end', () => {
this._log('Voice end.');
this.pttEndSuccessfully = true; this.pttEndSuccessfully = true;
setTimeout(() => { setTimeout(() => {
this._sendPttRelease(); 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) { _sendPttPress(callback) {
this._log('Sending ptt-press...' + '| priority: ' + this.assetProps.priority + ' | Group: ' + this.groupId);
let hub = this.hub; let hub = this.hub;
if (hub && hub.connected) { if (hub && hub.connected) {
@ -420,8 +475,7 @@ class Asset {
if (data.asset_id != this.id) { if (data.asset_id != this.id) {
return; return;
} }
utils.writeLog(`Asset ${this.id} sending PTT-PRESS to group ${this.groupId}`)
this._log('Received ptt-accept');
hub.removeListener('ptt-deny', pttDenyHandler); hub.removeListener('ptt-deny', pttDenyHandler);
callback(true); callback(true);
}; };
@ -432,8 +486,7 @@ class Asset {
if (data.asset_id != this.id) { if (data.asset_id != this.id) {
return; return;
} }
utils.writeLog(`Asset ${this.id} received PTT-DENY`);
this._log('Received ptt-deny');
hub.removeListener('ptt-accept', pttAcceptHandler); hub.removeListener('ptt-accept', pttAcceptHandler);
callback(false); callback(false);
}; };
@ -460,7 +513,7 @@ class Asset {
let hub = this.hub; let hub = this.hub;
if (hub && hub.connected) { 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( hub.emit('ptt-release', JSON.stringify(
{ {
destination_group_id: this.groupId, destination_group_id: this.groupId,

View File

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

View File

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

View File

@ -1,5 +1,11 @@
const fs = require('fs');
const moment = require('moment');
module.exports.writeLog = async (value) => {
module.exports.log = function(actor, message) { return new Promise(async (resolve, reject) => {
console.log((new Date()).toISOString() + ' ' + actor + ': '+ message); 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(); }
});
});
} }