1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 | 'use strict';
|
25 |
|
26 | function create(inputStream, outputStream) {
|
27 | var devicesStorage = new Map();
|
28 |
|
29 | setUpDeviceListeners();
|
30 |
|
31 |
|
32 | return { get_api: get_api };
|
33 |
|
34 | function setUpDeviceListeners() {
|
35 | inputStream.subscribe(handleSystemEvent);
|
36 |
|
37 | function handleSystemEvent(event) {
|
38 | if (!event) {
|
39 | return;
|
40 | }
|
41 |
|
42 | var device = getDevice(event.device);
|
43 |
|
44 | if (!device) {
|
45 | return;
|
46 | }
|
47 |
|
48 | device.value = event.value;
|
49 | }
|
50 | }
|
51 |
|
52 | function getDevice(deviceId) {
|
53 | if (!deviceId) {
|
54 | return;
|
55 | }
|
56 |
|
57 | var device = void 0;
|
58 | if (devicesStorage.has(deviceId)) {
|
59 | device = devicesStorage.get(deviceId);
|
60 | } else {
|
61 | device = createDevice(deviceId);
|
62 | devicesStorage.set(deviceId, device);
|
63 | }
|
64 | return device;
|
65 | }
|
66 |
|
67 | function createDevice(deviceId) {
|
68 | return {
|
69 | send: send
|
70 | };
|
71 |
|
72 | function send(outValue) {
|
73 | outputStream.next({
|
74 | device: deviceId,
|
75 | value: outValue,
|
76 | event: 'status'
|
77 | });
|
78 | }
|
79 | }
|
80 |
|
81 | function get_api(version) {
|
82 | var hasDevicesSubscribed = false;
|
83 |
|
84 | if (version === '0.0.1') {
|
85 | var api = create_api();
|
86 | api.version = version;
|
87 | return Promise.resolve(api);
|
88 | }
|
89 |
|
90 | return Promise.reject('This version of client script API is not supported');
|
91 |
|
92 | function create_api() {
|
93 |
|
94 | return {
|
95 | stream: {
|
96 | input: inputStream,
|
97 | output: outputStream.next.bind(outputStream)
|
98 | },
|
99 | on: onHandler,
|
100 | device: {
|
101 | get: getDevice
|
102 | }
|
103 | };
|
104 |
|
105 | function onHandler(eventName, devices, cb) {
|
106 | if (!hasDevicesSubscribed && devices.length) {
|
107 | process.on('message', function (message) {
|
108 | inputStream.next(message.content);
|
109 | });
|
110 | hasDevicesSubscribed = true;
|
111 | }
|
112 |
|
113 | if (eventName === 'message') {
|
114 | inputStream.filter(function (event) {
|
115 | return devices.indexOf(event.device) >= 0;
|
116 | }).subscribe(cb);
|
117 |
|
118 | return;
|
119 | }
|
120 |
|
121 | throw 'No such event is present';
|
122 | }
|
123 | }
|
124 | }
|
125 | }
|
126 |
|
127 | module.exports = { create: create };
|
128 |
|