-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpaceAPI.ts
282 lines (235 loc) · 8.46 KB
/
SpaceAPI.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
const MAP_ID = "custom-entrance";
const X = 30;
const Y = 25;
const OPEN_URL = "https://ackspace.nl/spaceAPI/ministate_open.png";
const CLOSED_URL = "https://ackspace.nl/spaceAPI/ministate_closed.png";
const SPACEAPI_URL = "https://ackspace.nl/spaceAPI/";
import { SPACEAPI_KEY } from "./api-key";
import https from 'https';
import { EventObject } from "./EventObject";
import { WireObject } from "@gathertown/gather-game-client";
// Flags: module feature disable options
const SPACESTATE = !process.argv.includes( "--nospacestate" );
const CLOSED_LOCKED = -2;
const OPEN_LOCKED = -1;
const CLOSED = 0;
const OPEN = 1;
// Please note that the `customState` seemed to return lower case string; keep the enum lowercase for compatibility
enum SwitchState
{
On = "on",
Off = "off",
Unknown = "unknown",
Disabled = "disabled"
}
export class Spacestate extends EventObject
{
private state: SwitchState;
private intervalTimer: NodeJS.Timer|undefined;
constructor()
{
super();
this.state = SwitchState.Unknown;
}
public init()
{
// Claim our object (or have it created)
this.emit( "objectRegister", { source: this, room: MAP_ID, id: "spacestate", create: true } );
// NOTE: we can only read the spaceAPI when our first `setObject` is called
// Read real spaceAPI every 10 seconds
this.intervalTimer = setInterval( async () =>
{
const state = await this.getSpaceAPI( );
this.setVirtualSpacestate( state );
}, 10000 );
}
public getObject( id: string, _full: boolean): WireObject
{
// Create object and return it
const image = this.switchStateToImage( this.state );
const object = {
//id: "spacestate",
//x: X,
//y: Y,
normal: image,
highlighted: image,
customState: this.state as string,
previewMessage: this.switchStateToMessage( this.state ),
_tags: [], // currently needed for this request to complete
};
// Full object (create mode)?
if ( _full )
{
Object.assign( object, {
id: "spacestate",
type: 5,
x: X,
y: Y,
height: 1,
width: 1,
distThreshold: 2
} );
}
return object as WireObject;
}
public setObject( _object: WireObject, initialCall: boolean ): void
{
// update object (deduct space state)
// NOTE: we're storing nothing except its state; all other properties are overridden at `getObject`
const state: SwitchState = _object.customState as SwitchState;
console.log( `setObject: ${state} (${this.state})` );
if ( this.state === state )
return;
// Unknown could mean initial call: update the state
//if ( this.state === SwitchState.Unknown )
if ( initialCall )
this.initSpaceAPI();
}
public objectInteract( id: string ): boolean
{
if ( id !== "spacestate" )
console.warn( "Expect id to be `spacestate` only" );
// We got an interact event: act accordingly (toggle the spacestate)
const state = this.invertState( this.state );
// Set both states accordingly
this.setVirtualSpacestate( state );
this.setRealSpacestate( state );
// Interaction success, object changed
return true;
}
public destroy()
{
// Stop the timer and update the switch first
if ( this.intervalTimer )
clearInterval( this.intervalTimer );
this.setVirtualSpacestate( SwitchState.Disabled );
// Trigger faux spacestate to release override
// assume the real switch is closed,
if ( SPACESTATE )
https.get( `${SPACEAPI_URL}?key=${SPACEAPI_KEY}&update=state&state=1` );
}
private async initSpaceAPI( ): Promise<void>
{
console.log( "init spaceAPI" );
const state = await this.getSpaceAPI( );
this.setVirtualSpacestate( state );
}
private invertState( state:SwitchState ): SwitchState
{
switch ( state )
{
case SwitchState.On:
return SwitchState.Off;
case SwitchState.Off:
return SwitchState.On;
// SwitchState.Disabled
// SwitchState.Unknown
default:
console.warn( "Unexpected: inverting from unknown or disabled state" )
return SwitchState.On;
}
}
private switchStateToTernary( state:SwitchState ):boolean|null
{
switch ( state )
{
case SwitchState.On:
return true;
case SwitchState.Off:
return false;
// SwitchState.Disabled
// SwitchState.Unknown
default:
return null;
}
}
private switchStateToImage( state:SwitchState ): string
{
switch ( state )
{
case SwitchState.On:
return OPEN_URL;
default:
return CLOSED_URL;
}
}
private switchStateToMessage( state:SwitchState ): string
{
switch ( state )
{
case SwitchState.On:
return "Open! press x to close the space";
case SwitchState.Off:
return "Closed. press x to open the space"
case SwitchState.Unknown:
return "unknown state";
case SwitchState.Disabled:
return "Disabled (script not running)";
}
}
private ternaryToSwitchState( state:boolean|null ): SwitchState
{
switch ( state )
{
case true:
return SwitchState.On;
case false:
return SwitchState.Off;
default:
return SwitchState.Unknown;
}
}
private setVirtualSpacestate( state:SwitchState )
{
console.log( `setVirtualSpacestate: ${state} (${this.state})`)
if ( this.state === state )
return;
this.state = state;
this.emit( "objectChanged", { source: this, room: MAP_ID, id: "spacestate" } );
}
private setRealSpacestate( state: SwitchState )
{
console.log( `setting real state (forced): ${state}`);
// NOTE: the override mechanism only works when the current spacestate has the opposite state:
// i.e.: when the switch emits "on" every 20 seconds, setting the override to off will lock it in its "off" position.
// after the switch has been turned to its equal (non-locked) state (off), the lock will "release" and normal operation can continue
// This is also the case when the state was locked to either value: locked off needs an on-trigger before it can be locked at its on position
// Since we really don't know what state it is (on, off, forced-on, forced-off), we emit a faux inverse to release any lock and lock it in place again with the desired state.
const spacestate = this.switchStateToTernary( state );
if ( SPACESTATE )
{
// Trigger faux spacestate to enable override
https.get( `${SPACEAPI_URL}?key=${SPACEAPI_KEY}&update=state&state=${spacestate ? CLOSED : OPEN}`, (res) =>
{
if ( res.statusCode === 200 )
https.get( `${SPACEAPI_URL}?key=${SPACEAPI_KEY}&update=state&state=${spacestate ? OPEN_LOCKED : CLOSED_LOCKED}` );
} ).on('error', ( e ) => {
console.error( e );
} );
}
}
private async getSpaceAPI(): Promise<SwitchState>
{
return new Promise((resolve) => {
https.get(SPACEAPI_URL,(res) => {
let body = "";
res.on("data", (chunk) => {
body += chunk;
});
res.on("end", () => {
try {
const json = JSON.parse( body );
resolve( this.ternaryToSwitchState( json.state.open ) );
} catch ( error: any )
{
console.error( error.message );
resolve( SwitchState.Unknown );
};
});
}).on("error", ( error: Error ) => {
console.error( error.message );
resolve( SwitchState.Unknown );
});
} );
}
}