You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

app.ts 1.4 KiB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. }