@wiotp/sdk 0.4.2 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +203 -203
  2. package/README.md +68 -68
  3. package/dist/BaseClient.js +259 -0
  4. package/dist/BaseConfig.js +194 -0
  5. package/dist/api/ApiClient.js +508 -0
  6. package/dist/api/ApiErrors.js +118 -0
  7. package/dist/api/DscClient.js +332 -0
  8. package/dist/api/LecClient.js +48 -0
  9. package/dist/api/MgmtClient.js +77 -0
  10. package/dist/api/RegistryClient.js +234 -0
  11. package/dist/api/RulesClient.js +105 -0
  12. package/dist/api/StateClient.js +738 -0
  13. package/dist/application/ApplicationClient.js +436 -0
  14. package/dist/application/ApplicationConfig.js +233 -0
  15. package/dist/application/index.js +23 -0
  16. package/dist/bundled/wiotp-bundle.js +35592 -0
  17. package/dist/bundled/wiotp-bundle.min.js +47 -0
  18. package/dist/device/DeviceClient.js +125 -0
  19. package/dist/device/DeviceConfig.js +216 -0
  20. package/dist/device/index.js +23 -0
  21. package/dist/gateway/GatewayClient.js +159 -0
  22. package/dist/gateway/GatewayConfig.js +52 -0
  23. package/dist/gateway/index.js +23 -0
  24. package/dist/index.js +55 -0
  25. package/dist/util.js +50 -0
  26. package/package.json +92 -84
  27. package/src/BaseClient.js +215 -215
  28. package/src/BaseConfig.js +157 -157
  29. package/src/api/ApiClient.js +454 -454
  30. package/src/api/ApiErrors.js +33 -33
  31. package/src/api/DscClient.js +164 -145
  32. package/src/api/LecClient.js +32 -32
  33. package/src/api/MgmtClient.js +57 -57
  34. package/src/api/RegistryClient.js +194 -194
  35. package/src/api/RulesClient.js +84 -84
  36. package/src/api/StateClient.js +650 -650
  37. package/src/application/ApplicationClient.js +348 -348
  38. package/src/application/ApplicationConfig.js +191 -191
  39. package/src/application/index.js +12 -12
  40. package/src/device/DeviceClient.js +78 -78
  41. package/src/device/DeviceConfig.js +175 -175
  42. package/src/device/index.js +14 -14
  43. package/src/gateway/GatewayClient.js +114 -114
  44. package/src/gateway/GatewayConfig.js +21 -21
  45. package/src/gateway/index.js +13 -13
  46. package/{index.js → src/index.js} +19 -19
  47. package/src/util.js +38 -38
  48. package/src/util/IoTFoundation.pem +0 -82
