├── .gitignore ├── LICENSE ├── README.md ├── ifc2.js ├── package-lock.json └── package.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | 106 | # Privste tests 107 | tests/ 108 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ifc2 2 | 3 | A Javascript client for the Infinite Flight simulator Connect API version 2 4 | 5 | ## Table of Contents 6 | 7 | - [Installing `ifc2`](#installing-ifc2) 8 | - [Using the API](#using-the-api) 9 | - [Connecting to the Infinite Flight Connect v2 API](#connecting-to-the-infinite-flight-connect-v2-api) 10 | - [Including `ifc2` in your scripts/applications](#including-ifc2-in-your-scriptsapplications) 11 | - [Initialisation](#initialisation) 12 | - [Using the Infinite Flight Connect API through `ifc2`](#using-the-infinite-flight-connect-api-through-ifc2) 13 | - [Using the Manifest](#using-the-manifest) 14 | - [Getting states from Infinite Flight](#getting-states-from-infinite-flight) 15 | - [Setting states in Infinite Flight](#setting-states-in-infinite-flight) 16 | - [Running Commands in Infinite Flight](#running-commands-in-infinite-flight) 17 | - [Events](#events) 18 | - [Polling](#polling) 19 | - [Callback](#callbacks) 20 | - [Initialising `ifc2` to Use Callbacks](#initialising-ifc2-to-use-callbacks) 21 | - [Provide a Callback Function to `get` and `pollRegister`](#provide-a-callback-function-to-get-and-pollregister) 22 | - [Dependencies](#dependencies) 23 | - [Applications using `ifc2`](#applications-using-ifc2) 24 | - [Copyright and Licence](#dependencies) 25 | 26 | 27 | ## Installing `ifc2` 28 | 29 | `ifc2` is available as a Node module on [npmjs.com](https://www.npmjs.com/) and can simply be installed with: 30 | 31 | ``` 32 | npm install ifc2 33 | ``` 34 | 35 | ## Using the API 36 | 37 | ### Connecting to the Infinite Flight Connect v2 API 38 | 39 | [Infinite Flight Connect v2](https://infiniteflight.com/guide/developer-reference/connect-api/version-2) is a built-in API that allows you to send commands to Infinite Flight. You must enable it in Infinite Flight Settings > General > "Enable Infinite Flight Connect". 40 | 41 | > An older Connect v1 API still exists and is available in Infinite Flight -- however it is less efficient for many use cases that need to retrieve and/or set states in Infinite Flight at high speed. The [`ifc` JavaScript client](https://github.com/likeablegeek/ifc) offers an interface to the Connect v1 API. 42 | 43 | ### Including `ifc2` in your scripts/applications 44 | 45 | To use `ifc2` you need to include it in your scripts: 46 | 47 | ``` 48 | let IFC2 = require("ifc2"); 49 | ``` 50 | 51 | Or, if you aren't installing with `npm` then you can simply clone this repository and directly reference `ifc2.js`: 52 | 53 | ``` 54 | let IFC2 = require("/path/to/ifc2.js); 55 | ``` 56 | 57 | ### Initialisation 58 | 59 | To initialise `ifc2` and connect to an Infinite Flight device you use the `init` function. The `init` function takes the following arguments: 60 | 61 | `init(successCallback, {params})` 62 | 63 | * `successCallback` is the function to be executed after the connection has been established with Infinite Flight 64 | * `params` is an optional parameter which allows you to configure and control various aspects of the module, including: 65 | * `callback` is a boolean value indicating if callback functions should be used to return values instead of the standard `ifc2` event model; default is `false` 66 | * `infoCallback` is a function to use as callback when `ifc2` fetches certain default information during initialisation (such as livery); if this function is not provided when `callback` is true, it will default to an empty function that takes no action 67 | * `pollThrottle` is an integer value specifying how many milliseconds to wait between each polling request to Infinite Flight; default is `0` 68 | * `enableLog` is a boolean value to enable/disable logging in the Module; default is `false` 69 | * `loggingLevel` is an integer value for logging level in the module (2: INFO, 1: WARN, 0: ERROR); default is 0 (ERROR) 70 | * `keepAlive` is a boolean value indicating if the socket connection should have TCP keep alive enabled; default is `false` 71 | * `doReconnect` is a boolean value indicating if `ifc2` should attempt to reconnect the socket connection when the connection generates an error; default is `true` 72 | * `timeout` is an integer value indicating if the socket connection should generate timeout events after a set number of milliseconds -- no timeouts occur if set to `0`; default is `0` 73 | * `host` is the IP address of a device running Infinite Flight to which you want to connect without polling for UDP broadcasts from Infinite Flight; if not set the module will wait for a UDP broadcast to determine which device to connect to 74 | * `port` is the port to use when manually connecting to a device running Infinite Flight without polling for UDP broadcasts from Infinite Flight; if not set the module will wait for a UDP broadcast to determine which device to connect to 75 | 76 | Example : 77 | 78 | ``` 79 | IFC2.init( 80 | function() { 81 | console.log("IFC connected"); 82 | IFC2.get("aircraft/0/pitch"); 83 | }, 84 | { 85 | "enableLog": true, 86 | "loggingLevel": 1, 87 | "host": "192.168.2.123", 88 | "port": 10112 89 | } 90 | ) 91 | ``` 92 | 93 | If you do not include a host and port, `ifc2` will search your local network for an active Infinite Flight device and connect to the first device to respond. 94 | 95 | ## Using the Infinite Flight Connect API through `ifc2` 96 | 97 | ### Using the Manifest 98 | 99 | Version 2 of the Infinite Flight Connect API uses a manifest to specify what statuses and commands are available for any specific aircraft. After connecting to Infinite Flight, `ifc2` will fetch the manifest for your aircraft before becoming ready for use. 100 | 101 | Once the manifest is successfully retrieved, `ifc2` will emit and `IFC2manifest` event which you can use in your script to respond to the manifest being fetched. The even will return an object containing the manifest. The manifest object will contain a series of objects where the key is the commnd name. Each of these object will contain two properties: 102 | 103 | * `command`: The numeric command used when invoking the command through the API 104 | * `type`: An integer specifying the data type used by the command when you data is sent/received to/from the API 105 | 106 | The data types are: 107 | 108 | * `0`: Boolean 109 | * `1`: Four-byte integer 110 | * `2`: Floating point number 111 | * `3`: Double-length floating point number 112 | * `4`: String 113 | * `5`: Long string 114 | 115 | An example of the manifest looks like this: 116 | 117 | ``` 118 | { 119 | 'infiniteflight/cameras/14/roll': { command: 891, type: 3 }, 120 | 'aircraft/0/systems/nav_sources/adf/2/distance_to_glide_path': { command: 515, type: 2 }, 121 | 'infiniteflight/cameras/2/z_angle': { command: 782, type: 3 }, 122 | 'infiniteflight/cameras/4/x_angle': { command: 804, type: 3 }, 123 | 'api_joystick/buttons/8/name': { command: 81, type: 4 }, 124 | 'api_joystick/buttons/47/name': { command: 159, type: 4 }, 125 | 'aircraft/0/systems/nav_sources/nav/4/distance_to_glide_path': { command: 461, type: 2 }, 126 | 'api_joystick/buttons/30/value': { command: 126, type: 1 }, 127 | 'aircraft/0/systems/nav_sources/nav/2/location/longitude': { command: 389, type: 3 }, 128 | ... 129 | } 130 | ``` 131 | 132 | You can handle the `IFC2manifest` event by using the `on` method of your `ifc2` object. For example: 133 | 134 | ``` 135 | IFC2.on("IFC2manifest", function(manifest) { 136 | // You can respond to the IFC2manifest event here -- the manifest object will be in the "manifest" variab;e 137 | }); 138 | ``` 139 | 140 | ### Getting states from Infinite Flight 141 | 142 | The majority of the commands in the manifest allow you to retrieve state information from various aircraft information and systems. 143 | 144 | Some examples of this are: 145 | 146 | * `aircraft/0/heading_magnetic`: Returns the (magnetic) heading in radians as a floating point number 147 | * `aircraft/0/altitude_msl`: Returns the altitude relative to sea level in feet as an integer 148 | * `aircraft/0/bank`: Returns the bank angle in radians as a floating point number 149 | * `aircraft/0/flightplan`: Returns the current flight plan (if any) as a string 150 | 151 | You can fetch states by using the `get` function and passing the command name from the manifest as a parameter to the function. For instance, to fetch the bank angle, you would use: 152 | 153 | ``` 154 | IFC2.get("aircraft/0/bank"); 155 | ``` 156 | 157 | When fetching states, the `ifc2` module treats this as an asynchronous activity to avoid blocking while waiting for a response from Infinite Flight. When `ifc2` receives a response, by default it will emit an `IFC2data` event and return a data object containing two properties: 158 | 159 | * `command`: The name of the command being returned 160 | * `data`: The value returned by Infinite Flight for the command 161 | 162 | In this case, we could simply log the data returned by the event like this: 163 | 164 | ``` 165 | IFC2.on("IFC2data", function(data) { 166 | console.log(data); 167 | }); 168 | ``` 169 | 170 | If we had sent the `aircraft/0/bank` command as in the example above, the resulting console output displayed when we receive the associated `IFC2data` event would look like this: 171 | 172 | ``` 173 | { command: 'aircraft/0/bank', data: 0.0004447073442861438 } 174 | ``` 175 | 176 | > `ifc2` offers an alternative to events using callback functions which is discussed below 177 | 178 | Additionally, all state values fetched from Infinite Flight are stored in the `ifData` property of the `ifc2` object. At any time, this object will have one entry for each state ever fetched since `ifc2` was instantiated and will contain the last fetched value for that state along with a timestamp. The timestamp will be represented as a [UNIX-style time stamp](https://www.unixtimestamp.com/). 179 | 180 | This allows you to get a list of all states you have ever requested and their most recent fetched values. For instance, the following code snip requests the bank and pitch and outputs the `ifData` object each time the `IFC2data` event is triggered: 181 | 182 | ``` 183 | IFC2.on("IFC2data", function(data) { 184 | console.log(IFC2.ifData); 185 | }); 186 | 187 | IFC2.get("aircraft/0/bank"); 188 | IFC2.get("aircraft/0/pitch"); 189 | ``` 190 | 191 | The output would look like this: 192 | 193 | ``` 194 | { 195 | 'aircraft/0/bank': { data: 0.0004445366212166846, ts: 1640273977393 } 196 | } 197 | { 198 | 'aircraft/0/bank': { data: 0.0004445366212166846, ts: 1640273977393 }, 199 | 'aircraft/0/pitch': { data: 0.004999594762921333, ts: 1640273977399 } 200 | } 201 | ``` 202 | 203 | Additionally, immediately after connecting to an Infinite Flight device, `ifc2` will fetch the following states and add them to `ifData` so they will be available shortly after connection to provide context about the Infinite Flight device and aircraft being used: 204 | 205 | ``` 206 | infiniteflight/app_state 207 | infiniteflight/app_version 208 | infiniteflight/api_version 209 | aircraft/0/name 210 | aircraft/0/livery 211 | ``` 212 | 213 | Each of these requests will generate an `IFC2data` event when the API returns the relevant data to `ifc2` and the data will be available in `ifData`. 214 | 215 | ### Setting states in Infinite Flight 216 | 217 | Many of the state commands in a manifest can also be used to set a state such as changing the position of flaps. 218 | 219 | You can set states by using the `set` function and passing the command name from the manifest and a new values for the state as aparameters to the function. For instance, to fetch the flap position to `3` you could use the following: 220 | 221 | ``` 222 | IFC2.set("aircraft/0/systems/flaps/state",3); 223 | ``` 224 | 225 | > Not all states can be set but there is no indication in the manifest of which states can be set nor is the set of states which can be set consistent for each aircraft. Also, Infinite Flight doesn't return any confirmation after a state is set so the only way to determine if a state is successfully set is to fetch the state after setting it and seeing if is updated/changed. 226 | 227 | ### Running commands in Infinite Flight 228 | 229 | In addition to the state commands used by the `get` and `set` functions in `ifc2`, the API offers a set of special commands which can been issued to Infinite Flight to perform tasks commonly performed through the user interface of Infinite Flight -- tasks such as toggling the parking brakes or the autopilot state. 230 | 231 | These are distringuished in the manifest by two attributes: 232 | 233 | * The command names start with `commands/` 234 | * The data type is `-1` indicating there is no data to send or receive 235 | 236 | A representative list of these commands is: 237 | 238 | * `commands/ElevatorTrimUp` 239 | * `commands/ElevatorTrimDown` 240 | * `commands/ThrottleUpCommand` 241 | * `commands/ThrottleDownCommand` 242 | * `commands/SetThrottleCommand` 243 | * `commands/SetCockpitCamera` 244 | * `commands/SetVirtualCockpitCameraCommand` 245 | * `commands/SetFollowCameraCommand` 246 | * `commands/SetFlyByCamera` 247 | * `commands/SetOnboardCameraCommand` 248 | * `commands/SetTowerCameraCommand` 249 | * `commands/NextCamera` 250 | * `commands/PrevCamera` 251 | * `commands/CameraMoveLeft` 252 | * `commands/CameraMoveRight` 253 | * `commands/CameraMoveDown` 254 | * `commands/CameraMoveUp` 255 | * `commands/CameraMoveHorizontal` 256 | * `commands/CameraMoveVertical` 257 | * `commands/CameraZoomIn` 258 | * `commands/CameraZoomOut` 259 | * `commands/Reset` 260 | * `commands/ShowATCWindowCommand` 261 | * `commands/ATCEntry1` 262 | * `commands/ATCEntry2` 263 | * `commands/ATCEntry3` 264 | * `commands/ATCEntry4` 265 | * `commands/ATCEntry5` 266 | * `commands/ATCEntry6` 267 | * `commands/ATCEntry7` 268 | * `commands/ATCEntry8` 269 | * `commands/ATCEntry9` 270 | * `commands/ATCEntry10` 271 | * `commands/Live.SetCOMFrequencies` 272 | * `commands/FlightPlan.AddWaypoints` 273 | * `commands/FlightPlan.Clear` 274 | * `commands/FlightPlan.ActivateLeg` 275 | * `commands/Brakes` 276 | * `commands/ParkingBrakes` 277 | * `commands/FlapsDown` 278 | * `commands/FlapsUp` 279 | * `commands/FlapsFullDown` 280 | * `commands/FlapsFullUp` 281 | * `commands/Aircraft.SetFlapState` 282 | * `commands/Spoilers` 283 | * `commands/LandingGear` 284 | * `commands/Pushback` 285 | * `commands/FuelDump` 286 | * `commands/ReverseThrust` 287 | * `commands/LandingLights` 288 | * `commands/TaxiLights` 289 | * `commands/StrobeLights` 290 | * `commands/BeaconLights` 291 | * `commands/NavLights` 292 | * `commands/SetLandingLightsState` 293 | * `commands/SetTaxiLightsState` 294 | * `commands/SetStrobeLightsState` 295 | * `commands/SetBeaconLightsState` 296 | * `commands/SetNavLightsState` 297 | * `commands/Autopilot.Toggle` 298 | * `commands/Autopilot.SetState` 299 | * `commands/Autopilot.SetHeading` 300 | * `commands/Autopilot.SetAltitude` 301 | * `commands/Autopilot.SetVS` 302 | * `commands/Autopilot.SetSpeed` 303 | * `commands/Autopilot.SetHeadingState` 304 | * `commands/Autopilot.SetAltitudeState` 305 | * `commands/Autopilot.SetVSState` 306 | * `commands/Autopilot.SetSpeedState` 307 | * `commands/Autopilot.SetApproachModeState` 308 | * `commands/Autopilot.SetLNavApproachModeState` 309 | * `commands/ToggleHUD` 310 | * `commands/ToggleFlightPathVector` 311 | * `commands/AutoStart` 312 | * `commands/TogglePause` 313 | * `commands/Selection Mode` 314 | * `commands/Rotation Mode` 315 | * `commands/Translation Mode` 316 | * `commands/Delete Selected` 317 | * `commands/Engine.Start` 318 | * `commands/Engine.Stop` 319 | 320 | In `ifc2` you can use these commands with the `run` function as in this example to toggle the parking brakes: 321 | 322 | ``` 323 | IFC2.run("commands/ParkingBrakes"); 324 | ``` 325 | 326 | ### Events 327 | 328 | The module emits the following events: 329 | 330 | * `IFC2data`: Emitted when data is returned by the API; the event returns the results from the API to listeners as a JSON object. 331 | * `IFC2manifest`: Emitted after the manifest is retrieved; the event returns the manifest to the listener as a JSON object. 332 | * `IFC2msg`: Emmitted when the `ifc2` module needs to send a log message to the calling script; the event returns a JSON object containing the message and the log level of the message to the listener. 333 | 334 | The following is an example of binding an event to the `IFC2Data` events in a calling scripts: 335 | 336 | ``` 337 | var IFC2 = require("ifc2"); 338 | 339 | IFC2.eventEmitter.addListener('IFC2data', function(data) { 340 | // perform actions on the data 341 | console.log(data); 342 | }); 343 | ``` 344 | 345 | ### Polling 346 | 347 | Some applications will need to regularly retrieve state information from Infinite Flight. 348 | 349 | To enable this, `ifc2` offers a polling mechanism which allows you to register a list of states to retrieve on rolling, sequential basis. 350 | 351 | The polling mechanism simply works through the list of states in order they are registered -- when it receives the value of a state, it requests the next in the list and moves to the next when that state is returned by Infinite Flight. When it gets to the end of the list it returns to the start of the list and continues. 352 | 353 | To register a state in the polling list, use the `pollRegister` function: 354 | 355 | ``` 356 | IFC2.pollRegister("aircraft/0/heading_magnetic"); 357 | IFC2.pollRegister("aircraft/0/bank"); 358 | ``` 359 | 360 | As with the `get` function, each time a value is returned by Infinite Flight during the polling, an `IFC2data` event will be emitted. Also, the last retrieved value for each state will be stored and retained in the `ifData` data object for future reference. 361 | 362 | > `ifc2` offers an alternative to events using callback functions which is discussed below 363 | 364 | `ifc2` will continue to poll for the states in the polling queue until either they are deregistered or `ifc2` disconnects from Infinite Flight`. 365 | 366 | You can register a command from the polling list with the `pollDeregister` function: 367 | 368 | ``` 369 | IFC2.pollRegister("aircraft/0/heading_magnetic"); 370 | ``` 371 | 372 | Although this means `ifc2` will stop polling the state, the last retrieved value for the state will persist in the `ifData` data objects. 373 | 374 | #### Throttling 375 | 376 | By default, polling happens without delays. That means as soon as `ifc2` receives back a response from Infinite Flight from a poll request, it immeidately sends the next request in the polling queue. That means a very high rate of requests to Infinite Flight and a very high rate of results being returned. 377 | 378 | For some applications you may want to throttle the polling mechanism and insert a fixed delay between receiving a response and sending the next polling request. You do this by specifying the `pollThrottle` parameter when initialising `ifc2`. 379 | 380 | For instance, to wait 100 milliseconds before seconding the next request in the polling queue, you specify this when initialising: 381 | 382 | ``` 383 | IFC2.init( 384 | function() { 385 | console.log("IFC connected"); 386 | IFC2.get("aircraft/0/pitch"); 387 | }, 388 | { 389 | "pollThrottle": 100, 390 | "enableLog": true, 391 | "loggingLevel": 1, 392 | "host": "192.168.2.123", 393 | "port": 10112 394 | } 395 | ) 396 | ``` 397 | 398 | Keep in mind that if you are polling multiple states, this can lead to a significant delay for getting updates to a specific state. 399 | 400 | For instance, consider registering five states for polling: 401 | 402 | ``` 403 | IFC2.pollRegister('aircraft/0/latitude'); 404 | IFC2.pollRegister('aircraft/0/longitude'); 405 | IFC2.pollRegister('aircraft/0/bank'); 406 | IFC2.pollRegister('aircraft/0/pitch'); 407 | IFC2.pollRegister('aircraft/0/altitude_msl'); 408 | ``` 409 | 410 | This means that the polling works sequentially like this: 411 | 412 | * Fetch `aircraft/0/latitude` 413 | * Once a response is recceived, fetch `aircraft/0/longitude` 414 | * Once a response is recceived, fetch `aircraft/0/bank` 415 | * Once a response is recceived, fetch `aircraft/0/pitch` 416 | * Once a response is recceived, fetch `aircraft/0/altitude_msl` 417 | * Once a response is recceived, fetch `aircraft/0/latitude` 418 | * Once a response is recceived, fetch `aircraft/0/longitude` 419 | * Once a response is recceived, fetch `aircraft/0/bank` 420 | * Once a response is recceived, fetch `aircraft/0/pitch` 421 | * etc. 422 | 423 | If a `pollThrottle` value is set to `100` this means the following will happen: 424 | 425 | * Fetch `aircraft/0/latitude` 426 | * Once a response is recceived, wait for 100 millisecnds and then fetch `aircraft/0/longitude` 427 | * Once a response is recceived, wait for 100 millisecnds and then fetch `aircraft/0/bank` 428 | * Once a response is recceived, wait for 100 millisecnds and then fetch `aircraft/0/pitch` 429 | * Once a response is recceived, wait for 100 millisecnds and then fetch `aircraft/0/altitude_msl` 430 | * Once a response is recceived, wait for 100 millisecnds and then fetch `aircraft/0/latitude` 431 | * Once a response is recceived, wait for 100 millisecnds and then fetch `aircraft/0/longitude` 432 | * Once a response is recceived, wait for 100 millisecnds and then fetch `aircraft/0/bank` 433 | * Once a response is recceived, wait for 100 millisecnds and then fetch `aircraft/0/pitch` 434 | * etc. 435 | 436 | As a result, this means that there will be at least a 500 millisecond delay between requests for `aircraft/0/latitude`, at least a 500 millisecond delay between requests for `aircraft/0/longitude`, and the same for all the states in the polling queue. 437 | 438 | ### Callbacks 439 | 440 | By default, `ifc2` returns state values to the calling script by emitting the `IFC2data` event. However, some use cases are better serverd by using callbacks. For this reason, `ifc2` offers an alternate callback mechanism. 441 | 442 | Using callbacks instead of events is an either-or proposition. When you choose to use callbacks, the `IFC2data` event will not be emitted by `ifc2`. 443 | 444 | > While the `IFC2data` event is not emitted, the `IFC2manifest` and `IFC2msg` events will still be emitted. 445 | 446 | To use callbacks to receive state data returned by Infinite Flight requires three steps: 447 | 448 | 1. Set the `callback` parameter when initialising `ifc2` 449 | 450 | 2. Provide an callback function to handle default state information fetched by `ifc2` during initialisation such as `aircraft/0/livery` 451 | 452 | 3. Specify a callback function when invoking `get` or `pollRegister` 453 | 454 | #### Initialising `ifc2` to Use Callbacks 455 | 456 | To use callbacks make sure you set the `callback` parameter to `true` and provide an callback function with the `infoCallback` parameter: 457 | 458 | ``` 459 | IFC2.init( 460 | function() { 461 | console.log("IFC connected"); 462 | IFC2.get("aircraft/0/pitch"); 463 | }, 464 | { 465 | "callback": true, 466 | "infoCallback": (result) => { console.log(result); } 467 | "enableLog": true, 468 | "loggingLevel": 1, 469 | "host": "192.168.2.123", 470 | "port": 10112 471 | } 472 | ) 473 | ``` 474 | 475 | The callback function set in `infoCallback` will be invoked when Infinite Flight returns each of the following five values which `ifc2` requests during initialisation: 476 | 477 | ``` 478 | infiniteflight/app_state 479 | infiniteflight/app_version 480 | infiniteflight/api_version 481 | aircraft/0/name 482 | aircraft/0/livery 483 | ``` 484 | 485 | If you don't want to handle and take action with these values when they returned, leave out the `infoCallback` parameter since by default `ifc2` will use an empty function for this callback. 486 | 487 | #### Provide a Callback Function to `get` and `pollRegister` 488 | 489 | Both the `get` and `pollRegister` functions accept a callback function as a second parameter. When using callback functions instead of events, this is a required parameter as in these examples: 490 | 491 | ``` 492 | IFC2.get('aircraft/0/pitch', (result) => { console.log(result); }); 493 | IFC2.polLRegister('aircraft/0/pitch', (result) => { console.log(result); }); 494 | ``` 495 | 496 | ## Dependencies 497 | 498 | `ifc2` depends on the following `npm`/Node packages: 499 | 500 | * [`dgram`](https://nodejs.org/api/dgram.html) - core Node module: For listening for UDP broadcast messages from Infinite Flight 501 | * [`net`](https://nodejs.org/api/net.html) - core Node module: For establishing TCP socket connections with Infinite Flight to communicate with the Connect v2 API 502 | * [`events`](https://nodejs.org/api/events.html) - core Node module: For emitting events to calling scripts 503 | * [`stringview`](https://www.npmjs.com/package/stringview) - `npm` module: Extends Node data views to support string data types 504 | 505 | ## Applications using `ifc2` 506 | 507 | The following applications are using `ifc2` and have asked for a link from this README: 508 | 509 | - [PanelNinja](https://flightsim.ninja/#panelninja): A Windows and Mac OS tool for displaying instrument panels for Infinite Flight flights. 510 | 511 | > If you are using `ifc2` and would like to have your application listed here, submit a query through the [FlightSim Ninja support site](https://support.flightsim.ninja/) or contact the author (@likeablegeek) by a direct message in the [Infinite Flight Community](https://community.infiniteflight.com/). 512 | 513 | ## Copyright and License 514 | 515 | This version is `ifc2` Copyright 2022, @likeablegeek. Distributed by [FlightSim Ninja](https://flightsim.ninja/). 516 | 517 | You may not use this work/module/file except in compliance with the License. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 518 | -------------------------------------------------------------------------------- /ifc2.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | ifc2: A Node JS module providing a client the Infinite Flight Connect version 2 API. 4 | 5 | Version: 1.0.22 6 | Author: @likeablegeek (https://likeablegeek.com/) 7 | Distributed by: FlightSim Ninja (http://flightim.ninja) 8 | 9 | Copyright 2022. 10 | 11 | Licensed under the Apache License, Version 2.0 (the "License"); 12 | you may not use this file except in compliance with the License. 13 | You may obtain a copy of the License at 14 | 15 | http://www.apache.org/licenses/LICENSE-2.0 16 | 17 | Unless required by applicable law or agreed to in writing, software 18 | distributed under the License is distributed on an "AS IS" BASIS, 19 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 20 | See the License for the specific language governing permissions and 21 | limitations under the License. 22 | 23 | */ 24 | 25 | /***** 26 | * Import required modules 27 | */ 28 | const dgram = require('dgram'); // For listening for UDP broadcasts 29 | const net = require('net'); // For establishing socket connections 30 | const events = require('events'); // For emitting events back to calling scripts 31 | const { SlowBuffer } = require('buffer'); 32 | require('stringview'); // DataView extensions for reading/writing strings 33 | 34 | /**** 35 | * Define IFC2 object 36 | */ 37 | let IFC2 = { 38 | 39 | /***** 40 | * Module name 41 | */ 42 | name: "IFC2", // Module name 43 | 44 | /***** 45 | * Constants for referencing error levels in logging 46 | */ 47 | INFO: 3, 48 | WARN: 2, 49 | ERROR: 1, 50 | MANDATORY: 0, 51 | 52 | /***** 53 | * Constants for sending the correct flag for get/set calls in v2 API 54 | */ 55 | GETCMD: 0, 56 | SETCMD: 1, 57 | RUNCMD: -1, 58 | LE: true, 59 | 60 | /***** 61 | * Constant for the manifest command 62 | */ 63 | MANIFESTCMD: -1, 64 | 65 | /***** 66 | * Constants for IF Connect v2 data types 67 | */ 68 | BOOLEAN: 0, 69 | INTEGER: 1, 70 | FLOAT: 2, 71 | DOUBLE: 3, 72 | STRING: 4, 73 | LONG: 5, 74 | 75 | /***** 76 | * Object to hold connection data, manifest data, socket objects and more 77 | */ 78 | infiniteFlight: { // Infinite Flight connection data 79 | broadcastPort: 15000, // Port to listen for broadcast from Infinite Flight 80 | serverPort: 10112, // Port for socket connection to Infinite Flight 81 | serverAddress: '127.0.0.1', // Default is localhost just as a placeholder 82 | clientSocket: new net.Socket(), // Socket for regular one-off commands 83 | manifestSocket: new net.Socket(), // Socket for fetching the manifest 84 | pollSocket: new net.Socket(), // Socket for the regular polling loop 85 | manifestTimeout: 1000, // How long to wait for the manifest before giving up 86 | manifestData: "", // String to hold raw manifest data 87 | manifestByName: {}, // Object to hold the manifest organised by command name 88 | manifestByCommand: {}, // Object to hold the manifest organised by command number 89 | manifestLength: 0, // Manifest length -- zero is initial placeholder 90 | manifestBuffer: null // Placeholder variable for future manifest buffer 91 | }, 92 | 93 | /***** 94 | * Default logging state 95 | */ 96 | enableLog: false, // Control logging -- default is false 97 | logLevel: this.MANDATORY, // Logging message level -- default is MANDATORY 98 | 99 | /***** 100 | * Default keepalive, reconnect and timeout 101 | */ 102 | keepAlive: false, // By default we don't keep alive 103 | doReconnect: true, // By default we reconnect when sockets error 104 | timeout: 0, // By default we don't time out the sockets (except the manifest) 105 | 106 | /***** 107 | * State tracking: are we connected? are we waiting? 108 | */ 109 | isConnected: false, // Are we connected to IF? 110 | isWaiting: false, // Are we waiting? 111 | isPollWaiting: false, // Are we waiting for a poll result?, 112 | isCallback: false, // Are we using callbacks? 113 | 114 | /***** 115 | * Command queues 116 | */ 117 | q: [], // Queue for processing one-off requests 118 | pollQ: [], // Queue for recurring poll requests 119 | pollCurrent: 0, // Position in poll queue, 120 | pollWaiting: 0, // Place holder for poll command currently pending data from IF 121 | callbacks: {}, // Holds callback functions for when callbacks are enabled 122 | 123 | /***** 124 | * Timeout placeholder for slow polling handler 125 | */ 126 | pollTimeout: null, 127 | 128 | /***** 129 | * 130 | * Queue buffers 131 | * 132 | */ 133 | 134 | qBuffer: null, 135 | pollBuffer: null, 136 | 137 | /***** 138 | * List to keep track of the commands pending responses from IF 139 | */ 140 | waitList: [], 141 | 142 | /***** 143 | * Event emitter for return events to client 144 | */ 145 | eventEmitter: new events.EventEmitter(), 146 | 147 | /***** 148 | * Default empty infoCallback function 149 | */ 150 | 151 | infoCallback: () => {}, 152 | 153 | /***** 154 | * Default polling throttle (0ms) 155 | */ 156 | 157 | pollThrottle: 0, 158 | 159 | /***** 160 | * Object to hold last value fetched for all states that have been fetched from API 161 | */ 162 | ifData: {}, 163 | 164 | /***** 165 | * Logging function 166 | */ 167 | log: (msg,level = IFC2.logLevel) => { // generic logging function 168 | if (IFC2.enableLog) { 169 | if (level <= IFC2.logLevel) { 170 | let info = "("; 171 | info += (IFC2.isConnected) ? 'c' : ''; 172 | info += (IFC2.isWaiting) ? 'w' : ''; 173 | info += IFC2.q.length; 174 | info += IFC2.pollQ.length; 175 | info += ")"; 176 | } 177 | } 178 | }, 179 | 180 | /***** 181 | * Function to allow client to define listener for events emitted by module 182 | */ 183 | on: (event, listener) => { 184 | IFC2.log("Setting listener for: " + event); 185 | IFC2.eventEmitter.on(event, listener); 186 | }, 187 | 188 | /***** 189 | * Returns command formatted to send on TCP socket to API for getState commands 190 | */ 191 | getCommand: (cmd) => { // Prepare command ready to send to IF 192 | 193 | IFC2.log('getCommand: ' + cmd); 194 | 195 | let abCommand = new ArrayBuffer(5); 196 | let dvCommand = new DataView(abCommand); 197 | dvCommand.setInt32(0, cmd, IFC2.LE); // Encode the command itself 198 | dvCommand.setInt8(4, IFC2.GETCMD, IFC2.LE); // Encode get marker 199 | let u8Command = new Uint8Array(abCommand); 200 | 201 | IFC2.log("getCommand: " + u8Command); 202 | 203 | return u8Command; 204 | 205 | }, 206 | 207 | /***** 208 | * Sends command formatted to send on TCP socket to API for setState commands 209 | */ 210 | setCommand: (cmd, val) => { // Prepare command ready to send to IF 211 | 212 | IFC2.log('setCommand: ' + cmd + "," + val, IFC2.MANDATORY); 213 | 214 | let cmdType = IFC2.infiniteFlight.manifestByCommand[cmd].type; 215 | 216 | let dataLength = 1; 217 | 218 | switch(cmdType) { 219 | case IFC2.INTEGER: 220 | dataLength = 4; 221 | break; 222 | case IFC2.FLOAT: 223 | dataLength = 4; 224 | break; 225 | case IFC2.DOUBLE: 226 | dataLength = 4; 227 | break; 228 | case IFC2.STRING: 229 | dataLength = 4 + val.length; // length is 4 for string length + string length 230 | break; 231 | case IFC2.LONG: 232 | dataLength = 8; 233 | break; 234 | } 235 | 236 | let abCommand = new ArrayBuffer(5 + dataLength); // 5 is command + true/false divider + value to be sent 237 | let dvCommand = new DataView(abCommand); 238 | dvCommand.setInt32(0, cmd, IFC2.LE); // Encode the command itself 239 | dvCommand.setInt8(4, IFC2.SETCMD, IFC2.LE); // Encode set marker 240 | 241 | switch(cmdType) { 242 | case IFC2.BOOLEAN: 243 | dvCommand.setInt8(5, val, true); 244 | break; 245 | case IFC2.INTEGER: 246 | dvCommand.setInt32(5, val, true); 247 | break; 248 | case IFC2.FLOAT: 249 | dvCommand.setFloat32(5, val, true); 250 | break; 251 | case IFC2.DOUBLE: 252 | dvCommand.setFloat64(5, val, true); 253 | break; 254 | case IFC2.STRING: 255 | dvCommand.setInt32(5, val.length, true); 256 | dvCommand.setString(9, val); 257 | break; 258 | case IFC2.LONG: 259 | dvCommand.setBigInt64(5, val, true); 260 | break; 261 | } 262 | 263 | let u8Command = new Uint8Array(abCommand); 264 | 265 | IFC2.log("setCommand u8Command: " + u8Command, IFC2.MANDATORY); 266 | 267 | IFC2.log(dvCommand, IFC2.MANDATORY); 268 | 269 | return u8Command; 270 | 271 | }, 272 | 273 | 274 | /***** 275 | * Process next command in one-off command queue (if any commands are pending) 276 | */ 277 | processQueue: () => { 278 | 279 | IFC2.log("processQueue: isConnected: " + IFC2.isConnected); 280 | IFC2.log("processQueue: isWaiting: " + IFC2.isWaiting); 281 | 282 | if (IFC2.isConnected && !IFC2.isWaiting) { // only send if connected and not already waiting for a response 283 | 284 | IFC2.log("Q length: " + IFC2.q.length); 285 | 286 | if (IFC2.q.length > 0) { // only send if there is a command in the queue 287 | 288 | let cmdObj = IFC2.q.shift(); // grab the next command from the queue 289 | 290 | if (IFC2.infiniteFlight.manifestByName[cmdObj.cmd]) { // only send if the command is in the manifest 291 | 292 | IFC2.isWaiting = true; // indicate we are now waiting for a response 293 | 294 | IFC2.log('Sending command: ' + cmdObj.cmdCode); 295 | 296 | IFC2.infiniteFlight.clientSocket.write(cmdObj.cmdBuf, () => { // Send the command 297 | IFC2.waitList.push(cmdObj.cmdCode); // Add the command to the wait list 298 | IFC2.log("Command sent: " + cmdObj.cmdCode); 299 | }); 300 | 301 | } 302 | 303 | } else { 304 | 305 | setTimeout(IFC2.processQueue, 250); // No command in queue -- try again in 250ms 306 | 307 | } 308 | 309 | } 310 | 311 | }, 312 | 313 | /**** 314 | * Add a one-off command to the command queue 315 | */ 316 | enqueueCommand: (cmd, action = IFC2.GETCMD, val) => { 317 | 318 | IFC2.log("Enqueueing: " + cmd + "," + action); 319 | 320 | let cmdCode = IFC2.infiniteFlight.manifestByName[cmd].command; // Get the command code 321 | 322 | let cmdBuf = (action == IFC2.GETCMD || action == IFC2.RUNCMD) ? IFC2.getCommand(cmdCode) : IFC2.setCommand(cmdCode,val); 323 | 324 | if (action == IFC2.GETCMD) { 325 | IFC2.q.push({cmd: cmd, cmdCode: cmdCode, cmdBuf: cmdBuf}); // Push the command into the queue 326 | IFC2.log(IFC2.q); 327 | if (IFC2.q.length > 0 && !IFC2.isWaiting) { IFC2.processQueue(); } // If not currently waiting for a response, start processing the queue 328 | } else if (action == IFC2.SETCMD) { 329 | IFC2.infiniteFlight.clientSocket.write(cmdBuf, () => { // Send the command 330 | IFC2.log("SetState Command sent: " + cmdBuf); 331 | }); 332 | } else if (action == IFC2.RUNCMD) { 333 | IFC2.infiniteFlight.clientSocket.write(cmdBuf, () => { // Send the command 334 | IFC2.log("Run Command sent: " + cmdBuf); 335 | }); 336 | } 337 | 338 | }, 339 | 340 | /***** 341 | * Function for client to request a one-off get command 342 | */ 343 | get: (cmd, callback) => { 344 | 345 | IFC2.log("Processing get request: " + cmd); 346 | 347 | if (IFC2.isConnected) { // Only enqueue if connected 348 | 349 | if (IFC2.isCallback) { // Save the callback function if we are using it 350 | IFC2.callbacks[cmd] = callback; 351 | } 352 | 353 | IFC2.enqueueCommand(cmd,IFC2.GETCMD); 354 | } 355 | 356 | }, 357 | 358 | /***** 359 | * Function for client to request a one-off get command 360 | */ 361 | set: (cmd,val) => { 362 | 363 | IFC2.log("Processing set request: " + cmd + "," + val); 364 | 365 | if (IFC2.isConnected) { // Only enqueue if connected 366 | IFC2.enqueueCommand(cmd,IFC2.SETCMD,val); 367 | } 368 | 369 | }, 370 | 371 | /***** 372 | * Function run an Infinite Flight command 373 | */ 374 | run: (cmd) => { 375 | 376 | IFC2.log("Processing run request: " + cmd); 377 | 378 | if (IFC2.isConnected) { // Only enqueue if connected 379 | IFC2.enqueueCommand(cmd,IFC2.RUNCMD); 380 | } 381 | 382 | }, 383 | 384 | /***** 385 | * Process the manifest after fetching it 386 | */ 387 | processManifest: () => { 388 | 389 | IFC2.log('Processing manifest into objects'); 390 | 391 | let manifestLines = IFC2.infiniteFlight.manifestData.split("\n"); // Split the data into lines 392 | 393 | for (key in manifestLines) { // Loop through the lines 394 | 395 | let line = manifestLines[key]; 396 | 397 | let lineData = line.split(','); // Split the line at commas 398 | 399 | let command = parseInt(lineData[0]); // Get the command 400 | let type = parseInt(lineData[1]); // Get the command data type 401 | let name = lineData[2]; // Get the command name 402 | 403 | if (!isNaN(command)) { // Save the manifest data for this command 404 | IFC2.infiniteFlight.manifestByCommand[command] = { 405 | name: name, 406 | type: type 407 | }; 408 | IFC2.infiniteFlight.manifestByName[name] = { 409 | command: command, 410 | type: type 411 | }; 412 | } 413 | 414 | } 415 | 416 | // Emit Event 417 | IFC2.eventEmitter.emit('IFC2manifest',IFC2.infiniteFlight.manifestByName); // Return data to calling script through an event 418 | 419 | // Move on to post-manifest actions 420 | IFC2.postManifest(); 421 | 422 | }, 423 | 424 | /***** 425 | * Return the manifest by name 426 | */ 427 | manifestByName: () => { 428 | return IFC2.infiniteFlight.manifestByName; 429 | }, 430 | 431 | /***** 432 | * Return the manifest by command 433 | */ 434 | manifestByCommand: () => { 435 | return IFC2.infiniteFlight.manifestByCommand; 436 | }, 437 | 438 | /***** 439 | * Get the manifest 440 | */ 441 | getManifest: () => { 442 | 443 | IFC2.log("Getting manifest from: " + IFC2.infiniteFlight.serverAddress); 444 | 445 | // Reset manifest data variables 446 | IFC2.infiniteFlight.manifestData = ""; 447 | IFC2.infiniteFlight.manifestByName = {}; 448 | IFC2.infiniteFlight.manifestByCommand = {}; 449 | IFC2.infiniteFlight.manifestLength = 0; 450 | IFC2.infiniteFlight.manifestBuffer = null; 451 | 452 | // Set up connection to the manifest socket 453 | IFC2.infiniteFlight.manifestSocket.on('data', (data) => { // Handle "data" event 454 | 455 | IFC2.log("Receiving Manifest Data"); 456 | 457 | if (IFC2.infiniteFlight.manifestBuffer == null) { // We haven't stored any buffer data yet 458 | 459 | // Store the first batch of data in the buffer 460 | IFC2.infiniteFlight.manifestBuffer = data; 461 | 462 | } else { // We already have buffer data 463 | 464 | // Concat the new buffer data into the main manifest buffer 465 | let bufArr = [IFC2.infiniteFlight.manifestBuffer,data]; 466 | IFC2.infiniteFlight.manifestBuffer = Buffer.concat(bufArr); 467 | 468 | } 469 | 470 | IFC2.log("Buffer length: " + IFC2.infiniteFlight.manifestBuffer.length); 471 | 472 | if (IFC2.infiniteFlight.manifestLength <= 0 && IFC2.infiniteFlight.manifestBuffer.length >= 12) { 473 | 474 | // The first 12 bytes of the manifest are: 475 | // 476 | // 4 bytes: Int32 (-10 to specify the manifest command 477 | // 4 bytes: Int32 Specify the length of all data to follow 478 | // 4 bytes: Int32 specifying the length of the manifest data string to follow (so this is always four less than the preceding Int 32 value) 479 | 480 | // If we don't have a manifest length and we have at least three Int32s in the buffer, get the manifest length from bytes 9-12 481 | IFC2.infiniteFlight.manifestLength = IFC2.infiniteFlight.manifestBuffer.readInt32LE(8); 482 | 483 | IFC2.log("Manifest length: " + IFC2.infiniteFlight.manifestLength); 484 | 485 | } else { 486 | 487 | // Check if we have hit the manifest length -- and remember the manifest length will be 12 less than the buffer length because 488 | // the first 12 bytes are not part of the manifest itself 489 | if (IFC2.infiniteFlight.manifestBuffer.length >= IFC2.infiniteFlight.manifestLength + 12) { 490 | 491 | // Convert buffer to a string 492 | IFC2.infiniteFlight.manifestData = IFC2.infiniteFlight.manifestBuffer.toString("utf8",12); 493 | 494 | IFC2.log(IFC2.infiniteFlight.manifestData); 495 | 496 | // Close the manifest socket 497 | IFC2.infiniteFlight.manifestSocket.destroy(); 498 | 499 | // Process the manifest 500 | IFC2.processManifest(); 501 | 502 | } 503 | 504 | } 505 | 506 | IFC2.log("-----"); 507 | 508 | }); 509 | 510 | IFC2.infiniteFlight.manifestSocket.on('timeout', () => { // Handle "timeout" evenet 511 | 512 | IFC2.log("Manifest data done/timed out"); 513 | IFC2.eventEmitter.emit('IFC2msg',{"type": "error", code: "timeout", context: "manifest", "msg": "Manifest socket connection to Infinite Flight timed out"}); // Return data to calling script through an event 514 | 515 | IFC2.infiniteFlight.manifestSocket.destroy(); // Destroy the socket 516 | 517 | }) 518 | 519 | IFC2.infiniteFlight.manifestSocket.on('close', () => { // Handle "close" event 520 | IFC2.log('Manifest Connection closed'); 521 | IFC2.eventEmitter.emit('IFC2msg',{"type": "info", code: "close", context: "manifest", "msg": "Manifest socket connection to Infinite Flight closed"}); // Return data to calling script through an event 522 | }); 523 | 524 | // IFC2.infiniteFlight.manifestSocket.on('connect', () => { // Handle "connect" event 525 | // }); 526 | 527 | IFC2.infiniteFlight.manifestSocket.on('error', function(data) { 528 | IFC2.log('Error: ' + data, IFC2.INFO); 529 | IFC2.eventEmitter.emit('IFC2msg',{"type": "error", code: "error", context: "manifest", "msg": "Error on Infinite Flight manifest socket"}); // Return data to calling script through an event 530 | }); 531 | 532 | IFC2.infiniteFlight.manifestSocket.on('drain', function(data) { 533 | IFC2.log('Drain: ' + data, IFC2.INFO); 534 | IFC2.eventEmitter.emit('IFC2msg',{"type": "info", code: "drain", context: "manifest", "msg": "Manifest socket connection to Infinite Flight drained"}); // Return data to calling script through an event 535 | }); 536 | 537 | IFC2.infiniteFlight.manifestSocket.on('end', function(data) { 538 | IFC2.log('End: ' + data, IFC2.WARN); 539 | IFC2.eventEmitter.emit('IFC2msg',{"type": "info", code: "end", context: "manifest", "msg": "Manifest socket connection to Infinite Flight ended"}); // Return data to calling script through an event 540 | }); 541 | 542 | IFC2.infiniteFlight.manifestSocket.on('lookup', function(data) { 543 | IFC2.log('Lookup: ' + data, IFC2.INFO); 544 | }); 545 | 546 | IFC2.infiniteFlight.manifestSocket.connect(IFC2.infiniteFlight.serverPort, IFC2.infiniteFlight.serverAddress, () => { 547 | IFC2.log('Manifest Connected'); 548 | IFC2.eventEmitter.emit('IFC2msg',{"type": "info", code: "connect", context: "manifest", "msg": "Manifest socket connection to Infinite Flight created"}); // Return data to calling script through an event 549 | IFC2.infiniteFlight.manifestSocket.setTimeout(IFC2.infiniteFlight.manifestTimeout); // Set the socket timeout 550 | IFC2.infiniteFlight.manifestSocket.write(IFC2.getCommand(IFC2.MANIFESTCMD), () => {}); // Issue the get manifest command (-1) 551 | }); 552 | 553 | }, 554 | 555 | /***** 556 | * Place holder to hold success callback function provided by client 557 | */ 558 | successCallback: () => {}, 559 | 560 | /***** 561 | * Process the poll queue 562 | */ 563 | processPoll: () => { 564 | 565 | IFC2.log("Processing poll Q"); 566 | 567 | if (IFC2.pollQ.length > 0 && !IFC2.isPollWaiting) { // Only process if the queue has entries and we are not waiting for data from IF 568 | 569 | IFC2.log(IFC2.pollQ); 570 | 571 | // Get current command to process 572 | let cmd = IFC2.pollQ[IFC2.pollCurrent]; 573 | let cmdCode = IFC2.infiniteFlight.manifestByName[cmd].command; // Get the command code 574 | 575 | IFC2.log('Polling command: ' + cmdCode); 576 | 577 | // Prep for next poll 578 | IFC2.pollCurrent = ((IFC2.pollCurrent + 1) == IFC2.pollQ.length) ? 0 : (IFC2.pollCurrent + 1); 579 | 580 | // Set isPollWaiting 581 | IFC2.isPollWaiting = true; 582 | 583 | // Send the command 584 | if (IFC2.pollThrottle > 0) { // Wait before polling 585 | setTimeout(() => { 586 | IFC2.infiniteFlight.pollSocket.write(IFC2.getCommand(cmdCode), () => { 587 | IFC2.log("Poll command sent: " + cmdCode); 588 | if (IFC2.waitList.indexOf(cmdCode) < 0) { // Check if we are already waiting for this command 589 | 590 | IFC2.waitList.push(cmdCode); // Add the command to the wait list 591 | 592 | IFC2.pollWaiting = cmdCode; 593 | 594 | } 595 | }); 596 | }, IFC2.pollThrottle); 597 | 598 | } else { // Don't delay -- just get on and poll 599 | 600 | if (IFC2.waitList.indexOf(cmdCode) < 0) { // Check if we are already waiting for this command 601 | 602 | IFC2.infiniteFlight.pollSocket.write(IFC2.getCommand(cmdCode), () => { 603 | 604 | IFC2.log("Poll command sent: " + cmdCode); 605 | 606 | IFC2.waitList.push(cmdCode); // Add the command to the wait list 607 | 608 | IFC2.pollWaiting = cmdCode; 609 | 610 | }); 611 | } 612 | } 613 | 614 | } else { // There was nothing in the queue 615 | 616 | IFC2.log("Set poll timeout"); 617 | 618 | } 619 | 620 | }, 621 | 622 | /***** 623 | * Register a command into the poll queue 624 | */ 625 | pollRegister: (cmd, callback) => { 626 | 627 | if (!IFC2.pollQ.hasOwnProperty(cmd)) { 628 | 629 | if (IFC2.isCallback) { // Save callback function if we are using callbacks 630 | IFC2.callbacks[cmd] = callback; 631 | } 632 | 633 | IFC2.pollQ.push(cmd); 634 | if (!IFC2.isPollWaiting) { IFC2.processPoll(); } 635 | 636 | } 637 | 638 | }, 639 | 640 | /***** 641 | * Deregister a command from the poll queue 642 | */ 643 | pollDeregister: (cmd) => { 644 | 645 | let index = IFC2.pollQ.indexOf(cmd); 646 | IFC2.pollQ.splice(index,1); 647 | 648 | if (IFC2.pollCurrent >= IFC2.pollQ.length) { IFC2.pollCurrent = 0; } 649 | 650 | if (IFC2.pollQ.length == 0) { IFC2.isPollWaiting = false; } 651 | 652 | }, 653 | 654 | /***** 655 | * Process command data returned by the API 656 | * 657 | * nextFN is a function to call after data processing is done 658 | */ 659 | processData: (source, nextFN) => { 660 | 661 | IFC2.log('processData: Processing data source: ' + source, IFC2.INFO); 662 | 663 | let data = (source == "client") ? IFC2.qBuffer : IFC2.pollBuffer; 664 | 665 | let command = data.readInt32LE(0); // Get the command from the data 666 | 667 | IFC2.log("processData: Got data for command: " + command); 668 | let inManifest = IFC2.infiniteFlight.manifestByCommand.hasOwnProperty(command); // See if command is in manifest 669 | 670 | IFC2.log("processData: inManifest: " + inManifest); 671 | 672 | if (inManifest) { // Only proceed if we have the command in the manifest 673 | 674 | let waitIndex = IFC2.waitList.indexOf(command); // See if the command is in the waitList 675 | 676 | IFC2.log("processData: waitList: " + JSON.stringify(IFC2.waitList)); 677 | IFC2.log("processData: In waitList: " + waitIndex); 678 | 679 | if (waitIndex >= 0) { // Only proceed if command is in the waitList 680 | 681 | IFC2.log("processData: Waiting for command: " + command); 682 | 683 | IFC2.log("processData: data length: " + data.length); 684 | 685 | if (data.length > 4) { // See if we have a data length greater than 4 686 | 687 | IFC2.log("processData: data length gt 4"); 688 | 689 | let bufLength = data.readInt32LE(4); 690 | 691 | if (data.length >= bufLength + 8) { // Do we have the full command data? 692 | 693 | IFC2.log("processData: data is complete so process"); 694 | 695 | IFC2.log(data); 696 | 697 | IFC2.log("processData: waitList before splice: " + JSON.stringify(IFC2.waitList)); 698 | 699 | IFC2.waitList.splice(waitIndex,1); 700 | 701 | IFC2.log("processData: waitList after splice: " + JSON.stringify(IFC2.waitList)); 702 | 703 | switch(IFC2.infiniteFlight.manifestByCommand[command].type) { 704 | case IFC2.BOOLEAN: 705 | IFC2.processResult(command, (data.readUInt8(8) == 1) ? true : false); 706 | break; 707 | case IFC2.INTEGER: 708 | IFC2.processResult(command, data.readUInt32LE(8)); 709 | break; 710 | case IFC2.FLOAT: 711 | IFC2.processResult(command, data.readFloatLE(8)); 712 | break; 713 | case IFC2.DOUBLE: 714 | IFC2.processResult(command, data.readDoubleLE(8)); 715 | break; 716 | case IFC2.STRING: 717 | strLen = data.readUInt32LE(8); 718 | IFC2.processResult(command, data.toString("utf8",12,strLen + 12)); 719 | break; 720 | case IFC2.LONG: 721 | IFC2.processResult(command, data.readBigInt64LE(8)); 722 | break; 723 | } 724 | 725 | // remove data from buffer 726 | 727 | if (source == "client") { 728 | 729 | if (data.length > bufLength + 8) { 730 | IFC2.qBuffer = IFC2.qBuffer.slice(bufLength + 8,IFC2.qBuffer.length); 731 | } else { 732 | IFC2.qBuffer = null; 733 | if (IFC2.waitList.length == 0) { 734 | IFC2.isWaiting = false; // No longer waiting 735 | } 736 | } 737 | 738 | } else { 739 | 740 | if (data.length > bufLength + 8) { 741 | IFC2.pollBuffer = IFC2.pollBuffer.slice(bufLength + 8,IFC2.pollBuffer.length); 742 | } else { 743 | IFC2.pollBuffer = null; 744 | IFC2.isPollWaiting = false; // No longer waiting 745 | } 746 | 747 | } 748 | 749 | nextFN(); 750 | 751 | } else { 752 | 753 | nextFN(); 754 | 755 | } 756 | 757 | } else { 758 | 759 | nextFN(); 760 | 761 | } 762 | 763 | } else { 764 | 765 | nextFN(); 766 | 767 | } 768 | 769 | } else { 770 | 771 | nextFN(); 772 | 773 | } 774 | 775 | }, 776 | 777 | /***** 778 | * After processing the manifest, connect to IF Connect v2 API 779 | */ 780 | postManifest: function() { 781 | 782 | IFC2.infiniteFlight.clientSocket.connect(IFC2.infiniteFlight.serverPort, IFC2.infiniteFlight.serverAddress, function() { 783 | IFC2.infiniteFlight.clientSocket.setTimeout(IFC2.timeout); 784 | IFC2.infiniteFlight.clientSocket.setKeepAlive(IFC2.keepAlive); 785 | }); 786 | 787 | IFC2.infiniteFlight.clientSocket.on('data', function(data) { 788 | 789 | IFC2.log('***** Received: ' + data, IFC2.INFO); 790 | 791 | if (IFC2.qBuffer == null) { // We haven't stored any buffer data yet 792 | 793 | // Store the first batch of data in the buffer 794 | IFC2.qBuffer = data; 795 | 796 | } else { // We already have buffer data 797 | 798 | // Concat the new buffer data into the main manifest buffer 799 | let bufArr = [IFC2.qBuffer,data]; 800 | IFC2.qBuffer = Buffer.concat(bufArr); 801 | 802 | } 803 | 804 | IFC2.processData("client", IFC2.processQueue); 805 | 806 | }); 807 | 808 | IFC2.infiniteFlight.clientSocket.on('error', function(data) { 809 | IFC2.log('Client: Error: ' + JSON.stringify(data), IFC2.INFO); 810 | 811 | if (IFC2.isConnected && IFC2.doReconnect) { 812 | IFC2.log("Client: Trying to reconnect"); 813 | IFC2.eventEmitter.emit('IFC2msg',{"type": "info", code: "reconnect", context: "client", "msg": "Reconnecting for general queries"}); // Return data to calling script through an event 814 | IFC2.infiniteFlight.clientSocket.destroy(); 815 | // IFC2.infiniteFlight.pollSocket = new net.Socket(); 816 | IFC2.infiniteFlight.clientSocket.connect(IFC2.infiniteFlight.serverPort, IFC2.infiniteFlight.serverAddress, function() { 817 | IFC2.infiniteFlight.clientSocket.setTimeout(IFC2.timeout); 818 | IFC2.infiniteFlight.clientSocket.setKeepAlive(IFC2.keepAlive); 819 | IFC2.eventEmitter.emit('IFC2msg',{"type": "info", code: "reconnected", context: "client", "msg": "Reconnected for general queries"}); // Return data to calling script through an event 820 | }); 821 | } 822 | 823 | IFC2.eventEmitter.emit('IFC2msg',{"type": "error", code: "error", context: "client", "msg": "Error on Infinite Flight socket"}); // Return data to calling script through an event 824 | }); 825 | 826 | IFC2.infiniteFlight.clientSocket.on('timeout', function(data) { 827 | IFC2.log('Client: Timeout: ' + JSON.stringify(data), IFC2.INFO); 828 | IFC2.eventEmitter.emit('IFC2msg',{"type": "error", code: "timeout", context: "client", "msg": "Timeout on socket connection to Infinite Flight"}); // Return data to calling script through an event 829 | }); 830 | 831 | IFC2.infiniteFlight.clientSocket.on('close', function(data) { 832 | IFC2.log('Client: Closer: ' + JSON.stringify(data), IFC2.INFO); 833 | IFC2.eventEmitter.emit('IFC2msg',{"type": "info", code: "close", context: "client", "msg": "Socket connection to Infinite Flight closed"}); // Return data to calling script through an event 834 | }); 835 | 836 | IFC2.infiniteFlight.clientSocket.on('connect', function(data) { 837 | IFC2.log('Connected to IF server ' + IFC2.infiniteFlight.serverAddress, IFC2.MANDATORY); 838 | 839 | /* if (IFC2.isConnected && IFC2.infiniteFlight.keepAlive) { 840 | IFC2.infiniteFlight.clientSocket.connect(IFC2.infiniteFlight.serverPort, IFC2.infiniteFlight.serverAddress, function() { 841 | IFC2.infiniteFlight.clientSocket.setTimeout(IFC2.timeout); 842 | IFC2.infiniteFlight.clientSocket.setKeepAlive(IFC2.keepAlive); 843 | }); 844 | }*/ 845 | 846 | IFC2.eventEmitter.emit('IFC2msg',{"type": "info", code: "connect", context: "client", "msg": "Socket connection to Infinite Flight created"}); // Return data to calling script through an event 847 | if (!IFC2.isConnected) { 848 | IFC2.postConnect(); 849 | } 850 | }); 851 | 852 | IFC2.infiniteFlight.clientSocket.on('drain', function(data) { 853 | IFC2.log('Client: Drain: ' + JSON.stringify(data), IFC2.INFO); 854 | IFC2.eventEmitter.emit('IFC2msg',{"type": "info", code: "drain", context: "client", "msg": "Socket connection to Infinite Flight drained"}); // Return data to calling script through an event 855 | }); 856 | 857 | IFC2.infiniteFlight.clientSocket.on('end', function(data) { 858 | IFC2.log('Client: End: ' + JSON.stringify(data), IFC2.INFO); 859 | IFC2.eventEmitter.emit('IFC2msg',{"type": "info", code: "end", context: "client", "msg": "Socket connection to Infinite Flight ended"}); // Return data to calling script through an event 860 | }); 861 | 862 | IFC2.infiniteFlight.clientSocket.on('lookup', function(data) { 863 | IFC2.log('Client: Lookup: ' + JSON.stringify(data), IFC2.INFO); 864 | }); 865 | 866 | }, 867 | 868 | /***** 869 | * Pre-connection tasts 870 | */ 871 | preConnect: function() { 872 | IFC2.log("Connecting...", IFC2.INFO); 873 | IFC2.getManifest(); 874 | }, 875 | 876 | /***** 877 | * Post-connection tasks 878 | */ 879 | postConnect: function() { 880 | 881 | IFC2.log("clientSocket Connected ...", IFC2.MANDATORY); 882 | 883 | // Connect to Polling Socket 884 | IFC2.infiniteFlight.pollSocket.connect(IFC2.infiniteFlight.serverPort, IFC2.infiniteFlight.serverAddress, function() { 885 | IFC2.infiniteFlight.pollSocket.setTimeout(IFC2.timeout); 886 | IFC2.infiniteFlight.pollSocket.setKeepAlive(IFC2.keepAlive); 887 | }); 888 | 889 | IFC2.infiniteFlight.pollSocket.on('data', function(data) { 890 | 891 | IFC2.log('Received poll: ' + data, IFC2.INFO); 892 | 893 | if (IFC2.pollBuffer == null) { // We haven't stored any buffer data yet 894 | 895 | // Store the first batch of data in the buffer 896 | IFC2.pollBuffer = data; 897 | 898 | } else { // We already have buffer data 899 | 900 | // Concat the new buffer data into the main manifest buffer 901 | let bufArr = [IFC2.pollBuffer,data]; 902 | IFC2.pollBuffer = Buffer.concat(bufArr); 903 | 904 | } 905 | 906 | // Clear poll timeout 907 | clearTimeout(IFC2.pollTimeout); 908 | 909 | IFC2.processData("poll", IFC2.processPoll); 910 | 911 | }); 912 | 913 | IFC2.infiniteFlight.pollSocket.on('error', function(data) { 914 | IFC2.log('Poll: Error: ' + JSON.stringify(data), IFC2.INFO); 915 | 916 | if (IFC2.isConnected && IFC2.doReconnect) { 917 | IFC2.log("Poll: Trying to reconnect"); 918 | IFC2.eventEmitter.emit('IFC2msg',{"type": "info", code: "reconnect", context: "poll", "msg": "Reconnecting for polling"}); // Return data to calling script through an event 919 | IFC2.infiniteFlight.pollSocket.destroy(); 920 | // IFC2.infiniteFlight.pollSocket = new net.Socket(); 921 | IFC2.infiniteFlight.pollSocket.connect(IFC2.infiniteFlight.serverPort, IFC2.infiniteFlight.serverAddress, function() { 922 | IFC2.infiniteFlight.pollSocket.setTimeout(IFC2.timeout); 923 | IFC2.infiniteFlight.pollSocket.setKeepAlive(IFC2.keepAlive); 924 | IFC2.isPollWaiting = false; 925 | IFC2.eventEmitter.emit('IFC2msg',{"type": "info", code: "reconnected", context: "poll", "msg": "Reconnected for polling"}); // Return data to calling script through an event 926 | IFC2.processPoll(); 927 | }); 928 | } 929 | 930 | IFC2.eventEmitter.emit('IFC2msg',{"type": "error", code: "error", context: "poll", "msg": "Error polling Infinite Flight"}); // Return data to calling script through an event 931 | }); 932 | 933 | IFC2.infiniteFlight.pollSocket.on('timeout', function(data) { 934 | IFC2.log('Poll: Timeout: ' + JSON.stringify(data), IFC2.INFO); 935 | IFC2.eventEmitter.emit('IFC2msg',{"type": "error", code: "timeout", context: "poll", "msg": "Timeout on polling socket connection to Infinite Flight"}); // Return data to calling script through an event 936 | IFC2.processPoll(); 937 | }); 938 | 939 | IFC2.infiniteFlight.pollSocket.on('close', function(data) { 940 | IFC2.log('Poll: Close: ' + JSON.stringify(data), IFC2.INFO); 941 | IFC2.eventEmitter.emit('IFC2msg',{"type": "info", code: "close", context: "poll", "msg": "Polling socket connection to Infinite Flight closed"}); // Return data to calling script through an event 942 | }); 943 | 944 | IFC2.infiniteFlight.pollSocket.on('connect', function(data) { 945 | IFC2.log('Connected for polling to IF server ' + IFC2.infiniteFlight.serverAddress, IFC2.MANDATORY); 946 | IFC2.eventEmitter.emit('IFC2msg',{"type": "info", code: "connect", context: "poll", "msg": "Polling socket connection to Infinite Flight created"}); // Return data to calling script through an event 947 | IFC2.isConnected = true; 948 | 949 | // Fetch one-time data about aircraft, IF, etc 950 | if (IFC2.isCallback) { 951 | IFC2.get('infiniteflight/app_state',IFC2.infoCallback); 952 | IFC2.get('infiniteflight/app_version',IFC2.infoCallback); 953 | IFC2.get('infiniteflight/api_version',IFC2.infoCallback); 954 | IFC2.get('aircraft/0/name',IFC2.infoCallback); 955 | IFC2.get('aircraft/0/livery',IFC2.infoCallback); 956 | } else { 957 | IFC2.get('infiniteflight/app_state'); 958 | IFC2.get('infiniteflight/app_version'); 959 | IFC2.get('infiniteflight/api_version'); 960 | IFC2.get('aircraft/0/name'); 961 | IFC2.get('aircraft/0/livery'); 962 | } 963 | 964 | // Issue callback 965 | IFC2.successCallback(); 966 | 967 | // Start Polling 968 | IFC2.processPoll(); 969 | 970 | }); 971 | 972 | IFC2.infiniteFlight.pollSocket.on('drain', function(data) { 973 | IFC2.log('Poll: Drain: ' + JSON.stringify(data), IFC2.INFO); 974 | IFC2.eventEmitter.emit('IFC2msg',{"type": "info", code: "drain", context: "poll", "msg": "Polling socket connection to Infinite Flight drained"}); // Return data to calling script through an event 975 | }); 976 | 977 | IFC2.infiniteFlight.pollSocket.on('end', function(data) { 978 | IFC2.log('Poll: End: ' + JSON.stringify(data), IFC2.INFO); 979 | IFC2.eventEmitter.emit('IFC2msg',{"type": "info", code: "end", context: "poll", "msg": "Polling socket connection to Infinite Flight ended"}); // Return data to calling script through an event 980 | }); 981 | 982 | IFC2.infiniteFlight.pollSocket.on('lookup', function(data) { 983 | IFC2.log('Poll: Lookup: ' + JSON.stringify(data), IFC2.INFO); 984 | }); 985 | 986 | }, 987 | 988 | /***** 989 | * Process results of data returned from IF 990 | */ 991 | processResult: function(command, data) { 992 | 993 | IFC2.log("Processing result: " + command + " > " + data); 994 | 995 | // Save data in ifData data object 996 | IFC2.ifData[IFC2.infiniteFlight.manifestByCommand[command].name] = { 997 | data: data, 998 | ts: Date.now() 999 | }; 1000 | 1001 | // Return IFC2data event 1002 | if (IFC2.isCallback) { // Use a callback if one is available 1003 | 1004 | IFC2.callbacks[IFC2.infiniteFlight.manifestByCommand[command].name]({"command": IFC2.infiniteFlight.manifestByCommand[command].name, "data": data}) 1005 | 1006 | } else { // Use an event 1007 | 1008 | IFC2.eventEmitter.emit('IFC2data',{"command": IFC2.infiniteFlight.manifestByCommand[command].name, "data": data}); // Return data to calling script through an event 1009 | 1010 | } 1011 | 1012 | }, 1013 | 1014 | // SHORTCUTS FUNCTIONS // 1015 | 1016 | /***** 1017 | * Initialise module and connection to IF 1018 | */ 1019 | init: function(successCallback, params={}) { 1020 | IFC2.log("Initialisting IFC2"); 1021 | if (successCallback) IFC2.successCallback = successCallback; // Set success callback function 1022 | if (params.enableLog) IFC2.enableLog = params.enableLog; // Set Logging on/off 1023 | if (params.logLevel) IFC2.logLevel = params.logLevel; // Set logging message level 1024 | if (params.keepAlive) IFC2.keepAlive = params.keepAlive; // Set keepalive 1025 | if (params.doReconnect) IFC2.doReconnect = params.doReconnect; // Set reconnect 1026 | if (params.timeout) IFC2.timeout = params.timeout; // Set socket timeout 1027 | if (params.callback) IFC2.isCallback = params.callback; // Set if we are using callbacks 1028 | if (params.infoCallback) IFC2.infoCallback = params.infoCallback; // Callback function for initial info fetches 1029 | if (params.pollThrottle) IFC2.pollThrottle = params.pollThrottle; // Set polling throttle if provided 1030 | if (params.host && params.port) { // Host provided so connect directly to it 1031 | IFC2.infiniteFlight.serverAddress = params.host; 1032 | IFC2.infiniteFlight.serverPort = params.port; 1033 | IFC2.preConnect(); 1034 | } else { // No host provided so search for a host via UDP 1035 | IFC2.searchHost(); // Search for Infinite Flight host 1036 | } 1037 | }, 1038 | 1039 | /***** 1040 | * Use UDP broadcast to find an IF client on the local network 1041 | */ 1042 | searchHost: function() { 1043 | 1044 | // We only connect to the first device to respond. 1045 | // If you have multiple devices on the network you might not connect to the device you want. 1046 | // 1047 | // Future roadmap: send an event for each one that answers to calling script and let them decide what to do 1048 | 1049 | IFC2.log('Searching for Infinite Flight device',IFC2.INFO); 1050 | 1051 | // Create udp server socket object. 1052 | const server = dgram.createSocket("udp4"); 1053 | 1054 | // Make udp server listen on port 8089. 1055 | server.bind(IFC2.infiniteFlight.broadcastPort); 1056 | 1057 | // When udp server receive message. 1058 | server.on("message", function (message) { 1059 | IFC2.log("UDP broadcast received",IFC2.INFO); 1060 | IFC2.log(message.toString(),IFC2.INFO); 1061 | let data = JSON.parse(message.toString()); 1062 | let regex = /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]/; 1063 | for (key in data.Addresses) { 1064 | let ip = data.Addresses[key]; 1065 | IFC2.log("Found IF on: " + ip,IFC2.INFO); 1066 | if (ip.match(regex)) { // only match IPv4 addresses for now 1067 | IFC2.infiniteFlight.serverAddress = ip; 1068 | } 1069 | } 1070 | server.close(); 1071 | 1072 | IFC2.preConnect(); 1073 | 1074 | }); 1075 | 1076 | // When udp server started and listening. 1077 | server.on('listening', function () { 1078 | // Get and print udp server listening ip address and port number in log console. 1079 | let address = server.address(); 1080 | IFC2.log('UDP Server started and listening on ' + address.address + ":" + address.port,IFC2.INFO); 1081 | }); 1082 | 1083 | }, 1084 | 1085 | /***** 1086 | * Close active connections 1087 | */ 1088 | close: function(callback) { 1089 | 1090 | // Only close if connected 1091 | if (IFC2.isConnected) { 1092 | 1093 | // Reset isConnected flag 1094 | IFC2.isConnected = false; 1095 | 1096 | // Reset the sucess callback function 1097 | IFC2.successCallback = () => {}; 1098 | 1099 | // Destroy client socket 1100 | IFC2.infiniteFlight.clientSocket.destroy(); 1101 | IFC2.infiniteFlight.clientSocket.emit('error', new Error('ECONNRESET')); 1102 | 1103 | // Delete client socket 1104 | delete IFC2.infiniteFlight.clientSocket; 1105 | 1106 | // Recreate client socket 1107 | IFC2.infiniteFlight.clientSocket = new net.Socket(); 1108 | 1109 | // Destory poll socket 1110 | IFC2.infiniteFlight.pollSocket.destroy(); 1111 | IFC2.infiniteFlight.pollSocket.emit('error', new Error('ECONNRESET')); 1112 | 1113 | // Delete poll socket 1114 | delete IFC2.infiniteFlight.pollSocket; 1115 | 1116 | // Recreate poll socket 1117 | IFC2.infiniteFlight.pollSocket = new net.Socket(); 1118 | 1119 | // Destory poll socket 1120 | IFC2.infiniteFlight.manifestSocket.destroy(); 1121 | IFC2.infiniteFlight.manifestSocket.emit('error', new Error('ECONNRESET')); 1122 | 1123 | // Delete manifest socket 1124 | delete IFC2.infiniteFlight.manifestSocket; 1125 | 1126 | // Recreate manifest socket 1127 | IFC2.infiniteFlight.manifestSocket = new net.Socket(); 1128 | 1129 | // Reset manfiest data 1130 | IFC2.infiniteFlight.manifestData = ""; // String to hold raw manifest data 1131 | IFC2.infiniteFlight.manifestByName = {}, // Object to hold the manifest organised by command name 1132 | IFC2.infiniteFlight.manifestByCommand = {}; // Object to hold the manifest organised by command number 1133 | IFC2.infiniteFlight.manifestLength = 0; // Manifest length -- zero is initial placeholder 1134 | IFC2.infiniteFlight.manifestBuffer = null; // Placeholder variable for future manifest buffer 1135 | 1136 | // Reset isWaiting flag 1137 | IFC2.isWaiting = false; 1138 | 1139 | // Reset queues 1140 | IFC2.q = []; 1141 | IFC2.pollQ =[]; 1142 | 1143 | // Reset wait list 1144 | IFC2.waitList = []; 1145 | 1146 | // Reset ifData data object 1147 | IFC2.ifData = {}; 1148 | 1149 | } 1150 | 1151 | // Execute callback function 1152 | callback(); 1153 | 1154 | } 1155 | 1156 | }; 1157 | 1158 | module.exports = IFC2; -------------------------------------------------------------------------------- /package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ifc2", 3 | "version": "1.0.20", 4 | "lockfileVersion": 2, 5 | "requires": true, 6 | "packages": { 7 | "": { 8 | "name": "ifc2", 9 | "version": "1.0.20", 10 | "license": "Apache 2", 11 | "dependencies": { 12 | "dgram": "^1.0.1", 13 | "events": "^3.3.0", 14 | "net": "^1.0.2", 15 | "stringview": "^2.1.1" 16 | } 17 | }, 18 | "node_modules/dgram": { 19 | "version": "1.0.1", 20 | "resolved": "https://registry.npmjs.org/dgram/-/dgram-1.0.1.tgz", 21 | "integrity": "sha1-N/OyAPgDOl/3WTAwicgc42G2UcM=", 22 | "deprecated": "npm is holding this package for security reasons. As it's a core Node module, we will not transfer it over to other users. You may safely remove the package from your dependencies." 23 | }, 24 | "node_modules/events": { 25 | "version": "3.3.0", 26 | "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", 27 | "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", 28 | "engines": { 29 | "node": ">=0.8.x" 30 | } 31 | }, 32 | "node_modules/net": { 33 | "version": "1.0.2", 34 | "resolved": "https://registry.npmjs.org/net/-/net-1.0.2.tgz", 35 | "integrity": "sha1-0XV+yaf7I3HYPPR1XOPifhCCk4g=" 36 | }, 37 | "node_modules/stringview": { 38 | "version": "2.1.1", 39 | "resolved": "https://registry.npmjs.org/stringview/-/stringview-2.1.1.tgz", 40 | "integrity": "sha512-hsaj+P//gLkAnYB6QUT5Kg/2T/ExTfNJUvKhRe980H8rRrXLlG4Q3U2EITbu4Ku1k/Aw/4MZHUUiNZVJtm63PQ==" 41 | } 42 | }, 43 | "dependencies": { 44 | "dgram": { 45 | "version": "1.0.1", 46 | "resolved": "https://registry.npmjs.org/dgram/-/dgram-1.0.1.tgz", 47 | "integrity": "sha1-N/OyAPgDOl/3WTAwicgc42G2UcM=" 48 | }, 49 | "events": { 50 | "version": "3.3.0", 51 | "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", 52 | "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==" 53 | }, 54 | "net": { 55 | "version": "1.0.2", 56 | "resolved": "https://registry.npmjs.org/net/-/net-1.0.2.tgz", 57 | "integrity": "sha1-0XV+yaf7I3HYPPR1XOPifhCCk4g=" 58 | }, 59 | "stringview": { 60 | "version": "2.1.1", 61 | "resolved": "https://registry.npmjs.org/stringview/-/stringview-2.1.1.tgz", 62 | "integrity": "sha512-hsaj+P//gLkAnYB6QUT5Kg/2T/ExTfNJUvKhRe980H8rRrXLlG4Q3U2EITbu4Ku1k/Aw/4MZHUUiNZVJtm63PQ==" 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ifc2", 3 | "version": "1.0.22", 4 | "description": "A Javascript client for Infinite Flight simulator API version 2", 5 | "main": "ifc2.js", 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/likeablegeek/ifc2" 9 | }, 10 | "keywords": [ 11 | "api", 12 | "infinite flight", 13 | "flight", 14 | "simulator", 15 | "client" 16 | ], 17 | "dependencies": { 18 | "dgram": "^1.0.1", 19 | "events": "^3.3.0", 20 | "net": "^1.0.2", 21 | "stringview": "^2.1.1" 22 | }, 23 | "author": "Arman Danesh", 24 | "license": "Apache 2", 25 | "bugs": { 26 | "url": "https://github.com/likeablegeek/ifc2/issues" 27 | }, 28 | "homepage": "https://github.com/likeablegeek/ifc2" 29 | } 30 | --------------------------------------------------------------------------------