├── .htaccess ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── HEADER ├── LICENSE ├── README.md ├── assets ├── arrow_down.png ├── arrow_up.png ├── chevron-double-3-01.png ├── chevron-double-3-02.png ├── hivemq-logo.svg ├── jquery.minicolors.png └── logo.png ├── config.js ├── css ├── foundation.css ├── foundation.min.css ├── jquery.minicolors.css ├── normalize.css └── style.css ├── fancybox ├── blank.gif ├── fancy_close.png ├── fancy_loading.png ├── fancy_nav_left.png ├── fancy_nav_right.png ├── fancy_shadow_e.png ├── fancy_shadow_n.png ├── fancy_shadow_ne.png ├── fancy_shadow_nw.png ├── fancy_shadow_s.png ├── fancy_shadow_se.png ├── fancy_shadow_sw.png ├── fancy_shadow_w.png ├── fancy_title_left.png ├── fancy_title_main.png ├── fancy_title_over.png ├── fancy_title_right.png ├── fancybox-x.png ├── fancybox-y.png └── fancybox.png ├── img └── .gitkeep ├── index.html └── js ├── app.js ├── arrow.gif ├── cross.gif ├── custom-combobox.js ├── encoder.js ├── hs.png ├── hv.png ├── jquery.minicolors.min.js └── mqttws31.js /.htaccess: -------------------------------------------------------------------------------- 1 | RewriteEngine On 2 | RewriteCond %{HTTPS} =on 3 | RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI}$1 [L,R=301] -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # HiveMQ Code of Conduct 2 | 3 | Please refer to our [HiveMQ Code of Conduct](https://github.com/hivemq/hivemq-community/blob/master/code-of-conduct.md). 4 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Welcome to the HiveMQ Community! Glad to see your interest in contributing to HiveMQ MQTT Web Client. Please checkout our [Contribution Guide](https://github.com/hivemq/hivemq-community/blob/master/CONTRIBUTING.adoc) to make sure your contribution will be accepted by the HiveMQ team. 4 | 5 | For information on how the HiveMQ Community is organized and how contributions will be accepted please have a look at our [HiveMQ Community Repo](https://github.com/hivemq/hivemq-community). 6 | -------------------------------------------------------------------------------- /HEADER: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 dc-square GmbH 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | hivemq-mqtt-web-client 2 | ====================== 3 | 4 | ## A websockets based MQTT Client for your browser. 5 | 6 | This client runs on any modern browser, which supports websockets (sorry Internet Explorer <10!). 7 | You can use it to publish and subscribe at the same time. 8 | 9 | See it in action at [http://hivemq.com/demos/websocket-client/](http://www.hivemq.com/demos/websocket-client/ "MQTT Websocket Client") 10 | 11 | ## How to use it 12 | 13 | Read the blog post about ["A full-featured MQTT client for your browser"](http://www.hivemq.com/full-featured-mqtt-client-browser/ "A full-featured MQTT client for your browser") 14 | 15 | 16 | ## Localhost / Local network 17 | 18 | You can also use this client to connect to a broker on your local machine ("localhost") or any machine in your local network which is reachable from the machine which your browser runs on. 19 | 20 | 21 | 22 | ## MQTT Broker 23 | 24 | This web client works perfectly with the [HiveMQ MQTT broker](https://www.hivemq.com/hivemq/ "HiveMQ MQTT Broker") with enabled websockets. 25 | 26 | If you don’t like to use a self hosted (or locally running) HiveMQ, you can use the [public MQTT broker](http://www.hivemq.com/showcase/public-mqtt-broker/ "Public MQTT Server") from the [MQTTDashboard](http://www.mqttdashboard.com/ "MQTT Dashboard"). 27 | 28 | * Host: **broker.mqttdashboard.com** 29 | * Websockets port: **8000** 30 | 31 | 32 | ## Why another MQTT Client 33 | 34 | We at [HiveMQ](https://www.hivemq.com/ "HiveMQ") needed a quick and simple way to develop and test our applications which use MQTT over websockets, so we sat down for a few hours and built this client which also works for your local development machine. 35 | 36 | ## Can I embedd it / ship it with my software? 37 | 38 | Sure! We would however be very glad if you would honor the work by linking to the original client source or mentioning that this websocket client was developed initially for HiveMQs websocket support. 39 | 40 | # Contributing 41 | 42 | If you want to contribute to HiveMQ MQTT Web Client, see the [contribution guidelines](CONTRIBUTING.md). 43 | 44 | # License 45 | 46 | HiveMQ MQTT Web Client is licensed under the `APACHE LICENSE, VERSION 2.0`. A copy of the license can be found [here](LICENSE). 47 | 48 | -------------------------------------------------------------------------------- /assets/arrow_down.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/assets/arrow_down.png -------------------------------------------------------------------------------- /assets/arrow_up.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/assets/arrow_up.png -------------------------------------------------------------------------------- /assets/chevron-double-3-01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/assets/chevron-double-3-01.png -------------------------------------------------------------------------------- /assets/chevron-double-3-02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/assets/chevron-double-3-02.png -------------------------------------------------------------------------------- /assets/hivemq-logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/jquery.minicolors.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/assets/jquery.minicolors.png -------------------------------------------------------------------------------- /assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/assets/logo.png -------------------------------------------------------------------------------- /config.js: -------------------------------------------------------------------------------- 1 | websocketserver = 'broker.mqttdashboard.com'; 2 | websocketport = 8000; 3 | -------------------------------------------------------------------------------- /css/jquery.minicolors.css: -------------------------------------------------------------------------------- 1 | .minicolors { 2 | position: relative; 3 | } 4 | 5 | .minicolors-swatch { 6 | position: absolute; 7 | vertical-align: middle; 8 | background: url(../assets/jquery.minicolors.png) -80px 0; 9 | border: solid 1px #ccc; 10 | cursor: text; 11 | padding: 0; 12 | margin: 0; 13 | display: inline-block; 14 | } 15 | 16 | .minicolors-swatch-color { 17 | position: absolute; 18 | top: 0; 19 | left: 0; 20 | right: 0; 21 | bottom: 0; 22 | } 23 | 24 | .minicolors input[type=hidden] + .minicolors-swatch { 25 | width: 28px; 26 | position: static; 27 | cursor: pointer; 28 | } 29 | 30 | /* Panel */ 31 | .minicolors-panel { 32 | position: absolute; 33 | width: 173px; 34 | height: 152px; 35 | background: white; 36 | border: solid 1px #CCC; 37 | box-shadow: 0 0 20px rgba(0, 0, 0, .2); 38 | z-index: 99999; 39 | -moz-box-sizing: content-box; 40 | -webkit-box-sizing: content-box; 41 | box-sizing: content-box; 42 | display: none; 43 | } 44 | 45 | .minicolors-panel.minicolors-visible { 46 | display: block; 47 | } 48 | 49 | /* Panel positioning */ 50 | .minicolors-position-top .minicolors-panel { 51 | top: -154px; 52 | } 53 | 54 | .minicolors-position-right .minicolors-panel { 55 | right: 0; 56 | } 57 | 58 | .minicolors-position-bottom .minicolors-panel { 59 | top: auto; 60 | } 61 | 62 | .minicolors-position-left .minicolors-panel { 63 | left: 0; 64 | } 65 | 66 | .minicolors-with-opacity .minicolors-panel { 67 | width: 194px; 68 | } 69 | 70 | .minicolors .minicolors-grid { 71 | position: absolute; 72 | top: 1px; 73 | left: 1px; 74 | width: 150px; 75 | height: 150px; 76 | background: url(../assets/jquery.minicolors.png) -120px 0; 77 | cursor: crosshair; 78 | } 79 | 80 | .minicolors .minicolors-grid-inner { 81 | position: absolute; 82 | top: 0; 83 | left: 0; 84 | width: 150px; 85 | height: 150px; 86 | background: none; 87 | } 88 | 89 | .minicolors-slider-saturation .minicolors-grid { 90 | background-position: -420px 0; 91 | } 92 | 93 | .minicolors-slider-saturation .minicolors-grid-inner { 94 | background: url(../assets/jquery.minicolors.png) -270px 0; 95 | } 96 | 97 | .minicolors-slider-brightness .minicolors-grid { 98 | background-position: -570px 0; 99 | } 100 | 101 | .minicolors-slider-brightness .minicolors-grid-inner { 102 | background: black; 103 | } 104 | 105 | .minicolors-slider-wheel .minicolors-grid { 106 | background-position: -720px 0; 107 | } 108 | 109 | .minicolors-slider, 110 | .minicolors-opacity-slider { 111 | position: absolute; 112 | top: 1px; 113 | left: 152px; 114 | width: 20px; 115 | height: 150px; 116 | background: white url(../assets/jquery.minicolors.png) 0 0; 117 | cursor: row-resize; 118 | } 119 | 120 | .minicolors-slider-saturation .minicolors-slider { 121 | background-position: -60px 0; 122 | } 123 | 124 | .minicolors-slider-brightness .minicolors-slider { 125 | background-position: -20px 0; 126 | } 127 | 128 | .minicolors-slider-wheel .minicolors-slider { 129 | background-position: -20px 0; 130 | } 131 | 132 | .minicolors-opacity-slider { 133 | left: 173px; 134 | background-position: -40px 0; 135 | display: none; 136 | } 137 | 138 | .minicolors-with-opacity .minicolors-opacity-slider { 139 | display: block; 140 | } 141 | 142 | /* Pickers */ 143 | .minicolors-grid .minicolors-picker { 144 | position: absolute; 145 | top: 70px; 146 | left: 70px; 147 | width: 12px; 148 | height: 12px; 149 | border: solid 1px black; 150 | border-radius: 10px; 151 | margin-top: -6px; 152 | margin-left: -6px; 153 | background: none; 154 | } 155 | 156 | .minicolors-grid .minicolors-picker > div { 157 | position: absolute; 158 | top: 0; 159 | left: 0; 160 | width: 8px; 161 | height: 8px; 162 | border-radius: 8px; 163 | border: solid 2px white; 164 | -moz-box-sizing: content-box; 165 | -webkit-box-sizing: content-box; 166 | box-sizing: content-box; 167 | } 168 | 169 | .minicolors-picker { 170 | position: absolute; 171 | top: 0; 172 | left: 0; 173 | width: 18px; 174 | height: 2px; 175 | background: white; 176 | border: solid 1px black; 177 | margin-top: -2px; 178 | -moz-box-sizing: content-box; 179 | -webkit-box-sizing: content-box; 180 | box-sizing: content-box; 181 | } 182 | 183 | /* Inline controls */ 184 | .minicolors-inline { 185 | display: inline-block; 186 | } 187 | 188 | .minicolors-inline .minicolors-input { 189 | display: none !important; 190 | } 191 | 192 | .minicolors-inline .minicolors-panel { 193 | position: relative; 194 | top: auto; 195 | left: auto; 196 | box-shadow: none; 197 | z-index: auto; 198 | display: inline-block; 199 | } 200 | 201 | /* Default theme */ 202 | .minicolors-theme-default .minicolors-swatch { 203 | top: 5px; 204 | left: 5px; 205 | width: 18px; 206 | height: 18px; 207 | } 208 | .minicolors-theme-default.minicolors-position-right .minicolors-swatch { 209 | left: auto; 210 | right: 5px; 211 | } 212 | .minicolors-theme-default.minicolors { 213 | width: auto; 214 | display: inline-block; 215 | } 216 | .minicolors-theme-default .minicolors-input { 217 | height: 20px; 218 | width: auto; 219 | display: inline-block; 220 | padding-left: 26px; 221 | } 222 | .minicolors-theme-default.minicolors-position-right .minicolors-input { 223 | padding-right: 26px; 224 | padding-left: inherit; 225 | } 226 | 227 | /* Bootstrap theme */ 228 | .minicolors-theme-bootstrap .minicolors-swatch { 229 | top: 3px; 230 | left: 3px; 231 | width: 28px; 232 | height: 28px; 233 | border-radius: 3px; 234 | } 235 | .minicolors-theme-bootstrap.minicolors-position-right .minicolors-swatch { 236 | left: auto; 237 | right: 3px; 238 | } 239 | .minicolors-theme-bootstrap .minicolors-input { 240 | padding-left: 44px; 241 | } 242 | .minicolors-theme-bootstrap.minicolors-position-right .minicolors-input { 243 | padding-right: 44px; 244 | padding-left: 12px; 245 | } -------------------------------------------------------------------------------- /css/normalize.css: -------------------------------------------------------------------------------- 1 | /*! normalize.css v2.1.1 | MIT License | git.io/normalize */ 2 | 3 | /* ========================================================================== 4 | HTML5 display definitions 5 | ========================================================================== */ 6 | 7 | /** 8 | * Correct `block` display not defined in IE 8/9. 9 | */ 10 | 11 | article, 12 | aside, 13 | details, 14 | figcaption, 15 | figure, 16 | footer, 17 | header, 18 | hgroup, 19 | main, 20 | nav, 21 | section, 22 | summary { 23 | display: block; 24 | } 25 | 26 | /** 27 | * Correct `inline-block` display not defined in IE 8/9. 28 | */ 29 | 30 | audio, 31 | canvas, 32 | video { 33 | display: inline-block; 34 | } 35 | 36 | /** 37 | * Prevent modern browsers from displaying `audio` without controls. 38 | * Remove excess height in iOS 5 devices. 39 | */ 40 | 41 | audio:not([controls]) { 42 | display: none; 43 | height: 0; 44 | } 45 | 46 | /** 47 | * Address styling not present in IE 8/9. 48 | */ 49 | 50 | [hidden] { 51 | display: none; 52 | } 53 | 54 | /* ========================================================================== 55 | Base 56 | ========================================================================== */ 57 | 58 | /** 59 | * 1. Prevent system color scheme's background color being used in Firefox, IE, 60 | * and Opera. 61 | * 2. Prevent system color scheme's text color being used in Firefox, IE, and 62 | * Opera. 63 | * 3. Set default font family to sans-serif. 64 | * 4. Prevent iOS text size adjust after orientation change, without disabling 65 | * user zoom. 66 | */ 67 | 68 | html { 69 | background: #fff; /* 1 */ 70 | color: #000; /* 2 */ 71 | font-family: sans-serif; /* 3 */ 72 | -ms-text-size-adjust: 100%; /* 4 */ 73 | -webkit-text-size-adjust: 100%; /* 4 */ 74 | } 75 | 76 | /** 77 | * Remove default margin. 78 | */ 79 | 80 | body { 81 | margin: 0; 82 | } 83 | 84 | /* ========================================================================== 85 | Links 86 | ========================================================================== */ 87 | 88 | /** 89 | * Address `outline` inconsistency between Chrome and other browsers. 90 | */ 91 | 92 | a:focus { 93 | outline: thin dotted; 94 | } 95 | 96 | /** 97 | * Improve readability when focused and also mouse hovered in all browsers. 98 | */ 99 | 100 | a:active, 101 | a:hover { 102 | outline: 0; 103 | } 104 | 105 | /* ========================================================================== 106 | Typography 107 | ========================================================================== */ 108 | 109 | /** 110 | * Address variable `h1` font-size and margin within `section` and `article` 111 | * contexts in Firefox 4+, Safari 5, and Chrome. 112 | */ 113 | 114 | h1 { 115 | font-size: 2em; 116 | margin: 0.67em 0; 117 | } 118 | 119 | /** 120 | * Address styling not present in IE 8/9, Safari 5, and Chrome. 121 | */ 122 | 123 | abbr[title] { 124 | border-bottom: 1px dotted; 125 | } 126 | 127 | /** 128 | * Address style set to `bolder` in Firefox 4+, Safari 5, and Chrome. 129 | */ 130 | 131 | b, 132 | strong { 133 | font-weight: bold; 134 | } 135 | 136 | /** 137 | * Address styling not present in Safari 5 and Chrome. 138 | */ 139 | 140 | dfn { 141 | font-style: italic; 142 | } 143 | 144 | /** 145 | * Address differences between Firefox and other browsers. 146 | */ 147 | 148 | hr { 149 | -moz-box-sizing: content-box; 150 | box-sizing: content-box; 151 | height: 0; 152 | } 153 | 154 | /** 155 | * Address styling not present in IE 8/9. 156 | */ 157 | 158 | mark { 159 | background: #ff0; 160 | color: #000; 161 | } 162 | 163 | /** 164 | * Correct font family set oddly in Safari 5 and Chrome. 165 | */ 166 | 167 | code, 168 | kbd, 169 | pre, 170 | samp { 171 | font-family: monospace, serif; 172 | font-size: 1em; 173 | } 174 | 175 | /** 176 | * Improve readability of pre-formatted text in all browsers. 177 | */ 178 | 179 | pre { 180 | white-space: pre-wrap; 181 | } 182 | 183 | /** 184 | * Set consistent quote types. 185 | */ 186 | 187 | q { 188 | quotes: "\201C" "\201D" "\2018" "\2019"; 189 | } 190 | 191 | /** 192 | * Address inconsistent and variable font size in all browsers. 193 | */ 194 | 195 | small { 196 | font-size: 80%; 197 | } 198 | 199 | /** 200 | * Prevent `sub` and `sup` affecting `line-height` in all browsers. 201 | */ 202 | 203 | sub, 204 | sup { 205 | font-size: 75%; 206 | line-height: 0; 207 | position: relative; 208 | vertical-align: baseline; 209 | } 210 | 211 | sup { 212 | top: -0.5em; 213 | } 214 | 215 | sub { 216 | bottom: -0.25em; 217 | } 218 | 219 | /* ========================================================================== 220 | Embedded content 221 | ========================================================================== */ 222 | 223 | /** 224 | * Remove border when inside `a` element in IE 8/9. 225 | */ 226 | 227 | img { 228 | border: 0; 229 | } 230 | 231 | /** 232 | * Correct overflow displayed oddly in IE 9. 233 | */ 234 | 235 | svg:not(:root) { 236 | overflow: hidden; 237 | } 238 | 239 | /* ========================================================================== 240 | Figures 241 | ========================================================================== */ 242 | 243 | /** 244 | * Address margin not present in IE 8/9 and Safari 5. 245 | */ 246 | 247 | figure { 248 | margin: 0; 249 | } 250 | 251 | /* ========================================================================== 252 | Forms 253 | ========================================================================== */ 254 | 255 | /** 256 | * Define consistent border, margin, and padding. 257 | */ 258 | 259 | fieldset { 260 | border: 1px solid #c0c0c0; 261 | margin: 0 2px; 262 | padding: 0.35em 0.625em 0.75em; 263 | } 264 | 265 | /** 266 | * 1. Correct `color` not being inherited in IE 8/9. 267 | * 2. Remove padding so people aren't caught out if they zero out fieldsets. 268 | */ 269 | 270 | legend { 271 | border: 0; /* 1 */ 272 | padding: 0; /* 2 */ 273 | } 274 | 275 | /** 276 | * 1. Correct font family not being inherited in all browsers. 277 | * 2. Correct font size not being inherited in all browsers. 278 | * 3. Address margins set differently in Firefox 4+, Safari 5, and Chrome. 279 | */ 280 | 281 | button, 282 | input, 283 | select, 284 | textarea { 285 | font-family: inherit; /* 1 */ 286 | font-size: 100%; /* 2 */ 287 | margin: 0; /* 3 */ 288 | } 289 | 290 | /** 291 | * Address Firefox 4+ setting `line-height` on `input` using `!important` in 292 | * the UA stylesheet. 293 | */ 294 | 295 | button, 296 | input { 297 | line-height: normal; 298 | } 299 | 300 | /** 301 | * Address inconsistent `text-transform` inheritance for `button` and `select`. 302 | * All other form control elements do not inherit `text-transform` values. 303 | * Correct `button` style inheritance in Chrome, Safari 5+, and IE 8+. 304 | * Correct `select` style inheritance in Firefox 4+ and Opera. 305 | */ 306 | 307 | button, 308 | select { 309 | text-transform: none; 310 | } 311 | 312 | /** 313 | * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio` 314 | * and `video` controls. 315 | * 2. Correct inability to style clickable `input` types in iOS. 316 | * 3. Improve usability and consistency of cursor style between image-type 317 | * `input` and others. 318 | */ 319 | 320 | button, 321 | html input[type="button"], /* 1 */ 322 | input[type="reset"], 323 | input[type="submit"] { 324 | -webkit-appearance: button; /* 2 */ 325 | cursor: pointer; /* 3 */ 326 | } 327 | 328 | /** 329 | * Re-set default cursor for disabled elements. 330 | */ 331 | 332 | button[disabled], 333 | html input[disabled] { 334 | cursor: default; 335 | } 336 | 337 | /** 338 | * 1. Address box sizing set to `content-box` in IE 8/9. 339 | * 2. Remove excess padding in IE 8/9. 340 | */ 341 | 342 | input[type="checkbox"], 343 | input[type="radio"] { 344 | box-sizing: border-box; /* 1 */ 345 | padding: 0; /* 2 */ 346 | } 347 | 348 | /** 349 | * 1. Address `appearance` set to `searchfield` in Safari 5 and Chrome. 350 | * 2. Address `box-sizing` set to `border-box` in Safari 5 and Chrome 351 | * (include `-moz` to future-proof). 352 | */ 353 | 354 | input[type="search"] { 355 | -webkit-appearance: textfield; /* 1 */ 356 | -moz-box-sizing: content-box; 357 | -webkit-box-sizing: content-box; /* 2 */ 358 | box-sizing: content-box; 359 | } 360 | 361 | /** 362 | * Remove inner padding and search cancel button in Safari 5 and Chrome 363 | * on OS X. 364 | */ 365 | 366 | input[type="search"]::-webkit-search-cancel-button, 367 | input[type="search"]::-webkit-search-decoration { 368 | -webkit-appearance: none; 369 | } 370 | 371 | /** 372 | * Remove inner padding and border in Firefox 4+. 373 | */ 374 | 375 | button::-moz-focus-inner, 376 | input::-moz-focus-inner { 377 | border: 0; 378 | padding: 0; 379 | } 380 | 381 | /** 382 | * 1. Remove default vertical scrollbar in IE 8/9. 383 | * 2. Improve readability and alignment in all browsers. 384 | */ 385 | 386 | textarea { 387 | overflow: auto; /* 1 */ 388 | vertical-align: top; /* 2 */ 389 | } 390 | 391 | /* ========================================================================== 392 | Tables 393 | ========================================================================== */ 394 | 395 | /** 396 | * Remove most spacing between table cells. 397 | */ 398 | 399 | table { 400 | border-collapse: collapse; 401 | border-spacing: 0; 402 | } 403 | -------------------------------------------------------------------------------- /css/style.css: -------------------------------------------------------------------------------- 1 | #header { 2 | float: none; 3 | margin: 0 auto; 4 | padding: 0; 5 | height: 80px; 6 | background-color: #f2f2f2; 7 | border-bottom: solid 2px #000000; 8 | margin-bottom: 20px; 9 | width: 100%; 10 | background: #f2f2f2; /* Old browsers */ 11 | background-image: -moz-linear-gradient(top, #f8f8f8 0%, #f2f2f2 100%); /* FF3.6+ */ 12 | background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #f8f8f8), color-stop(100%, #f2f2f2)); /* Chrome,Safari4+ */ 13 | background-image: -webkit-linear-gradient(top, #f8f8f8 0%, #f2f2f2 100%); /* Chrome10+,Safari5.1+ */ 14 | background-image: -o-linear-gradient(top, #f8f8f8 0%, #f2f2f2 100%); /* Opera 11.10+ */ 15 | background-image: -ms-linear-gradient(top, #f8f8f8 0%, #f2f2f2 100%); /* IE10+ */ 16 | background-image: linear-gradient(to bottom, #f8f8f8 0%, #f2f2f2 100%); /* W3C */ 17 | filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f8f8f8', endColorstr='#f2f2f2', GradientType=0); /* IE6-8 */ 18 | } 19 | 20 | #header > div { 21 | max-width: 62.5em; 22 | margin: 0 auto; 23 | } 24 | 25 | #headertitle { 26 | float: right; 27 | margin-top: 30px; 28 | margin-right: 20px; 29 | } 30 | 31 | #headerlogo { 32 | margin-left: 20px; 33 | margin-top: 5px; 34 | } 35 | 36 | .conniTop { 37 | margin-left: 15px; 38 | background-color: #f2f2f2; 39 | width: 180px; 40 | } 41 | 42 | .publishTop { 43 | background-color: #f2f2f2; 44 | width: 160px; 45 | } 46 | 47 | .subTop { 48 | background-color: #f2f2f2; 49 | width: 215px; 50 | } 51 | 52 | .messagesTop { 53 | background-color: #f2f2f2; 54 | width: 180px; 55 | } 56 | 57 | div.conniArrow, div.publishArrow, div.subArrow, div.messagesArrow { 58 | float: right; 59 | text-align: right; 60 | } 61 | 62 | .checky { 63 | margin-left: 22px; 64 | } 65 | 66 | .connection { 67 | margin-bot: 20px; 68 | } 69 | 70 | .publish { 71 | 72 | margin-top: 20px; 73 | width: 60%; 74 | } 75 | 76 | .disc li { 77 | list-style-type: none; 78 | margin-bottom: 10px; 79 | background-color: #ffffff; 80 | } 81 | 82 | #colorChooser { 83 | width: 20px; 84 | padding-left: 30px; 85 | line-height: 24px; 86 | } 87 | 88 | /*.subs0, .mess0{ 89 | border-left: solid 10px #ffff00; 90 | background-color: #ffffff; 91 | } 92 | .subs1, .mess1{ 93 | border-left: solid 10px #ff00ff; 94 | background-color: #ffffff; 95 | } 96 | 97 | .subs2, .mess2{ 98 | border-left: solid 10px #00ffff; 99 | background-color: #ffffff; 100 | } 101 | 102 | .subs3, .mess3{ 103 | border-left: solid 10px #f0fff0; 104 | background-color: #ffffff; 105 | } 106 | 107 | .subs4, .mess4{ 108 | border-left: solid 10px #ff0f0f; 109 | background-color: #ffffff; 110 | }*/ 111 | 112 | .subText { 113 | border-style: solid; 114 | border-width: 1px; 115 | border-color: #cccccc; 116 | background-color: #ffffff; 117 | text-overflow: ellipsis; 118 | overflow: hidden; 119 | white-space: nowrap; 120 | } 121 | 122 | .messageText { 123 | border: solid 1px #cccccc; 124 | } 125 | 126 | .closer { 127 | margin-bot: 20px; 128 | padding: 0; 129 | } 130 | 131 | .left { 132 | width: 10px; 133 | background-color: #ffff00; 134 | } 135 | 136 | .right { 137 | float: right; 138 | color: #bababa; 139 | } 140 | 141 | .colorSub { 142 | background-color: #ffff00; 143 | } 144 | 145 | .addSubButton { 146 | width: 100%; 147 | } 148 | 149 | .empty { 150 | clear: both; 151 | height: 20px; 152 | } 153 | 154 | #connectButton, #disconnectButton { 155 | margin-top: 17px; 156 | } 157 | 158 | #publishButton { 159 | margin-top: 17px; 160 | margin-left: -10px; 161 | } 162 | 163 | #filterButton { 164 | margin-top: 17px; 165 | } 166 | 167 | #subscribeButton { 168 | margin-top: 17px; 169 | margin-left: -30px; 170 | } 171 | 172 | #lwQosInput { 173 | margin-top: 7px; 174 | margin-left: 20px; 175 | width: 50px; 176 | } 177 | 178 | #publishQoSInput { 179 | margin-top: 7px; 180 | margin-left: -5px; 181 | width: 50px; 182 | } 183 | 184 | #QoSInput { 185 | margin-top: 7px; 186 | margin-left: -5px; 187 | width: 50px; 188 | } 189 | 190 | .qos, .date, .topicM, .retain { 191 | color: #bababa; 192 | font-size: 12px; 193 | } 194 | 195 | .columns h3 { 196 | margin-bottom: 0; 197 | margin-top: 0; 198 | font-size: 23px; 199 | } 200 | 201 | form.custom .custom.dropdown.small { 202 | width: 70px; 203 | } 204 | 205 | form.custom .custom.checkbox { 206 | margin-left: 0.7em; 207 | margin-top: 10px; 208 | } 209 | 210 | #connection, #publish-sub { 211 | width: 100%; 212 | } 213 | 214 | .columns.subArrow, .columns.publishArrow, .columns.messagesArrow { 215 | padding-right: 0; 216 | } 217 | 218 | #addSubButton { 219 | margin-top: 15px; 220 | } 221 | 222 | #publishPanel { 223 | padding-right: 0; 224 | padding-left: 0; 225 | } 226 | 227 | div.messageText { 228 | padding-left: 0; 229 | padding-right: 0; 230 | } 231 | 232 | .row .messLine div.row, .row .subLine div.row { 233 | margin-left: auto; 234 | margin-right: auto; 235 | } 236 | 237 | #messagesMain { 238 | margin-bottom: 20px; 239 | } 240 | 241 | div.icon-arrow-chevron { 242 | background-image: url('../assets/chevron-double-3-01.png'); 243 | min-height: 32px; 244 | min-width: 32px; 245 | background-repeat: no-repeat; 246 | background-position: right; 247 | } 248 | 249 | .closed div.icon-arrow-chevron { 250 | background-image: url('../assets/chevron-double-3-02.png'); 251 | } 252 | 253 | #connectionStatus { 254 | margin-top: 7px; 255 | width: 16px; 256 | height: 16px; 257 | border-radius: 8px; 258 | } 259 | 260 | body.notconnected #connectionStatus { 261 | background-color: #bc0000; 262 | } 263 | 264 | body.connected #connectionStatus { 265 | background-color: #009700; 266 | } 267 | 268 | body.notconnected #disconnectButton { 269 | display: none; 270 | } 271 | 272 | body.connected #disconnectButton { 273 | display: inline-block; 274 | } 275 | 276 | body.notconnected #connectButton { 277 | display: inline-block; 278 | } 279 | 280 | body.connected #connectButton { 281 | display: none; 282 | } 283 | 284 | body.connected #connectionStatus:after { 285 | content: 'connected'; 286 | padding-left: 22px; 287 | } 288 | 289 | body.connectionbroke #connectionStatus:after { 290 | content: 'disconnected'; 291 | padding-left: 22px; 292 | } 293 | 294 | .columns.subText { 295 | padding-right: 2px; 296 | } 297 | 298 | .truncate { 299 | white-space: nowrap; 300 | overflow: hidden; 301 | text-overflow: ellipsis; 302 | } 303 | 304 | .break-words { 305 | word-wrap: break-word; 306 | } -------------------------------------------------------------------------------- /fancybox/blank.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/fancybox/blank.gif -------------------------------------------------------------------------------- /fancybox/fancy_close.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/fancybox/fancy_close.png -------------------------------------------------------------------------------- /fancybox/fancy_loading.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/fancybox/fancy_loading.png -------------------------------------------------------------------------------- /fancybox/fancy_nav_left.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/fancybox/fancy_nav_left.png -------------------------------------------------------------------------------- /fancybox/fancy_nav_right.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/fancybox/fancy_nav_right.png -------------------------------------------------------------------------------- /fancybox/fancy_shadow_e.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/fancybox/fancy_shadow_e.png -------------------------------------------------------------------------------- /fancybox/fancy_shadow_n.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/fancybox/fancy_shadow_n.png -------------------------------------------------------------------------------- /fancybox/fancy_shadow_ne.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/fancybox/fancy_shadow_ne.png -------------------------------------------------------------------------------- /fancybox/fancy_shadow_nw.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/fancybox/fancy_shadow_nw.png -------------------------------------------------------------------------------- /fancybox/fancy_shadow_s.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/fancybox/fancy_shadow_s.png -------------------------------------------------------------------------------- /fancybox/fancy_shadow_se.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/fancybox/fancy_shadow_se.png -------------------------------------------------------------------------------- /fancybox/fancy_shadow_sw.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/fancybox/fancy_shadow_sw.png -------------------------------------------------------------------------------- /fancybox/fancy_shadow_w.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/fancybox/fancy_shadow_w.png -------------------------------------------------------------------------------- /fancybox/fancy_title_left.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/fancybox/fancy_title_left.png -------------------------------------------------------------------------------- /fancybox/fancy_title_main.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/fancybox/fancy_title_main.png -------------------------------------------------------------------------------- /fancybox/fancy_title_over.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/fancybox/fancy_title_over.png -------------------------------------------------------------------------------- /fancybox/fancy_title_right.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/fancybox/fancy_title_right.png -------------------------------------------------------------------------------- /fancybox/fancybox-x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/fancybox/fancybox-x.png -------------------------------------------------------------------------------- /fancybox/fancybox-y.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/fancybox/fancybox-y.png -------------------------------------------------------------------------------- /fancybox/fancybox.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/fancybox/fancybox.png -------------------------------------------------------------------------------- /img/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/img/.gitkeep -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | MQTT Websocket Client 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 24 |
25 |
26 | 27 |
28 |

