UNPKG

3.27 kBJavaScriptView Raw
1/**
2* @file Provides particular version of script API
3*
4* @example
5* // get API instance
6* <this>
7* .create(input: Rx.Stream, output: Rx.Stream)
8* .get_api('0.0.1')
9* .then(function(api){
10* // subscribe to events from particular devices
11* api.on('message', ['device_01', 'device_02'], function(){
12* // calculate new state when any of values have changed
13* if (
14* api.device.get('device_01').value > 0
15* && api.device.get('device_02').value == 'ON'
16* ) {
17* api.device.get('device_03').send('OFF');
18* }
19* });
20* });
21*
22*/
23
24'use strict';
25
26function create(inputStream, outputStream) {
27 var devicesStorage = new Map();
28
29 setUpDeviceListeners();
30
31 // NOTE: this is 0.0.1 only version of the api
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
127module.exports = { create: create };
128//# sourceMappingURL=scenario-api.manager.js.map