2019-09-05 15:44:12 -06:00
|
|
|
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,
|
2019-09-05 15:44:12 -06:00
|
|
|
} from "./index";
|
2017-12-26 20:05:15 -07:00
|
|
|
import { isNumber } from "lodash";
|
2017-12-27 08:51:52 -07:00
|
|
|
import axios from "axios";
|
|
|
|
import { API } from "../api/index";
|
2018-05-01 18:19:30 -06:00
|
|
|
import { FarmBotInternalConfig } from "farmbot/dist/config";
|
2019-09-05 16:27:42 -06:00
|
|
|
import { now } from "../devices/connectivity/qos";
|
2017-12-26 20:05:15 -07:00
|
|
|
|
2019-09-12 14:51:35 -06:00
|
|
|
export const PING_INTERVAL = 2000;
|
2018-01-28 15:00:37 -07:00
|
|
|
|
2018-05-01 18:19:30 -06: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 {
|
2018-05-01 18:19:30 -06:00
|
|
|
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
|
|
|
}
|
2017-12-27 08:51:52 -07:00
|
|
|
|
|
|
|
export function pingAPI() {
|
2019-09-05 16:27:42 -06:00
|
|
|
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);
|
2017-12-27 08:51:52 -07:00
|
|
|
}
|