ctucx.git: mqtt-webui

webui for mqtt, can be used to control/display data in mqtt-topics

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80 
81 
82 
83 
84 
85 
86 
87 
88 
89 
90 
91 
92 
93 
94 
95 
96 
97 
98 
99 
100 
101 
102 
103 
104 
105 
106 
107 
108 
109 
110 
111 
112 
113 
114 
115 
116 
117 
118 
119 
120 
121 
122 
123 
124 
125 
126 
127 
128 
129 
130 
131 
132 
133 
134 
135 
136 
137 
138 
139 
140 
141 
142 
143 
144 
145 
146 
147 
148 
149 
150 
151 
152 
153 
154 
155 
156 
157 
158 
159 
160 
161 
162 
163 
164 
165 
166 
167 
168 
169 
170 
171 
172 
173 
174 
175 
176 
177 
178 
179 
180 
181 
182 
183 
184 
185 
186 
187 
188 
189 
190 
191 
192 
193 
194 
195 
196 
197 
198 
199 
200 
201 
202 
203 
204 
205 
206 
207 
208 
209 
210 
211 
212 
213 
214 
215 
216 
217 
218 
219 
220 
221 
222 
223 
224 
225 
226 
227 
228 
229 
230 
231 
232 
233 
234 
235 
236 
237 
238 
239 
240 
241 
242 
243 
244 
245 
246 
247 
248 
249 
250 
251 
252 
253 
254 
255 
256 
257 
258 
259 
260 
261 
262 
263 
264 
265 
266 
267 
268 
269 
270 
271 
272 
273 
274 
275 
276 
277 
278 
279 
280 
281 
282 
283 
284 
285 
286 
287 
288 
289 
290 
291 
292 
293 
294 
295 
296 
297 
298 
299 
300 
301 
302 
303 
304 
305 
306 
307 
308 
309 
310 
311 
312 
313 
314 
315 
316 
317 
318 
319 
320 
321 
322 
323 
324 
325 
326 
327 
328 
329 
330 
331 
332 
333 
334 
335 
336 
337 
338 
339 
340 
341 
342 
343 
344 
345 
346 
347 
348 
349 
350 
351 
352 
353 
354 
355 
356 
357 
358 
359 
360 
361 
362 
363 
364 
365 
366 
367 
368 
369 
370 
371 
372 
373 
374 
375 
376 
377 
378 
379 
380 
381 
382 
383 
384 
385 
386 
387 
388 
389 
390 
391 
392 
393 
394 
395 
396 
397 
398 
399 
400 
401 
402 
403 
404 
405 
406 
407 
408 
409 
410 
411 
412 
413 
414 
415 
416 
417 
418 
419 
420 
421 
422 
423 
424 
425 
426 
427 
428 
429 
430 
431 
432 
433 
434 
435 
436 
437 
438 
439 
440 
441 
442 
443 'use strict';

import "./webui.css";

import { html, render } from 'lit-html';
import { map }          from 'lit-html/directives/map.js';
import { ifDefined }    from 'lit-html/directives/if-defined.js';
import { unsafeSVG }    from 'lit-html/directives/unsafe-svg.js';
import { unsafeHTML }    from 'lit-html/directives/unsafe-html.js';

import { connect }      from "mqtt";

var client;

const connectedSvg    = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-wifi"><path d="M5 12.55a11 11 0 0 1 14.08 0"></path><path d="M1.42 9a16 16 0 0 1 21.16 0"></path><path d="M8.53 16.11a6 6 0 0 1 6.95 0"></path><line x1="12" y1="20" x2="12.01" y2="20"></line></svg>';
const disconnectedSvg = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-wifi-off"><line x1="1" y1="1" x2="23" y2="23"></line><path d="M16.72 11.06A10.94 10.94 0 0 1 19 12.55"></path><path d="M5 12.55a10.94 10.94 0 0 1 5.17-2.39"></path><path d="M10.71 5.05A16 16 0 0 1 22.58 9"></path><path d="M1.42 9a15.91 15.91 0 0 1 4.7-2.88"></path><path d="M8.53 16.11a6 6 0 0 1 6.95 0"></path><line x1="12" y1="20" x2="12.01" y2="20"></line></svg>';
const backButtonSvg   = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-left"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>';

const goToPage = (pageHash) => {
	if (typeof pageHash !== 'string') pageHash = location.hash || '#mainpage';

	console.log('goToPage', pageHash);
	document.querySelectorAll(".page").forEach(element => {
		element.style.display = ('#'+element.id !== pageHash) ? 'none' : '';
	});
}

