All files / controller master-controller.js

92.35% Statements 326/353
86.33% Branches 240/278
96.82% Functions 61/63
92.42% Lines 305/330

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    25x 25x 25x     14x 14x 14x 14x 14x     14x       174x 174x 174x 4x 4x   170x 170x 170x 170x 170x                   58x 58x 58x 58x   58x 58x 21x     45x   58x 58x 58x 58x 58x                                 14x 1297x     14x     14x     1297x       1828x   1828x 1828x 8394x 346x   8394x 1820x   8394x 1670x   8394x 1670x       1828x 142x   1686x 8x   1678x 1670x   8x   8x 8x   1678x 90x 90x 90x     1297x 1297x 441x   1297x 1297x 1297x 84x 180x 92x 64x     28x 28x 9x     19x 19x 4x               441x 442x 14x   428x 428x 304x 304x 304x 304x 57x     57x 57x 57x 57x 57x 57x 57x       247x 186x         441x 441x 132x 132x 41x 18x   18x 18x     18x 23x 18x     23x 18x 18x 18x 18x 18x 18x 18x     441x 508x 508x 508x 444x 444x 444x 161x 161x 161x 4x     157x   161x 161x         441x 329x     441x 112x 112x 56x       329x 57x     441x 113x 113x 113x 113x 113x 112x   113x   441x 441x 441x 68x 68x 7x     61x   68x 56x   68x 68x 68x     373x           170x                           170x 170x 68x 68x   170x 170x 170x 127x 127x   170x 170x 170x     164x 74x   164x 164x     164x 164x     164x 164x 121x 121x 62x         3309x 3309x 1677x   1632x 1632x 498x   1134x     178x 178x 72x   106x     132x 132x 168x 168x 18x   150x   114x     170x 170x 170x 274x 22x   252x 59x     170x 110x 21x   89x 4x       170x 170x       441x 441x 115x   326x 22x     304x   137x 136x 136x 59x     78x     510x 510x 23x 23x 26x 23x       487x     137x     140x     540x     440x     883x     119x 140x 107x   119x     243x 172x 36x   172x 172x 172x 172x     243x 58x               58x 58x   185x 185x 185x 185x       185x 114x 114x   185x       185x       185x       185x       185x 114x         185x     185x 185x 185x       64x 64x 64x 64x 49x   64x     64x 64x       13x 13x 13x     62x 62x 62x 54x       19x 19x     1297x 123x   1174x   1814x 1814x 4443x 78x 78x   1174x 1174x 15x 15x   1159x 13x       34x   38x 95x 15x         25x  
"use strict";
/*! Copyright (c) 2021 Siemens AG. Licensed under the MIT License. */
Object.defineProperty(exports, "__esModule", { value: true });
exports.MasterController = void 0;
const __1 = require("..");
class MasterController extends __1.MasterControlClient {
    constructor(clientOptions, controllerOptions) {
        super(clientOptions);
        this._currentOrders = new __1.AgvIdMap();
        this._currentInstantActions = new __1.AgvIdMap();
        this._currentInstantActionsValidationErrors = [];
        this._controllerOptions = this._controllerOptionsWithDefaults(controllerOptions);
    }
    get controllerOptions() {
        return this._controllerOptions;
    }
    async assignOrder(agvId, order, eventHandler) {
        var _a;
        this.debug("Assigning order %o to AGV %o", order, agvId);
        let cache = this._getOrderStateCache(agvId, order.orderId, order.orderUpdateId);
        if (cache !== undefined) {
            this.debug("Discarded order %o for AGV %o", order, agvId);
            return undefined;
        }
        cache = this._addOrderStateCache(agvId, order, eventHandler);
        try {
            const orderWithHeader = await this.publish(__1.Topic.Order, agvId, order);
            this.debug("Assigned order with header %o to AGV %o", orderWithHeader, agvId);
            return orderWithHeader;
        }
        catch (error) {
            this.debug("Error assigning order %o to AGV %o: %s", order, agvId, (_a = error.message) !== null && _a !== void 0 ? _a : error);
            this._removeOrderStateCache(cache);
            throw error;
        }
    }
    async initiateInstantActions(agvId, instantActions, eventHandler) {
        var _a;
        this.debug("Initiating instant actions %o on AGV %o", instantActions, agvId);
        let actionStateCaches = this._currentInstantActions.get(agvId);
        Eif (!actionStateCaches) {
            this._currentInstantActions.set(agvId, actionStateCaches = new Map());
        }
        const newInstantActionsRef = this._currentInstantActionsRef === undefined ? 1 : this._currentInstantActionsRef + 1;
        if (this.clientOptions.vdaVersion === "1.1.0") {
            instantActions.instantActions.forEach(action => actionStateCaches.set(action.actionId, { agvId, action, eventHandler, instantActionsRef: newInstantActionsRef }));
        }
        else {
            instantActions.actions.forEach(action => actionStateCaches.set(action.actionId, { agvId, action, eventHandler, instantActionsRef: newInstantActionsRef }));
        }
        try {
            const actionsWithHeader = await this.publish(__1.Topic.InstantActions, agvId, instantActions);
            this._currentInstantActionsRef = newInstantActionsRef;
            this.debug("Initiated instant actions %o on AGV %o", actionsWithHeader, agvId);
            return actionsWithHeader;
        }
        catch (error) {
            this.debug("Error initiating instant actions %o on AGV %o: %s", instantActions, agvId, (_a = error.message) !== null && _a !== void 0 ? _a : error);
            if (this.clientOptions.vdaVersion === "1.1.0") {
                instantActions.instantActions.forEach(action => actionStateCaches.delete(action.actionId));
            }
            else {
                instantActions.actions.forEach(action => actionStateCaches.delete(action.actionId));
            }
            if (actionStateCaches.size === 0) {
                this._currentInstantActions.delete(agvId);
            }
            throw error;
        }
    }
    async onStarted() {
        await super.onStarted();
        await this.subscribe(__1.Topic.State, this.controllerOptions.targetAgvs, (state, agvId) => this._dispatchState(state, agvId));
    }
    _controllerOptionsWithDefaults(options) {
        const optionalDefaults = {
            targetAgvs: {},
        };
        return Object.assign(optionalDefaults, options);
    }
    _dispatchState(state, agvId) {
        for (const error of state.errors) {
            let topic;
            let orderId;
            let orderUpdateId;
            let hasActionIdRef = false;
            let cache;
            Eif (error.errorReferences !== undefined) {
                for (const errorRef of error.errorReferences) {
                    if (errorRef.referenceKey === "actionId") {
                        hasActionIdRef = true;
                    }
                    if (errorRef.referenceKey === "topic") {
                        topic = errorRef.referenceValue;
                    }
                    if (errorRef.referenceKey === "orderId") {
                        orderId = errorRef.referenceValue;
                    }
                    if (errorRef.referenceKey === "orderUpdateId") {
                        orderUpdateId = parseInt(errorRef.referenceValue, 10);
                    }
                }
            }
            if (topic !== undefined && topic !== __1.Topic.Order) {
                continue;
            }
            if (hasActionIdRef && error.errorType !== __1.ErrorType.Order) {
                continue;
            }
            if (orderId !== undefined && orderUpdateId !== undefined) {
                cache = this._getOrderStateCache(agvId, orderId, orderUpdateId);
            }
            else Iif (topic === __1.Topic.Order && error.errorType === __1.ErrorType.OrderValidation) {
            }
            else Eif (orderId === undefined) {
                cache = this._getLastAssignedOrderStateCache(agvId);
            }
            if (cache !== undefined) {
                this._removeOrderStateCache(cache);
                this.debug("onOrderProcessed with error %o for cache %o with state %j", error, cache, state);
                cache.eventHandler.onOrderProcessed(error, false, false, { order: cache.order, agvId, state });
            }
        }
        const orderStateCache = this._getOrderStateCache(agvId, state.orderId, state.orderUpdateId);
        if (orderStateCache) {
            this._dispatchOrderState(state, orderStateCache);
        }
        this._updateInstantActionsValidationError(state.errors);
        const actionStateCaches = this._currentInstantActions.get(agvId);
        if (actionStateCaches) {
            for (const [actionId, actionStateCache] of actionStateCaches) {
                const actionState = state.actionStates.find(s => s.actionId === actionId);
                if (actionState) {
                    this._dispatchInstantActionState(actionState, actionStateCache, state);
                }
                else {
                    const actionError = this._getActionError(state.errors, actionId, true);
                    if (actionError) {
                        this._dispatchInstantActionError(actionError, actionStateCache, state);
                    }
                    else {
                        const validationError = this._getInstantActionsValidationError(actionStateCache.instantActionsRef);
                        if (validationError) {
                            this._dispatchInstantActionError(validationError, actionStateCache, state);
                        }
                    }
                }
            }
        }
    }
    _dispatchOrderState(state, cache) {
        const processEdgeEvents = () => {
            if (this._isOrderCanceling(cache, state, [__1.ActionStatus.Running, __1.ActionStatus.Finished])) {
                return;
            }
            const nextEdge = this._getNextReleasedEdge(cache.combinedOrder, cache.lastNodeTraversed);
            if (nextEdge) {
                const startNode = this._getEdgeStartNode(cache.combinedOrder, nextEdge);
                const endNode = this._getEdgeEndNode(cache.combinedOrder, nextEdge);
                const edgeState = state.edgeStates.find(s => s.edgeId === nextEdge.edgeId && s.sequenceId === nextEdge.sequenceId);
                if (!edgeState) {
                    Iif (cache.lastEdgeProcessed === nextEdge) {
                        return;
                    }
                    this._updateEdgeStateChanges(nextEdge, startNode, endNode, cache, state);
                    cache.lastEdgeStateChanges = undefined;
                    cache.edgeStateChangeInvocations = 0;
                    cache.lastEdgeProcessed = nextEdge;
                    this.debug("onEdgeTraversed %o for cache %j", nextEdge, cache);
                    Eif (cache.eventHandler.onEdgeTraversed) {
                        cache.eventHandler.onEdgeTraversed(nextEdge, startNode, endNode, { order: cache.order, agvId: cache.agvId, state });
                    }
                }
                else {
                    if (cache.lastEdgeStateChanges !== undefined || this._areAllBlockingActionsEnded(cache.lastNodeTraversed, state)) {
                        this._updateEdgeStateChanges(nextEdge, startNode, endNode, cache, state);
                    }
                }
            }
        };
        this.debug("Dispatching order state %j \nfor cache %j", state, cache);
        if (cache.lastCache !== undefined) {
            const lastCache = this._getLastActiveOrderStateCache(cache);
            if (lastCache !== undefined) {
                let lastHorizonStartIndex = lastCache.combinedOrder.nodes.findIndex(n => !n.released);
                const lastBaseEnd = lastCache.combinedOrder.nodes[lastHorizonStartIndex === -1 ?
                    lastCache.combinedOrder.nodes.length - 1 : lastHorizonStartIndex - 1];
                const newFirstNodeActions = cache.combinedOrder.nodes[0].actions;
                cache.combinedOrder.nodes = lastCache.combinedOrder.nodes
                    .slice(0, lastHorizonStartIndex === -1 ? undefined : lastHorizonStartIndex)
                    .concat(cache.combinedOrder.nodes.slice(1));
                lastBaseEnd.actions = lastBaseEnd.actions.concat(newFirstNodeActions);
                lastHorizonStartIndex = lastCache.combinedOrder.edges.findIndex(n => !n.released);
                cache.combinedOrder.edges = lastCache.combinedOrder.edges
                    .slice(0, lastHorizonStartIndex === -1 ? undefined : lastHorizonStartIndex)
                    .concat(cache.combinedOrder.edges);
                cache.lastNodeTraversed = cache.combinedOrder.nodes.find(n => { var _a, _b; return n.nodeId === ((_a = lastCache.lastNodeTraversed) === null || _a === void 0 ? void 0 : _a.nodeId) && n.sequenceId === ((_b = lastCache.lastNodeTraversed) === null || _b === void 0 ? void 0 : _b.sequenceId); });
                cache.lastEdgeStateChanges = lastCache.lastEdgeStateChanges;
                cache.edgeStateChangeInvocations = lastCache.edgeStateChangeInvocations;
                cache.lastEdgeProcessed = lastCache.lastEdgeProcessed;
                cache.mappedActions = new Map([...lastCache.mappedActions, ...cache.mappedActions]);
                cache.lastActionStates = lastCache.lastActionStates;
                this.debug("stitching current order onto active order with combined cache %j", cache);
                this._removeOrderStateCache(lastCache, true);
            }
        }
        for (const actionState of state.actionStates) {
            const { actionId, actionStatus } = actionState;
            const actionTarget = cache.mappedActions.get(actionId);
            if (actionTarget) {
                const [action, target] = actionTarget;
                const lastActionState = cache.lastActionStates.get(actionId);
                if ((lastActionState === null || lastActionState === void 0 ? void 0 : lastActionState.actionStatus) !== actionStatus) {
                    cache.lastActionStates.set(actionId, actionState);
                    const error = actionStatus === __1.ActionStatus.Failed ? this._getActionError(state.errors, actionId, false) : undefined;
                    if (error) {
                        this.debug("onActionStateChanged %o with error %o for action %s on target %o for cache %j", actionState, error, action, target, cache);
                    }
                    else {
                        this.debug("onActionStateChanged %o for action %s on target %o for cache %j", actionState, action, target, cache);
                    }
                    Eif (cache.eventHandler.onActionStateChanged) {
                        cache.eventHandler.onActionStateChanged(actionState, error, action, target, { order: cache.order, agvId: cache.agvId, state });
                    }
                }
            }
        }
        if (cache.lastNodeTraversed) {
            processEdgeEvents();
        }
        let nextNode;
        if (cache.lastNodeTraversed === undefined) {
            const firstNode = cache.combinedOrder.nodes[0];
            if (!state.nodeStates.find(n => n.nodeId === firstNode.nodeId && n.sequenceId === firstNode.sequenceId)) {
                nextNode = firstNode;
            }
        }
        else {
            if (cache.lastNodeTraversed.nodeId !== state.lastNodeId || cache.lastNodeTraversed.sequenceId !== state.lastNodeSequenceId) {
                nextNode = this._getNode(cache.combinedOrder, state.lastNodeId, state.lastNodeSequenceId);
            }
        }
        if (nextNode !== undefined) {
            cache.lastNodeTraversed = nextNode;
            const nextEdge = this._getNextEdge(cache.combinedOrder, nextNode);
            const edgeEndNode = nextEdge ? this._getEdgeEndNode(cache.combinedOrder, nextEdge) : undefined;
            this.debug("onNodeTraversed %o for cache %j", nextNode, cache);
            if (cache.eventHandler.onNodeTraversed) {
                cache.eventHandler.onNodeTraversed(nextNode, nextEdge, edgeEndNode, { order: cache.order, agvId: cache.agvId, state });
            }
            processEdgeEvents();
        }
        const result = this._isOrderProcessed(cache, state);
        const isActive = result === undefined;
        if (result !== false && cache.lastOrderProcessedIsActive !== isActive) {
            const byCancelation = this._isOrderCanceling(cache, state, [__1.ActionStatus.Finished]);
            if (byCancelation) {
                this.debug("onOrderProcessed by cancelation in state active=%s", isActive);
            }
            else {
                this.debug("onOrderProcessed in state active=%s", isActive);
            }
            if (!isActive) {
                this._removeOrderStateCache(cache, true);
            }
            cache.lastOrderProcessedIsActive = isActive;
            cache.eventHandler.onOrderProcessed(undefined, byCancelation, isActive, { order: cache.order, agvId: cache.agvId, state });
            return;
        }
        else {
            Iif (cache.eventHandler.onStateUpdate) {
                cache.eventHandler.onStateUpdate({ order: cache.order, agvId: cache.agvId, state });
            }
        }
    }
    _addOrderStateCache(agvId, order, eventHandler) {
        const cache = {
            agvId,
            order: order,
            eventHandler,
            lastOrderProcessedIsActive: null,
            lastCache: this._getLastAssignedOrderStateCache(agvId),
            combinedOrder: {
                edges: [...order.edges],
                nodes: [...order.nodes],
                orderId: order.orderId,
                orderUpdateId: order.orderUpdateId,
                zoneSetId: order.zoneSetId,
            },
        };
        let orderIds = this._currentOrders.get(cache.agvId);
        if (!orderIds) {
            orderIds = new Map();
            this._currentOrders.set(cache.agvId, orderIds);
        }
        orderIds["lastCache"] = cache;
        let orderUpdateIds = orderIds.get(cache.order.orderId);
        if (!orderUpdateIds) {
            orderUpdateIds = new Map();
            orderIds.set(cache.order.orderId, orderUpdateIds);
        }
        this._initCachedActions(cache);
        orderUpdateIds.set(cache.order.orderUpdateId, cache);
        return cache;
    }
    _removeOrderStateCache(cache, deleteLastCache = false) {
        if (deleteLastCache) {
            cache.lastCache = undefined;
        }
        const orderIds = this._currentOrders.get(cache.agvId);
        Iif (!orderIds) {
            return;
        }
        const orderUpdateIds = orderIds.get(cache.order.orderId);
        Iif (!orderUpdateIds) {
            return;
        }
        orderUpdateIds.delete(cache.order.orderUpdateId);
        if (orderUpdateIds.size === 0) {
            orderIds.delete(cache.order.orderId);
            if (orderIds.size === 0) {
                this._currentOrders.delete(cache.agvId);
            }
        }
    }
    _getOrderStateCache(agvId, orderId, orderUpdateId) {
        const orderIds = this._currentOrders.get(agvId);
        if (!orderIds) {
            return undefined;
        }
        const orderUpdateIds = orderIds.get(orderId);
        if (!orderUpdateIds) {
            return undefined;
        }
        return orderUpdateIds.get(orderUpdateId);
    }
    _getLastAssignedOrderStateCache(agvId) {
        const orderIds = this._currentOrders.get(agvId);
        if (!orderIds) {
            return undefined;
        }
        return orderIds["lastCache"];
    }
    _getLastActiveOrderStateCache(cache) {
        let nextCache = cache.lastCache;
        do {
            const lastCache = this._getOrderStateCache(cache.agvId, nextCache.order.orderId, nextCache.order.orderUpdateId);
            if (lastCache === nextCache) {
                return lastCache;
            }
            nextCache = nextCache.lastCache;
        } while (nextCache !== undefined);
        return nextCache;
    }
    _initCachedActions(cache) {
        Eif (!cache.mappedActions) {
            cache.mappedActions = new Map();
            for (const node of cache.order.nodes) {
                if (!node.released) {
                    break;
                }
                for (const action of node.actions) {
                    cache.mappedActions.set(action.actionId, [action, node]);
                }
            }
            for (const edge of cache.order.edges) {
                if (!edge.released) {
                    break;
                }
                for (const action of edge.actions) {
                    cache.mappedActions.set(action.actionId, [action, edge]);
                }
            }
        }
        Eif (!cache.lastActionStates) {
            cache.lastActionStates = new Map();
        }
    }
    _isOrderProcessed(cache, state) {
        let isProcessed = false;
        if (state.nodeStates.length === 0 && state.edgeStates.length === 0) {
            isProcessed = true;
        }
        else if (state.nodeStates.every(s => !s.released) && state.edgeStates.every(s => !s.released)) {
            isProcessed = undefined;
        }
        else {
            return false;
        }
        for (const [, [action]] of cache.mappedActions) {
            const as = cache.lastActionStates.get(action.actionId);
            if (as === undefined || (as.actionStatus !== __1.ActionStatus.Finished && as.actionStatus !== __1.ActionStatus.Failed)) {
                return false;
            }
        }
        return isProcessed;
    }
    _isOrderCanceling(cache, state, cancelStatus) {
        const actionStateCaches = this._currentInstantActions.get(cache.agvId);
        if (actionStateCaches) {
            for (const [actionId, actionStateCache] of actionStateCaches) {
                Eif (actionStateCache.action.actionType === "cancelOrder") {
                    const as = state.actionStates.find(s => s.actionId === actionId);
                    return as !== undefined && cancelStatus.includes(as.actionStatus);
                }
            }
        }
        return false;
    }
    _getNode(order, nodeId, sequenceId) {
        return order.nodes.find(n => n.nodeId === nodeId && n.sequenceId === sequenceId);
    }
    _getNextEdge(order, node) {
        return order.edges.find(e => e.startNodeId === node.nodeId && e.sequenceId === node.sequenceId + 1);
    }
    _getNextReleasedEdge(order, node) {
        return order.edges.find(e => e.released && e.startNodeId === node.nodeId && e.sequenceId === node.sequenceId + 1);
    }
    _getEdgeStartNode(order, edge) {
        return order.nodes.find(n => n.nodeId === edge.startNodeId && n.sequenceId === edge.sequenceId - 1);
    }
    _getEdgeEndNode(order, edge) {
        return order.nodes.find(n => n.nodeId === edge.endNodeId && n.sequenceId === edge.sequenceId + 1);
    }
    _areAllBlockingActionsEnded(node, state) {
        const isActionEnded = (action) => {
            const as = state.actionStates.find(s => s.actionId === action.actionId);
            return as !== undefined && (as.actionStatus === __1.ActionStatus.Finished || as.actionStatus === __1.ActionStatus.Failed);
        };
        return node.actions.every(a => a.blockingType === __1.BlockingType.None || isActionEnded(a));
    }
    _updateEdgeStateChanges(edge, startNode, endNode, cache, state) {
        const reportChanges = (changes) => {
            if (cache.edgeStateChangeInvocations === undefined) {
                cache.edgeStateChangeInvocations = 0;
            }
            cache.edgeStateChangeInvocations++;
            this.debug("onEdgeTraversing %o with changes %o for cache %j", edge, changes, cache);
            Eif (cache.eventHandler.onEdgeTraversing) {
                cache.eventHandler.onEdgeTraversing(edge, startNode, endNode, changes, cache.edgeStateChangeInvocations, { order: cache.order, agvId: cache.agvId, state });
            }
        };
        if (cache.lastEdgeStateChanges === undefined) {
            cache.lastEdgeStateChanges = {
                distanceSinceLastNode: state.distanceSinceLastNode,
                driving: state.driving,
                newBaseRequest: state.newBaseRequest,
                operatingMode: state.operatingMode,
                paused: state.paused,
                safetyState: state.safetyState,
            };
            reportChanges(cache.lastEdgeStateChanges);
            return;
        }
        const currentChanges = cache.lastEdgeStateChanges;
        const newDeltas = {};
        let hasChanges = false;
        Iif (currentChanges.distanceSinceLastNode !== state.distanceSinceLastNode) {
            currentChanges.distanceSinceLastNode = newDeltas.distanceSinceLastNode = state.distanceSinceLastNode;
            hasChanges = true;
        }
        if (currentChanges.driving !== state.driving) {
            currentChanges.driving = newDeltas.driving = state.driving;
            hasChanges = true;
        }
        Iif (currentChanges.newBaseRequest !== state.newBaseRequest) {
            currentChanges.newBaseRequest = newDeltas.newBaseRequest = state.newBaseRequest;
            hasChanges = true;
        }
        Iif (currentChanges.operatingMode !== state.operatingMode) {
            currentChanges.operatingMode = newDeltas.operatingMode = state.operatingMode;
            hasChanges = true;
        }
        Iif (currentChanges.paused !== state.paused) {
            currentChanges.paused = newDeltas.paused = state.paused;
            hasChanges = true;
        }
        Iif (this._hasSafetyStateChanged(currentChanges.safetyState, state.safetyState)) {
            currentChanges.safetyState = newDeltas.safetyState = state.safetyState;
            hasChanges = true;
        }
        if (hasChanges) {
            reportChanges(newDeltas);
        }
    }
    _hasSafetyStateChanged(prev, next) {
        var _a, _b;
        Iif (prev.fieldViolation !== next.fieldViolation) {
            return true;
        }
        const prevEStop = (_a = prev.eStop) !== null && _a !== void 0 ? _a : prev.activeEmergencyStop;
        const nextEStop = (_b = next.eStop) !== null && _b !== void 0 ? _b : next.activeEmergencyStop;
        return prevEStop !== nextEStop;
    }
    _dispatchInstantActionState(actionState, cache, state) {
        var _a;
        this.debug("Dispatching instant action state %o for cache %o with state %j", actionState, cache, state);
        Eif (actionState.actionStatus !== ((_a = cache.lastActionState) === null || _a === void 0 ? void 0 : _a.actionStatus)) {
            cache.lastActionState = actionState;
            if (actionState.actionStatus === __1.ActionStatus.Finished || actionState.actionStatus === __1.ActionStatus.Failed) {
                this._removeInstantActionStateCache(cache);
            }
            const error = actionState.actionStatus === __1.ActionStatus.Failed ?
                this._getActionError(state.errors, cache.action.actionId, true) :
                undefined;
            this.debug("onActionStateChanged for instant action state %o with error %o for cache %o with state %j", actionState, error, cache, state);
            cache.eventHandler.onActionStateChanged(actionState, error, cache.action, cache.agvId, state);
        }
    }
    _dispatchInstantActionError(actionError, cache, state) {
        this._removeInstantActionStateCache(cache);
        this.debug("onActionError %o for instant action cache %o with state %j", actionError, cache, state);
        cache.eventHandler.onActionError(actionError, cache.action, cache.agvId, state);
    }
    _removeInstantActionStateCache(cache) {
        const actionStateCaches = this._currentInstantActions.get(cache.agvId);
        actionStateCaches.delete(cache.action.actionId);
        if (actionStateCaches.size === 0) {
            this._currentInstantActions.delete(cache.agvId);
        }
    }
    _getInstantActionsValidationError(instanceActionsRef) {
        const ref = this._currentInstantActionsValidationErrors.find(r => r[0] === instanceActionsRef);
        return ref ? ref[1] : undefined;
    }
    _updateInstantActionsValidationError(errors) {
        if (this._currentInstantActionsRef === undefined) {
            return;
        }
        const validationErrors = errors.filter(error => {
            var _a;
            const refs = (_a = error.errorReferences) !== null && _a !== void 0 ? _a : [];
            return error.errorType === __1.ErrorType.InstantActionValidation &&
                refs.some(r => r.referenceKey === "topic" && r.referenceValue === __1.Topic.InstantActions) &&
                !refs.some(r => r.referenceKey === "orderId") &&
                !refs.some(r => r.referenceKey === "actionId");
        });
        const delta = validationErrors.length - this._currentInstantActionsValidationErrors.length;
        if (delta > 0) {
            this._currentInstantActionsValidationErrors.push(...validationErrors.slice(validationErrors.length - delta)
                .map((e, i) => [this._currentInstantActionsRef - i, e]));
        }
        else if (delta < 0) {
            this._currentInstantActionsValidationErrors.splice(0, -delta);
        }
    }
    _getActionError(errors, actionId, asInstantAction) {
        return errors.find(e => {
            var _a;
            const refs = (_a = e.errorReferences) !== null && _a !== void 0 ? _a : [];
            return refs.some(r => r.referenceKey === "actionId" && r.referenceValue === actionId) &&
                refs.some(r => r.referenceKey === "topic" &&
                    r.referenceValue === (asInstantAction ? __1.Topic.InstantActions : __1.Topic.Order));
        });
    }
}
exports.MasterController = MasterController;