| 1 | <!DOCTYPE html> |
| 2 | <html lang="es"> |
| 3 | |
| 4 | <head> |
| 5 | |
| 6 | <meta charset="utf-8"> |
| 7 | <meta name="viewport" content="width=device-width"> |
| 8 | |
| 9 | <title>IoT</title> |
| 10 | |
| 11 | <script type="module" src="js/lib/manejaErrores.js"></script> |
| 12 | <script src="paho.javascript-1.0.3/paho-mqtt-min.js"></script> |
| 13 | |
| 14 | </head> |
| 15 | |
| 16 | <body> |
| 17 | |
| 18 | <h1>IoT</h1> |
| 19 | |
| 20 | <p> |
| 21 | <output id="salida"> |
| 22 | <progress max="100">Cargando…</progress> |
| 23 | </output> |
| 24 | </p> |
| 25 | |
| 26 | <p> |
| 27 | <button id="boton" type="button"> |
| 28 | Enviar |
| 29 | </button> |
| 30 | </p> |
| 31 | |
| 32 | <script type="module"> |
| 33 | |
| 34 | import { creaIdCliente } from "./js/lib/creaIdCliente.js" |
| 35 | import { falloEnLaConexionMqtt } from "./js/lib/falloEnLaConexionMqtt.js" |
| 36 | import { conexionMqttPerdida } from "./js/lib/conexionMqttPerdida.js" |
| 37 | import { enviaMensajeMqtt } from "./js/lib/enviaMensajeMqtt.js" |
| 38 | |
| 39 | |
| 40 | const TOPICO_FOCO = "gilpgdm/IoT/foco" |
| 41 | |
| 42 | let valor = "0" |
| 43 | |
| 44 | |
| 45 | const clientId = creaIdCliente("gilpgdmIoT-") |
| 46 | |
| 47 | |
| 48 | const cliente = new Paho.MQTT.Client("test.mosquitto.org", 8081, clientId) |
| 49 | |
| 50 | function clicEnBoton() { |
| 51 | enviaMensajeMqtt(cliente, valor === '1' ? '0' : '1', TOPICO_FOCO) |
| 52 | } |
| 53 | |
| 54 | |
| 55 | cliente.onMessageArrived = mensaje => { |
| 56 | if (mensaje.destinationName === TOPICO_FOCO) { |
| 57 | valor = mensaje.payloadString |
| 58 | salida.value = valor === "1" ? "🔴" : "⚪" |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | |
| 63 | cliente.onConnectionLost = conexionMqttPerdida |
| 64 | |
| 65 | |
| 66 | cliente.connect({ |
| 67 | |
| 68 | |
| 69 | |
| 70 | keepAliveInterval: 10, |
| 71 | |
| 72 | useSSL: true, |
| 73 | |
| 74 | |
| 75 | onFailure: falloEnLaConexionMqtt, |
| 76 | |
| 77 | |
| 78 | onSuccess: () => { |
| 79 | console.log("Conectado") |
| 80 | |
| 81 | cliente.subscribe(TOPICO_FOCO) |
| 82 | |
| 83 | enviaMensajeMqtt(cliente, valor, TOPICO_FOCO) |
| 84 | boton.addEventListener("click", clicEnBoton) |
| 85 | }, |
| 86 | |
| 87 | }) |
| 88 | |
| 89 | </script> |
| 90 | |
| 91 | </body> |
| 92 | |
| 93 | </html> |