forked from southlondonmakerspace/control-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
240 lines (201 loc) · 6.1 KB
/
app.js
File metadata and controls
240 lines (201 loc) · 6.1 KB
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
var net = require( 'net' ),
rl = require( 'readline' ),
request = require( 'request' )
config = require( __dirname + '/config.json' )
Membership = require( __dirname + '/membership.js' );
var client_id = 1;
var contactless_id = '21222324';
var cacheExpiry = 30;
var cache = [];
// Server
// =================================
// This function sets up the server
var server = net.createServer( function ( client ) {
client.rl = rl.createInterface( client, client );
client.rl.client = client;
client.name = client_id++;
console.log( '#' + client.name +' Connected (' + client.remoteAddress + ')' );
client.on( 'end', clientDisconnectionEvent );
client.on( 'timeout', clientTimeoutEvent );
client.rl.on( 'line', clientData );
client.on( 'error', errorEvent );
client.setTimeout( 2500 );
} );
server.listen( config.port, function () {
console.log( 'Server started' );
} );
// Client Disconnected Event Handler
// =================================
// This function handles client disconnection events by logging them to the console
function clientDisconnectionEvent() {
console.log( '#' + this.name + ' Disconnected' );
}
// Client Timeout Event Handler
// ============================
// This function handles client timeout events by logging them to the console and kicking the client
function clientTimeoutEvent() {
console.log( '#' + this.name + ' Timed Out' );
this.end();
}
// Client Data Event Handler
// =========================
// This function handles incoming client data and processing
function clientData( buffer ) {
var client = this.client;
var tag = buffer.toString().trim();
if ( tag.length > 50 ) {
console.log( 'Data too long' );
declineClient( client );
return;
}
// Get device ID
if ( client.device == undefined ) {
if ( config.devices[tag] == undefined ) {
console.log( '#' + client.name + ' Invalid device ID' );
declineClient( client );
return;
}
client.device = tag;
console.log( ' Device: ' + client.device );
return;
}
// Get tag #
if ( tag == '' ) {
console.log( '#' + client.name + ' Card Number Not Sent' );
declineClient( client );
return;
}
// Block Natwest contactless cards
if ( tag == contactless_id ) {
console.log( '#' + client.name + ' Contactless Card Use Blocked (21222324)' );
declineClient( client );
return;
}
console.log( '#' + client.name + ' Tag: ' + tag );
Membership.validate( tag, config.devices[ client.device ].permission, function( res ) {
if ( res.valid ) {
validateClient( client, res, tag );
} else {
declineClient( client, res, tag )
}
} );
}
// Validate Client
// ===============
// This function responds to a valid client request and handles notification and logging
function validateClient( client, data, tag ) {
var device = config.devices[ client.device ];
// Tell client
client.write( '1' );
client.end();
// Send notification
if ( checkCache( tag, device ) ) {
if ( data.name && device.message.success ) {
var msg = data.name + device.message.success;
postToDiscourse( msg );
} else if ( device.message.success ) {
var msg = 'Someone' + device.message.success;
postToDiscourse( msg );
}
}
// Log to console
console.log( '#' + client.name + ' Validated (' + data.name + ')' );
// Store to cache
storeInCache( tag, device );
}
// Decline Client
// ==============
// This function responds to a invalid client request and handles notification and logging
function declineClient( client, data, tag ) {
var device = config.devices[ client.device ];
// Tell client
client.write( '0' );
client.end();
// Send notification
if ( checkCache( tag, 'decline' ) ) {
if ( data !== undefined && tag !== undefined ) {
if ( data.name && device.message.failed ) {
var msg = data.name + device.message.failed;
postToDiscourse( msg );
} else if ( device.message.failed ) {
var msg = tag + ' ' + device.message.failed;
postToDiscourse( msg );
}
}
}
// Log to console
console.log( '#' + client.name + ' Declined' );
// Store to cache
storeInCache( tag, 'decline' );
}
// Error Event Handler
// ===================
// This function handles connection errors by logging them and closing the connection
function errorEvent( error ) {
if ( error.errno == 'ECONNRESET' ) {
console.log( '#' + this.name + ' Error: Connection reset by client (hard disconnect)' );
} else {
console.log( '#' + this.name + ' Error: ', error );
}
this.end();
}
// Check Cache
// ==============
// This function checks if an item is in the cache or not
function checkCache( tag, device ) {
for ( i in cache ) {
if ( cache[i].id === tag && cache[i].device === device ) {
var expires = new Date();
expires.setSeconds( expires.getSeconds() + cacheExpiry );
cache[i].expires = expires;
return false;
}
}
return true;
}
// Store In Cache
// ==============
// This function adds new items to the cache and marks the expiry date
function storeInCache( tag, device ) {
var expires = new Date();
expires.setSeconds( expires.getSeconds() + cacheExpiry );
var item = {
id: tag,
device: device,
expires: expires
};
cache.push( item );
}
// Clear Cache
// ===========
// This function periodically checks the cache and removes old entries
function clearCache() {
for ( i in cache ) {
if ( cache[i].expires <= new Date() ) {
cache.splice( i, 1 );
}
}
}
setInterval( clearCache, 1000 );
// Check Permision
// ===============
// This function checks the user level has permission.
function checkPermission( level, permission ) {
if ( level == 50 ) return true;
if ( config.devices[ permission ].permission.indexOf( level ) != -1 ) return true;
return false;
}
// Post to discourse
// =================
// This funciton sends a message to discourse
function postToDiscourse( msg ) {
request.post( {
url: config.discourse.url,
form: {
raw: msg,
topic_id: config.discourse.topic,
api_username: config.discourse.api_username,
api_key: config.discourse.api_key
}
} );
}