├── .gitignore
├── LICENSE.txt
├── README.md
├── docs
├── asset-manifest.json
├── favicon.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
├── precache-manifest.77724a8e4f1aaf6ade30ce996aceb5ee.js
├── robots.txt
├── service-worker.js
└── static
│ ├── css
│ ├── 2.1a1504c9.chunk.css
│ ├── 2.1a1504c9.chunk.css.map
│ ├── main.34de6062.chunk.css
│ └── main.34de6062.chunk.css.map
│ └── js
│ ├── 2.eef3e905.chunk.js
│ ├── 2.eef3e905.chunk.js.map
│ ├── main.d9e65e74.chunk.js
│ ├── main.d9e65e74.chunk.js.map
│ ├── runtime-main.25df1f47.js
│ └── runtime-main.25df1f47.js.map
├── package-lock.json
├── package.json
├── public
├── favicon.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
└── robots.txt
└── src
├── App.css
├── App.js
├── App.test.js
├── components
├── ConnectForm.js
├── HeaderActions.js
├── MessageList.js
├── PublishForm.js
├── SubscribeForm.js
└── widgets.js
├── context
└── AppContext.js
├── index.css
├── index.js
├── logo.svg
├── serviceWorker.js
└── utils
├── client.js
├── store.js
└── utils.js
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 | fake.js
8 | .history
9 |
10 | # testing
11 | /coverage
12 |
13 | # production
14 | /build
15 |
16 | # misc
17 | .DS_Store
18 | .env.local
19 | .env.development.local
20 | .env.test.local
21 | .env.production.local
22 |
23 | npm-debug.log*
24 | yarn-debug.log*
25 | yarn-error.log*
26 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## MQTT Monitor
4 |
5 |
6 | **MQTT Monitor** is a simple Web UI for IoT developers, using `javascript` + `react` + `bootstrap` + `websocket` + `mqtt.js`.
7 |
8 | You can try it [here](https://blog.mcxiaoke.com/mqtt-monitor/).
9 |
10 | ------
11 |
12 | ## Licence
13 |
14 | Copyright 2019 github@mcxiaoke.com
15 |
16 | Licensed under the Apache License, Version 2.0 (the "License");
17 | you may not use this file except in compliance with the License.
18 | You may obtain a copy of the License at
19 |
20 | http://www.apache.org/licenses/LICENSE-2.0
21 |
22 | Unless required by applicable law or agreed to in writing, software
23 | distributed under the License is distributed on an "AS IS" BASIS,
24 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25 | See the License for the specific language governing permissions and
26 | limitations under the License.
27 |
--------------------------------------------------------------------------------
/docs/asset-manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "files": {
3 | "main.css": "./static/css/main.34de6062.chunk.css",
4 | "main.js": "./static/js/main.d9e65e74.chunk.js",
5 | "main.js.map": "./static/js/main.d9e65e74.chunk.js.map",
6 | "runtime-main.js": "./static/js/runtime-main.25df1f47.js",
7 | "runtime-main.js.map": "./static/js/runtime-main.25df1f47.js.map",
8 | "static/css/2.1a1504c9.chunk.css": "./static/css/2.1a1504c9.chunk.css",
9 | "static/js/2.eef3e905.chunk.js": "./static/js/2.eef3e905.chunk.js",
10 | "static/js/2.eef3e905.chunk.js.map": "./static/js/2.eef3e905.chunk.js.map",
11 | "index.html": "./index.html",
12 | "precache-manifest.77724a8e4f1aaf6ade30ce996aceb5ee.js": "./precache-manifest.77724a8e4f1aaf6ade30ce996aceb5ee.js",
13 | "service-worker.js": "./service-worker.js",
14 | "static/css/2.1a1504c9.chunk.css.map": "./static/css/2.1a1504c9.chunk.css.map",
15 | "static/css/main.34de6062.chunk.css.map": "./static/css/main.34de6062.chunk.css.map"
16 | },
17 | "entrypoints": [
18 | "static/js/runtime-main.25df1f47.js",
19 | "static/css/2.1a1504c9.chunk.css",
20 | "static/js/2.eef3e905.chunk.js",
21 | "static/css/main.34de6062.chunk.css",
22 | "static/js/main.d9e65e74.chunk.js"
23 | ]
24 | }
--------------------------------------------------------------------------------
/docs/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mcxiaoke/mqtt-monitor/13255557dd81028c420f6e20975a38beebd0f76b/docs/favicon.ico
--------------------------------------------------------------------------------
/docs/index.html:
--------------------------------------------------------------------------------
1 |
MQTT Web Client You need to enable JavaScript to run this app.
--------------------------------------------------------------------------------
/docs/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mcxiaoke/mqtt-monitor/13255557dd81028c420f6e20975a38beebd0f76b/docs/logo192.png
--------------------------------------------------------------------------------
/docs/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mcxiaoke/mqtt-monitor/13255557dd81028c420f6e20975a38beebd0f76b/docs/logo512.png
--------------------------------------------------------------------------------
/docs/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/docs/precache-manifest.77724a8e4f1aaf6ade30ce996aceb5ee.js:
--------------------------------------------------------------------------------
1 | self.__precacheManifest = (self.__precacheManifest || []).concat([
2 | {
3 | "revision": "866deeb5580c5efd6ddd462f924c1ba9",
4 | "url": "./index.html"
5 | },
6 | {
7 | "revision": "9b89af9add8d4d13dc93",
8 | "url": "./static/css/2.1a1504c9.chunk.css"
9 | },
10 | {
11 | "revision": "ef457ac82af93fe0042a",
12 | "url": "./static/css/main.34de6062.chunk.css"
13 | },
14 | {
15 | "revision": "9b89af9add8d4d13dc93",
16 | "url": "./static/js/2.eef3e905.chunk.js"
17 | },
18 | {
19 | "revision": "ef457ac82af93fe0042a",
20 | "url": "./static/js/main.d9e65e74.chunk.js"
21 | },
22 | {
23 | "revision": "e6fddde8e8d90e4b80fd",
24 | "url": "./static/js/runtime-main.25df1f47.js"
25 | }
26 | ]);
--------------------------------------------------------------------------------
/docs/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 |
--------------------------------------------------------------------------------
/docs/service-worker.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Welcome to your Workbox-powered service worker!
3 | *
4 | * You'll need to register this file in your web app and you should
5 | * disable HTTP caching for this file too.
6 | * See https://goo.gl/nhQhGp
7 | *
8 | * The rest of the code is auto-generated. Please don't update this file
9 | * directly; instead, make changes to your Workbox build configuration
10 | * and re-run your build process.
11 | * See https://goo.gl/2aRDsh
12 | */
13 |
14 | importScripts("https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");
15 |
16 | importScripts(
17 | "./precache-manifest.77724a8e4f1aaf6ade30ce996aceb5ee.js"
18 | );
19 |
20 | self.addEventListener('message', (event) => {
21 | if (event.data && event.data.type === 'SKIP_WAITING') {
22 | self.skipWaiting();
23 | }
24 | });
25 |
26 | workbox.core.clientsClaim();
27 |
28 | /**
29 | * The workboxSW.precacheAndRoute() method efficiently caches and responds to
30 | * requests for URLs in the manifest.
31 | * See https://goo.gl/S9QRab
32 | */
33 | self.__precacheManifest = [].concat(self.__precacheManifest || []);
34 | workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
35 |
36 | workbox.routing.registerNavigationRoute(workbox.precaching.getCacheKeyForURL("./index.html"), {
37 |
38 | blacklist: [/^\/_/,/\/[^/?]+\.[^/]+$/],
39 | });
40 |
--------------------------------------------------------------------------------
/docs/static/css/main.34de6062.chunk.css:
--------------------------------------------------------------------------------
1 | body{margin:0;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}code{font-family:source-code-pro,Menlo,Monaco,Consolas,Courier New,monospace}
2 | /*# sourceMappingURL=main.34de6062.chunk.css.map */
--------------------------------------------------------------------------------
/docs/static/css/main.34de6062.chunk.css.map:
--------------------------------------------------------------------------------
1 | {"version":3,"sources":["index.css"],"names":[],"mappings":"AAAA,KACE,QAAS,CACT,mIAEY,CACZ,kCAAmC,CACnC,iCACF,CAEA,KACE,uEAEF","file":"main.34de6062.chunk.css","sourcesContent":["body {\n margin: 0;\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", \"Roboto\", \"Oxygen\",\n \"Ubuntu\", \"Cantarell\", \"Fira Sans\", \"Droid Sans\", \"Helvetica Neue\",\n sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\ncode {\n font-family: source-code-pro, Menlo, Monaco, Consolas, \"Courier New\",\n monospace;\n}\n"]}
--------------------------------------------------------------------------------
/docs/static/js/main.d9e65e74.chunk.js:
--------------------------------------------------------------------------------
1 | (this["webpackJsonpmqtt-monitor"]=this["webpackJsonpmqtt-monitor"]||[]).push([[0],{116:function(e,t,n){e.exports=n(240)},123:function(e,t,n){},126:function(e,t){},128:function(e,t){},192:function(e,t){},194:function(e,t){},209:function(e,t){},210:function(e,t){},212:function(e,t){},214:function(e,t){},222:function(e,t){},224:function(e,t){},240:function(e,t,n){"use strict";n.r(t);var a=n(0),o=n.n(a),c=n(36),s=n.n(c),i=(n(121),n(122),n(123),n(44)),r=n(25),l=n(100),u=n(101),m=n(114),b=n(102),p=n(115),d=n(103),f=n.n(d),h=function(e,t){window.localStorage.setItem("mqtt_store_item_"+e,JSON.stringify(t))},g=function(e){var t=window.localStorage.getItem("mqtt_store_item_"+e);return t?JSON.parse(t):void 0},E=n(104),v=n.n(E),C=n(105),S=n.n(C)()(v.a),y=function(e,t,n){S.fire({icon:"success",title:e,text:t,toast:!0,position:"bottom",timer:n||3e3})},w=function(e,t,n){S.fire({icon:"error",title:e,text:t,toast:!0,position:"center",timer:n||5e3})},O=n(112),k=n(33),j=n(6),x=n(54),F=n.n(x),N=o.a.createContext({isConnected:!1,options:{},topics:new Set}),P=n(106),T=n.n(P),D=n(58),M=n(57),K=n(107),R=function(e){var t=e.ts;return o.a.createElement("small",null,o.a.createElement(T.a,{format:"YYYY-MM-DD HH:mm:ss",unix:!0},t)," ")},_=function(e){return 0===e?o.a.createElement(K.a,{pill:!0,variant:"danger"},"New!"):null},Y=function(e){var t=e.item,n=e.index,a=e.length;return o.a.createElement(D.a.Item,null,o.a.createElement(M.a,null,o.a.createElement(M.a.Body,null,o.a.createElement("strong",{className:"text-primary"},t.topic,": "),o.a.createElement("span",{className:"text-secondary"},t.message),o.a.createElement("small",{className:"pl-2"},"(",a-n,")"),o.a.createElement("span",{className:"pl-2"},o.a.createElement(R,{ts:t.ts})),o.a.createElement("span",{className:"pl-2"},o.a.createElement(_,{index:n})))))},B=function(e){var t=Object(a.useContext)(N).messages,n=t.map((function(e,n){return o.a.createElement(o.a.Fragment,{key:"item_"+n},o.a.createElement(Y,{item:e,index:n,length:t.length}))}));return o.a.createElement(D.a,{variant:"flush"},n)},H=n(15),W=n(19),q=n(113),I=n(16),U=n(7),G=function(e){return e.isConnected?o.a.createElement(I.a,{className:"btn-block",variant:"danger",type:"submit"},"Disconnect"):o.a.createElement(I.a,{className:"btn-block",variant:"primary",type:"submit"},"Connect")},J=function(e){var t=Object(a.useContext)(N),n=t.isConnected,c=Object(a.useState)(t.options),s=Object(q.a)(c,2),r=s[0],l=s[1],u=function(e){var t=e.target,n=t.name,a=t.value;l(Object.assign({},r,Object(i.a)({},n,a)))};return o.a.createElement(U.a,{onSubmit:function(t){t.preventDefault();var n={host:r.host,username:r.username||null,password:r.password||null};n.host&&e.onConnectFormSubmit&&e.onConnectFormSubmit(n)}},o.a.createElement(U.a.Row,null,o.a.createElement(U.a.Group,{as:j.a,xs:12,md:4,lg:4},o.a.createElement(U.a.Control,{disabled:n,onChange:u,name:"host",type:"text",value:r.host,placeholder:"ws://test.mosquitto.org:8080"})),o.a.createElement(U.a.Group,{as:j.a,xs:6,md:3,lg:3},o.a.createElement(U.a.Control,{disabled:n,onChange:u,name:"username",type:"text",value:r.username,placeholder:"Username"})),o.a.createElement(U.a.Group,{as:j.a,xs:6,md:2,lg:3},o.a.createElement(U.a.Control,{disabled:n,onChange:u,name:"password",type:"password",value:r.password,placeholder:"Password"})),o.a.createElement(j.a,{xs:12,md:3,lg:2},o.a.createElement(G,{isConnected:n}))))},A=n(110),L=function(e){var t=e.topics,n=e.onTopicClick,a=function(e){n&&n(e.target.textContent)},c=Object(r.a)(t).map((function(e){return o.a.createElement(A.CopyToClipboard,{key:e,text:e},o.a.createElement(I.a,{onClick:a,variant:"outline-success",className:"mr-2",size:"sm"},e))}));return o.a.createElement("p",{className:"m-0 p-0"},o.a.createElement("strong",null,"Subscribed Topics:"),c)},Q=function(e){var t=Object(a.useContext)(N),n=t.isConnected,c=t.topics,s=Object(a.useRef)(null),i=Object(a.useRef)(null),r=function(t){var n={subscribe:!0,topics:s.current.value};console.log("SubscribeForm.handleClick1 ",n),n.topics&&e.onSubscribeFormSubmit&&e.onSubscribeFormSubmit(n),s.current.value=""},l=function(t){var n={subscribe:!1,topics:i.current.value};console.log("SubscribeForm.handleClick2 ",n),n.topics&&e.onSubscribeFormSubmit&&e.onSubscribeFormSubmit(n),i.current.value=""},u=function(e){"Enter"===e.key&&(e.preventDefault(),e.target===s.current?r():e.target===i.current&&l())};return o.a.createElement(o.a.Fragment,null,o.a.createElement(U.a,null,o.a.createElement(U.a.Row,{className:"align-items-center"},o.a.createElement(j.a,{as:j.a,sm:6,md:3,className:"mb-3 mt-3"},o.a.createElement(U.a.Control,{onKeyUp:u,ref:s,name:"subscribe-topics",type:"text",placeholder:"topic/test"})),o.a.createElement(j.a,{sm:6,md:3},o.a.createElement(I.a,{className:"btn-block",name:"subscribe",variant:"primary",type:"button",disabled:!n,onClick:r},"Subscribe")),o.a.createElement(j.a,{sm:6,md:3,className:"mb-3 mt-3"},o.a.createElement(U.a.Control,{onKeyUp:u,ref:i,name:"unsubscribe-topics",type:"text",placeholder:"topic/test"})),o.a.createElement(j.a,{sm:6,md:3},o.a.createElement(I.a,{className:"btn-block",name:"unsubscribe",variant:"danger",type:"button",disabled:!n,onClick:l},"Unsubscibe")))),o.a.createElement(L,{topics:c,onTopicClick:function(e){console.log("onTopicClick",e),i.current.value=e}}))},V=function(e){var t=Object(a.useContext)(N),n=t.isConnected,c=t.topics,s=Object(a.useRef)(null),i=Object(a.useRef)(null);return o.a.createElement(o.a.Fragment,null,o.a.createElement(U.a,{onSubmit:function(t){t.preventDefault();var n={topic:s.current.value,message:i.current.value,callback:function(e){e||(i.current.value="")},isValid:function(){return n.topic&&n.message}};n.isValid()&&e.onPublishFormSubmit&&e.onPublishFormSubmit(n)}},o.a.createElement(U.a.Row,null,o.a.createElement(U.a.Group,{as:j.a,xs:12,md:3},o.a.createElement(U.a.Control,{ref:s,name:"publish-topic",type:"text",placeholder:"topic name"})),o.a.createElement(U.a.Group,{as:j.a,xs:12,md:7},o.a.createElement(U.a.Control,{ref:i,name:"publish-message",type:"text",placeholder:"message content"})),o.a.createElement(j.a,{xs:12,md:2},o.a.createElement(I.a,{className:"btn-block",name:"publish",variant:"primary",type:"submit",disabled:!n},"Publish")))),o.a.createElement(L,{topics:c,onTopicClick:function(e){console.log("onTopicClick",e),s.current.value=e}}))};var z=function(e){return o.a.createElement(W.a,{defaultActiveKey:"0",className:"w-100"},o.a.createElement(H.a,null,o.a.createElement(W.a.Toggle,{as:H.a.Header,className:"bg-dark",eventKey:"0"},o.a.createElement("span",{className:"text-white"}," Connect Options")),o.a.createElement(W.a.Collapse,{eventKey:"0"},o.a.createElement(H.a.Body,null,o.a.createElement(J,{onConnectFormSubmit:e.onConnectFormSubmit})))),o.a.createElement(H.a,null,o.a.createElement(W.a.Toggle,{as:H.a.Header,className:"bg-dark",eventKey:"1"},o.a.createElement("span",{className:"text-white"}," Subscribe Options")),o.a.createElement(W.a.Collapse,{eventKey:"1"},o.a.createElement(H.a.Body,null,o.a.createElement(Q,{onSubscribeFormSubmit:e.onSubscribeFormSubmit})))),o.a.createElement(H.a,null,o.a.createElement(W.a.Toggle,{as:H.a.Header,className:"bg-dark",eventKey:"2"},o.a.createElement("span",{className:"text-white"}," Publish Options")),o.a.createElement(W.a.Collapse,{eventKey:"2"},o.a.createElement(H.a.Body,null,o.a.createElement(V,{onPublishFormSubmit:e.onPublishFormSubmit})))))};function $(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,a)}return n}var X={host:"ws://test.mosquitto.org:8080",username:null,password:null},Z=new Set(["test/#","monitor/#","device/#"]),ee=function(e){function t(e){var n;Object(l.a)(this,t),(n=Object(m.a)(this,Object(b.a)(t).call(this,e))).onClearClick=function(){n.setState({messages:[]})},n.onConnectFormSubmit=function(e){console.log("onConnectFormSubmit ",e),n.state.isConnected?n.client.end():e&&e.host&&n.connect(e)},n.onSubscribeFormSubmit=function(e){console.log("onSubscribeFormSubmit ",e);var t=e.subscribe,a=e.topics;if(n.state.isConnected&&a){var o=a.split(" ");t?n.subscribe(o):n.unsubscribe(o)}},n.onPublishFormSubmit=function(e){console.log("onPublishFormFormSubmit ",e);var t=e.topic,a=e.message;t.includes("#")||t.includes("*")?w("Invalid Topics","Can not publish to wildcard topics"):n.state.isConnected&&t&&a&&n.publish(t,a,e.callback)};var a=g("options")||X;return n.state={isConnected:!1,needReconnect:!0,options:a,topics:new Set,messages:[]},n}return Object(p.a)(t,e),Object(u.a)(t,[{key:"render",value:function(){var e=this.state,t=e.messages,n=e.isConnected,a=t&&t.length>0,c=n?"p-2 text-primary":"p-2 text-secondary";return o.a.createElement(N.Provider,{value:this.state},o.a.createElement(O.a,null,o.a.createElement(k.a,{className:"justify-content-center"},o.a.createElement("h2",{className:c,as:j.a},"MQTT Web Client")),o.a.createElement(k.a,null,o.a.createElement(z,{onConnectFormSubmit:this.onConnectFormSubmit,onSubscribeFormSubmit:this.onSubscribeFormSubmit,onPublishFormSubmit:this.onPublishFormSubmit})),o.a.createElement(k.a,{className:"m-3"},o.a.createElement("h4",{as:j.a},"Received Messages")),o.a.createElement(k.a,null,o.a.createElement(B,null)),o.a.createElement(k.a,{className:"justify-content-end p-3"},a?o.a.createElement(I.a,{as:j.a,md:3,lg:2,onClick:this.onClearClick,variant:"outline-dark"},"Clear Messages"):null)))}},{key:"cleanTopics",value:function(e){var t,n;return n=e,t="[object String]"===Object.prototype.toString.call(n)?e.split(" "):(function(e){null!=e&&e[Symbol.iterator]}(e),e),Object(r.a)(t).map((function(e){return e.trim()})).filter(Boolean)}},{key:"publish",value:function(e,t,n){console.log("publish",e,t),this.client.publish(e,t,(function(a){a?console.log("publish fail:",a):(console.log("published:",e,t),y("Message Sent","message is sent to "+e)),n&&n(a)}))}},{key:"unsubscribe",value:function(e,t){var n=this,a=this.cleanTopics(e);console.log("unsubscribe to",a),this.client.unsubscribe(a,(function(e){if(e)console.error("unsubscribe fail:",e);else{console.log("unsubscribed to",a);var o=n.state.topics;a.forEach((function(e){o.delete(e)})),n.setState({topics:o})}t&&t(e)}))}},{key:"subscribe",value:function(e,t){var n=this,a=this.cleanTopics(e);console.log("subscribe to",a),this.client.subscribe(a,null,(function(e,o){e?(console.error("subscribe fail:",e),w("Subscribe Failed",e)):(console.log("subscribed to",o),n.setState({topics:new Set([].concat(Object(r.a)(a),Object(r.a)(n.state.topics)))}),y("Subscribe Success","subscribed topics: "+a)),t&&t(e,o)}))}},{key:"disconnect",value:function(){this.state.isConnected&&this.client.end((function(){console.log("disconnect end")}))}},{key:"onConnected",value:function(e){var t=this;console.log("connected to",e),y("MQTT Connected!","server is "+e.host),h("options",e),this.setState({isConnected:this.client.connected,options:e,messages:[]},(function(){var e;e=t.state.topics&&t.state.topics.length>0?t.state.topics:Z,t.subscribe(e,(function(e){if(!e){var n=F()().format("YYYY-MM-DD HH:mm:ss");t.client.publish("device/online","Web Monitor online at ".concat(n,"!"))}}))}))}},{key:"connect",value:function(e){var t=this,n=function(e){for(var t=1;t {\n window.localStorage.setItem(\"mqtt_store_item_\" + key, JSON.stringify(obj));\n};\n\nexport const storeClear = () => {\n window.localStorage.clear();\n};\n\nexport const storeGet = (key) => {\n let s = window.localStorage.getItem(\"mqtt_store_item_\" + key);\n return s ? JSON.parse(s) : undefined;\n};\n\nexport const storeDelete = (key) => {\n window.localStorage.removeItem(\"mqtt_store_item_\" + key);\n};\n\nexport const saveMessages = (host, messages) => {\n storeSet(host + \"_messages\", messages);\n};\n\nexport const loadMessages = (host) => {\n return storeGet(host + \"_messages\") || [];\n};\n\nexport const deleteMessages = (host) => {\n storeDelete(host + \"_messages\");\n};\n","import Swal from \"sweetalert2\";\nimport withReactContent from \"sweetalert2-react-content\";\n\nconst MySwal = withReactContent(Swal);\n// https://www.npmjs.com/package/sweetalert2\n// eslint-disable-next-line no-unused-vars\nexport const toastInfo = (title, message, timeout) => {\n MySwal.fire({\n icon: \"success\",\n title: title,\n text: message,\n toast: true,\n position: \"bottom\",\n timer: timeout || 3000\n });\n};\n\nexport const toastError = (title, message, timeout) => {\n MySwal.fire({\n icon: \"error\",\n title: title,\n text: message,\n toast: true,\n position: \"center\",\n timer: timeout || 5000\n });\n};\n\nexport const isIterable = function(obj) {\n // checks for null and undefined\n if (obj == null) {\n return false;\n }\n return typeof obj[Symbol.iterator] === \"function\";\n};\n\nexport const isString = function(obj) {\n return Object.prototype.toString.call(obj) === \"[object String]\";\n};\n","import React from \"react\";\n\nexport default React.createContext({\n isConnected: false,\n options: {},\n topics: new Set()\n});\n","import React, { useContext } from \"react\";\nimport Moment from \"react-moment\";\nimport ListGroup from \"react-bootstrap/ListGroup\";\nimport Media from \"react-bootstrap/Media\";\nimport Badge from \"react-bootstrap/Badge\";\nimport AppContext from \"../context/AppContext\";\n\nconst CreatedAt = ({ ts }) => {\n return (\n \n \n {ts}\n {\" \"}\n \n );\n};\n\nconst NewBadge = index => {\n return index === 0 ? (\n \n New!\n \n ) : null;\n};\n\nconst MessageItem = ({ item, index, length }) => {\n // const message = item.message.split(\"\\n\").map((i, k) => {\n // return (\n // \n // {i}\n // \n // \n // );\n // });\n return (\n \n \n \n {item.topic}: \n {item.message} \n ({length - index}) \n \n \n \n \n \n \n \n \n \n );\n};\n\nexport default props => {\n const { messages } = useContext(AppContext);\n const listItems = messages.map((item, index) => (\n \n \n \n ));\n return {listItems} ;\n};\n","import React, { useState, useContext } from \"react\";\nimport Col from \"react-bootstrap/Col\";\nimport Button from \"react-bootstrap/Button\";\nimport Form from \"react-bootstrap/Form\";\nimport AppContxt from \"../context/AppContext\";\n\nconst ConnectButton = ({ isConnected }) => {\n return isConnected ? (\n \n Disconnect\n \n ) : (\n \n Connect\n \n );\n};\n\nexport default (props) => {\n const ctx = useContext(AppContxt);\n const { isConnected } = ctx;\n const [options, setOptions] = useState(ctx.options);\n const handleChange = (e) => {\n const { name, value } = e.target;\n setOptions(Object.assign({}, options, { [name]: value }));\n };\n\n const handleSubmit = (e) => {\n e.preventDefault();\n // empty username not equal to no username\n const fixedOptions = {\n host: options.host,\n username: options.username || null,\n password: options.password || null\n };\n // console.log(\"ConnectForm.handleSubmit \", fixedOptions);\n fixedOptions.host && props.onConnectFormSubmit && props.onConnectFormSubmit(fixedOptions);\n };\n\n return (\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n );\n};\n","import React from \"react\";\nimport Button from \"react-bootstrap/Button\";\nimport { CopyToClipboard } from \"react-copy-to-clipboard\";\n\nexport const TopicInfo = ({ topics, onTopicClick }) => {\n const handleClick = (e) => {\n onTopicClick && onTopicClick(e.target.textContent);\n };\n const tps = [...topics].map((text) => {\n return (\n \n \n {text}\n \n \n );\n });\n return (\n \n Subscribed Topics: \n {tps}\n
\n );\n};\n\nexport const SimpleInfo = ({ name, value }) => {\n return (\n \n {name} \n {value} \n
\n );\n};","import React, { useRef, useContext } from \"react\";\nimport Col from \"react-bootstrap/Col\";\nimport Button from \"react-bootstrap/Button\";\nimport Form from \"react-bootstrap/Form\";\nimport AppContxt from \"../context/AppContext\";\nimport { TopicInfo } from \"./widgets\";\n\nexport default (props) => {\n const { isConnected, topics } = useContext(AppContxt);\n const topicInput1 = useRef(null);\n const topicInput2 = useRef(null);\n\n const handleClick1 = (e) => {\n const options = {\n subscribe: true,\n topics: topicInput1.current.value\n };\n console.log(\"SubscribeForm.handleClick1 \", options);\n options.topics && props.onSubscribeFormSubmit && props.onSubscribeFormSubmit(options);\n topicInput1.current.value = \"\";\n };\n\n const handleClick2 = (e) => {\n const options = {\n subscribe: false,\n topics: topicInput2.current.value\n };\n console.log(\"SubscribeForm.handleClick2 \", options);\n options.topics && props.onSubscribeFormSubmit && props.onSubscribeFormSubmit(options);\n topicInput2.current.value = \"\";\n };\n\n // Pressing the enter key triggers the click handler of the first type=\"submit\" button\n // https://dzello.com/blog/2017/02/19/demystifying-enter-key-submission-for-react-forms/\n const handleKeyUp = (e) => {\n if (e.key === \"Enter\") {\n e.preventDefault();\n if (e.target === topicInput1.current) {\n handleClick1(null);\n } else if (e.target === topicInput2.current) {\n handleClick2(null);\n }\n }\n };\n\n const onTopicClick = (topic) => {\n console.log(\"onTopicClick\", topic);\n topicInput2.current.value = topic;\n };\n\n return (\n \n \n \n \n \n \n \n Subscribe\n \n \n \n \n \n \n \n Unsubscibe\n \n \n \n \n \n \n );\n};\n","import React, { useRef, useContext } from \"react\";\nimport Col from \"react-bootstrap/Col\";\nimport Button from \"react-bootstrap/Button\";\nimport Form from \"react-bootstrap/Form\";\nimport AppContxt from \"../context/AppContext\";\nimport { TopicInfo } from \"./widgets\";\n\nexport default (props) => {\n const { isConnected, topics } = useContext(AppContxt);\n const topicInput = useRef(null);\n const messageInput = useRef(null);\n\n const handleSubmit = (e) => {\n e.preventDefault();\n const options = {\n topic: topicInput.current.value,\n message: messageInput.current.value,\n callback: (err) => {\n if (!err) {\n messageInput.current.value = \"\";\n }\n },\n isValid: () => {\n return options.topic && options.message;\n }\n };\n // console.log(\"PublishForm.handleSubmit \", options);\n options.isValid() && props.onPublishFormSubmit && props.onPublishFormSubmit(options);\n };\n\n const onTopicClick = (topic) => {\n console.log(\"onTopicClick\", topic);\n topicInput.current.value = topic;\n };\n\n return (\n <>\n \n \n \n \n \n \n \n \n \n Publish\n \n \n \n \n \n >\n );\n};\n\n// https://zacjones.io/handle-multiple-inputs-in-react-with-hooks\n// first approach, useState\n// need: onChange= ()=>{setServer}\n// use: user\n// const [server, setServer] = useState(\"\");\n// const [user, setUser] = useState(\"\");\n// const [pass, setPass] = useState(\"\");\n// second approach, useRef\n// need: ref={serverInput}\n// use: serverInput.current.value\n// const serverInput = useRef(null);\n// const userInput = useRef(null);\n// const passInput = useRef(null);\n// third approach\n// use callback function\n// need: onFormChange\n// use: onFormChnage(e){ e.target.name, e.target.value }\n// fourth approach\n// use useReducer\n// fix https://stackoverflow.com/questions/47012169/\n// let extraOpts = props.isConnected ? { disabled: \"disabled\" } : {};\n","import React from \"react\";\nimport Card from \"react-bootstrap/Card\";\nimport Accordion from \"react-bootstrap/Accordion\";\nimport ConnectForm from \"./ConnectForm\";\nimport SubscribeForm from \"./SubscribeForm\";\nimport PublishForm from \"./PublishForm\";\n\n// onFormSubmit={this.onFormSubmit}\n// isConnected={this.state.isConnected}\n// options={this.state.options}\n// eslint-disable-next-line\nfunction FormCard(props) {\n return (\n \n \n {props.title} \n \n \n {props.children} \n \n \n );\n}\n\nexport default (props) => {\n return (\n \n {/* Connect Form Card */}\n \n \n Connect Options \n \n \n \n \n \n \n \n {/* Subscribe Form Card */}\n \n \n Subscribe Options \n \n \n \n \n \n \n \n {/* Publish Form Card */}\n \n \n Publish Options \n \n \n \n \n \n \n \n \n );\n};\n","import React from \"react\";\nimport mqtt from \"mqtt\";\nimport * as store from \"./utils/store\";\nimport { isIterable, isString, toastInfo, toastError } from \"./utils/utils\";\nimport Container from \"react-bootstrap/Container\";\nimport Row from \"react-bootstrap/Row\";\nimport Col from \"react-bootstrap/Col\";\nimport moment from \"moment\";\nimport AppContext from \"./context/AppContext\";\nimport MessageList from \"./components/MessageList\";\nimport HeaderActions from \"./components/HeaderActions\";\nimport Button from \"react-bootstrap/Button\";\n\nconst MQTT_OPTIONS = {\n host: \"ws://test.mosquitto.org:8080\",\n username: null,\n password: null\n};\n\nconst DEFAULT_TOPICS = new Set([\"test/#\", \"monitor/#\", \"device/#\"]);\n\nexport default class App extends React.Component {\n constructor(props) {\n super(props);\n const options = store.storeGet(\"options\") || MQTT_OPTIONS;\n this.state = {\n isConnected: false,\n needReconnect: true,\n options: options,\n topics: new Set(),\n messages: []\n };\n }\n\n render() {\n const { messages, isConnected } = this.state;\n const showClearButton = messages && messages.length > 0;\n const clsNames = isConnected ? \"p-2 text-primary\" : \"p-2 text-secondary\";\n return (\n \n \n \n \n MQTT Web Client\n \n
\n \n \n
\n \n Received Messages \n
\n \n \n
\n \n {showClearButton ? (\n \n Clear Messages\n \n ) : null}\n
\n \n \n );\n }\n\n onClearClick = () => {\n this.setState({ messages: [] });\n };\n\n onConnectFormSubmit = options => {\n console.log(\"onConnectFormSubmit \", options);\n if (this.state.isConnected) {\n this.client.end();\n } else {\n if (options && options.host) {\n this.connect(options);\n // this.setState({ options: options }, () => {\n // this.checkConnect();\n // });\n }\n }\n };\n\n onSubscribeFormSubmit = options => {\n console.log(\"onSubscribeFormSubmit \", options);\n const { subscribe, topics } = options;\n if (this.state.isConnected && topics) {\n const theTopics = topics.split(\" \");\n if (subscribe) {\n this.subscribe(theTopics);\n } else {\n this.unsubscribe(theTopics);\n }\n }\n };\n\n onPublishFormSubmit = options => {\n console.log(\"onPublishFormFormSubmit \", options);\n const { topic, message } = options;\n if (topic.includes(\"#\") || topic.includes(\"*\")) {\n toastError(\"Invalid Topics\", \"Can not publish to wildcard topics\");\n return;\n }\n if (this.state.isConnected && topic && message) {\n this.publish(topic, message, options.callback);\n }\n };\n\n cleanTopics(inTopics) {\n let topics;\n if (isString(inTopics)) {\n topics = inTopics.split(\" \");\n } else if (isIterable(inTopics)) {\n topics = inTopics;\n } else {\n topics = inTopics;\n }\n return [...topics].map(it => it.trim()).filter(Boolean);\n }\n\n publish(topic, message, callback) {\n console.log(\"publish\", topic, message);\n this.client.publish(topic, message, err => {\n if (!err) {\n console.log(\"published:\", topic, message);\n toastInfo(\"Message Sent\", \"message is sent to \" + topic);\n } else {\n console.log(\"publish fail:\", err);\n }\n callback && callback(err);\n });\n }\n\n unsubscribe(inTopics, callback) {\n const topics = this.cleanTopics(inTopics);\n console.log(\"unsubscribe to\", topics);\n this.client.unsubscribe(topics, err => {\n if (!err) {\n console.log(\"unsubscribed to\", topics);\n const newTopics = this.state.topics;\n topics.forEach(el => {\n newTopics.delete(el);\n });\n this.setState({ topics: newTopics });\n } else {\n console.error(\"unsubscribe fail:\", err);\n }\n callback && callback(err);\n });\n }\n\n subscribe(inTopics, callback) {\n const topics = this.cleanTopics(inTopics);\n console.log(\"subscribe to\", topics);\n this.client.subscribe(topics, null, (err, granted) => {\n if (!err) {\n console.log(\"subscribed to\", granted);\n this.setState({ topics: new Set([...topics, ...this.state.topics]) });\n toastInfo(\"Subscribe Success\", \"subscribed topics: \" + topics);\n } else {\n console.error(\"subscribe fail:\", err);\n toastError(\"Subscribe Failed\", err);\n }\n callback && callback(err, granted);\n });\n }\n\n disconnect() {\n this.state.isConnected &&\n this.client.end(() => {\n console.log(\"disconnect end\");\n });\n }\n\n onConnected(opts) {\n console.log(\"connected to\", opts);\n toastInfo(\"MQTT Connected!\", \"server is \" + opts.host);\n store.storeSet(\"options\", opts);\n this.setState(\n {\n isConnected: this.client.connected,\n options: opts,\n messages: []\n },\n () => {\n let topics;\n if (this.state.topics && this.state.topics.length > 0) {\n topics = this.state.topics;\n } else {\n topics = DEFAULT_TOPICS;\n }\n this.subscribe(topics, err => {\n if (!err) {\n const now = moment().format(\"YYYY-MM-DD HH:mm:ss\");\n this.client.publish(\"device/online\", `Web Monitor online at ${now}!`);\n }\n });\n }\n );\n }\n\n connect(opts) {\n let dateStr = new Date().toJSON().slice(0, 10).replaceAll('-', '');\n const connectOpts = { ...opts, reconnectPeriod: 120 * 1000, clientId: 'web_monitor_' + dateStr };\n console.log(\"connecting with\", connectOpts);\n this.client = mqtt.connect(opts.host, connectOpts);\n this.client.on(\"connect\", () => {\n this.onConnected(connectOpts);\n });\n this.client.on(\"disconnect\", () => {\n console.log(\"disconnect\");\n this.setState({ isConnected: this.client.connected });\n toastError(\n \"Connection Lost!\",\n \"Lost connection from \" + connectOpts.host\n );\n });\n this.client.on(\"reconnect\", () => {\n console.log(\"reconnect\");\n });\n this.client.on(\"offline\", () => {\n console.log(\"offline\");\n });\n this.client.on(\"close\", () => {\n console.log(\"close\");\n this.setState({ isConnected: this.client.connected });\n });\n this.client.on(\"error\", err => {\n console.log(\"Ooops\", \"Something is wrong!\", err);\n this.setState({ isConnected: this.client.connected });\n });\n this.client.stream.on(\"error\", err => {\n console.error(\"Connection error:\", err);\n toastError(\n \"Connection Error!\",\n \"Failed to connect to \" + connectOpts.host\n );\n });\n this.client.on(\"message\", (topic, message) => {\n // toastInfo(\"New Message\", message.toString() + \" (\" + topic + \")\");\n this.setState({\n messages: [\n {\n ts: Math.round(Date.now() / 1000),\n topic: topic,\n message: message.toString()\n },\n ...this.state.messages\n ]\n });\n });\n }\n\n checkConnect() {\n const options = this.state.options;\n options.host && options.host.startsWith(\"ws\") && this.connect(options);\n }\n\n componentDidMount() {\n console.log(\"componentDidMount\", this.state.options);\n }\n\n componentWillUnmount() {\n console.log(\"componentWillUnmount\");\n if (this.state.isConnected) {\n store.storeSet(\"options\", this.state.options);\n }\n // store.saveMessages(this.state.options.host, this.state.messages);\n }\n}\n","// This optional code is used to register a service worker.\n// register() is not called by default.\n\n// This lets the app load faster on subsequent visits in production, and gives\n// it offline capabilities. However, it also means that developers (and users)\n// will only see deployed updates on subsequent visits to a page, after all the\n// existing tabs open on the page have been closed, since previously cached\n// resources are updated in the background.\n\n// To learn more about the benefits of this model and instructions on how to\n// opt-in, read https://bit.ly/CRA-PWA\n\nconst isLocalhost = Boolean(\n window.location.hostname === 'localhost' ||\n // [::1] is the IPv6 localhost address.\n window.location.hostname === '[::1]' ||\n // 127.0.0.1/8 is considered localhost for IPv4.\n window.location.hostname.match(\n /^127(?:\\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/\n )\n);\n\nexport function register(config) {\n if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {\n // The URL constructor is available in all browsers that support SW.\n const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);\n if (publicUrl.origin !== window.location.origin) {\n // Our service worker won't work if PUBLIC_URL is on a different origin\n // from what our page is served on. This might happen if a CDN is used to\n // serve assets; see https://github.com/facebook/create-react-app/issues/2374\n return;\n }\n\n window.addEventListener('load', () => {\n const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;\n\n if (isLocalhost) {\n // This is running on localhost. Let's check if a service worker still exists or not.\n checkValidServiceWorker(swUrl, config);\n\n // Add some additional logging to localhost, pointing developers to the\n // service worker/PWA documentation.\n navigator.serviceWorker.ready.then(() => {\n console.log(\n 'This web app is being served cache-first by a service ' +\n 'worker. To learn more, visit https://bit.ly/CRA-PWA'\n );\n });\n } else {\n // Is not localhost. Just register service worker\n registerValidSW(swUrl, config);\n }\n });\n }\n}\n\nfunction registerValidSW(swUrl, config) {\n navigator.serviceWorker\n .register(swUrl)\n .then(registration => {\n registration.onupdatefound = () => {\n const installingWorker = registration.installing;\n if (installingWorker == null) {\n return;\n }\n installingWorker.onstatechange = () => {\n if (installingWorker.state === 'installed') {\n if (navigator.serviceWorker.controller) {\n // At this point, the updated precached content has been fetched,\n // but the previous service worker will still serve the older\n // content until all client tabs are closed.\n console.log(\n 'New content is available and will be used when all ' +\n 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'\n );\n\n // Execute callback\n if (config && config.onUpdate) {\n config.onUpdate(registration);\n }\n } else {\n // At this point, everything has been precached.\n // It's the perfect time to display a\n // \"Content is cached for offline use.\" message.\n console.log('Content is cached for offline use.');\n\n // Execute callback\n if (config && config.onSuccess) {\n config.onSuccess(registration);\n }\n }\n }\n };\n };\n })\n .catch(error => {\n console.error('Error during service worker registration:', error);\n });\n}\n\nfunction checkValidServiceWorker(swUrl, config) {\n // Check if the service worker can be found. If it can't reload the page.\n fetch(swUrl)\n .then(response => {\n // Ensure service worker exists, and that we really are getting a JS file.\n const contentType = response.headers.get('content-type');\n if (\n response.status === 404 ||\n (contentType != null && contentType.indexOf('javascript') === -1)\n ) {\n // No service worker found. Probably a different app. Reload the page.\n navigator.serviceWorker.ready.then(registration => {\n registration.unregister().then(() => {\n window.location.reload();\n });\n });\n } else {\n // Service worker found. Proceed as normal.\n registerValidSW(swUrl, config);\n }\n })\n .catch(() => {\n console.log(\n 'No internet connection found. App is running in offline mode.'\n );\n });\n}\n\nexport function unregister() {\n if ('serviceWorker' in navigator) {\n navigator.serviceWorker.ready.then(registration => {\n registration.unregister();\n });\n }\n}\n","import React from \"react\";\nimport ReactDOM from \"react-dom\";\nimport 'bootstrap/dist/css/bootstrap.min.css';\nimport '@sweetalert2/theme-bootstrap-4/bootstrap-4.css';\nimport \"./index.css\";\nimport App from \"./App\";\nimport * as serviceWorker from \"./serviceWorker\";\n\nReactDOM.render( , document.getElementById(\"root\"));\n\n// If you want your app to work offline and load faster, you can change\n// unregister() to register() below. Note this comes with some pitfalls.\n// Learn more about service workers: https://bit.ly/CRA-PWA\nserviceWorker.unregister();\n"],"sourceRoot":""}
--------------------------------------------------------------------------------
/docs/static/js/runtime-main.25df1f47.js:
--------------------------------------------------------------------------------
1 | !function(e){function t(t){for(var n,i,l=t[0],f=t[1],a=t[2],c=0,s=[];c0.2%",
57 | "not dead",
58 | "not op_mini all"
59 | ],
60 | "development": [
61 | "last 1 chrome version",
62 | "last 1 firefox version",
63 | "last 1 safari version"
64 | ]
65 | },
66 | "devDependencies": {
67 | "eslint-plugin-react-hooks": "^2.2.0"
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mcxiaoke/mqtt-monitor/13255557dd81028c420f6e20975a38beebd0f76b/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
15 |
16 |
25 |
27 | MQTT Web Client
28 |
29 |
30 |
31 | You need to enable JavaScript to run this app.
32 |
33 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mcxiaoke/mqtt-monitor/13255557dd81028c420f6e20975a38beebd0f76b/public/logo192.png
--------------------------------------------------------------------------------
/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mcxiaoke/mqtt-monitor/13255557dd81028c420f6e20975a38beebd0f76b/public/logo512.png
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 |
--------------------------------------------------------------------------------
/src/App.css:
--------------------------------------------------------------------------------
1 |
2 |
3 | .bottom-bubble {
4 | height: 40px;
5 | width: 100%;
6 | background-color: lightgray;
7 | padding: 4px;
8 | }
9 |
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import mqtt from "mqtt";
3 | import * as store from "./utils/store";
4 | import { isIterable, isString, toastInfo, toastError } from "./utils/utils";
5 | import Container from "react-bootstrap/Container";
6 | import Row from "react-bootstrap/Row";
7 | import Col from "react-bootstrap/Col";
8 | import moment from "moment";
9 | import AppContext from "./context/AppContext";
10 | import MessageList from "./components/MessageList";
11 | import HeaderActions from "./components/HeaderActions";
12 | import Button from "react-bootstrap/Button";
13 |
14 | const MQTT_OPTIONS = {
15 | host: "ws://test.mosquitto.org:8080",
16 | username: null,
17 | password: null
18 | };
19 |
20 | const DEFAULT_TOPICS = new Set(["test/#", "monitor/#", "device/#"]);
21 |
22 | export default class App extends React.Component {
23 | constructor(props) {
24 | super(props);
25 | const options = store.storeGet("options") || MQTT_OPTIONS;
26 | this.state = {
27 | isConnected: false,
28 | needReconnect: true,
29 | options: options,
30 | topics: new Set(),
31 | messages: []
32 | };
33 | }
34 |
35 | render() {
36 | const { messages, isConnected } = this.state;
37 | const showClearButton = messages && messages.length > 0;
38 | const clsNames = isConnected ? "p-2 text-primary" : "p-2 text-secondary";
39 | return (
40 |
41 |
42 |
43 |
44 | MQTT Web Client
45 |
46 |
47 |
48 |
53 |
54 |
55 | Received Messages
56 |
57 |
58 |
59 |
60 |
61 | {showClearButton ? (
62 |
69 | Clear Messages
70 |
71 | ) : null}
72 |
73 |
74 |
75 | );
76 | }
77 |
78 | onClearClick = () => {
79 | this.setState({ messages: [] });
80 | };
81 |
82 | onConnectFormSubmit = options => {
83 | console.log("onConnectFormSubmit ", options);
84 | if (this.state.isConnected) {
85 | this.client.end();
86 | } else {
87 | if (options && options.host) {
88 | this.connect(options);
89 | // this.setState({ options: options }, () => {
90 | // this.checkConnect();
91 | // });
92 | }
93 | }
94 | };
95 |
96 | onSubscribeFormSubmit = options => {
97 | console.log("onSubscribeFormSubmit ", options);
98 | const { subscribe, topics } = options;
99 | if (this.state.isConnected && topics) {
100 | const theTopics = topics.split(" ");
101 | if (subscribe) {
102 | this.subscribe(theTopics);
103 | } else {
104 | this.unsubscribe(theTopics);
105 | }
106 | }
107 | };
108 |
109 | onPublishFormSubmit = options => {
110 | console.log("onPublishFormFormSubmit ", options);
111 | const { topic, message } = options;
112 | if (topic.includes("#") || topic.includes("*")) {
113 | toastError("Invalid Topics", "Can not publish to wildcard topics");
114 | return;
115 | }
116 | if (this.state.isConnected && topic && message) {
117 | this.publish(topic, message, options.callback);
118 | }
119 | };
120 |
121 | cleanTopics(inTopics) {
122 | let topics;
123 | if (isString(inTopics)) {
124 | topics = inTopics.split(" ");
125 | } else if (isIterable(inTopics)) {
126 | topics = inTopics;
127 | } else {
128 | topics = inTopics;
129 | }
130 | return [...topics].map(it => it.trim()).filter(Boolean);
131 | }
132 |
133 | publish(topic, message, callback) {
134 | console.log("publish", topic, message);
135 | this.client.publish(topic, message, err => {
136 | if (!err) {
137 | console.log("published:", topic, message);
138 | toastInfo("Message Sent", "message is sent to " + topic);
139 | } else {
140 | console.log("publish fail:", err);
141 | }
142 | callback && callback(err);
143 | });
144 | }
145 |
146 | unsubscribe(inTopics, callback) {
147 | const topics = this.cleanTopics(inTopics);
148 | console.log("unsubscribe to", topics);
149 | this.client.unsubscribe(topics, err => {
150 | if (!err) {
151 | console.log("unsubscribed to", topics);
152 | const newTopics = this.state.topics;
153 | topics.forEach(el => {
154 | newTopics.delete(el);
155 | });
156 | this.setState({ topics: newTopics });
157 | } else {
158 | console.error("unsubscribe fail:", err);
159 | }
160 | callback && callback(err);
161 | });
162 | }
163 |
164 | subscribe(inTopics, callback) {
165 | const topics = this.cleanTopics(inTopics);
166 | console.log("subscribe to", topics);
167 | this.client.subscribe(topics, null, (err, granted) => {
168 | if (!err) {
169 | console.log("subscribed to", granted);
170 | this.setState({ topics: new Set([...topics, ...this.state.topics]) });
171 | toastInfo("Subscribe Success", "subscribed topics: " + topics);
172 | } else {
173 | console.error("subscribe fail:", err);
174 | toastError("Subscribe Failed", err);
175 | }
176 | callback && callback(err, granted);
177 | });
178 | }
179 |
180 | disconnect() {
181 | this.state.isConnected &&
182 | this.client.end(() => {
183 | console.log("disconnect end");
184 | });
185 | }
186 |
187 | onConnected(opts) {
188 | console.log("connected to", opts);
189 | toastInfo("MQTT Connected!", "server is " + opts.host);
190 | store.storeSet("options", opts);
191 | this.setState(
192 | {
193 | isConnected: this.client.connected,
194 | options: opts,
195 | messages: []
196 | },
197 | () => {
198 | let topics;
199 | if (this.state.topics && this.state.topics.length > 0) {
200 | topics = this.state.topics;
201 | } else {
202 | topics = DEFAULT_TOPICS;
203 | }
204 | this.subscribe(topics, err => {
205 | if (!err) {
206 | const now = moment().format("YYYY-MM-DD HH:mm:ss");
207 | this.client.publish("device/online", `Web Monitor online at ${now}!`);
208 | }
209 | });
210 | }
211 | );
212 | }
213 |
214 | connect(opts) {
215 | let dateStr = new Date().toJSON().slice(0, 10).replaceAll('-', '');
216 | const connectOpts = { ...opts, reconnectPeriod: 120 * 1000, clientId: 'web_monitor_' + dateStr };
217 | console.log("connecting with", connectOpts);
218 | this.client = mqtt.connect(opts.host, connectOpts);
219 | this.client.on("connect", () => {
220 | this.onConnected(connectOpts);
221 | });
222 | this.client.on("disconnect", () => {
223 | console.log("disconnect");
224 | this.setState({ isConnected: this.client.connected });
225 | toastError(
226 | "Connection Lost!",
227 | "Lost connection from " + connectOpts.host
228 | );
229 | });
230 | this.client.on("reconnect", () => {
231 | console.log("reconnect");
232 | });
233 | this.client.on("offline", () => {
234 | console.log("offline");
235 | });
236 | this.client.on("close", () => {
237 | console.log("close");
238 | this.setState({ isConnected: this.client.connected });
239 | });
240 | this.client.on("error", err => {
241 | console.log("Ooops", "Something is wrong!", err);
242 | this.setState({ isConnected: this.client.connected });
243 | });
244 | this.client.stream.on("error", err => {
245 | console.error("Connection error:", err);
246 | toastError(
247 | "Connection Error!",
248 | "Failed to connect to " + connectOpts.host
249 | );
250 | });
251 | this.client.on("message", (topic, message) => {
252 | // toastInfo("New Message", message.toString() + " (" + topic + ")");
253 | this.setState({
254 | messages: [
255 | {
256 | ts: Math.round(Date.now() / 1000),
257 | topic: topic,
258 | message: message.toString()
259 | },
260 | ...this.state.messages
261 | ]
262 | });
263 | });
264 | }
265 |
266 | checkConnect() {
267 | const options = this.state.options;
268 | options.host && options.host.startsWith("ws") && this.connect(options);
269 | }
270 |
271 | componentDidMount() {
272 | console.log("componentDidMount", this.state.options);
273 | }
274 |
275 | componentWillUnmount() {
276 | console.log("componentWillUnmount");
277 | if (this.state.isConnected) {
278 | store.storeSet("options", this.state.options);
279 | }
280 | // store.saveMessages(this.state.options.host, this.state.messages);
281 | }
282 | }
283 |
--------------------------------------------------------------------------------
/src/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import App from './App';
4 |
5 | it('renders without crashing', () => {
6 | const div = document.createElement('div');
7 | ReactDOM.render( , div);
8 | ReactDOM.unmountComponentAtNode(div);
9 | });
10 |
--------------------------------------------------------------------------------
/src/components/ConnectForm.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useContext } from "react";
2 | import Col from "react-bootstrap/Col";
3 | import Button from "react-bootstrap/Button";
4 | import Form from "react-bootstrap/Form";
5 | import AppContxt from "../context/AppContext";
6 |
7 | const ConnectButton = ({ isConnected }) => {
8 | return isConnected ? (
9 |
10 | Disconnect
11 |
12 | ) : (
13 |
14 | Connect
15 |
16 | );
17 | };
18 |
19 | export default (props) => {
20 | const ctx = useContext(AppContxt);
21 | const { isConnected } = ctx;
22 | const [options, setOptions] = useState(ctx.options);
23 | const handleChange = (e) => {
24 | const { name, value } = e.target;
25 | setOptions(Object.assign({}, options, { [name]: value }));
26 | };
27 |
28 | const handleSubmit = (e) => {
29 | e.preventDefault();
30 | // empty username not equal to no username
31 | const fixedOptions = {
32 | host: options.host,
33 | username: options.username || null,
34 | password: options.password || null
35 | };
36 | // console.log("ConnectForm.handleSubmit ", fixedOptions);
37 | fixedOptions.host && props.onConnectFormSubmit && props.onConnectFormSubmit(fixedOptions);
38 | };
39 |
40 | return (
41 |
43 |
44 |
52 |
53 |
54 |
62 |
63 |
64 |
72 |
73 |
74 |
75 |
76 |
77 |
78 | );
79 | };
80 |
--------------------------------------------------------------------------------
/src/components/HeaderActions.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import Card from "react-bootstrap/Card";
3 | import Accordion from "react-bootstrap/Accordion";
4 | import ConnectForm from "./ConnectForm";
5 | import SubscribeForm from "./SubscribeForm";
6 | import PublishForm from "./PublishForm";
7 |
8 | // onFormSubmit={this.onFormSubmit}
9 | // isConnected={this.state.isConnected}
10 | // options={this.state.options}
11 | // eslint-disable-next-line
12 | function FormCard(props) {
13 | return (
14 |
15 |
16 | {props.title}
17 |
18 |
19 | {props.children}
20 |
21 |
22 | );
23 | }
24 |
25 | export default (props) => {
26 | return (
27 |
28 | {/* Connect Form Card */}
29 |
30 |
31 | Connect Options
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 | {/* Subscribe Form Card */}
40 |
41 |
42 | Subscribe Options
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 | {/* Publish Form Card */}
51 |
52 |
53 | Publish Options
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 | );
63 | };
64 |
--------------------------------------------------------------------------------
/src/components/MessageList.js:
--------------------------------------------------------------------------------
1 | import React, { useContext } from "react";
2 | import Moment from "react-moment";
3 | import ListGroup from "react-bootstrap/ListGroup";
4 | import Media from "react-bootstrap/Media";
5 | import Badge from "react-bootstrap/Badge";
6 | import AppContext from "../context/AppContext";
7 |
8 | const CreatedAt = ({ ts }) => {
9 | return (
10 |
11 |
12 | {ts}
13 | {" "}
14 |
15 | );
16 | };
17 |
18 | const NewBadge = index => {
19 | return index === 0 ? (
20 |
21 | New!
22 |
23 | ) : null;
24 | };
25 |
26 | const MessageItem = ({ item, index, length }) => {
27 | // const message = item.message.split("\n").map((i, k) => {
28 | // return (
29 | //
30 | // {i}
31 | //
32 | //
33 | // );
34 | // });
35 | return (
36 |
37 |
38 |
39 | {item.topic}:
40 | {item.message}
41 | ({length - index})
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 | );
52 | };
53 |
54 | export default props => {
55 | const { messages } = useContext(AppContext);
56 | const listItems = messages.map((item, index) => (
57 |
58 |
59 |
60 | ));
61 | return {listItems} ;
62 | };
63 |
--------------------------------------------------------------------------------
/src/components/PublishForm.js:
--------------------------------------------------------------------------------
1 | import React, { useRef, useContext } from "react";
2 | import Col from "react-bootstrap/Col";
3 | import Button from "react-bootstrap/Button";
4 | import Form from "react-bootstrap/Form";
5 | import AppContxt from "../context/AppContext";
6 | import { TopicInfo } from "./widgets";
7 |
8 | export default (props) => {
9 | const { isConnected, topics } = useContext(AppContxt);
10 | const topicInput = useRef(null);
11 | const messageInput = useRef(null);
12 |
13 | const handleSubmit = (e) => {
14 | e.preventDefault();
15 | const options = {
16 | topic: topicInput.current.value,
17 | message: messageInput.current.value,
18 | callback: (err) => {
19 | if (!err) {
20 | messageInput.current.value = "";
21 | }
22 | },
23 | isValid: () => {
24 | return options.topic && options.message;
25 | }
26 | };
27 | // console.log("PublishForm.handleSubmit ", options);
28 | options.isValid() && props.onPublishFormSubmit && props.onPublishFormSubmit(options);
29 | };
30 |
31 | const onTopicClick = (topic) => {
32 | console.log("onTopicClick", topic);
33 | topicInput.current.value = topic;
34 | };
35 |
36 | return (
37 | <>
38 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 | Publish
49 |
50 |
51 |
52 |
53 |
54 | >
55 | );
56 | };
57 |
58 | // https://zacjones.io/handle-multiple-inputs-in-react-with-hooks
59 | // first approach, useState
60 | // need: onChange= ()=>{setServer}
61 | // use: user
62 | // const [server, setServer] = useState("");
63 | // const [user, setUser] = useState("");
64 | // const [pass, setPass] = useState("");
65 | // second approach, useRef
66 | // need: ref={serverInput}
67 | // use: serverInput.current.value
68 | // const serverInput = useRef(null);
69 | // const userInput = useRef(null);
70 | // const passInput = useRef(null);
71 | // third approach
72 | // use callback function
73 | // need: onFormChange
74 | // use: onFormChnage(e){ e.target.name, e.target.value }
75 | // fourth approach
76 | // use useReducer
77 | // fix https://stackoverflow.com/questions/47012169/
78 | // let extraOpts = props.isConnected ? { disabled: "disabled" } : {};
79 |
--------------------------------------------------------------------------------
/src/components/SubscribeForm.js:
--------------------------------------------------------------------------------
1 | import React, { useRef, useContext } from "react";
2 | import Col from "react-bootstrap/Col";
3 | import Button from "react-bootstrap/Button";
4 | import Form from "react-bootstrap/Form";
5 | import AppContxt from "../context/AppContext";
6 | import { TopicInfo } from "./widgets";
7 |
8 | export default (props) => {
9 | const { isConnected, topics } = useContext(AppContxt);
10 | const topicInput1 = useRef(null);
11 | const topicInput2 = useRef(null);
12 |
13 | const handleClick1 = (e) => {
14 | const options = {
15 | subscribe: true,
16 | topics: topicInput1.current.value
17 | };
18 | console.log("SubscribeForm.handleClick1 ", options);
19 | options.topics && props.onSubscribeFormSubmit && props.onSubscribeFormSubmit(options);
20 | topicInput1.current.value = "";
21 | };
22 |
23 | const handleClick2 = (e) => {
24 | const options = {
25 | subscribe: false,
26 | topics: topicInput2.current.value
27 | };
28 | console.log("SubscribeForm.handleClick2 ", options);
29 | options.topics && props.onSubscribeFormSubmit && props.onSubscribeFormSubmit(options);
30 | topicInput2.current.value = "";
31 | };
32 |
33 | // Pressing the enter key triggers the click handler of the first type="submit" button
34 | // https://dzello.com/blog/2017/02/19/demystifying-enter-key-submission-for-react-forms/
35 | const handleKeyUp = (e) => {
36 | if (e.key === "Enter") {
37 | e.preventDefault();
38 | if (e.target === topicInput1.current) {
39 | handleClick1(null);
40 | } else if (e.target === topicInput2.current) {
41 | handleClick2(null);
42 | }
43 | }
44 | };
45 |
46 | const onTopicClick = (topic) => {
47 | console.log("onTopicClick", topic);
48 | topicInput2.current.value = topic;
49 | };
50 |
51 | return (
52 |
53 |
55 |
56 |
63 |
64 |
65 |
73 | Subscribe
74 |
75 |
76 |
77 |
84 |
85 |
86 |
94 | Unsubscibe
95 |
96 |
97 |
98 |
99 |
100 |
101 | );
102 | };
103 |
--------------------------------------------------------------------------------
/src/components/widgets.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import Button from "react-bootstrap/Button";
3 | import { CopyToClipboard } from "react-copy-to-clipboard";
4 |
5 | export const TopicInfo = ({ topics, onTopicClick }) => {
6 | const handleClick = (e) => {
7 | onTopicClick && onTopicClick(e.target.textContent);
8 | };
9 | const tps = [...topics].map((text) => {
10 | return (
11 |
12 |
13 | {text}
14 |
15 |
16 | );
17 | });
18 | return (
19 |
20 | Subscribed Topics:
21 | {tps}
22 |
23 | );
24 | };
25 |
26 | export const SimpleInfo = ({ name, value }) => {
27 | return (
28 |
29 | {name}
30 | {value}
31 |
32 | );
33 | };
--------------------------------------------------------------------------------
/src/context/AppContext.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 |
3 | export default React.createContext({
4 | isConnected: false,
5 | options: {},
6 | topics: new Set()
7 | });
8 |
--------------------------------------------------------------------------------
/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
4 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
5 | sans-serif;
6 | -webkit-font-smoothing: antialiased;
7 | -moz-osx-font-smoothing: grayscale;
8 | }
9 |
10 | code {
11 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
12 | monospace;
13 | }
14 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import ReactDOM from "react-dom";
3 | import 'bootstrap/dist/css/bootstrap.min.css';
4 | import '@sweetalert2/theme-bootstrap-4/bootstrap-4.css';
5 | import "./index.css";
6 | import App from "./App";
7 | import * as serviceWorker from "./serviceWorker";
8 |
9 | ReactDOM.render( , document.getElementById("root"));
10 |
11 | // If you want your app to work offline and load faster, you can change
12 | // unregister() to register() below. Note this comes with some pitfalls.
13 | // Learn more about service workers: https://bit.ly/CRA-PWA
14 | serviceWorker.unregister();
15 |
--------------------------------------------------------------------------------
/src/logo.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.1/8 is considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl)
104 | .then(response => {
105 | // Ensure service worker exists, and that we really are getting a JS file.
106 | const contentType = response.headers.get('content-type');
107 | if (
108 | response.status === 404 ||
109 | (contentType != null && contentType.indexOf('javascript') === -1)
110 | ) {
111 | // No service worker found. Probably a different app. Reload the page.
112 | navigator.serviceWorker.ready.then(registration => {
113 | registration.unregister().then(() => {
114 | window.location.reload();
115 | });
116 | });
117 | } else {
118 | // Service worker found. Proceed as normal.
119 | registerValidSW(swUrl, config);
120 | }
121 | })
122 | .catch(() => {
123 | console.log(
124 | 'No internet connection found. App is running in offline mode.'
125 | );
126 | });
127 | }
128 |
129 | export function unregister() {
130 | if ('serviceWorker' in navigator) {
131 | navigator.serviceWorker.ready.then(registration => {
132 | registration.unregister();
133 | });
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/src/utils/client.js:
--------------------------------------------------------------------------------
1 | // mqtt client module
2 | import Paho from "paho-mqtt";
3 |
4 | function isValidURL(str) {
5 | // https://stackoverflow.com/questions/5717093
6 | // var parser = document.createElement("a");
7 | // parser.href = "http://example.com:3000/pathname/?search=test#hash";
8 |
9 | // parser.protocol; // => "http:"
10 | // parser.hostname; // => "example.com"
11 | // parser.port; // => "3000"
12 | // parser.pathname; // => "/pathname/"
13 | // parser.search; // => "?search=test"
14 | // parser.hash; // => "#hash"
15 | // parser.host; // => "example.com:3000"
16 | var a = document.createElement("a");
17 | a.href = str;
18 | return a.host && a.host !== window.location.host;
19 | }
20 |
21 | const getClientId = () => {
22 | return (
23 | "web_monitor_" +
24 | Math.random()
25 | .toString(16)
26 | .substr(2, 8)
27 | );
28 | };
29 |
30 | const Client = (serverUrl, options, onConnected2, onDisconnected, onMessageReceived) => {
31 | const url = new URL(serverUrl);
32 | const client = new Paho.Client(url.host, url.port, getClientId());
33 |
34 | const onConnLost = () => {
35 | console.log("onConnLost:");
36 | onDisconnected && onDisconnected();
37 | };
38 |
39 | const onConnected = (reconn, url) => {
40 | onConnected2 && onConnected2();
41 | };
42 |
43 | const onMessage = (message) => {
44 | console.log("onMessage:" + message.payloadString);
45 | onMessageReceived && onMessageReceived(message);
46 | };
47 |
48 | client.onConnectionLost = onConnLost;
49 | client.onMessageArrived = onMessage;
50 | client.onConnected = onConnected;
51 |
52 | const connect = (callback) => {
53 | client.connect({
54 | onSuccess: (res) => {
55 | console.log("connect success");
56 | client.subscribe("monitor/#");
57 | },
58 | onFailure: (res) => {
59 | console.log("connect failure", res);
60 | },
61 | timeout: 5000,
62 | userName: "",
63 | password: "",
64 | willMessage: null,
65 | cleanSession: false,
66 | reconnect: true,
67 | mqttVersion: 4
68 | });
69 | };
70 |
71 | const disconnect = (callback) => {
72 | client.disconnect();
73 | };
74 |
75 | const reconnect = () => { };
76 |
77 | const subscribe = (topics, callback) => {
78 | client.subscribe(topics, {
79 | onSuccess: (res) => {
80 | console.log("subscribe success");
81 | client.subscribe("monitor/#");
82 | },
83 | onFailure: (res) => {
84 | console.log("subscribe failure", res);
85 | },
86 | qos: 0
87 | // timeout: 3000
88 | });
89 | };
90 |
91 | const unsubscribe = (topics, callback) => {
92 | client.unsubscribe(topics, {
93 | onSuccess: (res) => {
94 | console.log("unsubscribe success");
95 | client.subscribe("monitor/#");
96 | },
97 | onFailure: (res) => {
98 | console.log("unsubscribe failure", res);
99 | },
100 | qos: 0
101 | // timeout: 3000
102 | });
103 | };
104 |
105 | const publish = (topic, message, callback) => {
106 | client.publish(topic, message);
107 | };
108 | };
109 |
110 | export default Client;
111 |
--------------------------------------------------------------------------------
/src/utils/store.js:
--------------------------------------------------------------------------------
1 | export const storeSet = (key, obj) => {
2 | window.localStorage.setItem("mqtt_store_item_" + key, JSON.stringify(obj));
3 | };
4 |
5 | export const storeClear = () => {
6 | window.localStorage.clear();
7 | };
8 |
9 | export const storeGet = (key) => {
10 | let s = window.localStorage.getItem("mqtt_store_item_" + key);
11 | return s ? JSON.parse(s) : undefined;
12 | };
13 |
14 | export const storeDelete = (key) => {
15 | window.localStorage.removeItem("mqtt_store_item_" + key);
16 | };
17 |
18 | export const saveMessages = (host, messages) => {
19 | storeSet(host + "_messages", messages);
20 | };
21 |
22 | export const loadMessages = (host) => {
23 | return storeGet(host + "_messages") || [];
24 | };
25 |
26 | export const deleteMessages = (host) => {
27 | storeDelete(host + "_messages");
28 | };
29 |
--------------------------------------------------------------------------------
/src/utils/utils.js:
--------------------------------------------------------------------------------
1 | import Swal from "sweetalert2";
2 | import withReactContent from "sweetalert2-react-content";
3 |
4 | const MySwal = withReactContent(Swal);
5 | // https://www.npmjs.com/package/sweetalert2
6 | // eslint-disable-next-line no-unused-vars
7 | export const toastInfo = (title, message, timeout) => {
8 | MySwal.fire({
9 | icon: "success",
10 | title: title,
11 | text: message,
12 | toast: true,
13 | position: "bottom",
14 | timer: timeout || 3000
15 | });
16 | };
17 |
18 | export const toastError = (title, message, timeout) => {
19 | MySwal.fire({
20 | icon: "error",
21 | title: title,
22 | text: message,
23 | toast: true,
24 | position: "center",
25 | timer: timeout || 5000
26 | });
27 | };
28 |
29 | export const isIterable = function(obj) {
30 | // checks for null and undefined
31 | if (obj == null) {
32 | return false;
33 | }
34 | return typeof obj[Symbol.iterator] === "function";
35 | };
36 |
37 | export const isString = function(obj) {
38 | return Object.prototype.toString.call(obj) === "[object String]";
39 | };
40 |
--------------------------------------------------------------------------------