@@ -0,0 +1,259 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports["default"] = void 0;
7
+
8
+ var _events = _interopRequireDefault(require("events"));
9
+
10
+ var _mqtt = _interopRequireDefault(require("mqtt"));
11
+
12
+ var _loglevel = _interopRequireDefault(require("loglevel"));
13
+
14
+ var _tinycache = _interopRequireDefault(require("tinycache"));
15
+
16
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
17
+
18
+ function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
19
+
20
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
21
+
22
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
23
+
24
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
25
+
26
+ function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
27
+
28
+ function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
29
+
30
+ function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
31
+
32
+ function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
33
+
34
+ function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
35
+
36
+ var uuidv4 = require('uuid/v4');
37
+
38
+ var BaseClient =
39
+ /*#__PURE__*/
40
+ function (_events$EventEmitter) {
41
+ _inherits(BaseClient, _events$EventEmitter);
42
+
43
+ function BaseClient(config) {
44
+ var _this;
45
+
46
+ _classCallCheck(this, BaseClient);
47
+
48
+ _this = _possibleConstructorReturn(this, _getPrototypeOf(BaseClient).call(this));
49
+ _this.log = _loglevel["default"];
50
+
51
+ _this.log.setDefaultLevel(config.options.logLevel);
52
+
53
+ _this.config = config;
54
+ _this.reconnectLog = 0;
55
+ _this.mqtt = null;
56
+ _this.lostConnectionLog = new _tinycache["default"]();
57
+ return _this;
58
+ }
59
+
60
+ _createClass(BaseClient, [{
61
+ key: "isConnected",
62
+ value: function isConnected() {
63
+ if (this.mqtt == null) {
64
+ return false;
65
+ }
66
+
67
+ return this.mqtt.connected;
68
+ }
69
+ }, {
70
+ key: "connect",
71
+ value: function connect() {
72
+ var _this2 = this;
73
+
74
+ if (this.mqtt != null) {
75
+ this.log.info("[BaseClient:connect] Reconnecting to " + this.config.getMqttHost() + " as " + this.config.getClientId());
76
+ this.mqtt.reconnect();
77
+ return;
78
+ }
79
+
80
+ this.log.info("[BaseClient:connect] Connecting to " + this.config.getMqttHost() + " as " + this.config.getClientId());
81
+ this.mqtt = _mqtt["default"].connect(this.config.getMqttHost(), this.config.getMqttConfig());
82
+ /* Events coming from mqtt
83
+ * Event 'connect' - Emitted on successful (re)connection (i.e. connack rc=0).
84
+ * Event 'reconnect' - Emitted when a reconnect starts.
85
+ * Event 'close' - Emitted after a disconnection.
86
+ * Event 'offline' - Emitted when the client goes offline.
87
+ * Event 'error' - Emitted when the client cannot connect (i.e. connack rc != 0) or when a parsing error occurs.
88
+ * Event 'end' - Emitted when mqtt.Client#end() is called. If a callback was passed to mqtt.Client#end(), this event is emitted once the callback returns.
89
+ * Event 'message' - Emitted when the client receives a publish packet
90
+ * Event 'packetsend' - Emitted when the client sends any packet. This includes .published() packets as well as packets used by MQTT for managing subscriptions and connections
91
+ * Event 'packetreceive' - Emitted when the client receives any packet. This includes packets from subscribed topics as well as packets used by MQTT for managing subscriptions and connections
92
+ */
93
+
94
+ this.mqtt.on('connect', function () {
95
+ _this2.log.info("[BaseClient:onConnect] MQTT client is connected.");
96
+
97
+ _this2.emit('connect'); // less than 3 connect attempts you get put to a connect delay of 1 second
98
+ // after 3 connect attempts you get put to a connect delay of 2 seconds (3 seconds elapsed - 3 attempts @ 1 second intervals)
99
+ // after 6 connect attempts you get put to a connect delay of 5 seconds (3 + 6 seconds elapsed - 3 attempts @ 2 second intervals)
100
+ // after 9 connect attempts you get put to a connect delay of 20 seconds (3 + 6 + 15 seconds elapsed - 3 attempts @ 5 second intervals)
101
+
102
+
103
+ var connectionLostCount = _this2.lostConnectionLog.size; // Default is 1 second reconnect period
104
+
105
+ var reconnectPeriod = 1000;
106
+
107
+ if (connectionLostCount >= 9) {
108
+ reconnectPeriod = 20000; // Log this and raise the error EVERY time we reconnect under these conditions.
109
+
110
+ _this2.log.warn("[BaseClient:onOffline] This client is likely suffering from clientId stealing (where two connections try to use the same client Id).");
111
+
112
+ _this2.emit("error", "Exceeded 9 connection losses in a 5 minute period. Check for clientId conflict with another connection.");
113
+ } else if (connectionLostCount >= 6) {
114
+ reconnectPeriod = 5000;
115
+ } else if (connectionLostCount >= 3) {
116
+ reconnectPeriod = 2000;
117
+ }
118
+
119
+ if (reconnectPeriod != _this2.mqtt.options.reconnectPeriod) {
120
+ _this2.log.info("[BaseClient:onOffline] Client has lost connection " + connectionLostCount + " times during the last 5 minutes, reconnect delay adjusted to " + reconnectPeriod + " ms");
121
+
122
+ _this2.mqtt.options.reconnectPeriod = reconnectPeriod;
123
+ }
124
+ });
125
+ this.mqtt.on('reconnect', function () {
126
+ _this2.log.info("[BaseClient:onReconnect] MQTT client is reconnecting."); // this.log.debug("[BaseClient:onReconnect] Resubscribe topics:");
127
+ // this.log.debug(this.mqtt._resubscribeTopics);
128
+
129
+
130
+ _this2.emit('reconnect');
131
+ });
132
+ this.mqtt.on('close', function () {
133
+ _this2.log.info("[BaseClient:onClose] MQTT client connection was closed.");
134
+
135
+ _this2.emit('close');
136
+ });
137
+ this.mqtt.on('offline', function () {
138
+ var newId = uuidv4();
139
+
140
+ _this2.log.info("[BaseClient:onOffline] MQTT client connection is offline. [" + newId + "]");
141
+
142
+ _this2.emit('offline'); // Record the disconnect event for 5 minutes
143
+
144
+
145
+ _this2.lostConnectionLog.put(newId, '1', 300000);
146
+
147
+ var connectionLostCount = _this2.lostConnectionLog.size;
148
+
149
+ _this2.log.info("[BaseClient:onOffline] Connection losses in the last 5 minutes: " + connectionLostCount);
150
+ });
151
+ this.mqtt.on('error', function (error) {
152
+ _this2.log.error("[BaseClient:onError] " + error);
153
+
154
+ var errorMsg = '' + error;
155
+
156
+ if (errorMsg.indexOf('Not authorized') > -1) {
157
+ _this2.log.error("[BaseClient:onError] One or more configuration parameters are wrong. Modify the configuration before trying to reconnect.");
158
+
159
+ _this2.mqtt.end(false, function () {
160
+ _this2.log.info("[BaseClient:onError] Closed the MQTT connection due to client misconfiguration");
161
+ });
162
+ }
163
+
164
+ _this2.emit('error', error);
165
+ });
166
+ }
167
+ }, {
168
+ key: "disconnect",
169
+ value: function disconnect() {
170
+ var _this3 = this;
171
+
172
+ if (this.mqtt == null) {
173
+ this.log.info("[BaseClient:disconnect] Client was never connected");
174
+ return;
175
+ }
176
+
177
+ this.mqtt.end(false, function () {
178
+ _this3.log.info("[BaseClient:disconnect] Closed the MQTT connection due to disconnect() call");
179
+ });
180
+ }
181
+ }, {
182
+ key: "_subscribe",
183
+ value: function _subscribe(topic, QoS, callback) {
184
+ if (this.mqtt == null) {
185
+ this.emit('error', "[BaseClient:_subscribe] MQTT Client is not initialized - call connect() first");
186
+ return;
187
+ }
188
+
189
+ if (!this.mqtt.connected) {
190
+ this.emit('error', "[BaseClient:_subscribe] MQTT Client is not connected - call connect() first");
191
+ return;
192
+ }
193
+
194
+ QoS = QoS || 0;
195
+
196
+ callback = callback || function (err, granted) {
197
+ if (err == null) {
198
+ for (var index in granted) {
199
+ var grant = granted[index];
200
+ this.log.debug("[BaseClient:_subscribe] Subscribed to " + grant.topic + " at QoS " + grant.qos);
201
+ }
202
+ } else {
203
+ this.log.error("[BaseClient:_subscribe] " + err);
204
+ this.emit("error", err);
205
+ }
206
+ }.bind(this);
207
+
208
+ this.log.debug("[BaseClient:_subscribe] Subscribing to topic " + topic + " with QoS " + QoS);
209
+ this.mqtt.subscribe(topic, {
210
+ qos: parseInt(QoS)
211
+ }, callback);
212
+ }
213
+ }, {
214
+ key: "_unsubscribe",
215
+ value: function _unsubscribe(topic, callback) {
216
+ if (this.mqtt == null) {
217
+ this.emit('error', "[BaseClient:_unsubscribe] MQTT Client is not initialized - call connect() first");
218
+ return;
219
+ }
220
+
221
+ if (!this.mqtt.connected) {
222
+ this.emit('error', "[BaseClient:_unsubscribe] MQTT Client is not connected - call connect() first");
223
+ return;
224
+ }
225
+
226
+ callback = callback || function (err) {
227
+ if (err == null) {
228
+ this.log.debug("[BaseClient:_unsubscribe] Unsubscribed from: " + topic);
229
+ } else {
230
+ this.log.error("[BaseClient:_unsubscribe] " + err);
231
+ this.emit("error", err);
232
+ }
233
+ }.bind(this);
234
+
235
+ this.log.debug("[BaseClient:_unsubscribe] Unsubscribe: " + topic);
236
+ this.mqtt.unsubscribe(topic, callback);
237
+ }
238
+ }, {
239
+ key: "_publish",
240
+ value: function _publish(topic, msg, QoS, callback) {
241
+ QoS = QoS || 0;
242
+
243
+ if ((_typeof(msg) === 'object' || typeof msg === 'boolean' || typeof msg === 'number') && !Buffer.isBuffer(msg)) {
244
+ // mqtt library does not support sending JSON/Boolean/Number data. So stringifying it.
245
+ // All JSON object, array will be encoded.
246
+ msg = JSON.stringify(msg);
247
+ }
248
+
249
+ this.log.debug("[BaseClient:_publish] Publish: " + topic + ", " + msg + ", QoS : " + QoS);
250
+ this.mqtt.publish(topic, msg, {
251
+ qos: parseInt(QoS)
252
+ }, callback);
253
+ }
254
+ }]);
255
+
256
+ return BaseClient;
257
+ }(_events["default"].EventEmitter);
258
+
259
+ exports["default"] = BaseClient;
@@ -0,0 +1,194 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports["default"] = void 0;
7
+
8
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
9
+
10
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
11
+
12
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
13
+
14
+ /**
15
+ *****************************************************************************
16
+ Copyright (c) 2019 IBM Corporation and other Contributors.
17
+ All rights reserved. This program and the accompanying materials
18
+ are made available under the terms of the Eclipse Public License v1.0
19
+ which accompanies this distribution, and is available at
20
+ http://www.eclipse.org/legal/epl-v10.html
21
+ *****************************************************************************
22
+ *
23
+ */
24
+ var BaseConfig =
25
+ /*#__PURE__*/
26
+ function () {
27
+ function BaseConfig(identity, auth, options) {
28
+ _classCallCheck(this, BaseConfig);
29
+
30
+ this.identity = identity;
31
+ this.auth = auth;
32
+ this.options = options; // Validation for options common to all confiugration
33
+
34
+ if (this.options != null && "mqtt" in this.options) {
35
+ // validate port
36
+ if ("port" in this.options.mqtt && this.options.mqtt.port != null) {
37
+ if (isNaN(this.options.mqtt.port)) {
38
+ throw new Error("Optional setting options.mqtt.port must be a number if provided");
39
+ }
40
+ } // Validate cleanStart
41
+
42
+
43
+ if ("cleanStart" in this.options.mqtt && typeof this.options.mqtt.cleanStart != "boolean") {
44
+ throw new Error("Optional setting options.mqtt.cleanStart must be a boolean if provided");
45
+ }
46
+ } // Set defaults for optional configuration
47
+
48
+
49
+ if (this.options == null) {
50
+ this.options = {};
51
+ }
52
+
53
+ if (!("domain" in this.options) || this.options.domain == null) {
54
+ this.options.domain = "internetofthings.ibmcloud.com";
55
+ }
56
+
57
+ if (!("logLevel" in this.options) || this.options.logLevel == null) {
58
+ this.options.logLevel = "info";
59
+ }
60
+
61
+ if (!("mqtt" in this.options)) {
62
+ this.options.mqtt = {};
63
+ }
64
+
65
+ if (!("port" in this.options.mqtt) || this.options.mqtt.port == null) {
66
+ this.options.mqtt.port = 8883;
67
+ }
68
+
69
+ if (!("transport" in this.options.mqtt) || this.options.mqtt.transport == null) {
70
+ this.options.mqtt.transport = "tcp";
71
+ }
72
+
73
+ if (!("cleanStart" in this.options.mqtt)) {
74
+ this.options.mqtt.cleanStart = true;
75
+ }
76
+
77
+ if (!("sessionExpiry" in this.options.mqtt)) {
78
+ this.options.mqtt.sessionExpiry = 3600;
79
+ }
80
+
81
+ if (!("keepAlive" in this.options.mqtt)) {
82
+ this.options.mqtt.keepAlive = 60;
83
+ }
84
+
85
+ if (!("caFile" in this.options.mqtt)) {
86
+ this.options.mqtt.caFile = null;
87
+ }
88
+ }
89
+
90
+ _createClass(BaseConfig, [{
91
+ key: "getOrgId",
92
+ value: function getOrgId() {
93
+ throw new Error("Sub class must implement getOrgId()");
94
+ }
95
+ }, {
96
+ key: "isQuickstart",
97
+ value: function isQuickstart() {
98
+ return this.getOrgId() == "quickstart";
99
+ }
100
+ }, {
101
+ key: "getClientId",
102
+ value: function getClientId() {
103
+ throw new Error("Sub class must implement getClientId()");
104
+ }
105
+ }, {
106
+ key: "getMqttUsername",
107
+ value: function getMqttUsername() {
108
+ throw new Error("Sub class must implement getMqttUsername()");
109
+ }
110
+ }, {
111
+ key: "getMqttPassword",
112
+ value: function getMqttPassword() {
113
+ throw new Error("Sub class must implement getMqttPassowrd()");
114
+ }
115
+ }, {
116
+ key: "getMqttConfig",
117
+ value: function getMqttConfig() {
118
+ // See: https://www.npmjs.com/package/mqtt#mqttclientstreambuilder-options
119
+ var mqttConfig = {
120
+ // Identity
121
+ clientId: this.getClientId(),
122
+ // Basic Connectivity
123
+ keepalive: this.options.mqtt.keepAlive,
124
+ // in seconds
125
+ connectTimeout: 90 * 1000,
126
+ // milliseconds, time to wait before a CONNACK is received
127
+ reconnectPeriod: 1000,
128
+ // milliseconds, interval between two reconnections
129
+ queueQoSZero: true,
130
+ // if connection is broken, queue outgoing QoS zero messages
131
+ resubscribe: true,
132
+ // if connection is broken and reconnects, subscribed topics are automatically subscribed again
133
+ clean: this.options.mqtt.cleanStart,
134
+ // set to false to receive QoS 1 and 2 messages while offline
135
+ // Authentication
136
+ username: this.getMqttUsername(),
137
+ password: this.getMqttPassword(),
138
+ // Security
139
+ // If you are using a self-signed certificate, pass the rejectUnauthorized: false option. Beware
140
+ // that you are exposing yourself to man in the middle attacks, so it is a configuration that
141
+ // is not recommended for production environments.
142
+ rejectUnauthorized: true // MQTTv5 support doesn't work with Watson IoT Platform, so stick to default for now
143
+ // protocolId: "MQTT",
144
+ // protocolVersion: 5
145
+
146
+ };
147
+ return mqttConfig;
148
+ }
149
+ }, {
150
+ key: "getMqttHost",
151
+ value: function getMqttHost() {
152
+ var server = this.getOrgId() + ".messaging." + this.options.domain + ":" + this.options.mqtt.port; // For unencrpyted ports
153
+
154
+ if (this.options.mqtt.port == 80 || this.options.mqtt.port == 1883) {
155
+ if (this.options.mqtt.transport == "tcp") {
156
+ return "tcp://" + server;
157
+ }
158
+
159
+ if (this.options.mqtt.transport == "websockets") {
160
+ return "ws://" + server;
161
+ }
162
+ } // For encrypted ports
163
+
164
+
165
+ if (this.options.mqtt.port == 433 || this.options.mqtt.port == 8883) {
166
+ if (this.options.mqtt.transport == "tcp") {
167
+ return "ssl://" + server;
168
+ }
169
+
170
+ if (this.options.mqtt.transport == "websockets") {
171
+ return "wss://" + server;
172
+ }
173
+ } // Default to something, but really shouldn't hit this scenario unless misconfigured
174
+
175
+
176
+ return "ssl://" + server;
177
+ }
178
+ }], [{
179
+ key: "parseEnvVars",
180
+ value: function parseEnvVars() {
181
+ throw new Error("Sub class must implement parseEnvVars()");
182
+ }
183
+ }, {
184
+ key: "parseConfigFile",
185
+ value: function parseConfigFile() {
186
+ throw new Error("Sub class must implement parseConfigFile()");
187
+ }
188
+ }]);
189
+
190
+ return BaseConfig;
191
+ }();
192
+
193
+ exports["default"] = BaseConfig;
194
+ ;