diff --git a/ExtPlaneJs.js b/ExtPlaneJs.js deleted file mode 100644 index 47bc930..0000000 --- a/ExtPlaneJs.js +++ /dev/null @@ -1,167 +0,0 @@ -'use strict'; - -/** - * - * @name: ExtPlaneJs - * @author: Wade Wildbore - Bluu Interactive - * @description: ExtPlane TCP Connector for NodeJS - * @see: https://github.com/vranki/ExtPlane - For more information - */ -var EventEmitter = require('events').EventEmitter; -var client = require('./client'); -var util = require('util'); -var async = require('async'); -var base64 = require('base-64'); - -function ExtPlaneJs(config){ - - // Ref to &this - var self = this; - - // CTOR - EventEmitter.call(this); - - // ExtPlaneJs Config - this.config = config; - - // ExtPlane TCP Client - this.client = client(this.config); - - // Couple the TCP clients on data event to ExtPlaneJs - this.client.on('data', function(data){ - self.emit('data', data); - }); - - /** - * - * Loaded - * - */ - this.on('loaded', function(){ - if(this.config.debug) console.log('ExtPlane Ready!'); - }); - - /** - * - * Data - * - * @param {string} data - */ - this.on('data', function(data){ - - // log incoming TCP stream - //console.log(data.toString()); - - if(data.toString().includes('EXTPLANE')) - { - // loaded.. - return this.emit('loaded'); - } - - // emit parse - return this.emit('parse', data.toString()); - - }); - - /** - * - * Parse - * - * Either emit single data-ref events, or broadcast all data-ref events on one handler - * - * @param {string} data - */ - this.on('parse', function(data){ - - // - var commands = data.trim().split('\n'); - - async.each(commands, function(cmd, cb){ - - self.parseDataRef(cmd, cb); - - }, function(err){ - if(err && this.config.debug) console.log(err); - }); - - }); - - /** - * - * Parse an Individual Data Ref - * - * @param {string} data_ref - The data_ref response - * @param {function} cb - The done callback - */ - this.parseDataRef = function(data_ref, cb){ - - var params = data_ref.split(' '); - - // if not data-ref output, break - if(params[0][0] !== 'u') - return false; - - // data-ref - data_ref = params[1]; - - var type = params[0].substring(1); - var value = this.parseValue(type, params[2]); - - // emit - data_ref, value or 'data-ref', data_ref, value - !this.config.broadcast ? this.emit(data_ref, data_ref, value) : this.emit('data-ref', data_ref, value); - - // done - return cb(null); - }; - - /** - * - * Parse ExtPlanes TCP Text Based Response - * - * Override type value conversions from ExtPlanes response - * - * @param {string} - type - * @param {string} - value - */ - this.parseValue = function(type, value){ - - switch(type) - { - // int - case 'i': - return parseInt(value); - break; - - // float - case 'f': - return parseFloat(value); - break; - - // int array - case 'ia': - return JSON.parse(value); - break; - - // float array - case 'fa': - return JSON.parse(value); - break; - - // base64 data - case 'b': - return base64.decode(value); - break; - - default: - return value; - break; - - } - - }; - -}; - -util.inherits(ExtPlaneJs, EventEmitter); - -module.exports = ExtPlaneJs; diff --git a/client.js b/client.js deleted file mode 100644 index e070ae2..0000000 --- a/client.js +++ /dev/null @@ -1,149 +0,0 @@ -'use strict'; - -var net = require('net'); - -/** - * - * @name: ExtPlaneJs - * @author: Wade Wildbore - Bluu Interactive - * @description: ExtPlane TCP Connector for NodeJS - * @see: https://github.com/vranki/ExtPlane - For more information - */ -module.exports = function(config){ - - /** - * Socket Connect - */ - var client = net.connect(config, function(){ - if(config.debug) console.log('Connected to '+config.host+':'+config.port); - }); - - /** - * - * On Socket End - */ - client.on('end', function(){ - if(config.debug) console.log('disconnected from server'); - }); - - /** - * On Socket Error - */ - client.on('error', function(error) { - if(config.debug) console.log('An error occurred!', error); - }); - - /** - * - * Key Press - * - * @param {string} key_id - XPlane key ID - */ - client.key = function(key_id){ - this.write('key '+key_id+'\r\n'); - }; - - /** - * - * CMD Once - * - * @param {string} cmd - The command - */ - client.cmd = function(cmd){ - this.write('cmd once '+cmd+'\r\n'); - }; - - /** - * - * CMD Begin - * - * @param {string} cmd - The command - */ - client.begin = function(cmd){ - this.write('cmd begin '+cmd+'\r\n'); - }; - - /** - * - * CMD End - * - * @param {string} cmd - The command - */ - client.end = function(cmd){ - this.write('cmd end '+cmd+'\r\n'); - }; - - /** - * - * Button Press - * - * @param {string} button_id - XPlane button ID - */ - client.button = function(button_id){ - this.write('but '+button_id+'\r\n'); - }; - - /** - * - * Release Button - * - * @param {string} button_id - XPlane button ID - */ - client.release = function(button_id){ - this.write('rel '+button_id+'\r\n'); - }; - - /** - * - * Set a Data Ref to a specific value - * - * @param {string} data_ref - the XPlane Data Ref - * @param {string} value - ExtPlane Values - */ - client.set = function(data_ref, value){ - this.write('set '+data_ref+' '+value+'\r\n'); - }; - - /** - * - * Subscribe to the XPlane Data Ref - * - * @param {string} data_ref - the XPlane Data Ref - * @param {float} accuracy - */ - client.subscribe = function(data_ref, accuracy){ - this.write('sub '+data_ref+(accuracy !== undefined ? ' '+accuracy : '')+'\r\n'); - }; - - /** - * - * Unsubscribe from the XPlane Data Ref - * - * @param {string} data_ref - the XPlane Data Ref - */ - client.unsubscribe = function(data_ref){ - this.write('unsub '+data_ref+'\r\n'); - }; - - /** - * - * How often ExtPlane should update its data from X-Plane, in seconds. Use as high value as possible here for best performance. For example 0.16 would mean 60Hz, 0.33 = 30Hz, 0.1 = 10Hz etc.. Must be a positive float. Default is 0.33. - * - * @param {float} value - */ - client.interval = function(value){ - this.write('extplane-set update_interval '+value+'\r\n'); - } - - /** - * - * Disconnect from ExtPlane and then close the TCP socket - */ - client.disconnect = function(){ - this.write('disconnect'+'\r\n'); - this.end(); - }; - - return client; - -}; diff --git a/dist/Client.d.ts b/dist/Client.d.ts new file mode 100644 index 0000000..2947f58 --- /dev/null +++ b/dist/Client.d.ts @@ -0,0 +1,104 @@ +/// +/// +import { Socket } from 'net'; +import { EventEmitter } from 'events'; +/** + * + * @name: ExtPlaneJs + * @author: Wade Wildbore - Bluu Interactive + * @author: Brian Vo (Typescript Rewrite) + * @description: ExtPlane TCP Connector for NodeJS + * @see: https://github.com/vranki/ExtPlane - For more information + */ +interface Config { + host: string; + port: number; + broadcast: boolean; + debug: boolean; +} +export default class Client extends EventEmitter { + h: string; + p: number; + b: boolean; + d: boolean; + s: Socket; + constructor(config: Config); + /** + * + * Key Press + * + * @param {string} key_id - XPlane key ID + */ + key(key_id: string): void; + /** + * + * CMD Once + * + * @param {string} cmd - The command + */ + cmd(cmd: string): void; + /** + * + * CMD Begin + * + * @param {string} cmd - The command + */ + begin(cmd: string): void; + /** + * + * CMD End + * + * @param {string} cmd - The command + */ + end(cmd: string): void; + /** + * + * Button Press + * + * @param {string} button_id - XPlane button ID + */ + button(button_id: string): void; + /** + * + * Release Button + * + * @param {string} button_id - XPlane button ID + */ + release(button_id: string): void; + /** + * + * Set a Data Ref to a specific value + * + * @param {string} data_ref - the XPlane Data Ref + * @param {string} value - ExtPlane Values + */ + set(data_ref: string, value: string): void; + /** + * + * Subscribe to the XPlane Data Ref + * + * @param {string} data_ref - the XPlane Data Ref + * @param {float} accuracy + */ + subscribe(data_ref: string, accuracy?: number): void; + /** + * + * Unsubscribe from the XPlane Data Ref + * + * @param {string} data_ref - the XPlane Data Ref + */ + unsubscribe(data_ref: string): void; + /** + * + * How often ExtPlane should update its data from X-Plane, in seconds. Use as high value as possible here for best performance. For example 0.16 would mean 60Hz, 0.33 = 30Hz, 0.1 = 10Hz etc.. Must be a positive float. Default is 0.33. + * + * @param {float} value + */ + interval(value: number): void; + /** + * + * Disconnect from ExtPlane and then close the TCP socket + */ + disconnect(): void; +} +export {}; diff --git a/dist/Client.js b/dist/Client.js new file mode 100644 index 0000000..87f6fc8 --- /dev/null +++ b/dist/Client.js @@ -0,0 +1,145 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const net_1 = require("net"); +const events_1 = require("events"); +class Client extends events_1.EventEmitter { + constructor(config) { + super(); + this.h = config.host; + this.p = config.port; + this.b = config.broadcast; + this.d = config.debug; + /** + * Socket Connect + */ + this.s = (0, net_1.connect)(config, () => { + if (this.d) + console.log(`Connected to ${this.h}:${this.p}`); + }); + /** + * On Socket End + */ + this.s.on('end', () => { + if (this.d) + console.log('Disconnected from server'); + }); + /** + * On Socket Error + */ + this.s.on('error', (err) => { + if (this.d) + console.log('An error occurred!', err); + }); + } + /** + * + * Key Press + * + * @param {string} key_id - XPlane key ID + */ + key(key_id) { + this.s.write(`key ${key_id}\r\n`); + } + ; + /** + * + * CMD Once + * + * @param {string} cmd - The command + */ + cmd(cmd) { + this.s.write(`cmd once ${cmd}\r\n`); + } + ; + /** + * + * CMD Begin + * + * @param {string} cmd - The command + */ + begin(cmd) { + this.s.write(`cmd begin ${cmd}\r\n`); + } + ; + /** + * + * CMD End + * + * @param {string} cmd - The command + */ + end(cmd) { + this.s.write(`cmd end ${cmd}\r\n`); + } + ; + /** + * + * Button Press + * + * @param {string} button_id - XPlane button ID + */ + button(button_id) { + this.s.write(`but ${button_id}\r\n`); + } + ; + /** + * + * Release Button + * + * @param {string} button_id - XPlane button ID + */ + release(button_id) { + this.s.write(`rel ${button_id}\r\n`); + } + ; + /** + * + * Set a Data Ref to a specific value + * + * @param {string} data_ref - the XPlane Data Ref + * @param {string} value - ExtPlane Values + */ + set(data_ref, value) { + this.s.write(`set ${data_ref} ${value}\r\n`); + } + ; + /** + * + * Subscribe to the XPlane Data Ref + * + * @param {string} data_ref - the XPlane Data Ref + * @param {float} accuracy + */ + subscribe(data_ref, accuracy) { + this.s.write(`sub ${data_ref}${accuracy !== undefined ? ' ' + accuracy : ''}\r\n`); + } + ; + /** + * + * Unsubscribe from the XPlane Data Ref + * + * @param {string} data_ref - the XPlane Data Ref + */ + unsubscribe(data_ref) { + this.s.write(`unsub ${data_ref}\r\n`); + } + ; + /** + * + * How often ExtPlane should update its data from X-Plane, in seconds. Use as high value as possible here for best performance. For example 0.16 would mean 60Hz, 0.33 = 30Hz, 0.1 = 10Hz etc.. Must be a positive float. Default is 0.33. + * + * @param {float} value + */ + interval(value) { + this.s.write(`extplane-set update_interval ${value}\r\n`); + } + /** + * + * Disconnect from ExtPlane and then close the TCP socket + */ + disconnect() { + this.s.write(`disconnect\r\n`); + this.s.end(); + } + ; +} +exports.default = Client; diff --git a/dist/ExtPlaneJs.d.ts b/dist/ExtPlaneJs.d.ts new file mode 100644 index 0000000..97e881d --- /dev/null +++ b/dist/ExtPlaneJs.d.ts @@ -0,0 +1,41 @@ +/** + * + * @name: ExtPlaneJs + * @author: Wade Wildbore - Bluu Interactive + * @author: Brian Vo (Typescript Rewrite) + * @description: ExtPlane TCP Connector for NodeJS + * @see: https://github.com/vranki/ExtPlane - For more information + */ +/// +import { EventEmitter } from "events"; +import Client from './Client'; +interface Config { + host: string; + port: number; + broadcast: boolean; + debug: boolean; +} +export default class ExtPlaneJs extends EventEmitter { + client: Client; + config: Config; + constructor(config: Config); + /** + * + * Parse an Individual Data Ref + * + * @param {string} data_ref - The data_ref response + * @param {function} cb - The done callback + */ + parseDataRef(data_ref: string, cb: Function): any; + /** + * + * Parse ExtPlanes TCP Text Based Response + * + * Override type value conversions from ExtPlanes response + * + * @param {string} - type + * @param {string} - value + */ + parseValue(type: string, value: string): any; +} +export {}; diff --git a/dist/ExtPlaneJs.js b/dist/ExtPlaneJs.js new file mode 100644 index 0000000..987df7e --- /dev/null +++ b/dist/ExtPlaneJs.js @@ -0,0 +1,124 @@ +"use strict"; +/** + * + * @name: ExtPlaneJs + * @author: Wade Wildbore - Bluu Interactive + * @author: Brian Vo (Typescript Rewrite) + * @description: ExtPlane TCP Connector for NodeJS + * @see: https://github.com/vranki/ExtPlane - For more information + */ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const events_1 = require("events"); +const Client_1 = __importDefault(require("./Client")); +const async_1 = __importDefault(require("async")); +class ExtPlaneJs extends events_1.EventEmitter { + constructor(config) { + super(); + // ExtPlane TCP Client + this.client = new Client_1.default(config); + this.config = config; + // Couple the TCP clients on data event to ExtPlaneJs + this.client.s.on('data', (data) => { + this.emit('data', data); + }); + /** + * + * Loaded + * + */ + this.on('loaded', () => { + if (config.debug) + console.log('ExtPlane Ready!'); + }); + /** + * + * Data + * + * @param {string} data + */ + this.on('data', (data) => { + // log incoming TCP stream + //console.log(data.toString()); + if (data.toString().includes('EXTPLANE')) + // loaded.. + return this.emit('loaded'); + // emit parse + return this.emit('parse', data.toString()); + }); + /** + * + * Parse + * + * Either emit single data-ref events, or broadcast all data-ref events on one handler + * + * @param {string} data + */ + this.on('parse', (data) => { + const commands = data.trim().split('\n'); + async_1.default.each(commands, (cmd, cb) => { + this.parseDataRef(cmd, cb); + }, err => { + if (err && config.debug) + console.log(err); + }); + }); + } + /** + * + * Parse an Individual Data Ref + * + * @param {string} data_ref - The data_ref response + * @param {function} cb - The done callback + */ + parseDataRef(data_ref, cb) { + const params = data_ref.split(' '); + // if not data-ref output, break + if (params[0][0] !== 'u') + return false; + // data-ref + data_ref = params[1]; + const type = params[0].substring(1); + const value = this.parseValue(type, params[2]); + // emit - data_ref, value or 'data-ref', data_ref, value + !this.config.broadcast ? this.emit(data_ref, data_ref, value) : this.emit('data-ref', data_ref, value); + // done + return cb(null); + } + ; + /** + * + * Parse ExtPlanes TCP Text Based Response + * + * Override type value conversions from ExtPlanes response + * + * @param {string} - type + * @param {string} - value + */ + parseValue(type, value) { + switch (type) { + // int + case 'i': + return parseInt(value); + // float + case 'f': + return parseFloat(value); + // int array + case 'ia': + return JSON.parse(value); + // float array + case 'fa': + return JSON.parse(value); + // base64 data + case 'b': + return Buffer.from(value, 'base64').toString('utf-8'); + default: + return value; + } + } + ; +} +exports.default = ExtPlaneJs; +; diff --git a/config.json b/dist/config.json similarity index 100% rename from config.json rename to dist/config.json diff --git a/dist/example.d.ts b/dist/example.d.ts new file mode 100644 index 0000000..14b2e4d --- /dev/null +++ b/dist/example.d.ts @@ -0,0 +1,9 @@ +/** + * + * @name: ExtPlaneJs + * @author: Wade Wildbore - Bluu Interactive + * @author: Brian Vo (Typescript Rewrite) + * @description: ExtPlane TCP Connector for NodeJS + * @see: https://github.com/vranki/ExtPlane - For more information + */ +export {}; diff --git a/dist/example.js b/dist/example.js new file mode 100644 index 0000000..fba3d06 --- /dev/null +++ b/dist/example.js @@ -0,0 +1,44 @@ +"use strict"; +/** + * + * @name: ExtPlaneJs + * @author: Wade Wildbore - Bluu Interactive + * @author: Brian Vo (Typescript Rewrite) + * @description: ExtPlane TCP Connector for NodeJS + * @see: https://github.com/vranki/ExtPlane - For more information + */ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const ExtPlaneJs_1 = __importDefault(require("./ExtPlaneJs")); +const config_json_1 = __importDefault(require("./config.json")); +const ExtPlane = new ExtPlaneJs_1.default(config_json_1.default); +// Loaded CB +ExtPlane.on('loaded', () => { + ExtPlane.client.subscribe('sim/flightmodel/engine/ENGN_thro'); + //this.client.unsubscribe('sim/flightmodel/engine/ENGN_thro'); + // See: http://www.xsquawkbox.net/xpsdk/mediawiki/XPLMUtilities - For key and button ids + //this.client.subscribe('sim/flightmodel/position/local_y', 100); + //this.client.subscribe('sim/cockpit/electrical/night_vision_on'); + //this.client.subscribe('sim/flightmodel/position/q'); + ExtPlane.client.subscribe('sim/cockpit2/engine/indicators/N1_percent'); + //this.client.write('sub sim/flightmodel/engine/ENGN_thro'); + //this.client.write('sub sim/cockpit/electrical/night_vision_on'); + //this.client.write('sub sim/flightmodel/position/local_y 100'); + //this.client.write('set sim/flightmodel/engine/ENGN_thro [1,0]'); + //this.client.write('set sim/flightmodel/engine/ENGN_thro [0,0]'); + //this.client.set('data_ref', 'value'); + //this.client.key('key_id'); + //this.client.button('button_id'); + //this.client.release('button_id'); + //this.client.disconnect(); +}); +// Listen on invidiual data-ref events - broadcast = false +ExtPlane.on('sim/flightmodel/engine/ENGN_thro', (data_ref, value) => { + console.log(`${data_ref} - ${value}`); +}); +// Listen for all data-ref events - broadcast = true +ExtPlane.on('data-ref', (data_ref, value) => { + console.log(`${data_ref} - ${value}`); +}); diff --git a/package.json b/package.json index 0a27d01..60af2df 100644 --- a/package.json +++ b/package.json @@ -8,9 +8,10 @@ "extplane", "extplanejs" ], - "main": "ExtPlaneJs.js", + "main": "dist/ExtPlaneJs.js", "scripts": { - "test": "mocha --reporter spec", + "build": "tsc", + "test": "mocha --reporter spec test/unit/ExtPlaneJs.test.js", "start": "node ./example.js" }, "author": "wadedos", @@ -25,12 +26,14 @@ "node": ">= 4.0.0" }, "dependencies": { - "async": "^3.1.0", - "base-64": "^0.1.0" + "async": "^3.1.0" }, "devDependencies": { + "@types/async": "^3.2.15", + "@types/node": "^18.11.2", "assert": "^1.3.0", - "mocha": "^5.2.0" + "mocha": "^10.1.0", + "typescript": "^4.8.4" }, "license": "MIT" } diff --git a/src/Client.ts b/src/Client.ts new file mode 100644 index 0000000..aaa8eab --- /dev/null +++ b/src/Client.ts @@ -0,0 +1,168 @@ +import { connect, Socket } from 'net'; +import { EventEmitter } from 'events'; + +/** + * + * @name: ExtPlaneJs + * @author: Wade Wildbore - Bluu Interactive + * @author: Brian Vo (Typescript Rewrite) + * @description: ExtPlane TCP Connector for NodeJS + * @see: https://github.com/vranki/ExtPlane - For more information + */ + +interface Config { + host: string; + port: number; + broadcast: boolean; + debug: boolean; +} + +export default class Client extends EventEmitter { + h: string; + p: number; + b: boolean; + d: boolean; + + s: Socket; + + constructor(config: Config) { + super(); + + this.h = config.host; + this.p = config.port; + this.b = config.broadcast; + this.d = config.debug; + + /** + * Socket Connect + */ + this.s = connect(config, () => { + if (this.d) console.log(`Connected to ${this.h}:${this.p}`); + }); + + /** + * On Socket End + */ + this.s.on('end', () => { + if (this.d) console.log('Disconnected from server'); + }); + + /** + * On Socket Error + */ + this.s.on('error', (err: Error) => { + if (this.d) console.log('An error occurred!', err); + }); + } + + /** + * + * Key Press + * + * @param {string} key_id - XPlane key ID + */ + key(key_id: string) { + this.s.write(`key ${key_id}\r\n`); + }; + + /** + * + * CMD Once + * + * @param {string} cmd - The command + */ + cmd(cmd: string){ + this.s.write(`cmd once ${cmd}\r\n`); + }; + + /** + * + * CMD Begin + * + * @param {string} cmd - The command + */ + begin(cmd: string){ + this.s.write(`cmd begin ${cmd}\r\n`); + }; + + /** + * + * CMD End + * + * @param {string} cmd - The command + */ + end(cmd: string){ + this.s.write(`cmd end ${cmd}\r\n`); + }; + + /** + * + * Button Press + * + * @param {string} button_id - XPlane button ID + */ + button(button_id: string){ + this.s.write(`but ${button_id}\r\n`); + }; + + /** + * + * Release Button + * + * @param {string} button_id - XPlane button ID + */ + release(button_id: string){ + this.s.write(`rel ${button_id}\r\n`); + }; + + /** + * + * Set a Data Ref to a specific value + * + * @param {string} data_ref - the XPlane Data Ref + * @param {string} value - ExtPlane Values + */ + set(data_ref: string, value: string){ + this.s.write(`set ${data_ref} ${value}\r\n`); + }; + + /** + * + * Subscribe to the XPlane Data Ref + * + * @param {string} data_ref - the XPlane Data Ref + * @param {float} accuracy + */ + subscribe(data_ref: string, accuracy?: number){ + this.s.write(`sub ${data_ref}${accuracy !== undefined ? ' ' + accuracy : ''}\r\n`); + }; + + /** + * + * Unsubscribe from the XPlane Data Ref + * + * @param {string} data_ref - the XPlane Data Ref + */ + unsubscribe(data_ref: string){ + this.s.write(`unsub ${data_ref}\r\n`); + }; + + /** + * + * How often ExtPlane should update its data from X-Plane, in seconds. Use as high value as possible here for best performance. For example 0.16 would mean 60Hz, 0.33 = 30Hz, 0.1 = 10Hz etc.. Must be a positive float. Default is 0.33. + * + * @param {float} value + */ + interval(value: number){ + this.s.write(`extplane-set update_interval ${value}\r\n`); + } + + /** + * + * Disconnect from ExtPlane and then close the TCP socket + */ + disconnect(){ + this.s.write(`disconnect\r\n`); + this.s.end(); + }; +} \ No newline at end of file diff --git a/src/ExtPlaneJs.ts b/src/ExtPlaneJs.ts new file mode 100644 index 0000000..6eeda00 --- /dev/null +++ b/src/ExtPlaneJs.ts @@ -0,0 +1,152 @@ +/** + * + * @name: ExtPlaneJs + * @author: Wade Wildbore - Bluu Interactive + * @author: Brian Vo (Typescript Rewrite) + * @description: ExtPlane TCP Connector for NodeJS + * @see: https://github.com/vranki/ExtPlane - For more information + */ + +import { EventEmitter } from "events"; +import Client from './Client'; +import async from 'async'; + +interface Config { + host: string; + port: number; + broadcast: boolean; + debug: boolean; +} + +export default class ExtPlaneJs extends EventEmitter { + client: Client; + config: Config; + + constructor(config: Config) { + super(); + + // ExtPlane TCP Client + this.client = new Client(config); + this.config = config; + + // Couple the TCP clients on data event to ExtPlaneJs + this.client.s.on('data', (data: string) => { + this.emit('data', data); + }); + + /** + * + * Loaded + * + */ + this.on('loaded', () => { + if (config.debug) console.log('ExtPlane Ready!'); + }); + + /** + * + * Data + * + * @param {string} data + */ + this.on('data', (data: string) => { + + // log incoming TCP stream + //console.log(data.toString()); + + if (data.toString().includes('EXTPLANE')) + // loaded.. + return this.emit('loaded'); + + // emit parse + return this.emit('parse', data.toString()); + + }); + + /** + * + * Parse + * + * Either emit single data-ref events, or broadcast all data-ref events on one handler + * + * @param {string} data + */ + this.on('parse', (data: string) => { + const commands = data.trim().split('\n'); + async.each(commands, (cmd, cb) => { + this.parseDataRef(cmd, cb); + }, err => { + if (err && config.debug) console.log(err); + }); + }); + } + + + /** + * + * Parse an Individual Data Ref + * + * @param {string} data_ref - The data_ref response + * @param {function} cb - The done callback + */ + parseDataRef(data_ref: string, cb: Function) { + + const params = data_ref.split(' '); + + // if not data-ref output, break + if(params[0][0] !== 'u') + return false; + + // data-ref + data_ref = params[1]; + + const type = params[0].substring(1); + const value = this.parseValue(type, params[2]); + + // emit - data_ref, value or 'data-ref', data_ref, value + !this.config.broadcast ? this.emit(data_ref, data_ref, value) : this.emit('data-ref', data_ref, value); + + // done + return cb(null); + }; + + /** + * + * Parse ExtPlanes TCP Text Based Response + * + * Override type value conversions from ExtPlanes response + * + * @param {string} - type + * @param {string} - value + */ + parseValue(type: string, value: string){ + + switch (type) { + // int + case 'i': + return parseInt(value); + + // float + case 'f': + return parseFloat(value); + + // int array + case 'ia': + return JSON.parse(value); + + // float array + case 'fa': + return JSON.parse(value); + + // base64 data + case 'b': + return Buffer.from(value, 'base64').toString('utf-8'); + + default: + return value; + + } + + }; + +}; diff --git a/src/config.json b/src/config.json new file mode 100644 index 0000000..541197e --- /dev/null +++ b/src/config.json @@ -0,0 +1,6 @@ +{ + "host": "127.0.0.1", + "port": 51000, + "broadcast": false, + "debug": false +} diff --git a/example.js b/src/example.ts similarity index 58% rename from example.js rename to src/example.ts index c58a8c2..d5e5aff 100644 --- a/example.js +++ b/src/example.ts @@ -2,47 +2,52 @@ * * @name: ExtPlaneJs * @author: Wade Wildbore - Bluu Interactive + * @author: Brian Vo (Typescript Rewrite) * @description: ExtPlane TCP Connector for NodeJS * @see: https://github.com/vranki/ExtPlane - For more information */ -var ExtPlaneEmitter = require('./ExtPlaneJs'); -var ExtPlane = new ExtPlaneEmitter(require('./config.json')); -// Loaded CB -ExtPlane.on('loaded', function(){ +import ExtPlaneJs from "./ExtPlaneJs"; +import config from './config.json'; - this.client.subscribe('sim/flightmodel/engine/ENGN_thro'); +const ExtPlane = new ExtPlaneJs(config); + +// Loaded CB +ExtPlane.on('loaded', () => { + + ExtPlane.client.subscribe('sim/flightmodel/engine/ENGN_thro'); //this.client.unsubscribe('sim/flightmodel/engine/ENGN_thro'); - - + + // See: http://www.xsquawkbox.net/xpsdk/mediawiki/XPLMUtilities - For key and button ids - -// this.client.subscribe('sim/flightmodel/position/local_y', 100); -// this.client.subscribe('sim/cockpit/electrical/night_vision_on'); -// this.client.subscribe('sim/flightmodel/position/q'); - this.client.subscribe('sim/cockpit2/engine/indicators/N1_percent'); - - + + //this.client.subscribe('sim/flightmodel/position/local_y', 100); + //this.client.subscribe('sim/cockpit/electrical/night_vision_on'); + //this.client.subscribe('sim/flightmodel/position/q'); + ExtPlane.client.subscribe('sim/cockpit2/engine/indicators/N1_percent'); + + //this.client.write('sub sim/flightmodel/engine/ENGN_thro'); //this.client.write('sub sim/cockpit/electrical/night_vision_on'); //this.client.write('sub sim/flightmodel/position/local_y 100'); //this.client.write('set sim/flightmodel/engine/ENGN_thro [1,0]'); //this.client.write('set sim/flightmodel/engine/ENGN_thro [0,0]'); - + //this.client.set('data_ref', 'value'); //this.client.key('key_id'); //this.client.button('button_id'); //this.client.release('button_id'); //this.client.disconnect(); - + }); - + // Listen on invidiual data-ref events - broadcast = false -ExtPlane.on('sim/flightmodel/engine/ENGN_thro', function(data_ref, value){ - console.log(data_ref+' - '+value); +ExtPlane.on('sim/flightmodel/engine/ENGN_thro', (data_ref, value) => { + console.log(`${data_ref} - ${value}`); }); - + // Listen for all data-ref events - broadcast = true -ExtPlane.on('data-ref', function(data_ref, value){ - console.log(data_ref+' - '+value); +ExtPlane.on('data-ref', (data_ref, value) => { + console.log(`${data_ref} - ${value}`); }); + \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..fe2088e --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,104 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + "outDir": "./dist", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "include": ["src/**/*"] +}