| 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 src="paho.javascript-1.0.3/paho-mqtt-min.js"></script> |
| 12 | |
| 13 | </head> |
| 14 | |
| 15 | <body> |
| 16 | |
| 17 | <h1>IoT</h1> |
| 18 | |
| 19 | <p> |
| 20 | <output id="salida"> |
| 21 | <progress max="100">Cargando…</progress> |
| 22 | </output> |
| 23 | </p> |
| 24 | |
| 25 | <p> |
| 26 | <button type="button" onclick="clicEnBoton()"> |
| 27 | Enviar |
| 28 | </button> |
| 29 | </p> |
| 30 | |
| 31 | <script type="module"> |
| 32 | |
| 33 | import { exportaAHtml } from "./lib/js/exportaAHtml.js" |
| 34 | import { creaIdCliente } from "./lib/js/creaIdCliente.js" |
| 35 | import { falloEnLaConexionMqtt } from "./lib/js/falloEnLaConexionMqtt.js" |
| 36 | import { conexionMqttPerdida } from "./lib/js/conexionMqttPerdida.js" |
| 37 | import { muestraError } from "./lib/js/muestraError.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 | try { |
| 52 | enviaMensajeMqtt(valor === '1' ? '0' : '1', TOPICO_FOCO) |
| 53 | } catch (error) { |
| 54 | muestraError(error) |
| 55 | } |
| 56 | } |
| 57 | exportaAHtml(clicEnBoton) |
| 58 | |
| 59 | |
| 60 | cliente.onMessageArrived = mensaje => { |
| 61 | if (mensaje.destinationName === TOPICO_FOCO) { |
| 62 | valor = mensaje.payloadString |
| 63 | salida.value = valor === "1" ? "🔴" : "⚪" |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | |
| 68 | cliente.onConnectionLost = conexionMqttPerdida |
| 69 | |
| 70 | |
| 71 | cliente.connect({ |
| 72 | |
| 73 | keepAliveInterval: 10, |
| 74 | |
| 75 | useSSL: true, |
| 76 | |
| 77 | |
| 78 | onFailure: falloEnLaConexionMqtt, |
| 79 | |
| 80 | |
| 81 | onSuccess: () => { |
| 82 | console.log("Conectado") |
| 83 | |
| 84 | cliente.subscribe(TOPICO_FOCO) |
| 85 | |
| 86 | enviaMensajeMqtt(valor, TOPICO_FOCO) |
| 87 | }, |
| 88 | |
| 89 | }) |
| 90 | |
| 91 | |
| 92 | |
| 93 | |
| 94 | |
| 95 | |
| 96 | |
| 97 | function enviaMensajeMqtt(mensaje, topico) { |
| 98 | const mensajeMqtt = new Paho.MQTT.Message(mensaje) |
| 99 | mensajeMqtt.destinationName = topico |
| 100 | cliente.send(mensajeMqtt) |
| 101 | } |
| 102 | |
| 103 | </script> |
| 104 | |
| 105 | </body> |
| 106 | |
| 107 | </html> |