UNPKG

node-insim

Version:

An InSim library for NodeJS with TypeScript support

64 lines (63 loc) 2.26 kB
import defaults from 'lodash.defaults'; import { TypedEmitter } from 'tiny-typed-emitter'; import { InSimError } from '../errors'; import { log as baseLog } from '../log'; import { UDP } from '../protocols'; import { OutSimPack } from './OutSimPack'; import { OutSimPack2 } from './OutSimPack2'; const log = baseLog.extend('outsim'); export class OutSim extends TypedEmitter { constructor({ timeout = 0 } = {}) { super(); this._options = defaultOutSimOptions; this.connection = null; this.timeout = 0; this.timeout = timeout; this.on('connect', () => log(`Connected to ${this._options.Host}:${this._options.Port}`)); this.on('disconnect', () => log(`Disconnected from ${this._options.Host}:${this._options.Port}`)); } connect(options) { this._options = defaults(options, defaultOutSimOptions); log(`Connecting to ${this._options.Host}:${this._options.Port}...`); this.connection = new UDP({ host: this._options.Host, port: this._options.Port, timeout: this.timeout, socketInitialisationMode: 'bind', }); this.connection.connect(); this.connection.on('connect', () => { this.emit('connect'); }); this.connection.on('disconnect', () => { this.emit('disconnect'); }); this.connection.on('error', (error) => { throw new InSimError(`UDP connection error: ${error.message}`); }); this.connection.on('data', (data) => this.handleMessage(data)); this.connection.on('timeout', () => { this.emit('timeout'); }); } disconnect() { log('Disconnecting...'); if (this.connection === null) { log('Cannot disconnect - not connected'); return; } this.connection.disconnect(); } handleMessage(data) { const outSimPack = this._options.OutSimOpts > 0 ? new OutSimPack2(this._options.OutSimOpts) : new OutSimPack(); this.emit('packet', outSimPack.unpack(data)); } } OutSim.defaultMaxListeners = 255; const defaultOutSimOptions = { Host: '127.0.0.1', Port: 29997, OutSimOpts: 0, };