const transformMessage = (input, meta) => {
	if (typeof meta.transform !== 'object') return input;

	if (typeof meta.transform.set === 'string') {
		try {
			return new Function('input', meta.transform.set)(input);
		} catch (exception){
			console.log(exception);
			return;
		}
	}

	return input;
}

const onMessage = (topic, message) => {
	try {
		message = JSON.parse(message.toString());
	} catch(e) { }

	document.querySelectorAll('[data-mqtt-topic="' + topic + '"]').forEach((element) => {
		let value = null;

		if (typeof element.dataset.transform !== 'undefined') {
			try {
				value = new Function('topic', 'message', element.dataset.transform)(topic, message);
			} catch (exception){
				console.log(exception);
				return;
			}
		} else {
			value = message;
		}

		if (value === null) value = message;

		switch (element.dataset.type) {
			case 'html':
				element.innerHTML = value;
				break;

			case 'text':
				if (typeof value === 'object') return;

				element.textContent = value;
				break;

			case 'switch':
				if (typeof value !== 'boolean') return;

				element.checked = value;
				break;

			case 'slider':
				if (isNaN(value)) return;

				element.value                 = value;
				element.dataset.lastMqttValue = value;
				element.style.setProperty('--c', 0);
				break;

			case 'select':
				if (typeof value === 'object') return;

				element.value                 = value;
				element.dataset.lastMqttValue = value;
				element.parentNode.getElementsByTagName('div')[0].classList.remove('loader');
				break;

			case 'button':
				if (typeof value === 'object') return;

				element.classList.remove('working');

				if (element.dataset.mqttValue === value) {
					element.classList.add('active');
				} else {
					element.classList.remove('active');
				}

				break;

			case 'number':
				if (isNaN(value)) return;

				element.value = value;
				element.style.width = (element.value.length + 2) + "ch";
				element.classList.remove('working');
				break;
		}
	});
};

const getConfig = async () => {
	const response = await fetch('/config.json');

	if (!response.ok) {
		if (!localStorage.getItem('config')) return {
			pages: [{
				pageid: "mainpage",
				pagetitle: "No Config!",
				sections: []
			}]
		};

		return JSON.parse(localStorage.getItem('config'));
	}

	const config = await response.json();
	localStorage.setItem('config', JSON.stringify(config));

	return config;
};