Connection

29 |
30 | 31 |
32 |
33 |
34 | 35 |
36 | 37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 | 46 | 47 |
48 | 49 |
50 | 51 | 52 |
53 | 54 |
55 | 56 | 57 |
58 | 59 |
60 | Connect 61 |
62 | 63 |
64 | Disconnect 66 |
67 | 68 |
69 | 70 | 71 |
72 | 73 |
74 | 75 | 76 |
77 | 78 |
79 | 80 | 81 |
82 | 83 |
84 | 85 | 86 |
87 | 88 |
89 | 90 | 91 |
92 | 93 |
94 | 95 | 96 |
97 | 98 |
99 | 100 | 105 |
106 | 107 |
108 | 109 | 110 |
111 | 112 |
113 | 114 | 115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |

Publish

126 |
127 | 128 |
129 | 130 |
131 |
132 |
133 | 134 |
135 | 136 | 137 |
138 |
139 |
140 |
141 |
142 | 143 | 144 |
145 |
146 | 147 | 152 |
153 |
154 | 155 | 156 |
157 |
158 | Publish 159 |
160 |
161 |
162 |
163 | 164 | 165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |

Messages

174 |
175 | 176 |
177 | 178 |
179 |
180 |
181 | 182 |
183 | 184 | 185 |
186 |
187 |
188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 |
201 |
202 |
    203 | 204 |
205 |
206 |
207 |
208 | 209 |
210 |
211 | 212 |
213 | 214 |
215 |

Subscriptions

216 |
217 | 218 |
219 | 220 |
221 |
222 |
223 |
224 |
225 |
226 | 227 | Add New Topic Subscription 228 | 229 |
230 |
231 |
232 |
233 |
234 | 235 | 236 |
237 |
238 | 239 | 244 |
245 |
246 | Subscribe 248 |
249 |
250 |
251 |
252 | 253 | 254 |
255 |
256 |
257 |
258 |
259 | 260 |
    261 | 262 |
