From ea2e0168d3ae62a401363c0a805f9ed6c11660a4 Mon Sep 17 00:00:00 2001 From: sergiu Date: Wed, 25 Sep 2019 14:02:03 +0300 Subject: [PATCH] LAPI-298: Update to exit, to log in logs directory and to be able to send GPS --- config/default.toml | 20 +++----- package-lock.json | 5 ++ package.json | 1 + src/asset.js | 109 ++++++++++++++++++++++++++++++++------------ src/mumble.js | 18 ++++---- src/simulator.js | 27 ++++++++--- src/utils.js | 12 +++-- 7 files changed, 133 insertions(+), 59 deletions(-) diff --git a/config/default.toml b/config/default.toml index 2b08016..fe2c29c 100644 --- a/config/default.toml +++ b/config/default.toml @@ -12,23 +12,17 @@ use_secure = true accept_untrusted_certs = true [settings] -stay_only_connected = false +send_voice = true +send_gps = false +gps_report_interval = 1000 # The interval in which the GPS is sent [assets] -#ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] -# ids = [51] -# 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, -# 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] +ids = [1947,1957] +# ids = [1947,1957,1967] # 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 = [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-110 1957 colinde2 diff --git a/package-lock.json b/package-lock.json index 36f778b..e74d91b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -647,6 +647,11 @@ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", "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": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", diff --git a/package.json b/package.json index aaef9e6..15d7a50 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "config": "^1.30.0", "lame": "^1.2.4", "libsamplerate.js": "^1.0.0", + "moment": "^2.24.0", "mumble-client": "^1.1.1", "mumble-client-codecs-node": "0.0.1", "reconnect-core": "^1.3.0", diff --git a/src/asset.js b/src/asset.js index 2c798aa..188bd3d 100644 --- a/src/asset.js +++ b/src/asset.js @@ -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, diff --git a/src/mumble.js b/src/mumble.js index fba25ab..30680b4 100644 --- a/src/mumble.js +++ b/src/mumble.js @@ -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); diff --git a/src/simulator.js b/src/simulator.js index adb6112..5e539c2 100644 --- a/src/simulator.js +++ b/src/simulator.js @@ -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); diff --git a/src/utils.js b/src/utils.js index 499184b..16b342b 100644 --- a/src/utils.js +++ b/src/utils.js @@ -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(); } + }); + }); } \ No newline at end of file