Connection
29 |Publish
126 |-
203 |
204 |
Subscriptions
216 |-
261 |
262 |
├── img └── .gitkeep ├── js ├── hs.png ├── hv.png ├── arrow.gif ├── cross.gif ├── custom-combobox.js ├── jquery.minicolors.min.js ├── app.js ├── encoder.js └── mqttws31.js ├── config.js ├── assets ├── logo.png ├── arrow_up.png ├── arrow_down.png ├── jquery.minicolors.png ├── chevron-double-3-01.png ├── chevron-double-3-02.png └── hivemq-logo.svg ├── fancybox ├── blank.gif ├── fancybox.png ├── fancy_close.png ├── fancybox-x.png ├── fancybox-y.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 ├── .htaccess ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── HEADER ├── README.md ├── css ├── jquery.minicolors.css ├── style.css └── normalize.css ├── LICENSE └── index.html /img/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /js/hs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/js/hs.png -------------------------------------------------------------------------------- /js/hv.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/js/hv.png -------------------------------------------------------------------------------- /config.js: -------------------------------------------------------------------------------- 1 | websocketserver = 'broker.mqttdashboard.com'; 2 | websocketport = 8000; 3 | -------------------------------------------------------------------------------- /js/arrow.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/js/arrow.gif -------------------------------------------------------------------------------- /js/cross.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/js/cross.gif -------------------------------------------------------------------------------- /assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/assets/logo.png -------------------------------------------------------------------------------- /assets/arrow_up.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/assets/arrow_up.png -------------------------------------------------------------------------------- /fancybox/blank.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/fancybox/blank.gif -------------------------------------------------------------------------------- /assets/arrow_down.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/assets/arrow_down.png -------------------------------------------------------------------------------- /fancybox/fancybox.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/fancybox/fancybox.png -------------------------------------------------------------------------------- /fancybox/fancy_close.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/fancybox/fancy_close.png -------------------------------------------------------------------------------- /fancybox/fancybox-x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/fancybox/fancybox-x.png -------------------------------------------------------------------------------- /fancybox/fancybox-y.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/fancybox/fancybox-y.png -------------------------------------------------------------------------------- /fancybox/fancy_loading.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/fancybox/fancy_loading.png -------------------------------------------------------------------------------- /.htaccess: -------------------------------------------------------------------------------- 1 | RewriteEngine On 2 | RewriteCond %{HTTPS} =on 3 | RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI}$1 [L,R=301] -------------------------------------------------------------------------------- /assets/jquery.minicolors.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/assets/jquery.minicolors.png -------------------------------------------------------------------------------- /fancybox/fancy_nav_left.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/fancybox/fancy_nav_left.png -------------------------------------------------------------------------------- /fancybox/fancy_nav_right.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/fancybox/fancy_nav_right.png -------------------------------------------------------------------------------- /fancybox/fancy_shadow_e.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/fancybox/fancy_shadow_e.png -------------------------------------------------------------------------------- /fancybox/fancy_shadow_n.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/fancybox/fancy_shadow_n.png -------------------------------------------------------------------------------- /fancybox/fancy_shadow_ne.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/fancybox/fancy_shadow_ne.png -------------------------------------------------------------------------------- /fancybox/fancy_shadow_nw.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/fancybox/fancy_shadow_nw.png -------------------------------------------------------------------------------- /fancybox/fancy_shadow_s.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/fancybox/fancy_shadow_s.png -------------------------------------------------------------------------------- /fancybox/fancy_shadow_se.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/fancybox/fancy_shadow_se.png -------------------------------------------------------------------------------- /fancybox/fancy_shadow_sw.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/fancybox/fancy_shadow_sw.png -------------------------------------------------------------------------------- /fancybox/fancy_shadow_w.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/fancybox/fancy_shadow_w.png -------------------------------------------------------------------------------- /fancybox/fancy_title_left.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/fancybox/fancy_title_left.png -------------------------------------------------------------------------------- /fancybox/fancy_title_main.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/fancybox/fancy_title_main.png -------------------------------------------------------------------------------- /fancybox/fancy_title_over.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/fancybox/fancy_title_over.png -------------------------------------------------------------------------------- /assets/chevron-double-3-01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/assets/chevron-double-3-01.png -------------------------------------------------------------------------------- /assets/chevron-double-3-02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/assets/chevron-double-3-02.png -------------------------------------------------------------------------------- /fancybox/fancy_title_right.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hivemq/hivemq-mqtt-web-client/HEAD/fancybox/fancy_title_right.png -------------------------------------------------------------------------------- /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 | */ -------------------------------------------------------------------------------- /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 | }); -------------------------------------------------------------------------------- /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/hivemq-logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /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/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 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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){e27 | * 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 | *
39 | *
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 | *
75 | *
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 | *
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 | *
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 | *
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 | *
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 | *
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 | *
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 | --------------------------------------------------------------------------------