首页 > 解决方案 > 从传入的 mqtt 推送更新 alpinejs 变量

问题描述

我试图从使用 alpinejs 和蚊子的 iot 项目中从 mqtt 推送 ajax 请求方法中移开。在之前的帮助之后,我开始了解更多的 alpinejs 和 mqtt 客户端,但仍然无法做到我所期待的为了。

我想用传入的推送消息更新 alpinejs 数据变量。

我目前正在尝试简单地调用该函数,虽然它似乎在 dom 中工作,但它并没有反映在 html 中,我假设它根本没有正确触发事件。

例如,我试图调用 tester() 并让它设置值;我已经尝试了几件事,我知道我只是无法理解。

如何从传入消息中更新 alpinejs x-data 的值/状态?

<%- include('head'); %>
  <section class="text-gray-600 body-font flex" x-data="queryAjax()" x-init="fetchPinValue(); timer();"  >
    <div class="p-4 w-1/2 flex">
      <div class="w-1/4">
        <img src="images/fridge.svg">
      </div>
      <div class=" w-3/4">
        <div class="text-white px-5 py-4 border-0 rounded relative mb-4 bg-blue-400">
          <span class="text-xl inline-block mr-5 align-middle">
            <img src="images/air-compressor.svg" width="25px">
          </span>
          <span class="inline-block align-middle mr-8">
            Compressor Temp
            <h3 x-text="fridgeCompressorTemp"></h3>
            <button
              x-bind:class="{ 'animate-spin': fridgeFan == '0' }"
              @click="togglePin(fridgeFan)"
              type="button"
              class="absolute bg-transparent text-2xl font-semibold leading-none right-0 top-0 mt-4 mr-6 outline-none focus:outline-none border-white hover:bg-white hover:text-white rounded active:bg-blue-600 "
              >
              <img src="images/fan.svg" width="25px">
            </button>
          </span>
        </div>
        <div class="text-white px-5 py-4 border-0 rounded relative mb-4 bg-blue-400" >
          <span class="text-xl inline-block mr-5 align-middle">
            <img src="images/temp_cold.svg" width="25px">
          </span>
          <span class="inline-block align-middle mr-8">
            Fridge Ambient Temp
            <h3 x-text="ambientTemp"></h3>
          </span>
        </div>
      </div>
    </div>
    <div class="p-4 text-center w-1/2" id="mqtt_div">

    </div>
  </section>


  <script>
            function queryAjax(v) {
              return {
                isLoading: false,
                fridgeCompressorTemp: null,
                ambientTemp: null,
                fridgeFan: true,
                time: new Date(),
                timer() {
                  setInterval(() => {
                    this.time = new Date();
                    this.fetchPinValue();
                  }, 5000);
                },

                tester(dest, msg){
                  console.log(dest + " : " + msg);
                  //console.log(this.testtext);
                  //this.testtext = "msg";
                  // console.log(this.testtext);
                  //this.updateText();
                  //this.fridgeFan = 0;
                  //this.isLoading = true;

                },
                fetchPinValue() {
                  this.isLoading = true;

                  fetch(`${bserver}/${token_1}/get/V5`)
                    .then(res => res.json())
                    .then(data => {
                      this.isLoading = false;
                      this.fridgeCompressorTemp = data;
                      console.log("fridgeCompressorTemp = " + data)
                    });
                    fetch(`${bserver}/${token_1}/get/V7`)
                    .then(res => res.json())
                    .then(data => {
                      this.isLoading = false;
                      this.ambientTemp = data;
                      console.log("ambientTemp = " + data)
                    });
                  fetch(`${bserver}/${token_1}/get/D13`)
                    .then(res => res.json())
                    .then(data => {
                      this.isLoading = false;
                      console.log("fridgeFan = " + data)
                      this.fridgeFan = data;
                    });
                },
                togglePin(){
                  /////////////some pins and names hardcoded here.only works for fridgefan
                  var i = (this.fridgeFan == '0') ? 1 : 0;
                  fetch(`${bserver}/${token_1}/update/D13?value=${i}`)
                    .then(data => {
                      this.fridgeFan = i
                    })
                }
              }
            }

      client = new Paho.MQTT.Client("192.168.10.66", Number(1884), "node-admin-2");
      // set callback handlers
      client.onConnectionLost = onConnectionLost;
      client.onMessageArrived = onMessageArrived;
      // connect the client
      client.connect({onSuccess:onConnect});

      // called when the client connects
      function onConnect() {
        // Once a connection has been made, make a subscription and send a message.
        console.log("onConnect");
        client.subscribe("sensors/sensor1");
      }

      // called when the client loses its connection
      function onConnectionLost(responseObject) {
        if (responseObject.errorCode !== 0) {
          console.log("onConnectionLost:"+responseObject.errorMessage);
          alert("Connection to MQTT Lost");
        }
      }

      function onMessageArrived(message) {

        // Trying to call the function from outside. it gets there and seems to update the values BUT doesnt seem to "fire" alpinejs events to update page or anything
        queryAjax().tester(message.destinationName, message.payloadString);


        //queryAjax().togglePin();                                                  // works one direction err or maybe the the first time.
        $("#mqtt_div").html(message.destinationName + " " + message.payloadString)  // works as expected

      }
  $(() => {
    console.log( "---");
  })
</script>
<%- include('foot'); %>

标签: javascript

解决方案


推荐阅读