F. index.html

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
  // A cada control le corresponde un tópico diferente.
40
  const TOPICO_FOCO = "gilpgdm/IoT/foco"
41
42
  let valor = "0"
43
44
  // Cambia por una raíz para tu proyecto.
45
  const clientId = creaIdCliente("gilpgdmIoT-")
46
47
  // Si usas un servidor de MQTT diferente, necesitas cambiar los parámetros.
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
  // Acciones al recibir un mensaje.
55
  cliente.onMessageArrived = mensaje => {
56
   if (mensaje.destinationName === TOPICO_FOCO) {
57
    valor = mensaje.payloadString
58
    salida.value = valor === "1" ? "🔴" : "⚪"
59
   }
60
  }
61
62
  // Acciones al perder la conexión.
63
  cliente.onConnectionLost = conexionMqttPerdida
64
65
  // Configura el cliente.
66
  cliente.connect({
67
68
   // Manda un mensaje cada número de segundos indicados por este valor,
69
   // para que el sistema sepa que este dispositivo está activo.
70
   keepAliveInterval: 10,
71
72
   useSSL: true,
73
74
   // Acciones al fallar la conexión.
75
   onFailure: falloEnLaConexionMqtt,
76
77
   // Acciones al lograr la conexión.
78
   onSuccess: () => {
79
    console.log("Conectado")
80
    // Se suscribe a uno o más tópicos.
81
    cliente.subscribe(TOPICO_FOCO)
82
    // Envía el valor inicial al tópico.
83
    enviaMensajeMqtt(cliente, valor, TOPICO_FOCO)
84
    boton.addEventListener("click", clicEnBoton)
85
   },
86
87
  })
88
89
 </script>
90
91
</body>
92
93
</html>
skip_previous skip_next