"use strict";

var __createBinding = void 0 && (void 0).__createBinding || (Object.create ? function (o, m, k, k2) {
  if (k2 === undefined) k2 = k;
  var desc = Object.getOwnPropertyDescriptor(m, k);
  if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
    desc = {
      enumerable: true,
      get: function () {
        return m[k];
      }
    };
  }
  Object.defineProperty(o, k2, desc);
} : function (o, m, k, k2) {
  if (k2 === undefined) k2 = k;
  o[k2] = m[k];
});
var __setModuleDefault = void 0 && (void 0).__setModuleDefault || (Object.create ? function (o, v) {
  Object.defineProperty(o, "default", {
    enumerable: true,
    value: v
  });
} : function (o, v) {
  o["default"] = v;
});
var __importStar = void 0 && (void 0).__importStar || function () {
  var ownKeys = function (o) {
    ownKeys = Object.getOwnPropertyNames || function (o) {
      var ar = [];
      for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
      return ar;
    };
    return ownKeys(o);
  };
  return function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
    __setModuleDefault(result, mod);
    return result;
  };
}();
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.RobotInitService = void 0;
const aubo_sdk_1 = require("@aubo/aubo_sdk");
const aubo_logger_1 = require("@aubo/aubo_logger");
const unit_util_1 = require("../utils/unit.util");
const path_1 = require("path");
const fs = __importStar(require("fs"));
const agv_constant_1 = require("../entity/agv.constant");
const webscope_service_1 = require("../webscope-service");
const TOML = require("@iarna/toml");
class RobotInitService {
  constructor() {
    var _a, _b, _c, _d, _e, _f;
    this.robotProxy = null;
    this.payloadModel = null;
    this.tcpModel = null;
    this.logger = (_c = (_b = (_a = (0, webscope_service_1.getWebscopeService)()) === null || _a === void 0 ? void 0 : _a.getLogger) === null || _b === void 0 ? void 0 : _b.call(_a)) !== null && _c !== void 0 ? _c : new aubo_logger_1.AsLogger("RobotInitService");
    this.robotProxy = (_d = (0, webscope_service_1.getWebscopeService)()) === null || _d === void 0 ? void 0 : _d.getRobotProxy();
    this.payloadModel = (_e = (0, webscope_service_1.getWebscopeService)()) === null || _e === void 0 ? void 0 : _e.getPayloadModel();
    this.tcpModel = (_f = (0, webscope_service_1.getWebscopeService)()) === null || _f === void 0 ? void 0 : _f.getTcpModel();
  }
  async autoEnableRobot() {
    var _a, _b, _c, _d, _e, _f;
    const realtime = (_a = this.robotProxy) === null || _a === void 0 ? void 0 : _a.getRealtimeRobotState();
    const loginRes = (_b = this.robotProxy) === null || _b === void 0 ? void 0 : _b.hasLogin();
    if (!loginRes) {
      this.logger.warn("Auto enable robot: login robot failed.");
      return;
    }
    const safetyModeType = realtime === null || realtime === void 0 ? void 0 : realtime.getSafetyModeType().toString();
    if (safetyModeType == "RobotEmergencyStop" || safetyModeType == "SystemEmergencyStop") {
      this.logger.warn("Auto enable robot: emergency stop.");
      return;
    }
    const tcp = (_c = this.tcpModel) === null || _c === void 0 ? void 0 : _c.getDefaultTcp();
    const payload = (_d = this.payloadModel) === null || _d === void 0 ? void 0 : _d.getDefaultPayload();
    if (tcp) {
      this.logger.debug("Connecting this control. set TCP: " + tcp.getOffset());
      await ((_e = this.robotProxy) === null || _e === void 0 ? void 0 : _e.getRobotConfig().setTcpOffset(tcp.getOffset()));
    }
    if (payload) {
      const {
        mass,
        cog,
        inertiaMatrix
      } = payload;
      const inertia = unit_util_1.UnitUtil.transInertiaFromInsToControl(inertiaMatrix);
      this.logger.debug("Connecting this control. set payload { mass: " + mass + ", cog: " + cog + ", inertiaMatrix: " + inertia + " }");
      await ((_f = this.robotProxy) === null || _f === void 0 ? void 0 : _f.getRobotConfig().setPayload(mass, cog, [0, 0, 0], inertia));
    }
    let powerOnCount = 0;
    let canRun = true;
    const startupInterval = setInterval(async () => {
      var _a, _b;
      try {
        if (!canRun) {
          return;
        }
        canRun = false;
        const status = realtime === null || realtime === void 0 ? void 0 : realtime.getRuntimeState();
        const robotModeType = realtime === null || realtime === void 0 ? void 0 : realtime.getRobotModeType().toString();
        const safetyModeType = realtime === null || realtime === void 0 ? void 0 : realtime.getSafetyModeType().toString();
        this.logger.log("Before proweron. robot status: " + status + ",  mode type: " + robotModeType + ", safetyModeType:" + safetyModeType);
        if (safetyModeType == "RobotEmergencyStop" || safetyModeType == "SystemEmergencyStop" || safetyModeType == "SafeguardStop") {
          this.logger.warn("Auto enable robot: emergency stop.");
          clearInterval(startupInterval);
          return;
        }
        if (status === aubo_sdk_1.RuntimeState.Stopped && robotModeType === "PowerOff") {
          await ((_a = this.robotProxy) === null || _a === void 0 ? void 0 : _a.getRobotManage().poweron());
          this.logger.log("Robot has power on.");
        } else if (robotModeType === "Running" || safetyModeType === "SafeguardStop") {
          clearInterval(startupInterval);
        }
        if (robotModeType === "Idle") {
          await ((_b = this.robotProxy) === null || _b === void 0 ? void 0 : _b.getRobotManage().startup());
          this.logger.debug("Robot has startup.");
          clearInterval(startupInterval);
        }
        if (powerOnCount > 10) {
          this.logger.warn("Auto power on more than ten times.");
          clearInterval(startupInterval);
        }
        powerOnCount++;
      } catch (e) {
        this.logger.warn("Auto enable robot power on failed.");
      } finally {
        canRun = true;
      }
    }, 2 * 1000);
  }
  getAgvDeviceInfo() {
    if (fs.existsSync(agv_constant_1.DEVICE_INFO)) {
      let fileContent = fs.readFileSync((0, path_1.join)(agv_constant_1.DEVICE_INFO), "utf8");
      if (fileContent && fileContent.trim()) {
        return TOML.parse(fileContent);
      }
    }
    return null;
  }
  getAgvType() {
    var _a;
    const agvDeviceInfo = this.getAgvDeviceInfo();
    return agvDeviceInfo && agvDeviceInfo.category ? (_a = agvDeviceInfo === null || agvDeviceInfo === void 0 ? void 0 : agvDeviceInfo.category) === null || _a === void 0 ? void 0 : _a.type : null;
  }
}
exports.RobotInitService = RobotInitService;
//# sourceMappingURL=robot-init.service.js.map