-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
320 lines (286 loc) · 9.55 KB
/
index.ts
File metadata and controls
320 lines (286 loc) · 9.55 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
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
//index.ts
import WebSocket from 'ws';
const { ReadlineParser } = require('@serialport/parser-readline');
import { SerialPort } from "serialport";
const Datatypes = [
'int8',
'uint8',
'int16',
'uint16',
'int32',
'int64',
'float16',
'float32',
'float64',
'bool',
'ascii',
];
type babelJson = {
CMD: string,
Data: {
MID?: string,
PNo?: string,
TNo?: string,
PID?: string,
TID?: string,
Value?: string,
Target?: string,
datatype?: string,
ERR?: string
}
}
function openPort(port: string, baud: number): Promise<SerialPort> {
return new Promise((resolve, reject) => {
const serialPort = new SerialPort({ path: port, baudRate: baud }, (err) => {
if (err) {
console.error(`Error opening port: ${port}`, err);
reject(err);
}
});
serialPort.once('open', () => {
console.log(`Port opened successfully: ${port}`);
resolve(serialPort);
});
});
}
async function main() {
const translator = new BabelTranslator();
await translator.startSerial();
}
class BabelTranslator {
socket: WebSocket.Server;
serialPort: SerialPort | undefined;
parser: typeof ReadlineParser;
constructor() {
this.socket = this.startSocket();
}
async startSerial() {
try {
// some condition to find the right port
const portName = '/dev/ttyACM0'; // Replace with logic to find the correct port
this.serialPort = await openPort(portName, 115200);
//send UNC to start
this.serialPort.write('UNC:0x00:0x00:0x00:0x00:0x00:0x00:0x00:0x00\n');
this.parser = this.serialPort.pipe(new ReadlineParser({ delimiter: '\n' }));
this.parser.on('data', this.handleSerialMessage.bind(this));
//Test
setInterval(() => {
this.serialPort?.write('RQT:0x00:0x01:0x00:0x00:0x00:0x00:0x00:0x00\n');
}, 2000);
} catch (error) {
console.error('Failed to start serial port:', error);
}
}
startSocket() {
const socket = new WebSocket.Server({ port: 9000 });
console.log('WebSocket server is listening on port 9000');
socket.on('connection', (ws) => {
//ws.on('message', this.handleSocketMessage.bind(this));
});
return socket;
}
handleSocketMessage(message: babelJson) {
console.log('Received message from socket:', message);
// Handle incoming WebSocket message and make it into serial message
//Message structure "CMD:Data1:Data2:Data3:Data4:Data5:Data6:Data7:Data8"
//some need to be cracked down into bytes eg 500 to 2 bytes 0x01 0xF4 but as strings
let messageString = GenSerialCommand(message);
//send to serial
if (this.serialPort) {
this.serialPort.write(messageString);
}
}
handleSerialMessage(message: string) {
console.log('Received message from serial port:', message);
// Handle incoming serial message and translate to JSON
if (!/^[A-Za-z]{3}:/.test(message)) {
// The first four characters are letters followed by a colon
console.error('Invalid message format:', message);
return;
}
console.log('Message is valid');
let JSONMessage = GenCommand(message);
//send to socket
console.log('Sending message to socket:', JSONMessage);
if (JSONMessage.CMD !== '') {
this.socket.clients.forEach(client => {
if (client.readyState === client.OPEN) {
console.log('Sending message to socket:', JSONMessage);
client.send(JSON.stringify(JSONMessage));
}
});
}
}
}
main().catch(console.error);
/*
let JSONCommand = {
CMD: 'MOV',
Data: {
MID: arr[1],
PNo: arr[2],
TNo: arr[3],
}
}
*/
function GenCommand(input: string): babelJson {
let JSONCommand = {
CMD: '',
Data: {}
}
const arr = input.split(":")
if (arr.length < 10) {
JSONCommand.CMD = arr[0]
switch (arr[0]) {
case 'WHO':
JSONCommand.Data = {
MID: arr[1],
PNo: arr[2],
TNo: arr[3],
}
return JSONCommand;
case 'TLM':
JSONCommand.Data = {
MID: arr[1],
PID: parseInt(arr[2], 16).toString(),
//Add data together
Value: combineValue([arr[3], arr[4], arr[5], arr[6], arr[7]], Datatypes[parseInt(arr[8])]),
datatype: Datatypes[parseInt(arr[8])]
}
return JSONCommand;
case 'TLT':
JSONCommand.Data = {
MID: arr[1],
TID: arr[2],
Value: combineValue([arr[3], arr[4], arr[5]], Datatypes[parseInt(arr[8])]),
Target: combineValue([arr[6], arr[7]], Datatypes[parseInt(arr[8])]),
datatype: Datatypes[parseInt(arr[8])]
}
return JSONCommand;
case 'FCK':
JSONCommand.Data = {
MID: arr[1],
ERR: arr[2] + arr[3] + arr[4] + arr[5] + arr[6] + arr[7] + arr[8],
}
return JSONCommand;
}
} else {
console.error('Invalid message format:', input);
}
return JSONCommand;
}
function GenSerialCommand(JSONCommand: babelJson): any {
let SerialCommand = ''
switch (JSONCommand.CMD) {
case 'RQT':
//MID , PID/TID, TID? If TID? then TID is in json
return;
case 'SET':
//MID, TID, Value, datatype
return;
case 'RST':
//MID
return;
case 'SOF':
//No data
return;
case 'DBG':
//MID
return;
case 'SFT':
//MID
return;
case 'MOV':
//FLAngle, FLThrottle, FRThrottle, FRAngle, RLThrottle, RLAngle, RRThrottle, RRAngle
return;
case 'MOW':
//MID, Angle, Throttle, duration (s)
return;
case 'GET':
//MID, CID, part (else 0)
return;
case 'MOA':
//MID, JointNo, Angle, Absolute/Relative, datatype
return;
}
}
function crackValue(value: string, datatype: string, byteNo: number) {
//returns a byte array of byteNo length with checking for enough space
let tmp;
let byte_array = [];
switch (datatype) {
case 'raw':
case 'bool':
case 'u8':
//just return the char of the value
//return value.split('').map(char => '0x' + char.charCodeAt(0).toString(16).padStart(2, '0'));
break;
case 'int32':
tmp = parseInt(value).toString(16);
while (tmp.length < byteNo * 2) {
tmp = '0' + tmp;
}
for (let i = 0; i < value.length; i += 2) {
let byte = value.substring(i, i + 2);
byte_array.push(parseInt(byte, 16));
}
return byte_array.map(byte => '0x' + byte.toString(16).padStart(2, '0'));
case 'fl16':
//minimum 2 bytes
case 'float32':
//minimum 4 bytes
let fl32buffer = new ArrayBuffer(byteNo);
let fl32view = new DataView(fl32buffer);
fl32view.setFloat32(0, parseFloat(value));
let bytes = new Uint8Array(fl32buffer);
//convert each to string hex
return Array.from(bytes).map(byte => '0x' + byte.toString(16).padStart(2, '0'));
case 'fl64':
//Unsuppported
break;
}
return [];
}
function combineValue(valueArr: string[], datatype: string) {
//returns a string of the combined value from a string byte array
let tmp;
console.log(datatype);
console.log(valueArr);
switch (datatype) {
case 'raw':
case 'bool':
tmp = valueArr.map(byte => parseInt(byte, 16));
//if all bytes are 0 then return false else true
return tmp.every(byte => byte === 0) ? false : true;
case 'u8':
//just return the char of the value
//return value.split('').map(char => '0x' + char.charCodeAt(0).toString(16).padStart(2, '0'));
break;
case 'i32':
//minimum 4 bytes
//convert each string to a byte
let i32 = '';
tmp = valueArr.map(byte => parseInt(byte, 16));
tmp.forEach(byte => {
i32 += byte.toString(16).padStart(2, '0');
});
return parseInt(i32, 16);
case 'fl16':
//minimum 2 bytes
//unsupported
case 'float32':
// 4 bytes, forget the first occurrence of 0x
tmp = valueArr.slice(1); // Create a new array without the first element
console.log(tmp);
let fl32buffer = new ArrayBuffer(4);
let fl32view = new DataView(fl32buffer);
let fl32 = tmp.map(byte => parseInt(byte, 16));
fl32.forEach((byte, index) => {
fl32view.setInt8(index, byte);
});
return parseFloat(fl32view.getFloat32(0).toPrecision(6));
case 'fl64':
//Unsuppported
break;
}
}