263 |
264 |
265 |
266 |
267 |
268 |
269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 313 | 314 | 315 | -------------------------------------------------------------------------------- /js/app.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013 dc-square GmbH 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | * @author: Christoph Schäbel 17 | */ 18 | 19 | var websocketclient = { 20 | 'client': null, 21 | 'lastMessageId': 1, 22 | 'lastSubId': 1, 23 | 'subscriptions': [], 24 | 'messages': [], 25 | 'connected': false, 26 | 27 | 'prefill': function () { 28 | let parameters = new URLSearchParams(window.location.search) 29 | if (parameters.get('username') != null) {$('#userInput').val(parameters.get('username'))} ; 30 | if (parameters.get('host') != null) {$('#urlInput').val(parameters.get('host'))}; 31 | if (parameters.get('port') != null) {$('#portInput').val(parameters.get('port'))}; 32 | if (parameters.get('host') != null) {$('#sslInput').click()}; 33 | }, 34 | 35 | 'connect': function () { 36 | var host = $('#urlInput').val(); 37 | var port = parseInt($('#portInput').val(), 10); 38 | var clientId = $('#clientIdInput').val(); 39 | var username = $('#userInput').val(); 40 | var password = $('#pwInput').val(); 41 | var keepAlive = parseInt($('#keepAliveInput').val()); 42 | var cleanSession = $('#cleanSessionInput').is(':checked'); 43 | var lwTopic = $('#lwTopicInput').val(); 44 | var lwQos = parseInt($('#lwQosInput').val()); 45 | var lwRetain = $('#LWRInput').is(':checked'); 46 | var lwMessage = $('#LWMInput').val(); 47 | var ssl = $('#sslInput').is(':checked'); 48 | 49 | this.client = new Messaging.Client(host, port, clientId); 50 | this.client.onConnectionLost = this.onConnectionLost; 51 | this.client.onMessageArrived = this.onMessageArrived; 52 | 53 | var options = { 54 | timeout: 3, 55 | keepAliveInterval: keepAlive, 56 | cleanSession: cleanSession, 57 | useSSL: ssl, 58 | onSuccess: this.onConnect, 59 | onFailure: this.onFail 60 | }; 61 | 62 | if (username.length > 0) { 63 | options.userName = username; 64 | } 65 | if (password.length > 0) { 66 | options.password = password; 67 | } 68 | if (lwTopic.length > 0) { 69 | var willmsg = new Messaging.Message(lwMessage); 70 | willmsg.qos = lwQos; 71 | willmsg.destinationName = lwTopic; 72 | willmsg.retained = lwRetain; 73 | options.willMessage = willmsg; 74 | } 75 | 76 | this.client.connect(options); 77 | }, 78 | 79 | 'onConnect': function () { 80 | websocketclient.connected = true; 81 | console.log("connected"); 82 | var body = $('body').addClass('connected').removeClass('notconnected').removeClass('connectionbroke'); 83 | 84 | websocketclient.render.hide('conni'); 85 | websocketclient.render.show('publish'); 86 | websocketclient.render.show('sub'); 87 | websocketclient.render.show('messages'); 88 | }, 89 | 90 | 'onFail': function (message) { 91 | websocketclient.connected = false; 92 | console.log("error: " + message.errorMessage); 93 | websocketclient.render.showError('Connect failed: ' + message.errorMessage); 94 | }, 95 | 96 | 'onConnectionLost': function (responseObject) { 97 | websocketclient.connected = false; 98 | if (responseObject.errorCode !== 0) { 99 | console.log("onConnectionLost:" + responseObject.errorMessage); 100 | } 101 | $('body.connected').removeClass('connected').addClass('notconnected').addClass('connectionbroke'); 102 | websocketclient.render.show('conni'); 103 | websocketclient.render.hide('publish'); 104 | websocketclient.render.hide('sub'); 105 | websocketclient.render.hide('messages'); 106 | 107 | //Cleanup messages 108 | websocketclient.messages = []; 109 | websocketclient.render.clearMessages(); 110 | 111 | //Cleanup subscriptions 112 | websocketclient.subscriptions = []; 113 | websocketclient.render.clearSubscriptions(); 114 | }, 115 | 116 | 'onMessageArrived': function (message) { 117 | // console.log("onMessageArrived:" + message.payloadString + " qos: " + message.qos); 118 | 119 | var subscription = websocketclient.getSubscriptionForTopic(message.destinationName); 120 | 121 | var messageObj = { 122 | 'topic': message.destinationName, 123 | 'retained': message.retained, 124 | 'qos': message.qos, 125 | 'payload': message.payloadString, 126 | 'timestamp': moment(), 127 | 'subscriptionId': subscription.id, 128 | 'color': websocketclient.getColorForSubscription(subscription.id) 129 | }; 130 | 131 | console.log(messageObj); 132 | messageObj.id = websocketclient.render.message(messageObj); 133 | websocketclient.messages.push(messageObj); 134 | }, 135 | 136 | 'disconnect': function () { 137 | this.client.disconnect(); 138 | }, 139 | 140 | 'publish': function (topic, payload, qos, retain) { 141 | 142 | if (!websocketclient.connected) { 143 | websocketclient.render.showError("Not connected"); 144 | return false; 145 | } 146 | 147 | var message = new Messaging.Message(payload); 148 | message.destinationName = topic; 149 | message.qos = qos; 150 | message.retained = retain; 151 | this.client.send(message); 152 | }, 153 | 154 | 'subscribe': function (topic, qosNr, color) { 155 | 156 | if (!websocketclient.connected) { 157 | websocketclient.render.showError("Not connected"); 158 | return false; 159 | } 160 | 161 | if (topic.length < 1) { 162 | websocketclient.render.showError("Topic cannot be empty"); 163 | return false; 164 | } 165 | 166 | if (_.find(this.subscriptions, { 'topic': topic })) { 167 | websocketclient.render.showError('You are already subscribed to this topic'); 168 | return false; 169 | } 170 | 171 | this.client.subscribe(topic, {qos: qosNr}); 172 | if (color.length < 1) { 173 | color = '999999'; 174 | } 175 | 176 | var subscription = {'topic': topic, 'qos': qosNr, 'color': color}; 177 | subscription.id = websocketclient.render.subscription(subscription); 178 | this.subscriptions.push(subscription); 179 | return true; 180 | }, 181 | 182 | 'unsubscribe': function (id) { 183 | var subs = _.find(websocketclient.subscriptions, {'id': id}); 184 | this.client.unsubscribe(subs.topic); 185 | websocketclient.subscriptions = _.filter(websocketclient.subscriptions, function (item) { 186 | return item.id != id; 187 | }); 188 | 189 | websocketclient.render.removeSubscriptionsMessages(id); 190 | }, 191 | 192 | 'deleteSubscription': function (id) { 193 | var elem = $("#sub" + id); 194 | 195 | if (confirm('Are you sure ?')) { 196 | elem.remove(); 197 | this.unsubscribe(id); 198 | } 199 | }, 200 | 201 | 'getRandomColor': function () { 202 | var r = (Math.round(Math.random() * 255)).toString(16); 203 | var g = (Math.round(Math.random() * 255)).toString(16); 204 | var b = (Math.round(Math.random() * 255)).toString(16); 205 | return r + g + b; 206 | }, 207 | 208 | 'getSubscriptionForTopic': function (topic) { 209 | var i; 210 | for (i = 0; i < this.subscriptions.length; i++) { 211 | if (this.compareTopics(topic, this.subscriptions[i].topic)) { 212 | return this.subscriptions[i]; 213 | } 214 | } 215 | return false; 216 | }, 217 | 218 | 'getColorForPublishTopic': function (topic) { 219 | var id = this.getSubscriptionForTopic(topic); 220 | return this.getColorForSubscription(id); 221 | }, 222 | 223 | 'getColorForSubscription': function (id) { 224 | try { 225 | if (!id) { 226 | return '99999'; 227 | } 228 | 229 | var sub = _.find(this.subscriptions, { 'id': id }); 230 | if (!sub) { 231 | return '999999'; 232 | } else { 233 | return sub.color; 234 | } 235 | } catch (e) { 236 | return '999999'; 237 | } 238 | }, 239 | 240 | 'compareTopics': function (topic, subTopic) { 241 | var pattern = subTopic.replace("+", "(.*?)").replace("#", "(.*)"); 242 | var regex = new RegExp("^" + pattern + "$"); 243 | return regex.test(topic); 244 | }, 245 | 246 | 'render': { 247 | 248 | 'showError': function (message) { 249 | alert(message); 250 | }, 251 | 'messages': function () { 252 | 253 | websocketclient.render.clearMessages(); 254 | _.forEach(websocketclient.messages, function (message) { 255 | message.id = websocketclient.render.message(message); 256 | }); 257 | 258 | }, 259 | 'message': function (message) { 260 | 261 | var largest = websocketclient.lastMessageId++; 262 | 263 | var html = '
  • ' + 264 | '
    ' + 265 | '
    ' + 266 | '
    ' + message.timestamp.format("YYYY-MM-DD HH:mm:ss") + '
    ' + 267 | '
    Topic: ' + Encoder.htmlEncode(message.topic) + '
    ' + 268 | '
    Qos: ' + message.qos + '
    ' + 269 | '
    '; 270 | if (message.retained) { 271 | html += 'Retained'; 272 | } 273 | html += '
    ' + 274 | '
    ' + Encoder.htmlEncode(message.payload) + '
    ' + 275 | '
    ' + 276 | '
    ' + 277 | '
  • '; 278 | $("#messEdit").prepend(html); 279 | return largest; 280 | }, 281 | 282 | 'subscriptions': function () { 283 | websocketclient.render.clearSubscriptions(); 284 | _.forEach(websocketclient.subscriptions, function (subs) { 285 | subs.id = websocketclient.render.subscription(subs); 286 | }); 287 | }, 288 | 289 | 'subscription': function (subscription) { 290 | var largest = websocketclient.lastSubId++; 291 | $("#innerEdit").append( 292 | '
  • ' + 293 | '
    ' + 294 | '
    ' + 295 | '
    ' + 296 | ' x' + 297 | '
    ' + 298 | '
    Qos: ' + subscription.qos + '
    ' + 299 | '
    ' + Encoder.htmlEncode(subscription.topic) + '
    ' + 300 | '
    ' + 301 | '
    ' + 302 | '
  • '); 303 | return largest; 304 | }, 305 | 306 | 'toggleAll': function () { 307 | websocketclient.render.toggle('conni'); 308 | websocketclient.render.toggle('publish'); 309 | websocketclient.render.toggle('messages'); 310 | websocketclient.render.toggle('sub'); 311 | }, 312 | 313 | 'toggle': function (name) { 314 | $('.' + name + 'Arrow').toggleClass("closed"); 315 | $('.' + name + 'Top').toggleClass("closed"); 316 | var elem = $('#' + name + 'Main'); 317 | elem.slideToggle(); 318 | }, 319 | 320 | 'hide': function (name) { 321 | $('.' + name + 'Arrow').addClass("closed"); 322 | $('.' + name + 'Top').addClass("closed"); 323 | var elem = $('#' + name + 'Main'); 324 | elem.slideUp(); 325 | }, 326 | 327 | 'show': function (name) { 328 | $('.' + name + 'Arrow').removeClass("closed"); 329 | $('.' + name + 'Top').removeClass("closed"); 330 | var elem = $('#' + name + 'Main'); 331 | elem.slideDown(); 332 | }, 333 | 334 | 'removeSubscriptionsMessages': function (id) { 335 | websocketclient.messages = _.filter(websocketclient.messages, function (item) { 336 | return item.subscriptionId != id; 337 | }); 338 | websocketclient.render.messages(); 339 | }, 340 | 341 | 'clearMessages': function () { 342 | $("#messEdit").empty(); 343 | }, 344 | 345 | 'clearSubscriptions': function () { 346 | $("#innerEdit").empty(); 347 | } 348 | } 349 | }; 350 | 351 | websocketclient.prefill() -------------------------------------------------------------------------------- /js/arrow.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/js/arrow.gif -------------------------------------------------------------------------------- /js/cross.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/js/cross.gif -------------------------------------------------------------------------------- /js/custom-combobox.js: -------------------------------------------------------------------------------- 1 | var availableTags = [ 2 | "broker.mqtt-dashboard.com", 3 | "localhost" 4 | ]; 5 | 6 | var $input = $('#urlInput'); 7 | 8 | $input.autocomplete({ 9 | source: availableTags, 10 | minLength: 0 11 | }); 12 | 13 | $input.addClass("ui-widget ui-widget-content ui-corner-left"); 14 | 15 | $("") 16 | .attr("tabIndex", -1) 17 | .attr("title", "Show All Items") 18 | .insertAfter($input) 19 | .button({ 20 | icons: { 21 | primary: "ui-icon-triangle-1-s" 22 | }, 23 | text: false 24 | }) 25 | .removeClass("ui-corner-all") 26 | .addClass("ui-corner-right ui-button-icon") 27 | .click(function () { 28 | // close if already visible 29 | if ($input.autocomplete("widget").is(":visible")) { 30 | $input.autocomplete("close"); 31 | return; 32 | } 33 | $(this).blur(); 34 | $input.autocomplete("search", ""); 35 | $input.focus(); 36 | }); 37 | 38 | $("form").submit(function (e) { 39 | e.preventDefault(); 40 | alert($(this).serialize()); 41 | }); -------------------------------------------------------------------------------- /js/encoder.js: -------------------------------------------------------------------------------- 1 | /** 2 | * A Javascript object to encode and/or decode html characters using HTML or Numeric entities that handles double or partial encoding 3 | * Author: R Reid 4 | * source: http://www.strictly-software.com/htmlencode 5 | * Licences: GPL, The MIT License (MIT) 6 | * Copyright: (c) 2011 Robert Reid - Strictly-Software.com 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 9 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | * Revision: 13 | * 2011-07-14, Jacques-Yves Bleau: 14 | * - fixed conversion error with capitalized accentuated characters 15 | * + converted arr1 and arr2 to object property to remove redundancy 16 | * 17 | * Revision: 18 | * 2011-11-10, Ce-Yi Hio: 19 | * - fixed conversion error with a number of capitalized entity characters 20 | * 21 | * Revision: 22 | * 2011-11-10, Rob Reid: 23 | * - changed array format 24 | * 25 | * Revision: 26 | * 2012-09-23, Alex Oss: 27 | * - replaced string concatonation in numEncode with string builder, push and join for peformance with ammendments by Rob Reid 28 | */ 29 | 30 | Encoder = { 31 | 32 | // When encoding do we convert characters into html or numerical entities 33 | EncodeType: "entity", // entity OR numerical 34 | 35 | isEmpty: function (val) { 36 | if (val) { 37 | return ((val === null) || val.length == 0 || /^\s+$/.test(val)); 38 | } else { 39 | return true; 40 | } 41 | }, 42 | 43 | // arrays for conversion from HTML Entities to Numerical values 44 | arr1: [' ', '¡', '¢', '£', '¤', '¥', '¦', '§', '¨', '©', 'ª', '«', '¬', '­', '®', '¯', '°', '±', '²', '³', '´', 'µ', '¶', '·', '¸', '¹', 'º', '»', '¼', '½', '¾', '¿', 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', '×', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'Þ', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ð', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', '÷', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'þ', 'ÿ', '"', '&', '<', '>', 'Œ', 'œ', 'Š', 'š', 'Ÿ', 'ˆ', '˜', ' ', ' ', ' ', '‌', '‍', '‎', '‏', '–', '—', '‘', '’', '‚', '“', '”', '„', '†', '‡', '‰', '‹', '›', '€', 'ƒ', 'Α', 'Β', 'Γ', 'Δ', 'Ε', 'Ζ', 'Η', 'Θ', 'Ι', 'Κ', 'Λ', 'Μ', 'Ν', 'Ξ', 'Ο', 'Π', 'Ρ', 'Σ', 'Τ', 'Υ', 'Φ', 'Χ', 'Ψ', 'Ω', 'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'ι', 'κ', 'λ', 'μ', 'ν', 'ξ', 'ο', 'π', 'ρ', 'ς', 'σ', 'τ', 'υ', 'φ', 'χ', 'ψ', 'ω', 'ϑ', 'ϒ', 'ϖ', '•', '…', '′', '″', '‾', '⁄', '℘', 'ℑ', 'ℜ', '™', 'ℵ', '←', '↑', '→', '↓', '↔', '↵', '⇐', '⇑', '⇒', '⇓', '⇔', '∀', '∂', '∃', '∅', '∇', '∈', '∉', '∋', '∏', '∑', '−', '∗', '√', '∝', '∞', '∠', '∧', '∨', '∩', '∪', '∫', '∴', '∼', '≅', '≈', '≠', '≡', '≤', '≥', '⊂', '⊃', '⊄', '⊆', '⊇', '⊕', '⊗', '⊥', '⋅', '⌈', '⌉', '⌊', '⌋', '⟨', '⟩', '◊', '♠', '♣', '♥', '♦'], 45 | arr2: [' ', '¡', '¢', '£', '¤', '¥', '¦', '§', '¨', '©', 'ª', '«', '¬', '­', '®', '¯', '°', '±', '²', '³', '´', 'µ', '¶', '·', '¸', '¹', 'º', '»', '¼', '½', '¾', '¿', 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', '×', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'Þ', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ð', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', '÷', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'þ', 'ÿ', '"', '&', '<', '>', 'Œ', 'œ', 'Š', 'š', 'Ÿ', 'ˆ', '˜', ' ', ' ', ' ', '‌', '‍', '‎', '‏', '–', '—', '‘', '’', '‚', '“', '”', '„', '†', '‡', '‰', '‹', '›', '€', 'ƒ', 'Α', 'Β', 'Γ', 'Δ', 'Ε', 'Ζ', 'Η', 'Θ', 'Ι', 'Κ', 'Λ', 'Μ', 'Ν', 'Ξ', 'Ο', 'Π', 'Ρ', 'Σ', 'Τ', 'Υ', 'Φ', 'Χ', 'Ψ', 'Ω', 'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'ι', 'κ', 'λ', 'μ', 'ν', 'ξ', 'ο', 'π', 'ρ', 'ς', 'σ', 'τ', 'υ', 'φ', 'χ', 'ψ', 'ω', 'ϑ', 'ϒ', 'ϖ', '•', '…', '′', '″', '‾', '⁄', '℘', 'ℑ', 'ℜ', '™', 'ℵ', '←', '↑', '→', '↓', '↔', '↵', '⇐', '⇑', '⇒', '⇓', '⇔', '∀', '∂', '∃', '∅', '∇', '∈', '∉', '∋', '∏', '∑', '−', '∗', '√', '∝', '∞', '∠', '∧', '∨', '∩', '∪', '∫', '∴', '∼', '≅', '≈', '≠', '≡', '≤', '≥', '⊂', '⊃', '⊄', '⊆', '⊇', '⊕', '⊗', '⊥', '⋅', '⌈', '⌉', '⌊', '⌋', '〈', '〉', '◊', '♠', '♣', '♥', '♦'], 46 | 47 | // Convert HTML entities into numerical entities 48 | HTML2Numerical: function (s) { 49 | return this.swapArrayVals(s, this.arr1, this.arr2); 50 | }, 51 | 52 | // Convert Numerical entities into HTML entities 53 | NumericalToHTML: function (s) { 54 | return this.swapArrayVals(s, this.arr2, this.arr1); 55 | }, 56 | 57 | 58 | // Numerically encodes all unicode characters 59 | numEncode: function (s) { 60 | if (this.isEmpty(s)) return ""; 61 | 62 | var a = [], 63 | l = s.length; 64 | 65 | for (var i = 0; i < l; i++) { 66 | var c = s.charAt(i); 67 | if (c < " " || c > "~") { 68 | a.push("&#"); 69 | a.push(c.charCodeAt()); //numeric value of code point 70 | a.push(";"); 71 | } else { 72 | a.push(c); 73 | } 74 | } 75 | 76 | return a.join(""); 77 | }, 78 | 79 | // HTML Decode numerical and HTML entities back to original values 80 | htmlDecode: function (s) { 81 | 82 | var c, m, d = s; 83 | 84 | if (this.isEmpty(d)) return ""; 85 | 86 | // convert HTML entites back to numerical entites first 87 | d = this.HTML2Numerical(d); 88 | 89 | // look for numerical entities " 90 | arr = d.match(/&#[0-9]{1,5};/g); 91 | 92 | // if no matches found in string then skip 93 | if (arr != null) { 94 | for (var x = 0; x < arr.length; x++) { 95 | m = arr[x]; 96 | c = m.substring(2, m.length - 1); //get numeric part which is refernce to unicode character 97 | // if its a valid number we can decode 98 | if (c >= -32768 && c <= 65535) { 99 | // decode every single match within string 100 | d = d.replace(m, String.fromCharCode(c)); 101 | } else { 102 | d = d.replace(m, ""); //invalid so replace with nada 103 | } 104 | } 105 | } 106 | 107 | return d; 108 | }, 109 | 110 | // encode an input string into either numerical or HTML entities 111 | htmlEncode: function (s, dbl) { 112 | 113 | if (this.isEmpty(s)) return ""; 114 | 115 | // do we allow double encoding? E.g will & be turned into &amp; 116 | dbl = dbl || false; //default to prevent double encoding 117 | 118 | // if allowing double encoding we do ampersands first 119 | if (dbl) { 120 | if (this.EncodeType == "numerical") { 121 | s = s.replace(/&/g, "&"); 122 | } else { 123 | s = s.replace(/&/g, "&"); 124 | } 125 | } 126 | 127 | // convert the xss chars to numerical entities ' " < > 128 | s = this.XSSEncode(s, false); 129 | 130 | if (this.EncodeType == "numerical" || !dbl) { 131 | // Now call function that will convert any HTML entities to numerical codes 132 | s = this.HTML2Numerical(s); 133 | } 134 | 135 | // Now encode all chars above 127 e.g unicode 136 | s = this.numEncode(s); 137 | 138 | // now we know anything that needs to be encoded has been converted to numerical entities we 139 | // can encode any ampersands & that are not part of encoded entities 140 | // to handle the fact that I need to do a negative check and handle multiple ampersands &&& 141 | // I am going to use a placeholder 142 | 143 | // if we don't want double encoded entities we ignore the & in existing entities 144 | if (!dbl) { 145 | s = s.replace(/&#/g, "##AMPHASH##"); 146 | 147 | if (this.EncodeType == "numerical") { 148 | s = s.replace(/&/g, "&"); 149 | } else { 150 | s = s.replace(/&/g, "&"); 151 | } 152 | 153 | s = s.replace(/##AMPHASH##/g, "&#"); 154 | } 155 | 156 | // replace any malformed entities 157 | s = s.replace(/&#\d*([^\d;]|$)/g, "$1"); 158 | 159 | if (!dbl) { 160 | // safety check to correct any double encoded & 161 | s = this.correctEncoding(s); 162 | } 163 | 164 | // now do we need to convert our numerical encoded string into entities 165 | if (this.EncodeType == "entity") { 166 | s = this.NumericalToHTML(s); 167 | } 168 | 169 | return s; 170 | }, 171 | 172 | // Encodes the basic 4 characters used to malform HTML in XSS hacks 173 | XSSEncode: function (s, en) { 174 | if (!this.isEmpty(s)) { 175 | en = en || true; 176 | // do we convert to numerical or html entity? 177 | if (en) { 178 | s = s.replace(/\'/g, "'"); //no HTML equivalent as &apos is not cross browser supported 179 | s = s.replace(/\"/g, """); 180 | s = s.replace(//g, ">"); 182 | } else { 183 | s = s.replace(/\'/g, "'"); //no HTML equivalent as &apos is not cross browser supported 184 | s = s.replace(/\"/g, """); 185 | s = s.replace(//g, ">"); 187 | } 188 | return s; 189 | } else { 190 | return ""; 191 | } 192 | }, 193 | 194 | // returns true if a string contains html or numerical encoded entities 195 | hasEncoded: function (s) { 196 | if (/&#[0-9]{1,5};/g.test(s)) { 197 | return true; 198 | } else if (/&[A-Z]{2,6};/gi.test(s)) { 199 | return true; 200 | } else { 201 | return false; 202 | } 203 | }, 204 | 205 | // will remove any unicode characters 206 | stripUnicode: function (s) { 207 | return s.replace(/[^\x20-\x7E]/g, ""); 208 | 209 | }, 210 | 211 | // corrects any double encoded & entities e.g &amp; 212 | correctEncoding: function (s) { 213 | return s.replace(/(&)(amp;)+/, "$1"); 214 | }, 215 | 216 | 217 | // Function to loop through an array swaping each item with the value from another array e.g swap HTML entities with Numericals 218 | swapArrayVals: function (s, arr1, arr2) { 219 | if (this.isEmpty(s)) return ""; 220 | var re; 221 | if (arr1 && arr2) { 222 | //ShowDebug("in swapArrayVals arr1.length = " + arr1.length + " arr2.length = " + arr2.length) 223 | // array lengths must match 224 | if (arr1.length == arr2.length) { 225 | for (var x = 0, i = arr1.length; x < i; x++) { 226 | re = new RegExp(arr1[x], 'g'); 227 | s = s.replace(re, arr2[x]); //swap arr1 item with matching item from arr2 228 | } 229 | } 230 | } 231 | return s; 232 | }, 233 | 234 | inArray: function (item, arr) { 235 | for (var i = 0, x = arr.length; i < x; i++) { 236 | if (arr[i] === item) { 237 | return i; 238 | } 239 | } 240 | return -1; 241 | } 242 | 243 | } -------------------------------------------------------------------------------- /js/hs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/js/hs.png -------------------------------------------------------------------------------- /js/hv.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/33b947b5694e93cf65f53a601ec1e2389f1eb287/js/hv.png -------------------------------------------------------------------------------- /js/jquery.minicolors.min.js: -------------------------------------------------------------------------------- 1 | /* 2 | * jQuery MiniColors: A tiny color picker built on jQuery 3 | * 4 | * Copyright Cory LaViska for A Beautiful Site, LLC. (http://www.abeautifulsite.net/) 5 | * 6 | * Licensed under the MIT license: http://opensource.org/licenses/MIT 7 | * 8 | */jQuery&&function(e){function t(t,n){var r=e('
    '),i=e.minicolors.defaults;if(t.data("minicolors-initialized"))return;n=e.extend(!0,{},i,n);r.addClass("minicolors-theme-"+n.theme).toggleClass("minicolors-with-opacity",n.opacity);n.position!==undefined&&e.each(n.position.split(" "),function(){r.addClass("minicolors-position-"+this)});t.addClass("minicolors-input").data("minicolors-initialized",!0).data("minicolors-settings",n).prop("size",7).wrap(r).after('
    '+'
    '+'
    '+"
    "+'
    '+'
    '+"
    "+'
    '+'
    '+'
    '+"
    "+"
    ");if(!n.inline){t.after('');t.next(".minicolors-swatch").on("click",function(e){e.preventDefault();t.focus()})}t.parent().find(".minicolors-panel").on("selectstart",function(){return!1}).end();n.inline&&t.parent().addClass("minicolors-inline");u(t,!1);t.data("minicolors-lastChange",{hex:t.val(),opacity:t.attr("data-opacity")})}function n(e){var t=e.parent();e.removeData("minicolors-initialized").removeData("minicolors-settings").removeProp("size").removeClass("minicolors-input");t.before(e).remove()}function r(e){var t=e.parent(),n=t.find(".minicolors-panel"),r=e.data("minicolors-settings");if(!e.data("minicolors-initialized")||e.prop("disabled")||t.hasClass("minicolors-inline")||t.hasClass("minicolors-focus"))return;i();t.addClass("minicolors-focus");n.stop(!0,!0).fadeIn(r.showSpeed,function(){r.show&&r.show.call(e.get(0))})}function i(){e(".minicolors-input").each(function(){var t=e(this),n=t.data("minicolors-settings"),r=t.parent();if(n.inline)return;r.find(".minicolors-panel").fadeOut(n.hideSpeed,function(){r.hasClass("minicolors-focus")&&n.hide&&n.hide.call(t.get(0));r.removeClass("minicolors-focus")})})}function s(e,t,n){var r=e.parents(".minicolors").find(".minicolors-input"),i=r.data("minicolors-settings"),s=e.find("[class$=-picker]"),u=e.offset().left,a=e.offset().top,f=Math.round(t.pageX-u),l=Math.round(t.pageY-a),c=n?i.animationSpeed:0,h,p,d,v;if(t.originalEvent.changedTouches){f=t.originalEvent.changedTouches[0].pageX-u;l=t.originalEvent.changedTouches[0].pageY-a}f<0&&(f=0);l<0&&(l=0);f>e.width()&&(f=e.width());l>e.height()&&(l=e.height());if(e.parent().is(".minicolors-slider-wheel")&&s.parent().is(".minicolors-grid")){h=75-f;p=75-l;d=Math.sqrt(h*h+p*p);v=Math.atan2(p,h);v<0&&(v+=Math.PI*2);if(d>75){d=75;f=75-75*Math.cos(v);l=75-75*Math.sin(v)}f=Math.round(f);l=Math.round(l)}e.is(".minicolors-grid")?s.stop(!0).animate({top:l+"px",left:f+"px"},c,i.animationEasing,function(){o(r,e)}):s.stop(!0).animate({top:l+"px"},c,i.animationEasing,function(){o(r,e)})}function o(e,t){function n(e,t){var n,r;if(!e.length||!t)return null;n=e.offset().left;r=e.offset().top;return{x:n-t.offset().left+e.outerWidth()/2,y:r-t.offset().top+e.outerHeight()/2}}var r,i,s,o,u,f,l,h=e.val(),d=e.attr("data-opacity"),v=e.parent(),g=e.data("minicolors-settings"),y=v.find(".minicolors-swatch"),b=v.find(".minicolors-grid"),w=v.find(".minicolors-slider"),E=v.find(".minicolors-opacity-slider"),S=b.find("[class$=-picker]"),x=w.find("[class$=-picker]"),T=E.find("[class$=-picker]"),N=n(S,b),C=n(x,w),k=n(T,E);if(t.is(".minicolors-grid, .minicolors-slider")){switch(g.control){case"wheel":o=b.width()/2-N.x;u=b.height()/2-N.y;f=Math.sqrt(o*o+u*u);l=Math.atan2(u,o);l<0&&(l+=Math.PI*2);if(f>75){f=75;N.x=69-75*Math.cos(l);N.y=69-75*Math.sin(l)}i=p(f/.75,0,100);r=p(l*180/Math.PI,0,360);s=p(100-Math.floor(C.y*(100/w.height())),0,100);h=m({h:r,s:i,b:s});w.css("backgroundColor",m({h:r,s:i,b:100}));break;case"saturation":r=p(parseInt(N.x*(360/b.width()),10),0,360);i=p(100-Math.floor(C.y*(100/w.height())),0,100);s=p(100-Math.floor(N.y*(100/b.height())),0,100);h=m({h:r,s:i,b:s});w.css("backgroundColor",m({h:r,s:100,b:s}));v.find(".minicolors-grid-inner").css("opacity",i/100);break;case"brightness":r=p(parseInt(N.x*(360/b.width()),10),0,360);i=p(100-Math.floor(N.y*(100/b.height())),0,100);s=p(100-Math.floor(C.y*(100/w.height())),0,100);h=m({h:r,s:i,b:s});w.css("backgroundColor",m({h:r,s:i,b:100}));v.find(".minicolors-grid-inner").css("opacity",1-s/100);break;default:r=p(360-parseInt(C.y*(360/w.height()),10),0,360);i=p(Math.floor(N.x*(100/b.width())),0,100);s=p(100-Math.floor(N.y*(100/b.height())),0,100);h=m({h:r,s:i,b:s});b.css("backgroundColor",m({h:r,s:100,b:100}))}e.val(c(h,g.letterCase))}if(t.is(".minicolors-opacity-slider")){g.opacity?d=parseFloat(1-k.y/E.height()).toFixed(2):d=1;g.opacity&&e.attr("data-opacity",d)}y.find("SPAN").css({backgroundColor:h,opacity:d});a(e,h,d)}function u(e,t){var n,r,i,s,o,u,a,f=e.parent(),l=e.data("minicolors-settings"),d=f.find(".minicolors-swatch"),v=f.find(".minicolors-grid"),y=f.find(".minicolors-slider"),b=f.find(".minicolors-opacity-slider"),w=v.find("[class$=-picker]"),E=y.find("[class$=-picker]"),S=b.find("[class$=-picker]");n=c(h(e.val(),!0),l.letterCase);n||(n=c(h(l.defaultValue,!0),l.letterCase));r=g(n);t||e.val(n);if(l.opacity){i=e.attr("data-opacity")===""?1:p(parseFloat(e.attr("data-opacity")).toFixed(2),0,1);isNaN(i)&&(i=1);e.attr("data-opacity",i);d.find("SPAN").css("opacity",i);o=p(b.height()-b.height()*i,0,b.height());S.css("top",o+"px")}d.find("SPAN").css("backgroundColor",n);switch(l.control){case"wheel":u=p(Math.ceil(r.s*.75),0,v.height()/2);a=r.h*Math.PI/180;s=p(75-Math.cos(a)*u,0,v.width());o=p(75-Math.sin(a)*u,0,v.height());w.css({top:o+"px",left:s+"px"});o=150-r.b/(100/v.height());n===""&&(o=0);E.css("top",o+"px");y.css("backgroundColor",m({h:r.h,s:r.s,b:100}));break;case"saturation":s=p(5*r.h/12,0,150);o=p(v.height()-Math.ceil(r.b/(100/v.height())),0,v.height());w.css({top:o+"px",left:s+"px"});o=p(y.height()-r.s*(y.height()/100),0,y.height());E.css("top",o+"px");y.css("backgroundColor",m({h:r.h,s:100,b:r.b}));f.find(".minicolors-grid-inner").css("opacity",r.s/100);break;case"brightness":s=p(5*r.h/12,0,150);o=p(v.height()-Math.ceil(r.s/(100/v.height())),0,v.height());w.css({top:o+"px",left:s+"px"});o=p(y.height()-r.b*(y.height()/100),0,y.height());E.css("top",o+"px");y.css("backgroundColor",m({h:r.h,s:r.s,b:100}));f.find(".minicolors-grid-inner").css("opacity",1-r.b/100);break;default:s=p(Math.ceil(r.s/(100/v.width())),0,v.width());o=p(v.height()-Math.ceil(r.b/(100/v.height())),0,v.height());w.css({top:o+"px",left:s+"px"});o=p(y.height()-r.h/(360/y.height()),0,y.height());E.css("top",o+"px");v.css("backgroundColor",m({h:r.h,s:100,b:100}))}}function a(e,t,n){var r=e.data("minicolors-settings"),i=e.data("minicolors-lastChange");if(i.hex!==t||i.opacity!==n){e.data("minicolors-lastChange",{hex:t,opacity:n});if(r.change)if(r.changeDelay){clearTimeout(e.data("minicolors-changeTimeout"));e.data("minicolors-changeTimeout",setTimeout(function(){r.change.call(e.get(0),t,n)},r.changeDelay))}else r.change.call(e.get(0),t,n);e.trigger("change").trigger("input")}}function f(t){var n=h(e(t).val(),!0),r=b(n),i=e(t).attr("data-opacity");if(!r)return null;i!==undefined&&e.extend(r,{a:parseFloat(i)});return r}function l(t,n){var r=h(e(t).val(),!0),i=b(r),s=e(t).attr("data-opacity");if(!i)return null;s===undefined&&(s=1);return n?"rgba("+i.r+", "+i.g+", "+i.b+", "+parseFloat(s)+")":"rgb("+i.r+", "+i.g+", "+i.b+")"}function c(e,t){return t==="uppercase"?e.toUpperCase():e.toLowerCase()}function h(e,t){e=e.replace(/[^A-F0-9]/ig,"");if(e.length!==3&&e.length!==6)return"";e.length===3&&t&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]);return"#"+e}function p(e,t,n){en&&(e=n);return e}function d(e){var t={},n=Math.round(e.h),r=Math.round(e.s*255/100),i=Math.round(e.b*255/100);if(r===0)t.r=t.g=t.b=i;else{var s=i,o=(255-r)*i/255,u=(s-o)*(n%60)/60;n===360&&(n=0);if(n<60){t.r=s;t.b=o;t.g=o+u}else if(n<120){t.g=s;t.b=o;t.r=s-u}else if(n<180){t.g=s;t.r=o;t.b=o+u}else if(n<240){t.b=s;t.r=o;t.g=s-u}else if(n<300){t.b=s;t.g=o;t.r=o+u}else if(n<360){t.r=s;t.g=o;t.b=s-u}else{t.r=0;t.g=0;t.b=0}}return{r:Math.round(t.r),g:Math.round(t.g),b:Math.round(t.b)}}function v(t){var n=[t.r.toString(16),t.g.toString(16),t.b.toString(16)];e.each(n,function(e,t){t.length===1&&(n[e]="0"+t)});return"#"+n.join("")}function m(e){return v(d(e))}function g(e){var t=y(b(e));t.s===0&&(t.h=360);return t}function y(e){var t={h:0,s:0,b:0},n=Math.min(e.r,e.g,e.b),r=Math.max(e.r,e.g,e.b),i=r-n;t.b=r;t.s=r!==0?255*i/r:0;t.s!==0?e.r===r?t.h=(e.g-e.b)/i:e.g===r?t.h=2+(e.b-e.r)/i:t.h=4+(e.r-e.g)/i:t.h=-1;t.h*=60;t.h<0&&(t.h+=360);t.s*=100/255;t.b*=100/255;return t}function b(e){e=parseInt(e.indexOf("#")>-1?e.substring(1):e,16);return{r:e>>16,g:(e&65280)>>8,b:e&255}}e.minicolors={defaults:{animationSpeed:50,animationEasing:"swing",change:null,changeDelay:0,control:"hue",defaultValue:"",hide:null,hideSpeed:100,inline:!1,letterCase:"lowercase",opacity:!1,position:"bottom left",show:null,showSpeed:100,theme:"default"}};e.extend(e.fn,{minicolors:function(s,o){switch(s){case"destroy":e(this).each(function(){n(e(this))});return e(this);case"hide":i();return e(this);case"opacity":if(o===undefined)return e(this).attr("data-opacity");e(this).each(function(){u(e(this).attr("data-opacity",o))});return e(this);case"rgbObject":return f(e(this),s==="rgbaObject");case"rgbString":case"rgbaString":return l(e(this),s==="rgbaString");case"settings":if(o===undefined)return e(this).data("minicolors-settings");e(this).each(function(){var t=e(this).data("minicolors-settings")||{};n(e(this));e(this).minicolors(e.extend(!0,t,o))});return e(this);case"show":r(e(this).eq(0));return e(this);case"value":if(o===undefined)return e(this).val();e(this).each(function(){u(e(this).val(o))});return e(this);default:s!=="create"&&(o=s);e(this).each(function(){t(e(this),o)});return e(this)}}});e(document).on("mousedown.minicolors touchstart.minicolors",function(t){e(t.target).parents().add(t.target).hasClass("minicolors")||i()}).on("mousedown.minicolors touchstart.minicolors",".minicolors-grid, .minicolors-slider, .minicolors-opacity-slider",function(t){var n=e(this);t.preventDefault();e(document).data("minicolors-target",n);s(n,t,!0)}).on("mousemove.minicolors touchmove.minicolors",function(t){var n=e(document).data("minicolors-target");n&&s(n,t)}).on("mouseup.minicolors touchend.minicolors",function(){e(this).removeData("minicolors-target")}).on("mousedown.minicolors touchstart.minicolors",".minicolors-swatch",function(t){var n=e(this).parent().find(".minicolors-input");t.preventDefault();r(n)}).on("focus.minicolors",".minicolors-input",function(){var t=e(this);if(!t.data("minicolors-initialized"))return;r(t)}).on("blur.minicolors",".minicolors-input",function(){var t=e(this),n=t.data("minicolors-settings");if(!t.data("minicolors-initialized"))return;t.val(h(t.val(),!0));t.val()===""&&t.val(h(n.defaultValue,!0));t.val(c(t.val(),n.letterCase))}).on("keydown.minicolors",".minicolors-input",function(t){var n=e(this);if(!n.data("minicolors-initialized"))return;switch(t.keyCode){case 9:i();break;case 13:case 27:i();n.blur()}}).on("keyup.minicolors",".minicolors-input",function(){var t=e(this);if(!t.data("minicolors-initialized"))return;u(t,!0)}).on("paste.minicolors",".minicolors-input",function(){var t=e(this);if(!t.data("minicolors-initialized"))return;setTimeout(function(){u(t,!0)},1)})}(jQuery); -------------------------------------------------------------------------------- /js/mqttws31.js: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2013 IBM Corp. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Eclipse Distribution License v1.0 which accompany this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * and the Eclipse Distribution License is available at 11 | * http://www.eclipse.org/org/documents/edl-v10.php. 12 | * 13 | * Contributors: 14 | * Andrew Banks - initial API and implementation and initial documentation 15 | *******************************************************************************/ 16 | 17 | 18 | // Only expose a single object name in the global namespace. 19 | // Everything must go through this module. Global Messaging module 20 | // only has a single public function, client, which returns 21 | // a Messaging client object given connection details. 22 | 23 | /** 24 | * @namespace Messaging 25 | * Send and receive messages using web browsers. 26 | *

    27 | * This programming interface lets a JavaScript client application use the MQTT V3.1 protocol to 28 | * connect to an MQTT-supporting messaging server. 29 | * 30 | * The function supported includes: 31 | *

      32 | *
    1. Connecting to and disconnecting from a server. The server is identified by its host name and port number. 33 | *
    2. Specifying options that relate to the communications link with the server, 34 | * for example the frequency of keep-alive heartbeats, and whether SSL/TLS is required. 35 | *
    3. Subscribing to and receiving messages from MQTT Topics. 36 | *
    4. Publishing messages to MQTT Topics. 37 | *
    38 | *

    39 | *

    The API consists of two main objects:

    40 | * The Messaging.Client object. This contains methods that provide the functionality of the API, 41 | * including provision of callbacks that notify the application when a message arrives from or is delivered to the messaging server, 42 | * or when the status of its connection to the messaging server changes. 43 | *

    44 | * The Messaging.Message object. This encapsulates the payload of the message along with various attributes 45 | * associated with its delivery, in particular the destination to which it has been (or is about to be) sent. 46 | *

    47 | * The programming interface validates parameters passed to it, and will throw an Error containing an error message 48 | * intended for developer use, if it detects an error with any parameter. 49 | *

    50 | * Example: 51 | * 52 | *

      53 |  client = new Messaging.Client(location.hostname, Number(location.port), "clientId");
      54 |  client.onConnectionLost = onConnectionLost;
      55 |  client.onMessageArrived = onMessageArrived;
      56 |  client.connect({onSuccess:onConnect});
      57 | 
      58 |  function onConnect() {
      59 |   // Once a connection has been made, make a subscription and send a message.
      60 |   console.log("onConnect");
      61 |   client.subscribe("/World");
      62 |   message = new Messaging.Message("Hello");
      63 |   message.destinationName = "/World";
      64 |   client.send(message); 
      65 | };
      66 |  function onConnectionLost(responseObject) {
      67 |   if (responseObject.errorCode !== 0)
      68 |     console.log("onConnectionLost:"+responseObject.errorMessage);
      69 | };
      70 |  function onMessageArrived(message) {
      71 |   console.log("onMessageArrived:"+message.payloadString);
      72 |   client.disconnect(); 
      73 | };
      74 |  * 
    75 | *

    76 | * Other programming languages, 77 | * Java, 78 | * C. 79 | */ 80 | Messaging = (function (global) { 81 | 82 | // Private variables below, these are only visible inside the function closure 83 | // which is used to define the module. 84 | 85 | var version = "0.0.0.0"; 86 | var buildLevel = "@BUILDLEVEL@"; 87 | 88 | /** 89 | * Unique message type identifiers, with associated 90 | * associated integer values. 91 | * @private 92 | */ 93 | var MESSAGE_TYPE = { 94 | CONNECT: 1, 95 | CONNACK: 2, 96 | PUBLISH: 3, 97 | PUBACK: 4, 98 | PUBREC: 5, 99 | PUBREL: 6, 100 | PUBCOMP: 7, 101 | SUBSCRIBE: 8, 102 | SUBACK: 9, 103 | UNSUBSCRIBE: 10, 104 | UNSUBACK: 11, 105 | PINGREQ: 12, 106 | PINGRESP: 13, 107 | DISCONNECT: 14 108 | }; 109 | 110 | // Collection of utility methods used to simplify module code 111 | // and promote the DRY pattern. 112 | 113 | /** 114 | * Validate an object's parameter names to ensure they 115 | * match a list of expected variables name for this option 116 | * type. Used to ensure option object passed into the API don't 117 | * contain erroneous parameters. 118 | * @param {Object} obj User options object 119 | * @param {key:type, key2:type, ...} valid keys and types that may exist in obj. 120 | * @throws {Error} Invalid option parameter found. 121 | * @private 122 | */ 123 | var validate = function (obj, keys) { 124 | for (key in obj) { 125 | if (obj.hasOwnProperty(key)) { 126 | if (keys.hasOwnProperty(key)) { 127 | if (typeof obj[key] !== keys[key]) 128 | throw new Error(format(ERROR.INVALID_TYPE, [typeof obj[key], key])); 129 | } else { 130 | var errorStr = "Unknown property, " + key + ". Valid properties are:"; 131 | for (key in keys) 132 | if (keys.hasOwnProperty(key)) 133 | errorStr = errorStr + " " + key; 134 | throw new Error(errorStr); 135 | } 136 | } 137 | } 138 | }; 139 | 140 | /** 141 | * Return a new function which runs the user function bound 142 | * to a fixed scope. 143 | * @param {function} User function 144 | * @param {object} Function scope 145 | * @return {function} User function bound to another scope 146 | * @private 147 | */ 148 | var scope = function (f, scope) { 149 | return function () { 150 | return f.apply(scope, arguments); 151 | }; 152 | }; 153 | 154 | /** 155 | * Unique message type identifiers, with associated 156 | * associated integer values. 157 | * @private 158 | */ 159 | var ERROR = { 160 | OK: {code: 0, text: "AMQJSC0000I OK."}, 161 | CONNECT_TIMEOUT: {code: 1, text: "AMQJSC0001E Connect timed out."}, 162 | SUBSCRIBE_TIMEOUT: {code: 2, text: "AMQJS0002E Subscribe timed out."}, 163 | UNSUBSCRIBE_TIMEOUT: {code: 3, text: "AMQJS0003E Unsubscribe timed out."}, 164 | PING_TIMEOUT: {code: 4, text: "AMQJS0004E Ping timed out."}, 165 | INTERNAL_ERROR: {code: 5, text: "AMQJS0005E Internal error."}, 166 | CONNACK_RETURNCODE: {code: 6, text: "AMQJS0006E Bad Connack return code:{0} {1}."}, 167 | SOCKET_ERROR: {code: 7, text: "AMQJS0007E Socket error:{0}."}, 168 | SOCKET_CLOSE: {code: 8, text: "AMQJS0008I Socket closed."}, 169 | MALFORMED_UTF: {code: 9, text: "AMQJS0009E Malformed UTF data:{0} {1} {2}."}, 170 | UNSUPPORTED: {code: 10, text: "AMQJS0010E {0} is not supported by this browser."}, 171 | INVALID_STATE: {code: 11, text: "AMQJS0011E Invalid state {0}."}, 172 | INVALID_TYPE: {code: 12, text: "AMQJS0012E Invalid type {0} for {1}."}, 173 | INVALID_ARGUMENT: {code: 13, text: "AMQJS0013E Invalid argument {0} for {1}."}, 174 | UNSUPPORTED_OPERATION: {code: 14, text: "AMQJS0014E Unsupported operation."}, 175 | INVALID_STORED_DATA: {code: 15, text: "AMQJS0015E Invalid data in local storage key={0} value={1}."}, 176 | INVALID_MQTT_MESSAGE_TYPE: {code: 16, text: "AMQJS0016E Invalid MQTT message type {0}."}, 177 | MALFORMED_UNICODE: {code: 17, text: "AMQJS0017E Malformed Unicode string:{0} {1}."}, 178 | }; 179 | 180 | /** CONNACK RC Meaning. */ 181 | var CONNACK_RC = { 182 | 0: "Connection Accepted", 183 | 1: "Connection Refused: unacceptable protocol version", 184 | 2: "Connection Refused: identifier rejected", 185 | 3: "Connection Refused: server unavailable", 186 | 4: "Connection Refused: bad user name or password", 187 | 5: "Connection Refused: not authorized" 188 | }; 189 | 190 | /** 191 | * Format an error message text. 192 | * @private 193 | * @param {error} ERROR.KEY value above. 194 | * @param {substitutions} [array] substituted into the text. 195 | * @return the text with the substitutions made. 196 | */ 197 | var format = function (error, substitutions) { 198 | var text = error.text; 199 | if (substitutions) { 200 | for (var i = 0; i < substitutions.length; i++) { 201 | field = "{" + i + "}"; 202 | start = text.indexOf(field); 203 | if (start > 0) { 204 | var part1 = text.substring(0, start); 205 | var part2 = text.substring(start + field.length); 206 | text = part1 + substitutions[i] + part2; 207 | } 208 | } 209 | } 210 | return text; 211 | }; 212 | 213 | //MQTT protocol and version 6 M Q I s d p 3 214 | var MqttProtoIdentifier = [0x00, 0x06, 0x4d, 0x51, 0x49, 0x73, 0x64, 0x70, 0x03]; 215 | 216 | /** 217 | * @ignore 218 | * Construct an MQTT wire protocol message. 219 | * @param type MQTT packet type. 220 | * @param options optional wire message attributes. 221 | * 222 | * Optional properties 223 | * 224 | * messageIdentifier: message ID in the range [0..65535] 225 | * payloadMessage: Application Message - PUBLISH only 226 | * connectStrings: array of 0 or more Strings to be put into the CONNECT payload 227 | * topics: array of strings (SUBSCRIBE, UNSUBSCRIBE) 228 | * requestQoS: array of QoS values [0..2] 229 | * 230 | * "Flag" properties 231 | * cleanSession: true if present / false if absent (CONNECT) 232 | * willMessage: true if present / false if absent (CONNECT) 233 | * isRetained: true if present / false if absent (CONNECT) 234 | * userName: true if present / false if absent (CONNECT) 235 | * password: true if present / false if absent (CONNECT) 236 | * keepAliveInterval: integer [0..65535] (CONNECT) 237 | * 238 | * @private 239 | */ 240 | var WireMessage = function (type, options) { 241 | this.type = type; 242 | for (name in options) { 243 | if (options.hasOwnProperty(name)) { 244 | this[name] = options[name]; 245 | } 246 | } 247 | }; 248 | 249 | WireMessage.prototype.encode = function () { 250 | // Compute the first byte of the fixed header 251 | var first = ((this.type & 0x0f) << 4); 252 | 253 | /* 254 | * Now calculate the length of the variable header + payload by adding up the lengths 255 | * of all the component parts 256 | */ 257 | 258 | remLength = 0; 259 | topicStrLength = new Array(); 260 | 261 | // if the message contains a messageIdentifier then we need two bytes for that 262 | if (this.messageIdentifier != undefined) 263 | remLength += 2; 264 | 265 | switch (this.type) { 266 | // If this a Connect then we need to include 12 bytes for its header 267 | case MESSAGE_TYPE.CONNECT: 268 | remLength += MqttProtoIdentifier.length + 3; 269 | remLength += UTF8Length(this.clientId) + 2; 270 | if (this.willMessage != undefined) { 271 | remLength += UTF8Length(this.willMessage.destinationName) + 2; 272 | // Will message is always a string, sent as UTF-8 characters with a preceding length. 273 | var willMessagePayloadBytes = this.willMessage.payloadBytes; 274 | if (!(willMessagePayloadBytes instanceof Uint8Array)) 275 | willMessagePayloadBytes = new Uint8Array(payloadBytes); 276 | remLength += willMessagePayloadBytes.byteLength + 2; 277 | } 278 | if (this.userName != undefined) 279 | remLength += UTF8Length(this.userName) + 2; 280 | if (this.password != undefined) 281 | remLength += UTF8Length(this.password) + 2; 282 | break; 283 | 284 | // Subscribe, Unsubscribe can both contain topic strings 285 | case MESSAGE_TYPE.SUBSCRIBE: 286 | first |= 0x02; // Qos = 1; 287 | for (var i = 0; i < this.topics.length; i++) { 288 | topicStrLength[i] = UTF8Length(this.topics[i]); 289 | remLength += topicStrLength[i] + 2; 290 | } 291 | remLength += this.requestedQos.length; // 1 byte for each topic's Qos 292 | // QoS on Subscribe only 293 | break; 294 | 295 | case MESSAGE_TYPE.UNSUBSCRIBE: 296 | first |= 0x02; // Qos = 1; 297 | for (var i = 0; i < this.topics.length; i++) { 298 | topicStrLength[i] = UTF8Length(this.topics[i]); 299 | remLength += topicStrLength[i] + 2; 300 | } 301 | break; 302 | 303 | case MESSAGE_TYPE.PUBLISH: 304 | if (this.payloadMessage.duplicate) first |= 0x08; 305 | first = first |= (this.payloadMessage.qos << 1); 306 | if (this.payloadMessage.retained) first |= 0x01; 307 | destinationNameLength = UTF8Length(this.payloadMessage.destinationName); 308 | remLength += destinationNameLength + 2; 309 | var payloadBytes = this.payloadMessage.payloadBytes; 310 | remLength += payloadBytes.byteLength; 311 | if (payloadBytes instanceof ArrayBuffer) 312 | payloadBytes = new Uint8Array(payloadBytes); 313 | else if (!(payloadBytes instanceof Uint8Array)) 314 | payloadBytes = new Uint8Array(payloadBytes.buffer); 315 | break; 316 | 317 | case MESSAGE_TYPE.DISCONNECT: 318 | break; 319 | 320 | default: 321 | ; 322 | } 323 | 324 | // Now we can allocate a buffer for the message 325 | 326 | var mbi = encodeMBI(remLength); // Convert the length to MQTT MBI format 327 | var pos = mbi.length + 1; // Offset of start of variable header 328 | var buffer = new ArrayBuffer(remLength + pos); 329 | var byteStream = new Uint8Array(buffer); // view it as a sequence of bytes 330 | 331 | //Write the fixed header into the buffer 332 | byteStream[0] = first; 333 | byteStream.set(mbi, 1); 334 | 335 | // If this is a PUBLISH then the variable header starts with a topic 336 | if (this.type == MESSAGE_TYPE.PUBLISH) 337 | pos = writeString(this.payloadMessage.destinationName, destinationNameLength, byteStream, pos); 338 | // If this is a CONNECT then the variable header contains the protocol name/version, flags and keepalive time 339 | 340 | else if (this.type == MESSAGE_TYPE.CONNECT) { 341 | byteStream.set(MqttProtoIdentifier, pos); 342 | pos += MqttProtoIdentifier.length; 343 | var connectFlags = 0; 344 | if (this.cleanSession) 345 | connectFlags = 0x02; 346 | if (this.willMessage != undefined) { 347 | connectFlags |= 0x04; 348 | connectFlags |= (this.willMessage.qos << 3); 349 | if (this.willMessage.retained) { 350 | connectFlags |= 0x20; 351 | } 352 | } 353 | if (this.userName != undefined) 354 | connectFlags |= 0x80; 355 | if (this.password != undefined) 356 | connectFlags |= 0x40; 357 | byteStream[pos++] = connectFlags; 358 | pos = writeUint16(this.keepAliveInterval, byteStream, pos); 359 | } 360 | 361 | // Output the messageIdentifier - if there is one 362 | if (this.messageIdentifier != undefined) 363 | pos = writeUint16(this.messageIdentifier, byteStream, pos); 364 | 365 | switch (this.type) { 366 | case MESSAGE_TYPE.CONNECT: 367 | pos = writeString(this.clientId, UTF8Length(this.clientId), byteStream, pos); 368 | if (this.willMessage != undefined) { 369 | pos = writeString(this.willMessage.destinationName, UTF8Length(this.willMessage.destinationName), byteStream, pos); 370 | pos = writeUint16(willMessagePayloadBytes.byteLength, byteStream, pos); 371 | byteStream.set(willMessagePayloadBytes, pos); 372 | pos += willMessagePayloadBytes.byteLength; 373 | 374 | } 375 | if (this.userName != undefined) 376 | pos = writeString(this.userName, UTF8Length(this.userName), byteStream, pos); 377 | if (this.password != undefined) 378 | pos = writeString(this.password, UTF8Length(this.password), byteStream, pos); 379 | break; 380 | 381 | case MESSAGE_TYPE.PUBLISH: 382 | // PUBLISH has a text or binary payload, if text do not add a 2 byte length field, just the UTF characters. 383 | byteStream.set(payloadBytes, pos); 384 | 385 | break; 386 | 387 | // case MESSAGE_TYPE.PUBREC: 388 | // case MESSAGE_TYPE.PUBREL: 389 | // case MESSAGE_TYPE.PUBCOMP: 390 | // break; 391 | 392 | case MESSAGE_TYPE.SUBSCRIBE: 393 | // SUBSCRIBE has a list of topic strings and request QoS 394 | for (var i = 0; i < this.topics.length; i++) { 395 | pos = writeString(this.topics[i], topicStrLength[i], byteStream, pos); 396 | byteStream[pos++] = this.requestedQos[i]; 397 | } 398 | break; 399 | 400 | case MESSAGE_TYPE.UNSUBSCRIBE: 401 | // UNSUBSCRIBE has a list of topic strings 402 | for (var i = 0; i < this.topics.length; i++) 403 | pos = writeString(this.topics[i], topicStrLength[i], byteStream, pos); 404 | break; 405 | 406 | default: 407 | // Do nothing. 408 | } 409 | 410 | return buffer; 411 | } 412 | 413 | function decodeMessage(input) { 414 | //var msg = new Object(); // message to be constructed 415 | var first = input[0]; 416 | var type = first >> 4; 417 | var messageInfo = first &= 0x0f; 418 | var pos = 1; 419 | 420 | 421 | // Decode the remaining length (MBI format) 422 | 423 | var digit; 424 | var remLength = 0; 425 | var multiplier = 1; 426 | do { 427 | digit = input[pos++]; 428 | remLength += ((digit & 0x7F) * multiplier); 429 | multiplier *= 128; 430 | } while ((digit & 0x80) != 0); 431 | 432 | var wireMessage = new WireMessage(type); 433 | switch (type) { 434 | case MESSAGE_TYPE.CONNACK: 435 | wireMessage.topicNameCompressionResponse = input[pos++]; 436 | wireMessage.returnCode = input[pos++]; 437 | break; 438 | 439 | case MESSAGE_TYPE.PUBLISH: 440 | var qos = (messageInfo >> 1) & 0x03; 441 | 442 | var len = readUint16(input, pos); 443 | pos += 2; 444 | var topicName = parseUTF8(input, pos, len); 445 | pos += len; 446 | // If QoS 1 or 2 there will be a messageIdentifier 447 | if (qos > 0) { 448 | wireMessage.messageIdentifier = readUint16(input, pos); 449 | pos += 2; 450 | } 451 | 452 | var message = new Messaging.Message(input.subarray(pos)); 453 | if ((messageInfo & 0x01) == 0x01) 454 | message.retained = true; 455 | if ((messageInfo & 0x08) == 0x08) 456 | message.duplicate = true; 457 | message.qos = qos; 458 | message.destinationName = topicName; 459 | wireMessage.payloadMessage = message; 460 | break; 461 | 462 | case MESSAGE_TYPE.PUBACK: 463 | case MESSAGE_TYPE.PUBREC: 464 | case MESSAGE_TYPE.PUBREL: 465 | case MESSAGE_TYPE.PUBCOMP: 466 | case MESSAGE_TYPE.UNSUBACK: 467 | wireMessage.messageIdentifier = readUint16(input, pos); 468 | break; 469 | 470 | case MESSAGE_TYPE.SUBACK: 471 | wireMessage.messageIdentifier = readUint16(input, pos); 472 | pos += 2; 473 | wireMessage.grantedQos = input.subarray(pos); 474 | break; 475 | 476 | default: 477 | ; 478 | } 479 | 480 | return wireMessage; 481 | } 482 | 483 | function writeUint16(input, buffer, offset) { 484 | buffer[offset++] = input >> 8; //MSB 485 | buffer[offset++] = input % 256; //LSB 486 | return offset; 487 | } 488 | 489 | function writeString(input, utf8Length, buffer, offset) { 490 | offset = writeUint16(utf8Length, buffer, offset); 491 | stringToUTF8(input, buffer, offset); 492 | return offset + utf8Length; 493 | } 494 | 495 | function readUint16(buffer, offset) { 496 | return 256 * buffer[offset] + buffer[offset + 1]; 497 | } 498 | 499 | /** 500 | * Encodes an MQTT Multi-Byte Integer 501 | * @private 502 | */ 503 | function encodeMBI(number) { 504 | var output = new Array(1); 505 | var numBytes = 0; 506 | 507 | do { 508 | var digit = number % 128; 509 | number = number >> 7; 510 | if (number > 0) { 511 | digit |= 0x80; 512 | } 513 | output[numBytes++] = digit; 514 | } while ((number > 0) && (numBytes < 4)); 515 | 516 | return output; 517 | } 518 | 519 | /** 520 | * Takes a String and calculates its length in bytes when encoded in UTF8. 521 | * @private 522 | */ 523 | function UTF8Length(input) { 524 | var output = 0; 525 | for (var i = 0; i < input.length; i++) { 526 | var charCode = input.charCodeAt(i); 527 | if (charCode > 0x7FF) { 528 | // Surrogate pair means its a 4 byte character 529 | if (0xD800 <= charCode && charCode <= 0xDBFF) { 530 | i++; 531 | output++; 532 | } 533 | output += 3; 534 | } 535 | else if (charCode > 0x7F) 536 | output += 2; 537 | else 538 | output++; 539 | } 540 | return output; 541 | } 542 | 543 | /** 544 | * Takes a String and writes it into an array as UTF8 encoded bytes. 545 | * @private 546 | */ 547 | function stringToUTF8(input, output, start) { 548 | var pos = start; 549 | for (var i = 0; i < input.length; i++) { 550 | var charCode = input.charCodeAt(i); 551 | 552 | // Check for a surrogate pair. 553 | if (0xD800 <= charCode && charCode <= 0xDBFF) { 554 | lowCharCode = input.charCodeAt(++i); 555 | if (isNaN(lowCharCode)) { 556 | throw new Error(format(ERROR.MALFORMED_UNICODE, [charCode, lowCharCode])); 557 | } 558 | charCode = ((charCode - 0xD800) << 10) + (lowCharCode - 0xDC00) + 0x10000; 559 | 560 | } 561 | 562 | if (charCode <= 0x7F) { 563 | output[pos++] = charCode; 564 | } else if (charCode <= 0x7FF) { 565 | output[pos++] = charCode >> 6 & 0x1F | 0xC0; 566 | output[pos++] = charCode & 0x3F | 0x80; 567 | } else if (charCode <= 0xFFFF) { 568 | output[pos++] = charCode >> 12 & 0x0F | 0xE0; 569 | output[pos++] = charCode >> 6 & 0x3F | 0x80; 570 | output[pos++] = charCode & 0x3F | 0x80; 571 | } else { 572 | output[pos++] = charCode >> 18 & 0x07 | 0xF0; 573 | output[pos++] = charCode >> 12 & 0x3F | 0x80; 574 | output[pos++] = charCode >> 6 & 0x3F | 0x80; 575 | output[pos++] = charCode & 0x3F | 0x80; 576 | } 577 | ; 578 | } 579 | return output; 580 | } 581 | 582 | function parseUTF8(input, offset, length) { 583 | var output = ""; 584 | var utf16; 585 | var pos = offset; 586 | 587 | while (pos < offset + length) { 588 | var byte1 = input[pos++]; 589 | if (byte1 < 128) 590 | utf16 = byte1; 591 | else { 592 | var byte2 = input[pos++] - 128; 593 | if (byte2 < 0) 594 | throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16), ""])); 595 | if (byte1 < 0xE0) // 2 byte character 596 | utf16 = 64 * (byte1 - 0xC0) + byte2; 597 | else { 598 | var byte3 = input[pos++] - 128; 599 | if (byte3 < 0) 600 | throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16), byte3.toString(16)])); 601 | if (byte1 < 0xF0) // 3 byte character 602 | utf16 = 4096 * (byte1 - 0xE0) + 64 * byte2 + byte3; 603 | else { 604 | var byte4 = input[pos++] - 128; 605 | if (byte4 < 0) 606 | throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16), byte3.toString(16), byte4.toString(16)])); 607 | if (byte1 < 0xF8) // 4 byte character 608 | utf16 = 262144 * (byte1 - 0xF0) + 4096 * byte2 + 64 * byte3 + byte4; 609 | else // longer encodings are not supported 610 | throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16), byte3.toString(16), byte4.toString(16)])); 611 | } 612 | } 613 | } 614 | 615 | if (utf16 > 0xFFFF) // 4 byte character - express as a surrogate pair 616 | { 617 | utf16 -= 0x10000; 618 | output += String.fromCharCode(0xD800 + (utf16 >> 10)); // lead character 619 | utf16 = 0xDC00 + (utf16 & 0x3FF); // trail character 620 | } 621 | output += String.fromCharCode(utf16); 622 | } 623 | return output; 624 | } 625 | 626 | /** @ignore Repeat keepalive requests, monitor responses.*/ 627 | var Pinger = function (client, window, keepAliveInterval) { 628 | this._client = client; 629 | this._window = window; 630 | this._keepAliveInterval = keepAliveInterval * 1000; 631 | this.isReset = false; 632 | 633 | var pingReq = new WireMessage(MESSAGE_TYPE.PINGREQ).encode(); 634 | 635 | var doTimeout = function (pinger) { 636 | return function () { 637 | return doPing.apply(pinger); 638 | }; 639 | }; 640 | 641 | /** @ignore */ 642 | var doPing = function () { 643 | if (!this.isReset) { 644 | this._client._trace("Pinger.doPing", "Timed out"); 645 | this._client._disconnected(ERROR.PING_TIMEOUT.code, format(ERROR.PING_TIMEOUT)); 646 | } else { 647 | this.isReset = false; 648 | this._client._trace("Pinger.doPing", "send PINGREQ"); 649 | this._client.socket.send(pingReq); 650 | this.timeout = this._window.setTimeout(doTimeout(this), this._keepAliveInterval); 651 | } 652 | } 653 | 654 | this.reset = function () { 655 | this.isReset = true; 656 | this._window.clearTimeout(this.timeout); 657 | if (this._keepAliveInterval > 0) 658 | this.timeout = setTimeout(doTimeout(this), this._keepAliveInterval); 659 | } 660 | 661 | this.cancel = function () { 662 | this._window.clearTimeout(this.timeout); 663 | } 664 | }; 665 | 666 | /** @ignore Monitor request completion. */ 667 | var Timeout = function (client, window, timeoutSeconds, action, args) { 668 | this._window = window; 669 | if (!timeoutSeconds) 670 | timeoutSeconds = 30; 671 | 672 | var doTimeout = function (action, client, args) { 673 | return function () { 674 | return action.apply(client, args); 675 | }; 676 | }; 677 | this.timeout = setTimeout(doTimeout(action, client, args), timeoutSeconds * 1000); 678 | 679 | this.cancel = function () { 680 | this._window.clearTimeout(this.timeout); 681 | } 682 | }; 683 | 684 | /* 685 | * Internal implementation of the Websockets MQTT V3.1 client. 686 | * 687 | * @name Messaging.ClientImpl @constructor 688 | * @param {String} host the DNS nameof the webSocket host. 689 | * @param {Number} port the port number for that host. 690 | * @param {String} clientId the MQ client identifier. 691 | */ 692 | var ClientImpl = function (host, port, clientId) { 693 | // Check dependencies are satisfied in this browser. 694 | if (!("WebSocket" in global && global["WebSocket"] !== null)) { 695 | throw new Error(format(ERROR.UNSUPPORTED, ["WebSocket"])); 696 | } 697 | if (!("localStorage" in global && global["localStorage"] !== null)) { 698 | throw new Error(format(ERROR.UNSUPPORTED, ["localStorage"])); 699 | } 700 | if (!("ArrayBuffer" in global && global["ArrayBuffer"] !== null)) { 701 | throw new Error(format(ERROR.UNSUPPORTED, ["ArrayBuffer"])); 702 | } 703 | 704 | this._trace("Messaging.Client", host, port, clientId); 705 | 706 | this.host = host; 707 | this.port = port; 708 | this.clientId = clientId; 709 | 710 | // Local storagekeys are qualified with the following string. 711 | this._localKey = host + ":" + port + ":" + clientId + ":"; 712 | 713 | // Create private instance-only message queue 714 | // Internal queue of messages to be sent, in sending order. 715 | this._msg_queue = []; 716 | 717 | // Messages we have sent and are expecting a response for, indexed by their respective message ids. 718 | this._sentMessages = {}; 719 | 720 | // Messages we have received and acknowleged and are expecting a confirm message for 721 | // indexed by their respective message ids. 722 | this._receivedMessages = {}; 723 | 724 | // Internal list of callbacks to be executed when messages 725 | // have been successfully sent over web socket, e.g. disconnect 726 | // when it doesn't have to wait for ACK, just message is dispatched. 727 | this._notify_msg_sent = {}; 728 | 729 | // Unique identifier for SEND messages, incrementing 730 | // counter as messages are sent. 731 | this._message_identifier = 1; 732 | 733 | // Used to determine the transmission sequence of stored sent messages. 734 | this._sequence = 0; 735 | 736 | 737 | // Load the local state, if any, from the saved version, only restore state relevant to this client. 738 | for (key in localStorage) 739 | if (key.indexOf("Sent:" + this._localKey) == 0 740 | || key.indexOf("Received:" + this._localKey) == 0) 741 | this.restore(key); 742 | }; 743 | 744 | // Messaging Client public instance members. 745 | ClientImpl.prototype.host; 746 | ClientImpl.prototype.port; 747 | ClientImpl.prototype.clientId; 748 | 749 | // Messaging Client private instance members. 750 | ClientImpl.prototype.socket; 751 | /* true once we have received an acknowledgement to a CONNECT packet. */ 752 | ClientImpl.prototype.connected = false; 753 | /* The largest message identifier allowed, may not be larger than 2**16 but 754 | * if set smaller reduces the maximum number of outbound messages allowed. 755 | */ 756 | ClientImpl.prototype.maxMessageIdentifier = 65536; 757 | ClientImpl.prototype.connectOptions; 758 | ClientImpl.prototype.hostIndex; 759 | ClientImpl.prototype.onConnectionLost; 760 | ClientImpl.prototype.onMessageDelivered; 761 | ClientImpl.prototype.onMessageArrived; 762 | ClientImpl.prototype._msg_queue = null; 763 | ClientImpl.prototype._connectTimeout; 764 | /* The sendPinger monitors how long we allow before we send data to prove to the server that we are alive. */ 765 | ClientImpl.prototype.sendPinger = null; 766 | /* The receivePinger monitors how long we allow before we require evidence that the server is alive. */ 767 | ClientImpl.prototype.receivePinger = null; 768 | 769 | ClientImpl.prototype._traceBuffer = null; 770 | ClientImpl.prototype._MAX_TRACE_ENTRIES = 100; 771 | 772 | ClientImpl.prototype.connect = function (connectOptions) { 773 | var connectOptionsMasked = this._traceMask(connectOptions, "password"); 774 | this._trace("Client.connect", connectOptionsMasked, this.socket, this.connected); 775 | 776 | if (this.connected) 777 | throw new Error(format(ERROR.INVALID_STATE, ["already connected"])); 778 | if (this.socket) 779 | throw new Error(format(ERROR.INVALID_STATE, ["already connected"])); 780 | 781 | this.connectOptions = connectOptions; 782 | 783 | if (connectOptions.hosts) { 784 | this.hostIndex = 0; 785 | this._doConnect(connectOptions.hosts[0], connectOptions.ports[0]); 786 | } else { 787 | this._doConnect(this.host, this.port); 788 | } 789 | 790 | }; 791 | 792 | ClientImpl.prototype.subscribe = function (filter, subscribeOptions) { 793 | this._trace("Client.subscribe", filter, subscribeOptions); 794 | 795 | if (!this.connected) 796 | throw new Error(format(ERROR.INVALID_STATE, ["not connected"])); 797 | 798 | var wireMessage = new WireMessage(MESSAGE_TYPE.SUBSCRIBE); 799 | wireMessage.topics = [filter]; 800 | if (subscribeOptions.qos != undefined) 801 | wireMessage.requestedQos = [subscribeOptions.qos]; 802 | else 803 | wireMessage.requestedQos = [0]; 804 | 805 | if (subscribeOptions.onSuccess) { 806 | wireMessage.callback = function () { 807 | subscribeOptions.onSuccess({invocationContext: subscribeOptions.invocationContext}); 808 | }; 809 | } 810 | if (subscribeOptions.timeout) { 811 | wireMessage.timeOut = new Timeout(this, window, subscribeOptions.timeout, subscribeOptions.onFailure 812 | , [ 813 | {invocationContext: subscribeOptions.invocationContext, 814 | errorCode: ERROR.SUBSCRIBE_TIMEOUT.code, 815 | errorMessage: format(ERROR.SUBSCRIBE_TIMEOUT)} 816 | ]); 817 | } 818 | 819 | // All subscriptions return a SUBACK. 820 | this._requires_ack(wireMessage); 821 | this._schedule_message(wireMessage); 822 | }; 823 | 824 | /** @ignore */ 825 | ClientImpl.prototype.unsubscribe = function (filter, unsubscribeOptions) { 826 | this._trace("Client.unsubscribe", filter, unsubscribeOptions); 827 | 828 | if (!this.connected) 829 | throw new Error(format(ERROR.INVALID_STATE, ["not connected"])); 830 | 831 | var wireMessage = new WireMessage(MESSAGE_TYPE.UNSUBSCRIBE); 832 | wireMessage.topics = [filter]; 833 | 834 | if (unsubscribeOptions.onSuccess) { 835 | wireMessage.callback = function () { 836 | unsubscribeOptions.onSuccess({invocationContext: unsubscribeOptions.invocationContext}); 837 | }; 838 | } 839 | if (unsubscribeOptions.timeout) { 840 | wireMessage.timeOut = new Timeout(this, window, unsubscribeOptions.timeout, unsubscribeOptions.onFailure 841 | , [ 842 | {invocationContext: unsubscribeOptions.invocationContext, 843 | errorCode: ERROR.UNSUBSCRIBE_TIMEOUT.code, 844 | errorMessage: format(ERROR.UNSUBSCRIBE_TIMEOUT)} 845 | ]); 846 | } 847 | 848 | // All unsubscribes return a SUBACK. 849 | this._requires_ack(wireMessage); 850 | this._schedule_message(wireMessage); 851 | }; 852 | 853 | ClientImpl.prototype.send = function (message) { 854 | this._trace("Client.send", message); 855 | 856 | if (!this.connected) 857 | throw new Error(format(ERROR.INVALID_STATE, ["not connected"])); 858 | 859 | wireMessage = new WireMessage(MESSAGE_TYPE.PUBLISH); 860 | wireMessage.payloadMessage = message; 861 | 862 | if (message.qos > 0) 863 | this._requires_ack(wireMessage); 864 | else if (this.onMessageDelivered) 865 | this._notify_msg_sent[wireMessage] = this.onMessageDelivered(wireMessage.payloadMessage); 866 | this._schedule_message(wireMessage); 867 | }; 868 | 869 | ClientImpl.prototype.disconnect = function () { 870 | this._trace("Client.disconnect"); 871 | 872 | if (!this.socket) 873 | throw new Error(format(ERROR.INVALID_STATE, ["not connecting or connected"])); 874 | 875 | wireMessage = new WireMessage(MESSAGE_TYPE.DISCONNECT); 876 | 877 | // Run the disconnected call back as soon as the message has been sent, 878 | // in case of a failure later on in the disconnect processing. 879 | // as a consequence, the _disconected call back may be run several times. 880 | this._notify_msg_sent[wireMessage] = scope(this._disconnected, this); 881 | 882 | this._schedule_message(wireMessage); 883 | }; 884 | 885 | ClientImpl.prototype.getTraceLog = function () { 886 | if (this._traceBuffer !== null) { 887 | this._trace("Client.getTraceLog", new Date()); 888 | this._trace("Client.getTraceLog in flight messages", this._sentMessages.length); 889 | for (key in this._sentMessages) 890 | this._trace("_sentMessages ", key, this._sentMessages[key]); 891 | for (key in this._receivedMessages) 892 | this._trace("_receivedMessages ", key, this._receivedMessages[key]); 893 | 894 | return this._traceBuffer; 895 | } 896 | }; 897 | 898 | ClientImpl.prototype.startTrace = function () { 899 | if (this._traceBuffer === null) { 900 | this._traceBuffer = []; 901 | } 902 | this._trace("Client.startTrace", new Date(), version); 903 | }; 904 | 905 | ClientImpl.prototype.stopTrace = function () { 906 | delete this._traceBuffer; 907 | }; 908 | 909 | ClientImpl.prototype._doConnect = function (host, port) { 910 | // When the socket is open, this client will send the CONNECT WireMessage using the saved parameters. 911 | if (this.connectOptions.useSSL) 912 | wsurl = ["wss://", host, ":", port, "/mqtt"].join(""); 913 | else 914 | wsurl = ["ws://", host, ":", port, "/mqtt"].join(""); 915 | this.connected = false; 916 | this.socket = new WebSocket(wsurl, 'mqttv3.1'); 917 | this.socket.binaryType = 'arraybuffer'; 918 | this.socket.onopen = scope(this._on_socket_open, this); 919 | this.socket.onmessage = scope(this._on_socket_message, this); 920 | this.socket.onerror = scope(this._on_socket_error, this); 921 | this.socket.onclose = scope(this._on_socket_close, this); 922 | 923 | this.sendPinger = new Pinger(this, window, this.connectOptions.keepAliveInterval); 924 | this.receivePinger = new Pinger(this, window, this.connectOptions.keepAliveInterval); 925 | 926 | this._connectTimeout = new Timeout(this, window, this.connectOptions.timeout, this._disconnected, [ERROR.CONNECT_TIMEOUT.code, format(ERROR.CONNECT_TIMEOUT)]); 927 | }; 928 | 929 | 930 | // Schedule a new message to be sent over the WebSockets 931 | // connection. CONNECT messages cause WebSocket connection 932 | // to be started. All other messages are queued internally 933 | // until this has happened. When WS connection starts, process 934 | // all outstanding messages. 935 | ClientImpl.prototype._schedule_message = function (message) { 936 | this._msg_queue.push(message); 937 | // Process outstanding messages in the queue if we have an open socket, and have received CONNACK. 938 | if (this.connected) { 939 | this._process_queue(); 940 | } 941 | }; 942 | 943 | ClientImpl.prototype.store = function (prefix, wireMessage) { 944 | storedMessage = {type: wireMessage.type, messageIdentifier: wireMessage.messageIdentifier, version: 1}; 945 | 946 | switch (wireMessage.type) { 947 | case MESSAGE_TYPE.PUBLISH: 948 | if (wireMessage.pubRecReceived) 949 | storedMessage.pubRecReceived = true; 950 | 951 | // Convert the payload to a hex string. 952 | storedMessage.payloadMessage = {}; 953 | var hex = ""; 954 | var messageBytes = wireMessage.payloadMessage.payloadBytes; 955 | for (var i = 0; i < messageBytes.length; i++) { 956 | if (messageBytes[i] <= 0xF) 957 | hex = hex + "0" + messageBytes[i].toString(16); 958 | else 959 | hex = hex + messageBytes[i].toString(16); 960 | } 961 | storedMessage.payloadMessage.payloadHex = hex; 962 | 963 | storedMessage.payloadMessage.qos = wireMessage.payloadMessage.qos; 964 | storedMessage.payloadMessage.destinationName = wireMessage.payloadMessage.destinationName; 965 | if (wireMessage.payloadMessage.duplicate) 966 | storedMessage.payloadMessage.duplicate = true; 967 | if (wireMessage.payloadMessage.retained) 968 | storedMessage.payloadMessage.retained = true; 969 | 970 | // Add a sequence number to sent messages. 971 | if (prefix.indexOf("Sent:") == 0) { 972 | if (wireMessage.sequence === undefined) 973 | wireMessage.sequence = ++this._sequence; 974 | storedMessage.sequence = wireMessage.sequence; 975 | } 976 | break; 977 | 978 | default: 979 | throw Error(format(ERROR.INVALID_STORED_DATA, [key, storedMessage])); 980 | } 981 | localStorage.setItem(prefix + this._localKey + wireMessage.messageIdentifier, JSON.stringify(storedMessage)); 982 | }; 983 | 984 | ClientImpl.prototype.restore = function (key) { 985 | var value = localStorage.getItem(key); 986 | var storedMessage = JSON.parse(value); 987 | 988 | var wireMessage = new WireMessage(storedMessage.type, storedMessage); 989 | 990 | switch (storedMessage.type) { 991 | case MESSAGE_TYPE.PUBLISH: 992 | // Replace the payload message with a Message object. 993 | var hex = storedMessage.payloadMessage.payloadHex; 994 | var buffer = new ArrayBuffer((hex.length) / 2); 995 | var byteStream = new Uint8Array(buffer); 996 | var i = 0; 997 | while (hex.length >= 2) { 998 | var x = parseInt(hex.substring(0, 2), 16); 999 | hex = hex.substring(2, hex.length); 1000 | byteStream[i++] = x; 1001 | } 1002 | var payloadMessage = new Messaging.Message(byteStream); 1003 | 1004 | payloadMessage.qos = storedMessage.payloadMessage.qos; 1005 | payloadMessage.destinationName = storedMessage.payloadMessage.destinationName; 1006 | if (storedMessage.payloadMessage.duplicate) 1007 | payloadMessage.duplicate = true; 1008 | if (storedMessage.payloadMessage.retained) 1009 | payloadMessage.retained = true; 1010 | wireMessage.payloadMessage = payloadMessage; 1011 | 1012 | break; 1013 | 1014 | default: 1015 | throw Error(format(ERROR.INVALID_STORED_DATA, [key, value])); 1016 | } 1017 | 1018 | if (key.indexOf("Sent:" + this._localKey) == 0) { 1019 | this._sentMessages[wireMessage.messageIdentifier] = wireMessage; 1020 | } else if (key.indexOf("Received:" + this._localKey) == 0) { 1021 | this._receivedMessages[wireMessage.messageIdentifier] = wireMessage; 1022 | } 1023 | }; 1024 | 1025 | ClientImpl.prototype._process_queue = function () { 1026 | var message = null; 1027 | // Process messages in order they were added 1028 | var fifo = this._msg_queue.reverse(); 1029 | 1030 | // Send all queued messages down socket connection 1031 | while ((message = fifo.pop())) { 1032 | this._socket_send(message); 1033 | // Notify listeners that message was successfully sent 1034 | if (this._notify_msg_sent[message]) { 1035 | this._notify_msg_sent[message](); 1036 | delete this._notify_msg_sent[message]; 1037 | } 1038 | } 1039 | }; 1040 | 1041 | /** 1042 | * @ignore 1043 | * Expect an ACK response for this message. Add message to the set of in progress 1044 | * messages and set an unused identifier in this message. 1045 | */ 1046 | ClientImpl.prototype._requires_ack = function (wireMessage) { 1047 | var messageCount = Object.keys(this._sentMessages).length; 1048 | if (messageCount > this.maxMessageIdentifier) 1049 | throw Error("Too many messages:" + messageCount); 1050 | 1051 | while (this._sentMessages[this._message_identifier] !== undefined) { 1052 | this._message_identifier++; 1053 | } 1054 | wireMessage.messageIdentifier = this._message_identifier; 1055 | this._sentMessages[wireMessage.messageIdentifier] = wireMessage; 1056 | if (wireMessage.type === MESSAGE_TYPE.PUBLISH) { 1057 | this.store("Sent:", wireMessage); 1058 | } 1059 | if (this._message_identifier === this.maxMessagIdentifier) { 1060 | this._message_identifier = 1; 1061 | } 1062 | }; 1063 | 1064 | /** 1065 | * @ignore 1066 | * Called when the underlying websocket has been opened. 1067 | */ 1068 | ClientImpl.prototype._on_socket_open = function () { 1069 | // Create the CONNECT message object. 1070 | var wireMessage = new WireMessage(MESSAGE_TYPE.CONNECT, this.connectOptions); 1071 | wireMessage.clientId = this.clientId; 1072 | this._socket_send(wireMessage); 1073 | }; 1074 | 1075 | /** 1076 | * @ignore 1077 | * Called when the underlying websocket has received a complete packet. 1078 | */ 1079 | ClientImpl.prototype._on_socket_message = function (event) { 1080 | this._trace("Client._on_socket_message", event.data); 1081 | 1082 | // Reset the receive ping timer, we now have evidence the server is alive. 1083 | this.receivePinger.reset(); 1084 | var byteArray = new Uint8Array(event.data); 1085 | try { 1086 | var wireMessage = decodeMessage(byteArray); 1087 | } catch (error) { 1088 | this._disconnected(ERROR.INTERNAL_ERROR.code, format(ERROR.INTERNAL_ERROR, [error.message])); 1089 | return; 1090 | } 1091 | this._trace("Client._on_socket_message", wireMessage); 1092 | 1093 | switch (wireMessage.type) { 1094 | case MESSAGE_TYPE.CONNACK: 1095 | this._connectTimeout.cancel(); 1096 | 1097 | // If we have started using clean session then clear up the local state. 1098 | if (this.connectOptions.cleanSession) { 1099 | for (key in this._sentMessages) { 1100 | var sentMessage = this._sentMessages[key]; 1101 | localStorage.removeItem("Sent:" + this._localKey + sentMessage.messageIdentifier); 1102 | } 1103 | this._sentMessages = {}; 1104 | 1105 | for (key in this._receivedMessages) { 1106 | var receivedMessage = this._receivedMessages[key]; 1107 | localStorage.removeItem("Received:" + this._localKey + receivedMessage.messageIdentifier); 1108 | } 1109 | this._receivedMessages = {}; 1110 | } 1111 | // Client connected and ready for business. 1112 | if (wireMessage.returnCode === 0) { 1113 | this.connected = true; 1114 | // Jump to the end of the list of hosts and stop looking for a good host. 1115 | if (this.connectOptions.hosts) 1116 | this.hostIndex = this.connectOptions.hosts.length; 1117 | } else { 1118 | this._disconnected(ERROR.CONNACK_RETURNCODE.code, format(ERROR.CONNACK_RETURNCODE, [wireMessage.returnCode, CONNACK_RC[wireMessage.returnCode]])); 1119 | break; 1120 | } 1121 | 1122 | // Resend messages. 1123 | var sequencedMessages = new Array(); 1124 | for (var msgId in this._sentMessages) { 1125 | if (this._sentMessages.hasOwnProperty(msgId)) 1126 | sequencedMessages.push(this._sentMessages[msgId]); 1127 | } 1128 | 1129 | // Sort sentMessages into the original sent order. 1130 | var sequencedMessages = sequencedMessages.sort(function (a, b) { 1131 | return a.sequence - b.sequence; 1132 | }); 1133 | for (var i = 0, len = sequencedMessages.length; i < len; i++) { 1134 | var sentMessage = sequencedMessages[i]; 1135 | if (sentMessage.type == MESSAGE_TYPE.PUBLISH && sentMessage.pubRecReceived) { 1136 | var pubRelMessage = new WireMessage(MESSAGE_TYPE.PUBREL, {messageIdentifier: sentMessage.messageIdentifier}); 1137 | this._schedule_message(pubRelMessage); 1138 | } else { 1139 | this._schedule_message(sentMessage); 1140 | } 1141 | ; 1142 | } 1143 | 1144 | // Execute the connectOptions.onSuccess callback if there is one. 1145 | if (this.connectOptions.onSuccess) { 1146 | this.connectOptions.onSuccess({invocationContext: this.connectOptions.invocationContext}); 1147 | } 1148 | 1149 | // Process all queued messages now that the connection is established. 1150 | this._process_queue(); 1151 | break; 1152 | 1153 | case MESSAGE_TYPE.PUBLISH: 1154 | this._receivePublish(wireMessage); 1155 | break; 1156 | 1157 | case MESSAGE_TYPE.PUBACK: 1158 | var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; 1159 | // If this is a re flow of a PUBACK after we have restarted receivedMessage will not exist. 1160 | if (sentMessage) { 1161 | delete this._sentMessages[wireMessage.messageIdentifier]; 1162 | localStorage.removeItem("Sent:" + this._localKey + wireMessage.messageIdentifier); 1163 | if (this.onMessageDelivered) 1164 | this.onMessageDelivered(sentMessage.payloadMessage); 1165 | } 1166 | break; 1167 | 1168 | case MESSAGE_TYPE.PUBREC: 1169 | var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; 1170 | // If this is a re flow of a PUBREC after we have restarted receivedMessage will not exist. 1171 | if (sentMessage) { 1172 | sentMessage.pubRecReceived = true; 1173 | var pubRelMessage = new WireMessage(MESSAGE_TYPE.PUBREL, {messageIdentifier: wireMessage.messageIdentifier}); 1174 | this.store("Sent:", sentMessage); 1175 | this._schedule_message(pubRelMessage); 1176 | } 1177 | break; 1178 | 1179 | case MESSAGE_TYPE.PUBREL: 1180 | var receivedMessage = this._receivedMessages[wireMessage.messageIdentifier]; 1181 | localStorage.removeItem("Received:" + this._localKey + wireMessage.messageIdentifier); 1182 | // If this is a re flow of a PUBREL after we have restarted receivedMessage will not exist. 1183 | if (receivedMessage) { 1184 | this._receiveMessage(receivedMessage); 1185 | delete this._receivedMessages[wireMessage.messageIdentifier]; 1186 | } 1187 | // Always flow PubComp, we may have previously flowed PubComp but the server lost it and restarted. 1188 | pubCompMessage = new WireMessage(MESSAGE_TYPE.PUBCOMP, {messageIdentifier: wireMessage.messageIdentifier}); 1189 | this._schedule_message(pubCompMessage); 1190 | 1191 | 1192 | break; 1193 | 1194 | case MESSAGE_TYPE.PUBCOMP: 1195 | var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; 1196 | delete this._sentMessages[wireMessage.messageIdentifier]; 1197 | localStorage.removeItem("Sent:" + this._localKey + wireMessage.messageIdentifier); 1198 | if (this.onMessageDelivered) 1199 | this.onMessageDelivered(sentMessage.payloadMessage); 1200 | break; 1201 | 1202 | case MESSAGE_TYPE.SUBACK: 1203 | var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; 1204 | if (sentMessage) { 1205 | if (sentMessage.timeOut) 1206 | sentMessage.timeOut.cancel(); 1207 | if (sentMessage.callback) { 1208 | sentMessage.callback(); 1209 | } 1210 | delete this._sentMessages[wireMessage.messageIdentifier]; 1211 | } 1212 | break; 1213 | 1214 | case MESSAGE_TYPE.UNSUBACK: 1215 | var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; 1216 | if (sentMessage) { 1217 | if (sentMessage.timeOut) 1218 | sentMessage.timeOut.cancel(); 1219 | if (sentMessage.callback) { 1220 | sentMessage.callback(); 1221 | } 1222 | delete this._sentMessages[wireMessage.messageIdentifier]; 1223 | } 1224 | 1225 | break; 1226 | 1227 | case MESSAGE_TYPE.PINGRESP: 1228 | /* The sendPinger or receivePinger may have sent a ping, the receivePinger has already been reset. */ 1229 | this.sendPinger.reset(); 1230 | break; 1231 | 1232 | case MESSAGE_TYPE.DISCONNECT: 1233 | // Clients do not expect to receive disconnect packets. 1234 | this._disconnected(ERROR.INVALID_MQTT_MESSAGE_TYPE.code, format(ERROR.INVALID_MQTT_MESSAGE_TYPE, [wireMessage.type])); 1235 | break; 1236 | 1237 | default: 1238 | this._disconnected(ERROR.INVALID_MQTT_MESSAGE_TYPE.code, format(ERROR.INVALID_MQTT_MESSAGE_TYPE, [wireMessage.type])); 1239 | } 1240 | ; 1241 | }; 1242 | 1243 | /** @ignore */ 1244 | ClientImpl.prototype._on_socket_error = function (error) { 1245 | this._disconnected(ERROR.SOCKET_ERROR.code, format(ERROR.SOCKET_ERROR, [error.data])); 1246 | }; 1247 | 1248 | /** @ignore */ 1249 | ClientImpl.prototype._on_socket_close = function () { 1250 | this._disconnected(ERROR.SOCKET_CLOSE.code, format(ERROR.SOCKET_CLOSE)); 1251 | }; 1252 | 1253 | /** @ignore */ 1254 | ClientImpl.prototype._socket_send = function (wireMessage) { 1255 | if (wireMessage.type == 1) { 1256 | var wireMessageMasked = this._traceMask(wireMessage, "password"); 1257 | this._trace("Client._socket_send", wireMessageMasked); 1258 | } 1259 | else this._trace("Client._socket_send", wireMessage); 1260 | 1261 | this.socket.send(wireMessage.encode()); 1262 | /* We have proved to the server we are alive. */ 1263 | this.sendPinger.reset(); 1264 | }; 1265 | 1266 | /** @ignore */ 1267 | ClientImpl.prototype._receivePublish = function (wireMessage) { 1268 | switch (wireMessage.payloadMessage.qos) { 1269 | case "undefined": 1270 | case 0: 1271 | this._receiveMessage(wireMessage); 1272 | break; 1273 | 1274 | case 1: 1275 | var pubAckMessage = new WireMessage(MESSAGE_TYPE.PUBACK, {messageIdentifier: wireMessage.messageIdentifier}); 1276 | this._schedule_message(pubAckMessage); 1277 | this._receiveMessage(wireMessage); 1278 | break; 1279 | 1280 | case 2: 1281 | this._receivedMessages[wireMessage.messageIdentifier] = wireMessage; 1282 | this.store("Received:", wireMessage); 1283 | var pubRecMessage = new WireMessage(MESSAGE_TYPE.PUBREC, {messageIdentifier: wireMessage.messageIdentifier}); 1284 | this._schedule_message(pubRecMessage); 1285 | 1286 | break; 1287 | 1288 | default: 1289 | throw Error("Invaild qos=" + wireMmessage.payloadMessage.qos); 1290 | } 1291 | ; 1292 | }; 1293 | 1294 | /** @ignore */ 1295 | ClientImpl.prototype._receiveMessage = function (wireMessage) { 1296 | if (this.onMessageArrived) { 1297 | this.onMessageArrived(wireMessage.payloadMessage); 1298 | } 1299 | }; 1300 | 1301 | /** 1302 | * @ignore 1303 | * Client has disconnected either at its own request or because the server 1304 | * or network disconnected it. Remove all non-durable state. 1305 | * @param {errorCode} [number] the error number. 1306 | * @param {errorText} [string] the error text. 1307 | */ 1308 | ClientImpl.prototype._disconnected = function (errorCode, errorText) { 1309 | this._trace("Client._disconnected", errorCode, errorText); 1310 | 1311 | this.sendPinger.cancel(); 1312 | this.receivePinger.cancel(); 1313 | if (this._connectTimeout) 1314 | this._connectTimeout.cancel(); 1315 | // Clear message buffers. 1316 | this._msg_queue = []; 1317 | this._notify_msg_sent = {}; 1318 | 1319 | if (this.socket) { 1320 | // Cancel all socket callbacks so that they cannot be driven again by this socket. 1321 | this.socket.onopen = null; 1322 | this.socket.onmessage = null; 1323 | this.socket.onerror = null; 1324 | this.socket.onclose = null; 1325 | if (this.socket.readyState === 1) 1326 | this.socket.close(); 1327 | delete this.socket; 1328 | } 1329 | 1330 | if (this.connectOptions.hosts && this.hostIndex < this.connectOptions.hosts.length - 1) { 1331 | // Try the next host. 1332 | this.hostIndex++; 1333 | this._doConnect(this.connectOptions.hosts[this.hostIndex], this.connectOptions.ports[this.hostIndex]); 1334 | 1335 | } else { 1336 | 1337 | if (errorCode === undefined) { 1338 | errorCode = ERROR.OK.code; 1339 | errorText = format(ERROR.OK); 1340 | } 1341 | 1342 | // Run any application callbacks last as they may attempt to reconnect and hence create a new socket. 1343 | if (this.connected) { 1344 | this.connected = false; 1345 | // Execute the connectionLostCallback if there is one, and we were connected. 1346 | if (this.onConnectionLost) 1347 | this.onConnectionLost({errorCode: errorCode, errorMessage: errorText}); 1348 | } else { 1349 | // Otherwise we never had a connection, so indicate that the connect has failed. 1350 | if (this.connectOptions.onFailure) 1351 | this.connectOptions.onFailure({invocationContext: this.connectOptions.invocationContext, errorCode: errorCode, errorMessage: errorText}); 1352 | } 1353 | } 1354 | }; 1355 | 1356 | /** @ignore */ 1357 | ClientImpl.prototype._trace = function () { 1358 | if (this._traceBuffer !== null) { 1359 | for (var i = 0, max = arguments.length; i < max; i++) { 1360 | if (this._traceBuffer.length == this._MAX_TRACE_ENTRIES) { 1361 | this._traceBuffer.shift(); 1362 | } 1363 | if (i === 0) this._traceBuffer.push(arguments[i]); 1364 | else if (typeof arguments[i] === "undefined") this._traceBuffer.push(arguments[i]); 1365 | else this._traceBuffer.push(" " + JSON.stringify(arguments[i])); 1366 | } 1367 | ; 1368 | } 1369 | ; 1370 | }; 1371 | 1372 | /** @ignore */ 1373 | ClientImpl.prototype._traceMask = function (traceObject, masked) { 1374 | var traceObjectMasked = {}; 1375 | for (var attr in traceObject) { 1376 | if (traceObject.hasOwnProperty(attr)) { 1377 | if (attr == masked) 1378 | traceObjectMasked[attr] = "******"; 1379 | else 1380 | traceObjectMasked[attr] = traceObject[attr]; 1381 | } 1382 | } 1383 | return traceObjectMasked; 1384 | }; 1385 | 1386 | // ------------------------------------------------------------------------ 1387 | // Public Programming interface. 1388 | // ------------------------------------------------------------------------ 1389 | 1390 | /** 1391 | * The JavaScript application communicates to the server using a Messaging.Client object. 1392 | *

    1393 | * Other programming languages, 1394 | * Java, 1395 | * C. 1396 | *

    1397 | * Most applications will create just one Client object and then call its connect() method, 1398 | * however applications can create more than one Client object if they wish. 1399 | * In this case the combination of host, port and clientId attributes must be different for each Client object. 1400 | *

    1401 | * The send, subscribe and unsubscribe methods are implemented as asynchronous JavaScript methods 1402 | * (even though the underlying protocol exchange might be synchronous in nature). 1403 | * This means they signal their completion by calling back to the application, 1404 | * via Success or Failure callback functions provided by the application on the method in question. 1405 | * Such callbacks are called at most once per method invocation and do not persist beyond the lifetime 1406 | * of the script that made the invocation. 1407 | *

    1408 | * In contrast there are some callback functions most notably onMessageArrived 1409 | * that are defined on the Messaging.Client object. 1410 | * These may get called multiple times, and aren't directly related to specific method invocations made by the client. 1411 | * 1412 | * @name Messaging.Client 1413 | * 1414 | * @constructor 1415 | * Creates a Messaging.Client object that can be used to communicate with a Messaging server. 1416 | * 1417 | * @param {string} host the address of the messaging server, as a DNS name or dotted decimal IP address. 1418 | * @param {number} port the port number in the host to connect to. 1419 | * @param {string} clientId the Messaging client identifier, between 1 and 23 characters in length. 1420 | * 1421 | * @property {string} host read only the server's DNS hostname or dotted decimal IP address. 1422 | * @property {number} port read only the server's port. 1423 | * @property {string} clientId read only used when connecting to the server. 1424 | * @property {function} onConnectionLost called when a connection has been lost, 1425 | * after a connect() method has succeeded. 1426 | * Establish the call back used when a connection has been lost. The connection may be 1427 | * lost because the client initiates a disconnect or because the server or network 1428 | * cause the client to be disconnected. The disconnect call back may be called without 1429 | * the connectionComplete call back being invoked if, for example the client fails to 1430 | * connect. 1431 | * A single response object parameter is passed to the onConnectionLost callback containing the following fields: 1432 | *

      1433 | *
    1. errorCode 1434 | *
    2. errorMessage 1435 | *
    1436 | * @property {function} onMessageDelivered called when a message has been delivered. 1437 | * All processing that this Client will ever do has been completed. So, for example, 1438 | * in the case of a Qos=2 message sent by this client, the PubComp flow has been received from the server 1439 | * and the message has been removed from persistent storage before this callback is invoked. 1440 | * Parameters passed to the onMessageDelivered callback are: 1441 | *
      1442 | *
    1. Messaging.Message that was delivered. 1443 | *
    1444 | * @property {function} onMessageArrived called when a message has arrived in this Messaging.client. 1445 | * Parameters passed to the onMessageArrived callback are: 1446 | *
      1447 | *
    1. Messaging.Message that has arrived. 1448 | *
    1449 | */ 1450 | var Client = function (host, port, clientId) { 1451 | if (typeof host !== "string") 1452 | throw new Error(format(ERROR.INVALID_TYPE, [typeof host, "host"])); 1453 | if (typeof port !== "number" || port < 0) 1454 | throw new Error(format(ERROR.INVALID_TYPE, [typeof port, "port"])); 1455 | 1456 | var clientIdLength = 0; 1457 | for (var i = 0; i < clientId.length; i++) { 1458 | var charCode = clientId.charCodeAt(i); 1459 | if (0xD800 <= charCode && charCode <= 0xDBFF) { 1460 | i++; // Surrogate pair. 1461 | } 1462 | clientIdLength++; 1463 | } 1464 | if (typeof clientId !== "string" || clientIdLength < 1 | clientIdLength > 23) 1465 | throw new Error(format(ERROR.INVALID_ARGUMENT, [clientId, "clientId"])); 1466 | 1467 | var client = new ClientImpl(host, port, clientId); 1468 | this._getHost = function () { 1469 | return client.host; 1470 | }; 1471 | this._setHost = function () { 1472 | throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); 1473 | }; 1474 | 1475 | this._getPort = function () { 1476 | return client.port; 1477 | }; 1478 | this._setPort = function () { 1479 | throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); 1480 | }; 1481 | 1482 | this._getClientId = function () { 1483 | return client.clientId; 1484 | }; 1485 | this._setClientId = function () { 1486 | throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); 1487 | }; 1488 | 1489 | this._getOnConnectionLost = function () { 1490 | return client.onConnectionLost; 1491 | }; 1492 | this._setOnConnectionLost = function (newOnConnectionLost) { 1493 | if (typeof newOnConnectionLost === "function") 1494 | client.onConnectionLost = newOnConnectionLost; 1495 | else 1496 | throw new Error(format(ERROR.INVALID_TYPE, [typeof newOnConnectionLost, "onConnectionLost"])); 1497 | }; 1498 | 1499 | this._getOnMessageDelivered = function () { 1500 | return client.onMessageDelivered; 1501 | }; 1502 | this._setOnMessageDelivered = function (newOnMessageDelivered) { 1503 | if (typeof newOnMessageDelivered === "function") 1504 | client.onMessageDelivered = newOnMessageDelivered; 1505 | else 1506 | throw new Error(format(ERROR.INVALID_TYPE, [typeof newOnMessageDelivered, "onMessageDelivered"])); 1507 | }; 1508 | 1509 | this._getOnMessageArrived = function () { 1510 | return client.onMessageArrived; 1511 | }; 1512 | this._setOnMessageArrived = function (newOnMessageArrived) { 1513 | if (typeof newOnMessageArrived === "function") 1514 | client.onMessageArrived = newOnMessageArrived; 1515 | else 1516 | throw new Error(format(ERROR.INVALID_TYPE, [typeof newOnMessageArrived, "onMessageArrived"])); 1517 | }; 1518 | 1519 | /** 1520 | * Connect this Messaging client to its server. 1521 | * 1522 | * @name Messaging.Client#connect 1523 | * @function 1524 | * @param {Object} [connectOptions] attributes used with the connection. 1525 | *

    1526 | * Properties of the connect options are: 1527 | * @config {number} [timeout] If the connect has not succeeded within this number of seconds, it is deemed to have failed. 1528 | * The default is 30 seconds. 1529 | * @config {string} [userName] Authentication username for this connection. 1530 | * @config {string} [password] Authentication password for this connection. 1531 | * @config {Messaging.Message} [willMessage] sent by the server when the client disconnects abnormally. 1532 | * @config {Number} [keepAliveInterval] the server disconnects this client if there is no activity for this 1533 | * number of seconds. The default value of 60 seconds is assumed if not set. 1534 | * @config {boolean} [cleanSession] if true(default) the client and server persistent state is deleted on successful connect. 1535 | * @config {boolean} [useSSL] if present and true, use an SSL Websocket connection. 1536 | * @config {object} [invocationContext] passed to the onSuccess callback or onFailure callback. 1537 | * @config {function} [onSuccess] called when the connect acknowledgement has been received from the server. 1538 | * A single response object parameter is passed to the onSuccess callback containing the following fields: 1539 | *

      1540 | *
    1. invocationContext as passed in to the onSuccess method in the connectOptions. 1541 | *
    1542 | * @config {function} [onFailure] called when the connect request has failed or timed out. 1543 | * A single response object parameter is passed to the onFailure callback containing the following fields: 1544 | *
      1545 | *
    1. invocationContext as passed in to the onFailure method in the connectOptions. 1546 | *
    2. errorCode a number indicating the nature of the error. 1547 | *
    3. errorMessage text describing the error. 1548 | *
    1549 | * @config {Array} [hosts] If present this set of hostnames is tried in order in place 1550 | * of the host and port paramater on the construtor. The hosts and the matching ports are tried one at at time in order until 1551 | * one of then succeeds. 1552 | * @config {Array} [ports] If present this set of ports matching the hosts. 1553 | * @throws {InvalidState} if the client is not in disconnected state. The client must have received connectionLost 1554 | * or disconnected before calling connect for a second or subsequent time. 1555 | */ 1556 | this.connect = function (connectOptions) { 1557 | connectOptions = connectOptions || {}; 1558 | validate(connectOptions, {timeout: "number", 1559 | userName: "string", 1560 | password: "string", 1561 | willMessage: "object", 1562 | keepAliveInterval: "number", 1563 | cleanSession: "boolean", 1564 | useSSL: "boolean", 1565 | invocationContext: "object", 1566 | onSuccess: "function", 1567 | onFailure: "function", 1568 | hosts: "object", 1569 | ports: "object"}); 1570 | 1571 | // If no keep alive interval is set, assume 60 seconds. 1572 | if (connectOptions.keepAliveInterval === undefined) 1573 | connectOptions.keepAliveInterval = 60; 1574 | 1575 | if (connectOptions.willMessage) { 1576 | if (!(connectOptions.willMessage instanceof Message)) 1577 | throw new Error(format(ERROR.INVALID_TYPE, [connectOptions.willMessage, "connectOptions.willMessage"])); 1578 | // The will message must have a payload that can be represented as a string. 1579 | // Cause the willMessage to throw an exception if this is not the case. 1580 | connectOptions.willMessage.stringPayload; 1581 | 1582 | if (typeof connectOptions.willMessage.destinationName === "undefined") 1583 | throw new Error(format(ERROR.INVALID_TYPE, [typeof connectOptions.willMessage.destinationName, "connectOptions.willMessage.destinationName"])); 1584 | } 1585 | if (typeof connectOptions.cleanSession === "undefined") 1586 | connectOptions.cleanSession = true; 1587 | if (connectOptions.hosts) { 1588 | if (!connectOptions.ports) 1589 | throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.ports, "connectOptions.ports"])); 1590 | if (!(connectOptions.hosts instanceof Array)) 1591 | throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts, "connectOptions.hosts"])); 1592 | if (!(connectOptions.ports instanceof Array)) 1593 | throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.ports, "connectOptions.ports"])); 1594 | if (connectOptions.hosts.length < 1) 1595 | throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts, "connectOptions.hosts"])); 1596 | if (connectOptions.hosts.length != connectOptions.ports.length) 1597 | throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.ports, "connectOptions.ports"])); 1598 | for (var i = 0; i < connectOptions.hosts.length; i++) { 1599 | if (typeof connectOptions.hosts[i] !== "string") 1600 | throw new Error(format(ERROR.INVALID_TYPE, [typeof connectOptions.hosts[i], "connectOptions.hosts[" + i + "]"])); 1601 | if (typeof connectOptions.ports[i] !== "number" || connectOptions.ports[i] < 0) 1602 | throw new Error(format(ERROR.INVALID_TYPE, [typeof connectOptions.ports[i], "connectOptions.ports[" + i + "]"])); 1603 | } 1604 | } 1605 | 1606 | client.connect(connectOptions); 1607 | }; 1608 | 1609 | /** 1610 | * Subscribe for messages, request receipt of a copy of messages sent to the destinations described by the filter. 1611 | * 1612 | * @name Messaging.Client#subscribe 1613 | * @function 1614 | * @param {string} filter describing the destinations to receive messages from. 1615 | *
    1616 | * @param {object} [subscribeOptions] used to control the subscription, as follows: 1617 | *

    1618 | * @config {number} [qos] the maiximum qos of any publications sent as a result of making this subscription. 1619 | * @config {object} [invocationContext] passed to the onSuccess callback or onFailure callback. 1620 | * @config {function} [onSuccess] called when the subscribe acknowledgement has been received from the server. 1621 | * A single response object parameter is passed to the onSuccess callback containing the following fields: 1622 | *

      1623 | *
    1. invocationContext if set in the subscribeOptions. 1624 | *
    1625 | * @config {function} [onFailure] called when the subscribe request has failed or timed out. 1626 | * A single response object parameter is passed to the onFailure callback containing the following fields: 1627 | *
      1628 | *
    1. invocationContext if set in the subscribeOptions. 1629 | *
    2. errorCode a number indicating the nature of the error. 1630 | *
    3. errorMessage text describing the error. 1631 | *
    1632 | * @config {number} [timeout] which if present determines the number of seconds after which the onFailure calback is called 1633 | * the presence of a timeout does not prevent the onSuccess callback from being called when the MQTT Suback is eventually received. 1634 | * @throws {InvalidState} if the client is not in connected state. 1635 | */ 1636 | this.subscribe = function (filter, subscribeOptions) { 1637 | if (typeof filter !== "string") 1638 | throw new Error("Invalid argument:" + filter); 1639 | subscribeOptions = subscribeOptions || {}; 1640 | validate(subscribeOptions, {qos: "number", 1641 | invocationContext: "object", 1642 | onSuccess: "function", 1643 | onFailure: "function", 1644 | timeout: "number" 1645 | }); 1646 | if (subscribeOptions.timeout && !subscribeOptions.onFailure) 1647 | throw new Error("subscribeOptions.timeout specified with no onFailure callback."); 1648 | if (typeof subscribeOptions.qos !== "undefined" 1649 | && !(subscribeOptions.qos === 0 || subscribeOptions.qos === 1 || subscribeOptions.qos === 2 )) 1650 | throw new Error(format(ERROR.INVALID_ARGUMENT, [subscribeOptions.qos, "subscribeOptions.qos"])); 1651 | client.subscribe(filter, subscribeOptions); 1652 | }; 1653 | 1654 | /** 1655 | * Unsubscribe for messages, stop receiving messages sent to destinations described by the filter. 1656 | * 1657 | * @name Messaging.Client#unsubscribe 1658 | * @function 1659 | * @param {string} filter describing the destinations to receive messages from. 1660 | * @param {object} [unsubscribeOptions] used to control the subscription, as follows: 1661 | *

    1662 | * @config {object} [invocationContext] passed to the onSuccess callback or onFailure callback. 1663 | * @config {function} [onSuccess] called when the unsubscribe acknowledgement has been receive dfrom the server. 1664 | * A single response object parameter is passed to the onSuccess callback containing the following fields: 1665 | *

      1666 | *
    1. invocationContext if set in the unsubscribeOptions. 1667 | *
    1668 | * @config {function} [onFailure] called when the unsubscribe request has failed or timed out. 1669 | * A single response object parameter is passed to the onFailure callback containing the following fields: 1670 | *
      1671 | *
    1. invocationContext if set in the unsubscribeOptions. 1672 | *
    2. errorCode a number indicating the nature of the error. 1673 | *
    3. errorMessage text describing the error. 1674 | *
    1675 | * @config {number} [timeout] which if present determines the number of seconds after which the onFailure callback is called, the 1676 | * presence of a timeout does not prevent the onSuccess callback from being called when the MQTT UnSuback is eventually received. 1677 | * @throws {InvalidState} if the client is not in connected state. 1678 | */ 1679 | this.unsubscribe = function (filter, unsubscribeOptions) { 1680 | if (typeof filter !== "string") 1681 | throw new Error("Invalid argument:" + filter); 1682 | unsubscribeOptions = unsubscribeOptions || {}; 1683 | validate(unsubscribeOptions, {invocationContext: "object", 1684 | onSuccess: "function", 1685 | onFailure: "function", 1686 | timeout: "number" 1687 | }); 1688 | if (unsubscribeOptions.timeout && !unsubscribeOptions.onFailure) 1689 | throw new Error("unsubscribeOptions.timeout specified with no onFailure callback."); 1690 | client.unsubscribe(filter, unsubscribeOptions); 1691 | }; 1692 | 1693 | /** 1694 | * Send a message to the consumers of the destination in the Message. 1695 | * 1696 | * @name Messaging.Client#send 1697 | * @function 1698 | * @param {Messaging.Message} message to send. 1699 | 1700 | * @throws {InvalidState} if the client is not in connected state. 1701 | */ 1702 | this.send = function (message) { 1703 | if (!(message instanceof Message)) 1704 | throw new Error("Invalid argument:" + typeof message); 1705 | if (typeof message.destinationName === "undefined") 1706 | throw new Error("Invalid parameter Message.destinationName:" + message.destinationName); 1707 | 1708 | client.send(message); 1709 | }; 1710 | 1711 | /** 1712 | * Normal disconnect of this Messaging client from its server. 1713 | * 1714 | * @name Messaging.Client#disconnect 1715 | * @function 1716 | * @throws {InvalidState} if the client is not in connected or connecting state. 1717 | */ 1718 | this.disconnect = function () { 1719 | client.disconnect(); 1720 | }; 1721 | 1722 | /** 1723 | * Get the contents of the trace log. 1724 | * 1725 | * @name Messaging.Client#getTraceLog 1726 | * @function 1727 | * @return {Object[]} tracebuffer containing the time ordered trace records. 1728 | */ 1729 | this.getTraceLog = function () { 1730 | return client.getTraceLog(); 1731 | } 1732 | 1733 | /** 1734 | * Start tracing. 1735 | * 1736 | * @name Messaging.Client#startTrace 1737 | * @function 1738 | */ 1739 | this.startTrace = function () { 1740 | client.startTrace(); 1741 | }; 1742 | 1743 | /** 1744 | * Stop tracing. 1745 | * 1746 | * @name Messaging.Client#stopTrace 1747 | * @function 1748 | */ 1749 | this.stopTrace = function () { 1750 | client.stopTrace(); 1751 | }; 1752 | }; 1753 | 1754 | Client.prototype = { 1755 | get host() { 1756 | return this._getHost(); 1757 | }, 1758 | set host(newHost) { 1759 | this._setHost(newHost); 1760 | }, 1761 | 1762 | get port() { 1763 | return this._getPort(); 1764 | }, 1765 | set port(newPort) { 1766 | this._setPort(newPort); 1767 | }, 1768 | 1769 | get clientId() { 1770 | return this._getClientId(); 1771 | }, 1772 | set clientId(newClientId) { 1773 | this._setClientId(newClientId); 1774 | }, 1775 | 1776 | get onConnectionLost() { 1777 | return this._getOnConnectionLost(); 1778 | }, 1779 | set onConnectionLost(newOnConnectionLost) { 1780 | this._setOnConnectionLost(newOnConnectionLost); 1781 | }, 1782 | 1783 | get onMessageDelivered() { 1784 | return this._getOnMessageDelivered(); 1785 | }, 1786 | set onMessageDelivered(newOnMessageDelivered) { 1787 | this._setOnMessageDelivered(newOnMessageDelivered); 1788 | }, 1789 | 1790 | get onMessageArrived() { 1791 | return this._getOnMessageArrived(); 1792 | }, 1793 | set onMessageArrived(newOnMessageArrived) { 1794 | this._setOnMessageArrived(newOnMessageArrived); 1795 | } 1796 | }; 1797 | 1798 | /** 1799 | * An application message, sent or received. 1800 | *

    1801 | * Other programming languages, 1802 | * Java, 1803 | * C. 1804 | *

    1805 | * All attributes may be null, which implies the default values. 1806 | * 1807 | * @name Messaging.Message 1808 | * @constructor 1809 | * @param {String|ArrayBuffer} payload The message data to be sent. 1810 | *

    1811 | * @property {string} payloadString read only The payload as a string if the payload consists of valid UTF-8 characters. 1812 | * @property {ArrayBuffer} payloadBytes read only The payload as an ArrayBuffer. 1813 | *

    1814 | * @property {string} destinationName mandatory The name of the destination to which the message is to be sent 1815 | * (for messages about to be sent) or the name of the destination from which the message has been received. 1816 | * (for messages received by the onMessage function). 1817 | *

    1818 | * @property {number} qos The Quality of Service used to deliver the message. 1819 | *

    1820 | *
    0 Best effort (default). 1821 | *
    1 At least once. 1822 | *
    2 Exactly once. 1823 | *
    1824 | *

    1825 | * @property {Boolean} retained If true, the message is to be retained by the server and delivered 1826 | * to both current and future subscriptions. 1827 | * If false the server only delivers the message to current subscribers, this is the default for new Messages. 1828 | * A received message has the retained boolean set to true if the message was published 1829 | * with the retained boolean set to true 1830 | * and the subscrption was made after the message has been published. 1831 | *

    1832 | * @property {Boolean} duplicate read only If true, this message might be a duplicate of one which has already been received. 1833 | * This is only set on messages received from the server. 1834 | * 1835 | */ 1836 | var Message = function (newPayload) { 1837 | var payload; 1838 | if (typeof newPayload === "string" 1839 | || newPayload instanceof ArrayBuffer 1840 | || newPayload instanceof Int8Array 1841 | || newPayload instanceof Uint8Array 1842 | || newPayload instanceof Int16Array 1843 | || newPayload instanceof Uint16Array 1844 | || newPayload instanceof Int32Array 1845 | || newPayload instanceof Uint32Array 1846 | || newPayload instanceof Float32Array 1847 | || newPayload instanceof Float64Array 1848 | ) { 1849 | payload = newPayload; 1850 | } else { 1851 | throw (format(ERROR.INVALID_ARGUMENT, [newPayload, "newPayload"])); 1852 | } 1853 | 1854 | this._getPayloadString = function () { 1855 | if (typeof payload === "string") 1856 | return payload; 1857 | else 1858 | return parseUTF8(payload, 0, payload.length); 1859 | }; 1860 | 1861 | this._getPayloadBytes = function () { 1862 | if (typeof payload === "string") { 1863 | var buffer = new ArrayBuffer(UTF8Length(payload)); 1864 | var byteStream = new Uint8Array(buffer); 1865 | stringToUTF8(payload, byteStream, 0); 1866 | 1867 | return byteStream; 1868 | } else { 1869 | return payload; 1870 | } 1871 | ; 1872 | }; 1873 | 1874 | var destinationName = undefined; 1875 | this._getDestinationName = function () { 1876 | return destinationName; 1877 | }; 1878 | this._setDestinationName = function (newDestinationName) { 1879 | if (typeof newDestinationName === "string") 1880 | destinationName = newDestinationName; 1881 | else 1882 | throw new Error(format(ERROR.INVALID_ARGUMENT, [newDestinationName, "newDestinationName"])); 1883 | }; 1884 | 1885 | var qos = 0; 1886 | this._getQos = function () { 1887 | return qos; 1888 | }; 1889 | this._setQos = function (newQos) { 1890 | if (newQos === 0 || newQos === 1 || newQos === 2) 1891 | qos = newQos; 1892 | else 1893 | throw new Error("Invalid argument:" + newQos); 1894 | }; 1895 | 1896 | var retained = false; 1897 | this._getRetained = function () { 1898 | return retained; 1899 | }; 1900 | this._setRetained = function (newRetained) { 1901 | if (typeof newRetained === "boolean") 1902 | retained = newRetained; 1903 | else 1904 | throw new Error(format(ERROR.INVALID_ARGUMENT, [newRetained, "newRetained"])); 1905 | }; 1906 | 1907 | var duplicate = false; 1908 | this._getDuplicate = function () { 1909 | return duplicate; 1910 | }; 1911 | this._setDuplicate = function (newDuplicate) { 1912 | duplicate = newDuplicate; 1913 | }; 1914 | }; 1915 | 1916 | Message.prototype = { 1917 | get payloadString() { 1918 | return this._getPayloadString(); 1919 | }, 1920 | get payloadBytes() { 1921 | return this._getPayloadBytes(); 1922 | }, 1923 | 1924 | get destinationName() { 1925 | return this._getDestinationName(); 1926 | }, 1927 | set destinationName(newDestinationName) { 1928 | this._setDestinationName(newDestinationName); 1929 | }, 1930 | 1931 | get qos() { 1932 | return this._getQos(); 1933 | }, 1934 | set qos(newQos) { 1935 | this._setQos(newQos); 1936 | }, 1937 | 1938 | get retained() { 1939 | return this._getRetained(); 1940 | }, 1941 | set retained(newRetained) { 1942 | this._setRetained(newRetained); 1943 | }, 1944 | 1945 | get duplicate() { 1946 | return this._getDuplicate(); 1947 | }, 1948 | set duplicate(newDuplicate) { 1949 | this._setDuplicate(newDuplicate); 1950 | } 1951 | }; 1952 | 1953 | // Module contents. 1954 | return { 1955 | Client: Client, 1956 | Message: Message 1957 | }; 1958 | })(window); 1959 | --------------------------------------------------------------------------------