const renderItem = (itemData) => {
	if (typeof itemData.topic === 'string') {
		const temporary = itemData.topic;
		itemData.topic     = {};
		itemData.topic.get = temporary;
		itemData.topic.set = null;
	}

	if (typeof itemData.topic === 'undefined') itemData.topic = {}

	let transform = null;

	if (typeof itemData.transform !== 'undefined') {
		if (typeof itemData.transform     === 'string') transform = itemData.transform;
		if (typeof itemData.transform.get === 'string') transform = itemData.transform.get;
	};

	if (itemData.type !== 'html') {
		let element = html``;

		switch (itemData.type) {
			case 'text':
				if (typeof itemData.topic === 'undefined') break;

				element = html`<span data-type="${itemData.type}" data-mqtt-topic="${ifDefined(itemData.topic.get)}" data-transform="${ifDefined(transform)}"></span>`;
				break;

			case 'switch':
				const switchChangeHandler = (event) => {
					if (!client.connected)           return false;
					if (itemData.topic.set === null) return false;

					client.publish(itemData.topic.set, transformMessage(event.target.checked, itemData), itemData.mqtt);
					return false;
				}
			
				element = html`
					<label class="switch">
						<input type="checkbox" @change="${switchChangeHandler}" data-type="${itemData.type}" data-mqtt-topic="${itemData.topic.get}" data-transform="${ifDefined(transform)}">
						<span class="switch-handle">&nbsp;</span>
					</label>
				`;
				break;

			case 'slider':
				const sliderChangeHandler = (event) => {
					if (!client.connected)           return false;
					if (itemData.topic.set === null) return false;

					client.publish(itemData.topic.set, transformMessage(event.target.value, itemData), itemData.mqtt);
				}

				const sliderInputHandler = (event) => {
					if (!client.connected)           return false;
					if (itemData.topic.set === null) return false;

					const element = event.target;
					const value   = (element.dataset.lastMqttValue - element.value) / (element.max - element.min) * (element.getBoundingClientRect().width - 20);

					event.target.style.setProperty('--c', value + 'px');	
				}

				itemData.sliderMinValue  ??= 0;
				itemData.sliderMaxValue  ??= 1;
				itemData.sliderStepValue ??= 'any';
			
				element = html`<input class="slider" type="range" @change="${sliderChangeHandler}" @input="${sliderInputHandler}" min="${itemData.sliderMinValue}" max="${itemData.sliderMaxValue}" step="${itemData.sliderStepValue}" data-type="${itemData.type}" data-mqtt-topic="${itemData.topic.get}" data-transform="${ifDefined(transform)}">`;
				break;

			case 'select':
				const selectChangeHandler = (event) => {
					if (!client.connected)           return false;
					if (itemData.topic.set === null) return false
					const element = event.target;

					element.parentNode.getElementsByTagName('div')[0].classList.add('loader');

					client.publish(itemData.topic.set, transformMessage(element.value, itemData), itemData.mqtt);

					// Reset to last known state
					element.value = element.dataset.lastMqttValue
				}

				element = html`
					<div></div>
					<select @change="${selectChangeHandler}" data-type="${itemData.type}" data-mqtt-topic="${itemData.topic.get}" data-transform="${ifDefined(transform)}">
						${map(itemData.selectOptions, (option) => html`<option value="${option.value}">${option.label}</option>`)}
					</select>
				`;
				break;

			case 'button':
				const buttonClickHandler = (event) => {
					if (!client.connected)           return false;
					if (itemData.topic.set === null) return false;

					event.target.classList.add('working');

					client.publish(itemData.topic.set, transformMessage(event.target.dataset.mqttValue, itemData), itemData.mqtt);
					return false;
				}

				const buttonElement = (button) => html`<button class="button" type="button" @click="${buttonClickHandler}" data-type="${itemData.type}" data-mqtt-value="${button.value}" data-mqtt-topic="${itemData.topic.get}" data-transform="${ifDefined(transform)}">${button.label}</button>`;

				element = html`<div class="buttons">${map(itemData.buttons, buttonElement)}</div>`;
				break;

			case 'number':
				const keydownHandler = (event) => {
					const element = event.target;

					element.style.width = (element.value.length + 2) + "ch";

					if (event.code === 'Backspace') return true;
					if (event.code === 'Delete')    return true;

					if (!(/^([.,0-9]+)$/.test(event.key))) {
						event.preventDefault();
						return false;
					}
				}

				const numberHandlder = (event) => {
					if (!client.connected)           return false;
					if (itemData.topic.set === null) return false;

					const input      = event.target.parentNode.querySelector('input');
					let   inputValue = Number(input.value.replace(',', '.'));

					itemData.numberMinValue  ??= 1;
					itemData.numberMaxValue  ??= 254;
					itemData.numberIncrement ??= 1;
					itemData.numberDecrement ??= 1;

					if (event.target.textContent === '-') {
						if (inputValue === Number(itemData.numberMinValue)) return false;
						inputValue = inputValue - itemData.numberDecrement;
					}

					if (event.target.textContent === '+') {
						if (inputValue === Number(itemData.numberMaxValue)) return false;
						inputValue = inputValue + itemData.numberIncrement;
					}

					const transformedValue = transformMessage(inputValue, itemData);

					client.publish(itemData.topic.set, transformedValue, itemData.mqtt);
					input.classList.add('working');
				}

				element = html`
					<div class="number">
						<button type="button" @click="${numberHandlder}">-</button>
						<input type="text" inputmode="decimal" @keydown="${keydownHandler}" @change="${numberHandlder}" data-type="${itemData.type}" data-mqtt-topic="${itemData.topic.get}" data-transform="${ifDefined(transform)}">
						<button type="button" @click="${numberHandlder}">+</button>
					</div>
				`;
				break;

		}

		const clickHandler = (itemData.link) ? (event) => { window.location = itemData.link; } : null;
		const cursorStyle  = (itemData.link) ? 'cursor: pointer;' : null;

		return html`
			<div @click="${ifDefined(clickHandler)}" style="${ifDefined(cursorStyle)}">
				<img class="icon" src="${ifDefined(itemData.icon)}">
				<div class="title">${itemData.title}</div>
				<div class="right">${element}</div>
			</div>
		`;
	} else {
		return html`<div data-type="${itemData.type}" data-mqtt-topic="${ifDefined(itemData.topic.get)}" data-transform="${ifDefined(transform)}">${unsafeHTML(itemData.html)}</div>`;
	}
}

