# All files / stores devices.js

92.64% Statements 63/68
62.5% Branches 25/40
93.33% Functions 14/15
92.53% Lines 62/67

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

    2x

    13x

    6x

    1x
    1x

    1x

    1x
    1x

    1x

    3x
    3x

    3x
    2x
    2x
    2x

    3x

    2x
    10x

    2x

    2x
    2x
    2x

    2x
    2x

    2x
    2x
    2x

    2x
    1x

    1x
    1x

    1x
    2x
    2x

    5x

    5x
    1x

    4x

    3x
    3x
    3x
    3x
    3x

    3x
    3x

    3x
    3x
    1x

    2x

    2x

    3x
    3x
    2x

    2x

    2x

    3x
    3x

    1x
    1x

    1x

    1x
    1x

     import { defineStore } from "pinia";
    import { devicesApi } from "../api/modules/devices";

    const DEFAULT_STATE_CONCURRENCY = 4;

    function getDeviceId(device) {
      return String(device?.id || "");
    }

    function makeDeviceStatePatch(device, patch) {
      return {
        deviceId: getDeviceId(device),
        status: "idle",
        message: "",
        response: null,
        connectionStatus: device?.connection_status || "unknown",
        updatedAt: null,
        ...patch,
      };
    }

    function normalizeStatusSuccess(device, result) {
      const payload = result.data?.data?.device || {};
      const response = payload.device_response || {};

      return makeDeviceStatePatch(device, {
        status: "ready",
        message: response.status || "ok",
        response,
        connectionStatus: "active",
        updatedAt: new Date().toISOString(),
      });
    }

    function normalizeStatusError(device, result) {
      const raw = result.error?.raw || {};
      const connectionStatus = raw?.data?.connection_status || device?.connection_status || "unknown";

      return makeDeviceStatePatch(device, {
        status: "error",
        message: result.error?.message || "Device state is unavailable",
        response: raw,
        connectionStatus,
        updatedAt: new Date().toISOString(),
      });
    }

    async function runLimited(items, concurrency, worker) {
      let nextIndex = 0;
      const poolSize = Math.max(1, Math.min(concurrency, items.length));

      async function runWorker() {
        while (nextIndex < items.length) {
          const item = items[nextIndex];
          nextIndex += 1;
          await worker(item);
        }
      }

      await Promise.all(Array.from({ length: poolSize }, runWorker));
    }

    export const useDevicesStore = defineStore("devices", {
      state: () => ({
        devices: [],
        isLoading: false,
        error: null,
        isLoadingStates: false,
        stateError: null,
        stateByDeviceId: {},
        stateRunId: 0,
        rebootingIds: new Set(),
        _listAbortController: null,
        lastLoadedAt: null,
      }),

      getters: {
        total(state) {
          return state.devices.length;
        },
        isRebooting: (state) => (id) => state.rebootingIds.has(id),
      },

      actions: {
        async loadDevices() {
          this._listAbortController?.abort();
          const controller = new AbortController();
          this._listAbortController = controller;

          this.isLoading = true;
          this.error = null;

          const result = await devicesApi.list({ signal: controller.signal });
          this._listAbortController = null;
          this.isLoading = false;

          if (!result.ok) {
            Iif (result.error?.type === "timeout") {
              return result;
            }
            this.error = result.error;
            return result;
          }

          this.devices = result.data?.data?.devices || [];
          this.lastLoadedAt = new Date().toISOString();
          return result;
        },

        setDeviceState(device, patch) {
          const deviceId = getDeviceId(device);

          if (!deviceId) {
            return;
          }

          this.stateByDeviceId = {
            ...this.stateByDeviceId,
            [deviceId]: makeDeviceStatePatch(device, patch),
          };
        },

        async loadDeviceStates(options = {}) {
          const runId = this.stateRunId + 1;
          this.stateRunId = runId;
          this.isLoadingStates = true;
          this.stateError = null;
          this.stateByDeviceId = {};

          const devices = this.devices.slice();
          const targets = [];

          for (const device of devices) {
            if (device.connection_status === "lost") {
              this.setDeviceState(device, {
                status: "skipped",
                message: "Connection lost",
                connectionStatus: "lost",
              });
            } else {
              this.setDeviceState(device, {
                status: "loading",
                message: "Loading",
              });
              targets.push(device);
            }
          }

          try {
            await runLimited(targets, options.concurrency || DEFAULT_STATE_CONCURRENCY, async (device) => {
              const result = await devicesApi.status(device.id);

              Iif (this.stateRunId !== runId) {
                return;
              }

              this.stateByDeviceId = {
                ...this.stateByDeviceId,
                [getDeviceId(device)]: result.ok
                  ? normalizeStatusSuccess(device, result)
                  : normalizeStatusError(device, result),
              };
            });
          } catch (error) {
            if (this.stateRunId === runId) {
              this.stateError = {
                type: "state_loader_error",
                message: error?.message || "Device states loader failed",
              };
            }
          } finally {
            Eif (this.stateRunId === runId) {
              this.isLoadingStates = false;
            }
          }
        },

        async rebootDevice(id) {
          const deviceId = String(id);
          this.rebootingIds.add(deviceId);

          const result = await devicesApi.reboot(id);

          this.rebootingIds.delete(deviceId);
          return result;
        },
      },
    });