Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 

58 lignes
1.4 KiB

  1. import { connect } from "mqtt";
  2. var client = connect('ws://' + location.host + '/mqtt',
  3. {
  4. clientId: "client" + Math.floor(Math.random() * 6) + 1
  5. });
  6. window.onbeforeunload = () => {
  7. client.end();
  8. };
  9. var publishButton = document.getElementById("publish");
  10. var topicInput = <HTMLInputElement>document.getElementById("topic");
  11. var msgInput = <HTMLInputElement>document.getElementById("msg");
  12. var stateParagraph = document.getElementById("state");
  13. var msgsList = <HTMLUListElement>document.getElementById("msgs");
  14. publishButton.onclick = click => {
  15. var topic = topicInput.value;
  16. var msg = msgInput.value;
  17. client.publish(topic, msg);
  18. };
  19. client.on('connect', () => {
  20. client.subscribe('#', { qos: 0 }, (err, granted) => {
  21. console.log(err);
  22. });
  23. client.publish('presence', 'Hello mqtt');
  24. stateParagraph.innerText = "connected";
  25. showMsg("[connect]");
  26. });
  27. client.on("error", e => {
  28. showMsg("error: " + e.message);
  29. });
  30. client.on("reconnect", () => {
  31. stateParagraph.innerText = "reconnecting";
  32. showMsg("[reconnect]");
  33. });
  34. client.on('message', (topic, message) => {
  35. showMsg(topic + ": " + message.toString());
  36. });
  37. function showMsg(msg: string) {
  38. //console.log(msg);
  39. var node = document.createElement("LI");
  40. node.appendChild(document.createTextNode(msg));
  41. msgsList.appendChild(node);
  42. if (msgsList.childElementCount > 50) {
  43. msgsList.removeChild(msgsList.childNodes[0]);
  44. }
  45. }