All files / adapter virtual-agv-adapter.js

81.2% Statements 337/415
68.02% Branches 183/269
83.47% Functions 96/115
80.8% Lines 320/396

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803    25x 25x 25x     19x 19x 19x 19x 19x     3847x     501x     4x     38x     19x 19x                               19x 19x 19x 19x 1582x 1582x 1582x 1582x   19x 19x 19x                       19x 19x     77x 77x 77x 58x 58x 4x       4x     73x     156x 73x                               121x 121x 121x 121x 12x   109x 210x 99x   267x 510x 267x 12x     99x 8x     121x     59x 59x 48x   11x 11x 11x 4x 4x   11x 11x 7x   11x 11x                 141x 141x 239x 239x 4x 4x     141x     58x     7x 7x 7x 7x           222x         11x             3x                     30x 30x 30x   18x             18x 18x                     34x 34x 34x   22x             18x 18x                     8x 8x 8x 8x 8x 8x           8x 8x                   5x       5x 5x                   5x       5x 5x                     4x   4x               4x 4x                     4x   4x           4x 4x                     8x         8x                   57x 57x 57x 57x 57x 57x     57x 57x 57x 57x 57x 57x     24x 24x 24x 24x 40x 40x 40x 40x   40x   24x     65x     65x       65x       8x 8x     8x 16x 24x           24x 24x         8x     65x 65x 65x 65x 65x     168x     19x                           19x     872x       73x     1582x 161x   1582x 1582x       1582x 1460x   122x 122x 122x 122x 122x 122x 57x     57x 57x 57x     65x 65x 65x 57x 57x 57x 57x 57x 57x 57x 57x 57x     8x 8x 8x 8x 8x 8x 8x 8x                                       1582x 1498x   84x 84x 84x 84x 84x 84x 84x 84x   84x       84x 84x 41x 41x   84x         18x           18x 18x         18x 18x 18x           8x 16x 24x 32x 40x 44x 8x 8x 8x             5x     5x     5x 5x 5x         5x     5x     5x 5x 5x 5x         5x             4x     4x     4x 4x 4x     4x     4x 4x 4x     8x 8x 8x 8x 8x 8x     8x 8x           8x 8x       8x 8x 16x 16x 24x 24x 24x 24x             8x 8x 8x 16x 8x 8x   8x   8x     25x     128x 128x 57x   71x     71x 142x 71x 16x   55x             73x 73x 73x 73x 73x 73x 73x 73x 73x 357x             161x     161x         161x           161x 73x 73x   88x               88x               88x     88x 88x 88x 88x 88x 83x 83x     5x                                                     156x 156x 73x 73x 73x 73x   156x 156x           156x 156x      
"use strict";
/*! Copyright (c) 2021 Siemens AG. Licensed under the MIT License. */
Object.defineProperty(exports, "__esModule", { value: true });
exports.VirtualAgvAdapter = void 0;
const __1 = require("..");
class VirtualAgvAdapter {
    constructor(controller, adapterOptions, debug) {
        this.debug = debug;
        this._controller = controller;
        this._options = this._optionsWithDefaults(adapterOptions);
        this._actionStateMachines = [];
        this.debug("Create instance for apiVersion %d with adapterOptions %o", this.apiVersion, this.options);
    }
    get options() {
        return this._options;
    }
    get controller() {
        return this._controller;
    }
    get name() {
        return "VirtualAgvAdapter";
    }
    get apiVersion() {
        return 2;
    }
    attach(context) {
        Eif (this._vehicleState === undefined) {
            this._vehicleState = {
                isDriving: false,
                isPaused: false,
                position: { positionInitialized: true, lastNodeId: "0", ...this.options.initialPosition },
                velocity: { omega: 0, vx: 0, vy: 0 },
                batteryState: {
                    batteryCharge: this.options.initialBatteryCharge,
                    batteryVoltage: 24.0,
                    charging: false,
                    reach: this.getBatteryReach(this.options.initialBatteryCharge),
                },
                safetyState: { eStop: __1.EStop.None, fieldViolation: false },
                operatingMode: __1.OperatingMode.Automatic,
                currentLoad: undefined,
            };
        }
        this._tick = 0;
        const tickInterval = 1000 / this.options.tickRate;
        let realTime = Date.now();
        this._tickIntervalId = setInterval(() => {
            const now = Date.now();
            const realInterval = now - realTime;
            realTime = now;
            this._onTick(++this._tick, tickInterval * this.options.timeLapse, realInterval * this.options.timeLapse / 1000);
        }, tickInterval);
        this._controller.updateFactsheet({});
        const { lastNodeId, ...position } = this._vehicleState.position;
        context.attached({
            agvPosition: position,
            lastNodeId,
            velocity: this._vehicleState.velocity,
            batteryState: this._vehicleState.batteryState,
            driving: this._vehicleState.isDriving,
            operatingMode: this._vehicleState.operatingMode,
            paused: this._vehicleState.isPaused,
            safetyState: this._vehicleState.safetyState,
        });
    }
    detach(context) {
        clearInterval(this._tickIntervalId);
        context.detached({});
    }
    executeAction(context) {
        const { action, scope, activeOrderId, stopDriving } = context;
        const actionDef = this._getActionDefinition(action, scope);
        if (actionDef.actionExecutable !== undefined) {
            const errorDescription = actionDef.actionExecutable(action, scope, activeOrderId);
            if (!!errorDescription) {
                context.updateActionStatus({
                    actionStatus: __1.ActionStatus.Failed,
                    errorDescription,
                });
                return;
            }
        }
        Iif (stopDriving && this._vehicleState.isDriving) {
            this.stopDriving(true);
        }
        const asm = new VirtualActionStateMachine(context, actionDef, () => this._finalizeAction(asm), (formatter, ...args) => this.debug(formatter, ...args), action.actionType === "stopPause" || action.actionType === "startPause" ? false : this._vehicleState.isPaused);
        this._actionStateMachines.push(asm);
    }
    finishEdgeAction(context) {
        const asm = this._actionStateMachines.find(sm => sm.matches(context.action.actionId, context.scope));
        if (asm) {
            asm.terminate();
        }
    }
    cancelAction(context) {
        const asm = this._actionStateMachines.find(sm => sm.matches(context.action.actionId, context.scope));
        if (asm) {
            asm.cancel();
        }
    }
    isActionExecutable(context) {
        var _a, _b;
        const { action, scope } = context;
        const errorRefs = [];
        const actionDef = this._getActionDefinition(action, scope);
        if (!actionDef) {
            errorRefs.push({ referenceKey: __1.AgvController.REF_KEY_ERROR_DESCRIPTION_DETAIL, referenceValue: "not supported" });
        }
        else if (actionDef.actionParameterConstraints !== undefined) {
            const allActionParams = Object.fromEntries((_b = (_a = action.actionParameters) === null || _a === void 0 ? void 0 : _a.map(p => ([p.key, p.value]))) !== null && _b !== void 0 ? _b : []);
            Object.keys(actionDef.actionParameterConstraints).forEach(key => {
                var _a;
                const constraints = actionDef.actionParameterConstraints[key];
                const actionParam = (_a = action.actionParameters) === null || _a === void 0 ? void 0 : _a.find(p => p.key === key);
                if (!constraints(actionParam === null || actionParam === void 0 ? void 0 : actionParam.value, scope, allActionParams)) {
                    errorRefs.push({ referenceKey: "actionParameter", referenceValue: key });
                }
            });
            if (errorRefs.length > 0) {
                errorRefs.push({ referenceKey: __1.AgvController.REF_KEY_ERROR_DESCRIPTION_DETAIL, referenceValue: "invalid actionParameter" });
            }
        }
        return errorRefs;
    }
    isNodeWithinDeviationRange(node) {
        const errorRefs = [];
        if (!node.nodePosition) {
            return errorRefs;
        }
        const { allowedDeviationTheta, allowedDeviationXy, mapId, theta, x, y } = node.nodePosition;
        const { mapId: agvMapId, theta: agvTheta, x: agvX, y: agvY } = this._vehicleState.position;
        if (mapId !== agvMapId) {
            errorRefs.push({ referenceKey: "nodeId", referenceValue: node.nodeId });
            errorRefs.push({ referenceKey: "nodePosition.mapId", referenceValue: agvMapId });
        }
        const allowedXy = allowedDeviationXy || this.options.agvNormalDeviationXyTolerance;
        if ((agvX - x) ** 2 + (agvY - y) ** 2 > allowedXy ** 2) {
            errorRefs.push({ referenceKey: "nodePosition.allowedDeviationXy", referenceValue: allowedXy.toString() });
        }
        Eif (theta === undefined) {
            return errorRefs;
        }
        const allowedTheta = allowedDeviationTheta || this.options.agvNormalDeviationThetaTolerance;
        if (Math.abs(agvTheta - theta) > allowedTheta) {
            errorRefs.push({ referenceKey: "nodePosition.allowedDeviationTheta", referenceValue: allowedTheta.toString() });
        }
        return errorRefs;
    }
    isRouteTraversable(context) {
        const errorRefs = [];
        for (let i = 0; i < context.nodes.length; i++) {
            const node = context.nodes[i];
            if (node.nodePosition === undefined && i > 0) {
                errorRefs.push({ referenceKey: __1.AgvController.REF_KEY_ERROR_DESCRIPTION_DETAIL, referenceValue: "missing nodePosition" }, { referenceKey: "nodeId", referenceValue: node.nodeId }, { referenceKey: "nodePosition", referenceValue: "undefined" });
                break;
            }
        }
        return errorRefs;
    }
    traverseEdge(context) {
        this._traverseContext = context;
    }
    stopTraverse(context) {
        this._traverseContext = undefined;
        this._vehicleState.isDriving && this.stopDriving(true);
        this._vehicleState.isPaused && this._stopPause();
        context.stopped();
    }
    get vehicleState() {
        return this._vehicleState;
    }
    get actionDefinitions() {
        return [
            {
                actionType: "noop",
                actionScopes: ["instant", "node", "edge"],
                actionParameterConstraints: {
                    duration: (value) => value === undefined || typeof value === "number",
                },
                transitions: {
                    ON_INIT: { next: __1.ActionStatus.Running },
                    ON_CANCEL: {},
                    [__1.ActionStatus.Running]: { durationTime: ["duration", 5], next: __1.ActionStatus.Finished },
                    [__1.ActionStatus.Finished]: {
                        resultDescription: () => "noop action finished",
                    },
                    [__1.ActionStatus.Failed]: {
                        errorDescription: () => "noop action failed",
                    },
                },
            },
            {
                actionType: "pick",
                actionScopes: "node",
                actionParameterConstraints: {
                    stationType: (value) => value && value.startsWith("floor"),
                    loadType: (value) => value === "EPAL",
                    duration: (value) => value === undefined || typeof value === "number",
                },
                actionExecutable: () => this._vehicleState.currentLoad ? "load already picked" : "",
                transitions: {
                    ON_INIT: { next: __1.ActionStatus.Initializing },
                    ON_CANCEL: {},
                    [__1.ActionStatus.Initializing]: { durationTime: 1, next: __1.ActionStatus.Running },
                    [__1.ActionStatus.Running]: { durationTime: ["duration", 5], next: __1.ActionStatus.Finished },
                    [__1.ActionStatus.Finished]: {
                        resultDescription: () => "pick action finished",
                        linkedState: () => this._loadAdded(),
                    },
                    [__1.ActionStatus.Failed]: {
                        errorDescription: () => "pick action failed",
                    },
                },
            },
            {
                actionType: "drop",
                actionScopes: "node",
                actionParameterConstraints: {
                    stationType: (value) => value && value.startsWith("floor"),
                    loadType: (value) => value === "EPAL",
                    duration: (value) => value === undefined || typeof value === "number",
                },
                actionExecutable: () => this._vehicleState.currentLoad ? "" : "no load to drop",
                transitions: {
                    ON_INIT: { next: __1.ActionStatus.Initializing },
                    ON_CANCEL: {},
                    [__1.ActionStatus.Initializing]: { durationTime: 1, next: __1.ActionStatus.Running },
                    [__1.ActionStatus.Running]: { durationTime: ["duration", 5], next: __1.ActionStatus.Finished },
                    [__1.ActionStatus.Finished]: {
                        resultDescription: () => "drop action finished",
                        linkedState: () => this._loadRemoved(),
                    },
                    [__1.ActionStatus.Failed]: {
                        errorDescription: () => "drop action failed",
                    },
                },
            },
            {
                actionType: "initPosition",
                actionScopes: ["instant", "node"],
                actionParameterConstraints: {
                    x: (value) => typeof value === "number",
                    y: (value) => typeof value === "number",
                    theta: (value) => typeof value === "number",
                    mapId: (value) => typeof value === "string",
                    lastNodeId: (value) => typeof value === "string",
                    lastNodeSequenceId: (value) => value === undefined ? true : typeof value === "number",
                },
                transitions: {
                    ON_INIT: { next: __1.ActionStatus.Finished },
                    ON_CANCEL: {},
                    [__1.ActionStatus.Finished]: {
                        resultDescription: () => "Position initialized",
                        linkedState: context => this._initPosition(context.action),
                    },
                    [__1.ActionStatus.Failed]: {
                        errorDescription: () => "initPosition action failed",
                    },
                },
            },
            {
                actionType: "startPause",
                actionScopes: "instant",
                actionExecutable: () => this._vehicleState.isPaused ? "already paused" : "",
                transitions: {
                    ON_INIT: { next: __1.ActionStatus.Finished },
                    [__1.ActionStatus.Finished]: {
                        resultDescription: () => "Paused",
                        linkedState: context => this._startPause(context),
                    },
                    [__1.ActionStatus.Failed]: {
                        errorDescription: () => "startPause action failed",
                    },
                },
            },
            {
                actionType: "stopPause",
                actionScopes: "instant",
                actionExecutable: () => this._vehicleState.isPaused ? "" : "not yet paused",
                transitions: {
                    ON_INIT: { next: __1.ActionStatus.Finished },
                    [__1.ActionStatus.Finished]: {
                        resultDescription: () => "Unpaused",
                        linkedState: context => this._stopPause(context),
                    },
                    [__1.ActionStatus.Failed]: {
                        errorDescription: () => "stopPause action failed",
                    },
                },
            },
            {
                actionType: "startCharging",
                actionScopes: ["instant", "node"],
                actionParameterConstraints: {
                    duration: (value) => value === undefined || typeof value === "number",
                },
                actionExecutable: (action, scope, activeOrderId) => this._vehicleState.batteryState.charging ?
                    "charging already in progress" :
                    activeOrderId && scope === "instant" ? "charging denied as order is in progress" : "",
                transitions: {
                    ON_INIT: { next: __1.ActionStatus.Running },
                    ON_CANCEL: {},
                    [__1.ActionStatus.Running]: { durationTime: ["duration", 1], next: __1.ActionStatus.Finished },
                    [__1.ActionStatus.Finished]: {
                        resultDescription: () => "Started charging",
                        linkedState: () => this._startCharging(),
                    },
                    [__1.ActionStatus.Failed]: {
                        errorDescription: () => "startCharging action failed",
                    },
                },
            },
            {
                actionType: "stopCharging",
                actionScopes: ["instant", "node"],
                actionParameterConstraints: {
                    duration: (value) => value === undefined || typeof value === "number",
                },
                actionExecutable: () => this._vehicleState.batteryState.charging ? "" : "charging not in progress",
                transitions: {
                    ON_INIT: { next: __1.ActionStatus.Running },
                    ON_CANCEL: {},
                    [__1.ActionStatus.Running]: { durationTime: ["duration", 1], next: __1.ActionStatus.Finished },
                    [__1.ActionStatus.Finished]: {
                        resultDescription: () => "Stopped charging",
                        linkedState: () => this._stopCharging(),
                    },
                    [__1.ActionStatus.Failed]: {
                        errorDescription: () => "startCharging action failed",
                    },
                },
            },
            {
                actionType: "orderExecutionTime",
                actionScopes: "instant",
                actionParameterConstraints: {
                    orders: (value) => Array.isArray(value),
                },
                transitions: {
                    ON_INIT: { next: __1.ActionStatus.Finished },
                    [__1.ActionStatus.Finished]: {
                        resultDescription: context => this._calculateEstimatedOrderExecutionTimes(context.action),
                    },
                    [__1.ActionStatus.Failed]: {
                        errorDescription: () => "orderExecutionTime action failed",
                    },
                },
            },
        ];
    }
    startDriving(vx, vy, reportImmediately = false) {
        this._vehicleState.isDriving = true;
        this._vehicleState.velocity.vx = vx;
        this._vehicleState.velocity.vy = vy;
        this.controller.updateDrivingState(true);
        this.controller.updateAgvPositionVelocity(undefined, this._vehicleState.velocity, reportImmediately);
        this.debug("start driving vx=%d, vy=%d", vx, vy);
    }
    stopDriving(reportImmediately = false) {
        this._vehicleState.isDriving = false;
        this._vehicleState.velocity.vx = 0;
        this._vehicleState.velocity.vy = 0;
        this.controller.updateDrivingState(false);
        this.controller.updateAgvPositionVelocity(undefined, this._vehicleState.velocity, reportImmediately);
        this.debug("stop driving");
    }
    getNodeActionDuration(action) {
        const actionDef = this._getActionDefinition(action, "node");
        let duration = 0;
        let state = actionDef.transitions.ON_INIT.next;
        while (state !== __1.ActionStatus.Finished && state !== __1.ActionStatus.Failed) {
            const transition = actionDef.transitions[state];
            const transitionDuration = getTransitionDuration(transition, action);
            Eif (transitionDuration !== undefined) {
                duration += transitionDuration;
            }
            state = transition.next;
        }
        return duration;
    }
    getTargetSpeed(useMean = false, distance, maxSpeed) {
        Iif (this.options.vehicleSpeedDistribution) {
            return this.options.vehicleSpeedDistribution()[useMean ? 1 : 0];
        }
        else Iif (this.options.vehicleTimeDistribution) {
            return distance / this.options.vehicleTimeDistribution()[useMean ? 1 : 0];
        }
        else {
            return maxSpeed === undefined ? this.options.vehicleSpeed : Math.min(maxSpeed, this.options.vehicleSpeed);
        }
    }
    canExecuteOrder(nodes, edges) {
        let errorRefs = this.isRouteTraversable({ nodes, edges });
        Iif (errorRefs && errorRefs.length > 0) {
            return false;
        }
        for (const node of nodes) {
            for (const action of node.actions) {
                const context = {
                    action,
                    scope: "node",
                    updateActionStatus: undefined,
                    node,
                };
                errorRefs = this.isActionExecutable(context);
                Iif (errorRefs && errorRefs.length > 0) {
                    return false;
                }
            }
        }
        return true;
    }
    updateBatteryState(dx, dy) {
        const dist = Math.sqrt(dx * dx + dy * dy);
        const { batteryCharge } = this._vehicleState.batteryState;
        this._vehicleState.batteryState.batteryCharge = Math.max(0, batteryCharge - (dist * 100 / this.options.batteryMaxReach));
        this._vehicleState.batteryState.reach = this.getBatteryReach(this._vehicleState.batteryState.batteryCharge);
        this.controller.updateBatteryState(this._vehicleState.batteryState);
    }
    getBatteryReach(charge) {
        return Math.floor(this.options.batteryMaxReach * charge / 100);
    }
    _optionsWithDefaults(options) {
        const optionalDefaults = {
            initialPosition: { mapId: "local", x: 0, y: 0, theta: 0, lastNodeId: "0" },
            agvNormalDeviationXyTolerance: 0.5,
            agvNormalDeviationThetaTolerance: 0.349066,
            vehicleSpeed: 2,
            vehicleSpeedDistribution: undefined,
            vehicleTimeDistribution: undefined,
            batteryMaxReach: 28800,
            initialBatteryCharge: 100,
            fullBatteryChargeTime: 1,
            lowBatteryChargeThreshold: 1,
            tickRate: 5,
            timeLapse: 1,
        };
        return Object.assign(optionalDefaults, options);
    }
    _getActionDefinition(action, scope) {
        return this.actionDefinitions.find(d => d.actionType === action.actionType &&
            (d.actionScopes === scope || d.actionScopes.includes(scope)));
    }
    _finalizeAction(asm) {
        this._actionStateMachines.splice(this._actionStateMachines.indexOf(asm), 1);
    }
    _onTick(tick, tickInterval, realInterval) {
        for (const asm of this._actionStateMachines) {
            asm.tick(tick, tickInterval, realInterval);
        }
        this._advanceTraverse(realInterval);
        this._advanceBatteryCharge(tick, tickInterval, realInterval);
    }
    _advanceTraverse(realInterval) {
        var _a, _b;
        if (!this._traverseContext || this._vehicleState.isPaused || this._vehicleState.batteryState.charging) {
            return;
        }
        const traverseContext = this._traverseContext;
        const endNodePosition = traverseContext.endNode.nodePosition;
        const tx = endNodePosition.x - this._vehicleState.position.x;
        const ty = endNodePosition.y - this._vehicleState.position.y;
        const alpha = Math.atan2(ty, tx);
        if (!this._vehicleState.isDriving) {
            Iif (this._vehicleState.batteryState.batteryCharge < this.options.lowBatteryChargeThreshold) {
                return;
            }
            const targetDistance = Math.sqrt(tx ** 2 + ty ** 2);
            const targetSpeed = this.getTargetSpeed(false, targetDistance, traverseContext.edge.maxSpeed);
            this.startDriving(Math.cos(alpha) * targetSpeed, Math.sin(alpha) * targetSpeed, true);
        }
        else {
            const dx = this._vehicleState.velocity.vx * realInterval;
            const dy = this._vehicleState.velocity.vy * realInterval;
            if (tx ** 2 + ty ** 2 <= dx ** 2 + dy ** 2) {
                this._vehicleState.position.x = endNodePosition.x;
                this._vehicleState.position.y = endNodePosition.y;
                this._vehicleState.position.theta = (_a = endNodePosition.theta) !== null && _a !== void 0 ? _a : this._vehicleState.position.theta;
                this.updateBatteryState(tx, ty);
                const { lastNodeId: _, ...position } = this._vehicleState.position;
                this.controller.updateAgvPositionVelocity(position);
                this.stopDriving(true);
                this._traverseContext = undefined;
                traverseContext.edgeTraversed();
            }
            else {
                const isBatteryLow = this._vehicleState.batteryState.batteryCharge < this.options.lowBatteryChargeThreshold;
                this._vehicleState.position.x += dx;
                this._vehicleState.position.y += dy;
                this._vehicleState.position.theta = (_b = traverseContext.edge.orientation) !== null && _b !== void 0 ? _b : alpha;
                this.updateBatteryState(dx, dy);
                const { lastNodeId: _, ...position } = this._vehicleState.position;
                this.controller.updateAgvPositionVelocity(position);
                Iif (isBatteryLow) {
                    this.debug("low battery charge %d", this._vehicleState.batteryState.batteryCharge);
                    this.stopDriving();
                    this._batteryLowError = {
                        errorDescription: "stop driving due to low battery",
                        errorLevel: __1.ErrorLevel.Fatal,
                        errorType: "batteryLowError",
                        errorReferences: [
                            {
                                referenceKey: "batteryState.batteryCharge",
                                referenceValue: this._vehicleState.batteryState.batteryCharge.toString(),
                            },
                        ],
                    };
                    this.controller.updateErrors(this._batteryLowError, "add", true);
                }
            }
        }
    }
    _advanceBatteryCharge(tick, tickInterval, realInterval) {
        if (!this._vehicleState.batteryState.charging || this._vehicleState.isPaused) {
            return;
        }
        const chargeRate = 100 / 3600 / this.options.fullBatteryChargeTime;
        const currentCharge = this._vehicleState.batteryState.batteryCharge;
        const deltaCharge = chargeRate * realInterval;
        const newCharge = Math.min(100, currentCharge + deltaCharge);
        const isFullyCharged = newCharge === 100;
        this._vehicleState.batteryState.batteryCharge = newCharge;
        this._vehicleState.batteryState.reach = this.getBatteryReach(newCharge);
        this.controller.updateBatteryState(this._vehicleState.batteryState, false);
        let batteryLowError;
        Iif (this._batteryLowError && this._vehicleState.batteryState.batteryCharge >= this.options.lowBatteryChargeThreshold + 10) {
            batteryLowError = this._batteryLowError;
            this._batteryLowError = undefined;
        }
        const updateTicks = Math.ceil(1000 / chargeRate / tickInterval);
        if (tick % updateTicks === 0) {
            batteryLowError && this.controller.updateErrors(batteryLowError, "remove");
            this.controller.updateBatteryState(this._vehicleState.batteryState, !isFullyCharged);
        }
        Iif (isFullyCharged) {
            this.controller.updatePartialState(this._stopCharging(), true);
        }
    }
    _loadAdded() {
        this._vehicleState.currentLoad = {
            loadId: "RFID_" + this.controller.createUuid(),
            loadType: "EPAL",
            loadDimensions: { width: 1, height: 1, length: 1 },
            weight: 10 + 10 * Math.random(),
        };
        this.debug("picked load", this._vehicleState.currentLoad);
        return {
            loads: [this._vehicleState.currentLoad],
        };
    }
    _loadRemoved() {
        this.debug("dropped load", this._vehicleState.currentLoad);
        this._vehicleState.currentLoad = undefined;
        return {
            loads: [],
        };
    }
    _initPosition(action) {
        var _a;
        this._vehicleState.position.x = action.actionParameters.find(p => p.key === "x").value;
        this._vehicleState.position.y = action.actionParameters.find(p => p.key === "y").value;
        this._vehicleState.position.theta = action.actionParameters.find(p => p.key === "theta").value;
        this._vehicleState.position.mapId = action.actionParameters.find(p => p.key === "mapId").value;
        this._vehicleState.position.lastNodeId = action.actionParameters.find(p => p.key === "lastNodeId").value;
        const lastNodeSequenceId = (_a = action.actionParameters.find(p => p.key === "lastNodeSequenceId")) === null || _a === void 0 ? void 0 : _a.value;
        const { lastNodeId, ...position } = this._vehicleState.position;
        this.debug("init position %o with lastNodeId %s and lastNodeSequenceId %d", position, lastNodeId, lastNodeSequenceId);
        return {
            agvPosition: position,
            lastNodeId,
            lastNodeSequenceId: lastNodeSequenceId !== null && lastNodeSequenceId !== void 0 ? lastNodeSequenceId : 0,
        };
    }
    _startPause(context) {
        Iif (this._vehicleState.isPaused) {
            return undefined;
        }
        Iif (this._vehicleState.isDriving) {
            this.stopDriving();
        }
        this.debug("start pause");
        this._vehicleState.isPaused = true;
        for (const asm of this._actionStateMachines) {
            if (asm.actionContext !== context) {
                asm.pause();
            }
        }
        return { paused: true };
    }
    _stopPause(context) {
        Iif (!this._vehicleState.isPaused) {
            return undefined;
        }
        this.debug("stop pause");
        this._vehicleState.isPaused = false;
        Eif (context !== undefined) {
            for (const asm of this._actionStateMachines) {
                if (asm.actionContext !== context) {
                    asm.unpause();
                }
            }
            return { paused: false };
        }
        else {
            this.controller.updatePausedState(false, true);
        }
    }
    _startCharging() {
        Iif (this._vehicleState.batteryState.charging) {
            return undefined;
        }
        Iif (this._vehicleState.isDriving) {
            this.stopDriving();
        }
        this.debug("start charging");
        this._vehicleState.batteryState.charging = true;
        return { batteryState: this._vehicleState.batteryState };
    }
    _stopCharging() {
        Iif (!this._vehicleState.batteryState.charging) {
            return undefined;
        }
        this.debug("stop charging");
        this._vehicleState.batteryState.charging = false;
        return { batteryState: this._vehicleState.batteryState };
    }
    _calculateEstimatedOrderExecutionTimes(action) {
        const orders = action.actionParameters.find(p => p.key === "orders").value;
        const results = [];
        let currentNodePosition = this._vehicleState.position;
        try {
            for (const order of orders) {
                Iif (!this.canExecuteOrder(order.nodes, order.edges)) {
                    throw new Error("order is not executable");
                }
                results.push(this._calculateEstimatedOrderExecutionTime(order, currentNodePosition).toString());
                currentNodePosition = order.nodes[order.nodes.length - 1].nodePosition;
            }
        }
        catch {
            results.splice(0, results.length);
        }
        this.debug("calculated estimated order execution times: %o", results);
        return results.join(",");
    }
    _calculateEstimatedOrderExecutionTime(order, currentNodePosition) {
        var _a;
        let effectiveActionDuration = 0;
        for (const node of order.nodes) {
            let nonHardMaxDuration = 0;
            for (const action of node.actions) {
                Eif (action.blockingType === __1.BlockingType.Hard) {
                    effectiveActionDuration += nonHardMaxDuration;
                    effectiveActionDuration += this.getNodeActionDuration(action);
                    nonHardMaxDuration = 0;
                }
                else {
                    nonHardMaxDuration = Math.max(nonHardMaxDuration, this.getNodeActionDuration(action));
                }
            }
        }
        let edgeTraversalTime = 0;
        for (const edge of order.edges) {
            const startNode = order.nodes.find(n => n.nodeId === edge.startNodeId && n.sequenceId === edge.sequenceId - 1);
            const endNode = order.nodes.find(n => n.nodeId === edge.endNodeId && n.sequenceId === edge.sequenceId + 1);
            const startNodePosition = (_a = startNode.nodePosition) !== null && _a !== void 0 ? _a : currentNodePosition;
            const distance = Math.sqrt((endNode.nodePosition.x - startNodePosition.x) ** 2 +
                (endNode.nodePosition.y - startNodePosition.y) ** 2);
            edgeTraversalTime += (distance / this.getTargetSpeed(true, distance, edge.maxSpeed));
        }
        return edgeTraversalTime + effectiveActionDuration;
    }
}
exports.VirtualAgvAdapter = VirtualAgvAdapter;
function getTransitionDuration(transition, action) {
    var _a;
    Eif ("durationTime" in transition) {
        if (typeof transition.durationTime === "number") {
            return transition.durationTime;
        }
        Eif (Array.isArray(transition.durationTime) &&
            typeof transition.durationTime[0] === "string" &&
            typeof transition.durationTime[1] === "number") {
            const param = transition.durationTime[0];
            const kv = (_a = action.actionParameters) === null || _a === void 0 ? void 0 : _a.find(p => p.key === param);
            if (kv !== undefined) {
                return kv.value;
            }
            return transition.durationTime[1];
        }
    }
    return undefined;
}
class VirtualActionStateMachine {
    constructor(actionContext, actionDefinition, _finalizeAction, _debug, _shouldPause) {
        this.actionContext = actionContext;
        this.actionDefinition = actionDefinition;
        this._finalizeAction = _finalizeAction;
        this._debug = _debug;
        this._shouldPause = _shouldPause;
        this._actionStatus = undefined;
        this._actionStatusOnPause = undefined;
        this._shouldTerminate = false;
        this._shouldCancel = false;
        this._statusDurationTimes = new Map(Object.keys(actionDefinition.transitions).map((s) => [s, 0]));
    }
    matches(actionId, scope) {
        return this.actionContext.action.actionId === actionId &&
            this.actionContext.scope === scope;
    }
    tick(tick, tickInterval, realInterval) {
        Iif (this._shouldTerminate === undefined || this._shouldCancel === undefined) {
            return;
        }
        Iif (this._shouldPause && this._actionStatus !== __1.ActionStatus.Paused) {
            this._actionStatusOnPause = this._actionStatus || this.actionDefinition.transitions.ON_INIT.next;
            this._transition({ actionStatus: __1.ActionStatus.Paused });
            return;
        }
        Iif (!this._shouldPause && this._actionStatus === __1.ActionStatus.Paused) {
            const resumedStatus = this._actionStatusOnPause;
            this._actionStatusOnPause = undefined;
            this._transition({ actionStatus: resumedStatus });
            return;
        }
        if (this._actionStatus === undefined) {
            this._transition({ actionStatus: this.actionDefinition.transitions.ON_INIT.next });
            return;
        }
        Iif (this._shouldCancel === true && this.actionDefinition.transitions.ON_CANCEL) {
            const { linkedState: ls } = this.actionDefinition.transitions.ON_CANCEL;
            this._transition({
                actionStatus: __1.ActionStatus.Failed,
                linkedState: ls ? ls(this.actionContext) : undefined,
            });
            return;
        }
        Iif (this._shouldTerminate === true) {
            const { next: nxt, linkedState: ls } = this.actionDefinition.transitions.ON_TERMINATE;
            this._transition({
                actionStatus: nxt,
                linkedState: ls ? ls(this.actionContext) : undefined,
            });
            return;
        }
        Iif (this._actionStatus === __1.ActionStatus.Paused) {
            return;
        }
        const actionStatusDef = this.actionDefinition.transitions[this._actionStatus];
        let duration = this._statusDurationTimes.get(this._actionStatus);
        duration += realInterval;
        const transitionDuration = getTransitionDuration(actionStatusDef, this.actionContext.action);
        if (transitionDuration !== undefined && duration >= transitionDuration) {
            this._statusDurationTimes.set(this._actionStatus, 0);
            this._transition({ actionStatus: actionStatusDef.next });
        }
        else {
            this._statusDurationTimes.set(this._actionStatus, duration);
        }
    }
    terminate() {
        if (this.actionContext.scope !== "edge" || this._shouldTerminate !== false) {
            return;
        }
        this._debug("should terminate action %o", this.actionContext);
        this._shouldTerminate = true;
    }
    cancel() {
        if (this.actionContext.scope === "instant" || this._shouldCancel !== false || !this.actionDefinition.transitions.ON_CANCEL) {
            return;
        }
        this._debug("should cancel action %o", this.actionContext);
        this._shouldCancel = true;
    }
    pause() {
        this._debug("should pause action %o", this.actionContext);
        this._shouldPause = true;
    }
    unpause() {
        this._debug("should unpause action %o", this.actionContext);
        this._shouldPause = false;
    }
    _transition(change) {
        var _a;
        this._actionStatus = change.actionStatus;
        if (this._actionStatus === __1.ActionStatus.Finished || this._actionStatus === __1.ActionStatus.Failed) {
            this._shouldTerminate = undefined;
            this._shouldCancel = undefined;
            this._shouldPause = false;
            this._finalizeAction();
        }
        const { linkedState, resultDescription, errorDescription } = (_a = this.actionDefinition.transitions[this._actionStatus]) !== null && _a !== void 0 ? _a : {};
        change = {
            actionStatus: this._actionStatus,
            linkedState: Object.assign({}, change.linkedState, linkedState ? linkedState(this.actionContext) : undefined),
            resultDescription: resultDescription ? resultDescription(this.actionContext) : undefined,
            errorDescription: errorDescription ? errorDescription(this.actionContext) : undefined,
        };
        this._debug("transition action %o to status %o", this.actionContext, change);
        this.actionContext.updateActionStatus(change);
    }
}