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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { connect } from "mqtt";
  2. var client = connect('ws://' + location.host + '/mqtt',
  3. {
  4. clientId: "client1",
  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. });
  26. client.on("error", e => {
  27. showMsg("error: " + e.message);
  28. });
  29. client.on("reconnect", () => {
  30. stateParagraph.innerText = "reconnecting";
  31. });
  32. client.on('message', (topic, message) => {
  33. showMsg(topic + ": " + message.toString());
  34. });
  35. function showMsg(msg: string) {
  36. //console.log(msg);
  37. var node = document.createElement("LI");
  38. node.appendChild(document.createTextNode(msg));
  39. msgsList.appendChild(node);
  40. if (msgsList.childElementCount > 20) {
  41. msgsList.removeChild(msgsList.childNodes[0]);
  42. }
  43. }