@@ -2,38 +2,53 @@ import { AutodartsWsMessage } from '@/interfaces/AutodartsWsRawMessage'
22import { EventEmitter } from 'stream'
33import { WebSocket } from 'ws'
44import { websocketAddNormalizedValues } from './utils/websocketAddNormalizedValues'
5+ import { AutodartsBoardOptions } from './interfaces/AutodartsBoardOptions'
56
67export class AutodartsBoard {
7- private host : string
8- private port : number
8+ private _options : AutodartsBoardOptions
9+
910 private ws : null | WebSocket = null
1011
1112 // date of last connect or message from autodarts
1213 private wsLastInteraction : null | Date = null
1314
1415 private eventEmitter = new EventEmitter ( )
1516
16- constructor ( opts : { host : string ; port ?: number } ) {
17- this . host = opts . host
18- this . port = opts . port || 3180
17+ constructor ( opts : { host : string } & Partial < AutodartsBoardOptions > ) {
18+ this . _options = {
19+ port : 3180 ,
20+ reconnectAfter : 30 ,
21+ ...opts ,
22+ }
1923
2024 this . connect ( )
2125
2226 // reconnect if last message older that 30 sec
2327 setInterval ( ( ) => {
2428 const secondsSinceLastMessage = this . secondsSinceLastMessage ( )
25- if ( secondsSinceLastMessage && secondsSinceLastMessage > 30 ) {
29+ if (
30+ secondsSinceLastMessage &&
31+ secondsSinceLastMessage > this . options . reconnectAfter
32+ ) {
2633 this . reconnect ( )
2734 }
2835 } )
2936 }
3037
38+ get options ( ) {
39+ return {
40+ ...this . _options ,
41+ }
42+ }
43+
3144 /**
3245 * Connect to Autodarts
3346 */
3447 private connect ( ) {
3548 try {
36- this . ws = new WebSocket ( `ws://${ this . host } :${ this . port } /api/events` )
49+ this . ws = new WebSocket (
50+ `ws://${ this . options . host } :${ this . options . port } /api/events` ,
51+ )
3752 // set last message to now to also reconnect if no message was send
3853 this . wsLastInteraction = new Date ( )
3954
@@ -76,7 +91,10 @@ export class AutodartsBoard {
7691 }
7792
7893 private async fetch ( path : string , init : RequestInit ) {
79- return await fetch ( `http://${ this . host } :${ this . port } ${ path } ` , init )
94+ return await fetch (
95+ `http://${ this . options . host } :${ this . options . port } ${ path } ` ,
96+ init ,
97+ )
8098 }
8199
82100 /**
0 commit comments