Farmbot-Web-App/frontend/connectivity/ping_mqtt.tsx

67 lines
1.7 KiB
TypeScript
Raw Normal View History

import { Farmbot, uuid } from "farmbot";
import {
dispatchNetworkDown,
dispatchNetworkUp,
2019-09-11 15:58:53 -06:00
dispatchQosStart,
pingOK,
2020-02-28 09:35:32 -07:00
pingNO,
} from "./index";
2017-12-26 20:05:15 -07:00
import { isNumber } from "lodash";
import axios from "axios";
import { API } from "../api/index";
import { FarmBotInternalConfig } from "farmbot/dist/config";
import { now } from "../devices/connectivity/qos";
2017-12-26 20:05:15 -07:00
export const PING_INTERVAL = 2000;
2018-01-28 15:00:37 -07:00
export const LAST_IN: keyof FarmBotInternalConfig = "LAST_PING_IN";
export const LAST_OUT: keyof FarmBotInternalConfig = "LAST_PING_OUT";
2017-12-26 20:05:15 -07:00
type Direction = "in" | "out";
2017-12-26 21:22:15 -07:00
export function readPing(bot: Farmbot, direction: Direction): number | undefined {
const val = bot.getConfig(direction === "out" ? LAST_OUT : LAST_IN);
2017-12-26 20:05:15 -07:00
return isNumber(val) ? val : undefined;
}
2017-12-26 21:22:15 -07:00
export function sendOutboundPing(bot: Farmbot) {
2019-09-18 08:51:22 -06:00
return new Promise((resolve, reject) => {
const id = uuid();
const x = { done: false };
const ok = () => {
if (!x.done) {
x.done = true;
pingOK(id, now());
resolve();
}
};
const no = () => {
if (!x.done) {
x.done = true;
pingNO(id, now());
2019-09-19 13:09:00 -06:00
reject(new Error("sendOutboundPing failed: " + id));
2019-09-18 08:51:22 -06:00
}
};
dispatchQosStart(id);
setTimeout(no, PING_INTERVAL + 150);
bot.ping().then(ok, no);
});
2017-12-26 20:05:15 -07:00
}
2019-09-19 13:09:00 -06:00
const beep = (bot: Farmbot) => sendOutboundPing(bot)
.then(() => { }, () => { }); // Silence errors;
2017-12-26 20:05:15 -07:00
export function startPinging(bot: Farmbot) {
2019-09-19 13:09:00 -06:00
beep(bot);
setInterval(() => beep(bot), PING_INTERVAL);
2017-12-26 20:05:15 -07:00
}
export function pingAPI() {
const ok = () => dispatchNetworkUp("user.api", now());
const no = () => dispatchNetworkDown("user.api", now());
2019-05-28 09:13:43 -06:00
return axios.get(API.current.devicePath).then(ok, no);
}