1 | import * as net from 'net';
|
2 | import * as akala from '@akala/server';
|
3 | const log=akala.log('domojs:pioneer');
|
4 |
|
5 | function buildQueue(device: string)
|
6 | {
|
7 | var connection = net.createConnection({ port: 8102, allowHalfOpen: true, host: device }, function ()
|
8 | {
|
9 | log('connected');
|
10 | queue.process();
|
11 | });
|
12 | var queue = new akala.Queue<{ command: string, callback: (status: number, data: string | Error) => void }>((message, next) =>
|
13 | {
|
14 | var responseSent = false;
|
15 | var commandSent = false;
|
16 | var firstRReceived = false;
|
17 | var receiver = function (data)
|
18 | {
|
19 | if (commandSent && !responseSent)
|
20 | {
|
21 | if (!firstRReceived && data == 'R\r\n')
|
22 | {
|
23 | firstRReceived = true;
|
24 | }
|
25 | else
|
26 | {
|
27 | responseSent = true;
|
28 | connection.removeListener('data', receiver);
|
29 | next(true);
|
30 | if (!firstRReceived)
|
31 | data = data.replace(/(?:^R+)|(?:R+$)/, '');
|
32 | data = data.replace(/[\r\n]+/g, '');
|
33 | log('received:' + data);
|
34 | message.callback(200, data);
|
35 | }
|
36 | }
|
37 | };
|
38 | connection.on('data', receiver);
|
39 | connection.setEncoding('ASCII');
|
40 | connection.on('error', function (error)
|
41 | {
|
42 | message.callback(500, error)
|
43 | });
|
44 | connection.write('\r');
|
45 | setTimeout(function ()
|
46 | {
|
47 | connection.write('\r' + message.command + '\r');
|
48 | commandSent = true;
|
49 | }, 100);
|
50 | });
|
51 | return queue;
|
52 | }
|
53 |
|
54 | var queue: { [device: string]: akala.Queue<{ command: string, callback: (status: number, data: string | Error) => void }> } = {};
|
55 |
|
56 | export function send(command: string, device: string)
|
57 | {
|
58 | return new Promise<string>((resolve, reject) =>
|
59 | {
|
60 | if (!queue[device])
|
61 | queue[device] = buildQueue(device);
|
62 |
|
63 | queue[device].enqueue({
|
64 | command: command, callback: function (status, data)
|
65 | {
|
66 | if (status == 200 && typeof (data) == 'string')
|
67 | resolve(data);
|
68 | else
|
69 | reject(data);
|
70 | }
|
71 | });
|
72 | })
|
73 | };
|
74 |
|
75 | export function VL(id, device, callback)
|
76 | {
|
77 | var volume = (id * 185 / 100).toString();
|
78 | volume = '000'.substring(0, volume.toString().length) + volume;
|
79 | return send(volume + 'VL', device);
|
80 | } |
\ | No newline at end of file |