@wiotp/sdk 0.8.3-beta → 0.8.4

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