const renderSection = (sectionConfig) => {
	const title = (sectionConfig.title) ? html`<div class="title">${sectionConfig.title}</div>` : html``
	return html`
		<section>
			${title}
			${map(sectionConfig.items, (itemData) => renderItem(itemData))}			
		</section>
	`;
}

const renderPage = (pageConfig) => {
	const backButton = (pageConfig.id !== 'mainpage')        ? html`<button class="icon" onClick="window.history.back();">${unsafeSVG(backButtonSvg)}</button>` : html `<span class="icon"></span>`;
	const image      = (typeof pageConfig.icon === 'string') ? html`<img src="${pageConfig.icon}" width="30" height="30">`                                      : html``;

	return  html`
		<div id="${pageConfig.id}" class="page">
			<nav>
				<header>
					${backButton}
					<span>${image} ${pageConfig.title}</span>
					<button class="icon connectionStatus" @click="${() => window.location.reload(true)}">${unsafeSVG(disconnectedSvg)}</button>
				</header>
			</nav>
			${map(pageConfig.sections, (sectionConfig) => renderSection(sectionConfig))}
		</div>
	`;
}

const renderPages = (config) => html`${map(config.pages, (pageConfig) => renderPage(pageConfig))}`;

const scrollHandler = (event) => {
	let elements = [...document.getElementsByTagName('nav')];

	if (window.scrollY > 0) { elements.forEach((element) => element.classList.add('scroll')); }
	else                    { elements.forEach((element) => element.classList.remove('scroll')); }
}

window.addEventListener('hashchange', goToPage);
window.addEventListener("scroll", scrollHandler);
window.addEventListener('DOMContentLoaded', async (event) => {
	const config      = await getConfig();
	const topics      = new Set();
	const mqttUrl     = 'ws' + (location.protocol === 'https:' ? 's' : '') + '://' + location.hostname + ((location.port === '') ? '' : ':' + location.port) + '/mqtt';
	const mqttOptions = {
		clientId: localStorage.getItem('instanceId') ?? 'mqtt-webui_' + Math.random().toString(36).slice(2)
	};

	localStorage.setItem('instanceId', mqttOptions.clientId);

	if (typeof config.appName === 'string') {
		document.getElementsByTagName('title')[0].textContent                     = config.appName;
		document.querySelector('meta[name="apple-mobile-web-app-title"]').content = config.appName;
	}

	if (typeof config.extraCSS === 'string') {
		const link = document.createElement('link');
		link.href  = config.extraCSS;
		link.type  = 'text/css';
		link.rel   = 'stylesheet';
		document.getElementsByTagName('head')[0].appendChild(link);
	}

	// create UI
	render(renderPages(config), document.body);
	document.getElementById("loading").style.display = 'none';
	goToPage();

	if (!config.disableAuth) {
		mqttOptions.username = localStorage.getItem('username') ?? prompt("username:");
		mqttOptions.password = localStorage.getItem('password') ?? prompt("password:");

		localStorage.setItem('username',   mqttOptions.username);
		localStorage.setItem('password',   mqttOptions.password);
	}
	
	if (navigator.serviceWorker) {
		navigator.serviceWorker.register('sw.js', {
			scope: './'
		}).then(function(reg) {
			console.log('serviceWorker registration succeeded.');
		});
	}

	config.pages.forEach((page) => {
		page.sections.forEach((section) => {
			section.items.forEach((item) => {
				if (typeof item.topic     === 'undefined') return;
				if (typeof item.topic     === 'string') topics.add(item.topic);
				if (typeof item.topic.get === 'string') topics.add(item.topic.get);
			})
		})
	})

	// MQTT
	console.log('MQTT conencting to', mqttUrl);
	client = connect(mqttUrl, mqttOptions);

	client.on('connect', () => {
		console.log('Connected to mqtt-server!')
		document.querySelectorAll('.connectionStatus').forEach((element) => element.innerHTML = connectedSvg);
	});

	client.on('reconnect', () => console.log('Trying reconnect to mqtt-server!'));

	client.on('offline', () => {
		console.log('Disconnected from mqtt-server!')
		document.querySelectorAll('.connectionStatus').forEach((element) => element.innerHTML = disconnectedSvg);
	});

	client.on('error', (error) => {
		if (error.message === 'Connection refused: Not authorized') {
			alert('Authentication failed!');
			if (!config.disableAuth) {
				localStorage.setItem('username', prompt('username:') ?? localStorage.getItem('username'));
				localStorage.setItem('password', prompt('password:') ?? localStorage.getItem('password'));
			}
		}

		location.reload()
	});

	client.on('message', onMessage);

	client.subscribe([...topics])
});