我正在构建一个应用程序,我需要从特定硬件中获取一些价值。我可以通过API访问此数据。当我访问特定的HTTPS地址时,会得到数据(在这种情况下,是我的本地网络http://192.168.1.148/ay)。
更新-地址输出:
{t}{s}Voltage{m}128 V{e}{s}Current{m}0.035 A{e}{s}Power{m}2 W{e}{s}Apparent Power{m}5 VA{e}{s}Reactive Power{m}4 VAr{e}{s}Power Factor{m}0.50{e}{s}Energy Today{m}0.307 kWh{e}{s}Energy Yesterday{m}0.136 kWh{e}{s}Energy Total{m}2.985 kWh{e}{t}ON
当我访问该地址时,我得到了: https://i.imgur.com/dBbOdON.png
如果刷新页面,我可以获得更新的信息。
这不是JSON文件,因此我无法使用JSON Parse。 我想拥有两个具有两个字段值的var,并且当值更改时,我希望更改我的var,所以我认为我需要异步的东西。
具体来说,我想拥有这些值 -在这种情况下,“总能量”为2.571 KWh或2571Wh。因此它可以是浮点(KWh),整数(Wh)甚至是字符串,都没关系 -状态,可以是开或关。我在图片中显示的这次通话中,它处于开启状态--- {e} {t}处于开启状态
我希望具有更新值的变量 例如:
energyTotal =“ 3.00”; 状态=“开”;
如果状态更改为关闭,我希望我的var更改
状态=“关闭”
答案 0 :(得分:0)
正则表达式对此非常有用。查看这两个站点以了解如何使用它:
答案 1 :(得分:0)
这是将信息解码为对象的功能:
function parseInput(strInput) {
let obj = {};
// split the string on {t} this should give us three parts
// 1) empty string 2) key/value pairs string 3) status string
let splitT = strInput.split("{t}");
// loop through each string
for (let ndxT = 0; ndxT < splitT.length; ndxT++) {
let strT = splitT[ndxT];
// if it is an empty string, go to the next iteration
if (strT.trim().length === 0) continue;
// if it is starts with {s}, it is the key/value pairs
// we'll process that accordingly
if (strT.startsWith("{s}")) {
// split the string around {e}
let splitE = strT.split("{e}");
// loop through each string
for (let ndxE = 0; ndxE < splitE.length; ndxE++) {
let strE = splitE[ndxE];
// the last {e} has an empty string after it, just skip it
if (strE.trim().length === 0) continue;
// get rid of the {s} at the start of the string
if (strE.startsWith("{s}")) strE = strE.slice(3);
// now we can split on {m} and get our key and value
let splitM = strE.split("{m}");
let strKey = splitM[0];
let value = splitM[1];
let key;
// we need to convert our key into something
// we can code with
if (strKey === "Voltage") key = "voltage";
if (strKey === "Current") key = "current";
if (strKey === "Power") key = "power";
if (strKey === "Apparent Power") key = "apparentPower";
if (strKey === "Reactive Power") key = "reactivePower";
if (strKey === "Power Factor") key = "powerFactor";
if (strKey === "Energy Today") key = "energyToday";
if (strKey === "Energy Yesterday") key = "energyYesterday";
if (strKey === "Energy Total") key = "energyTotal";
obj[key] = value;
}
} else {
// we must be at the status part
obj.status = strT;
}
}
return obj;
}
这是您将如何使用它。
let obj = parseInput(myInputString);
console.log(obj.energyTotal);