Files
2026-07-27 14:07:26 +08:00

71 lines
1.9 KiB
JavaScript

"use strict";
const common_vendor = require("../common/vendor.js");
const utils_bluetooth = require("../utils/bluetooth.js");
const useBluetoothStore = common_vendor.defineStore("bluetooth", () => {
const isConnected = common_vendor.ref(false);
const isDiscovering = common_vendor.ref(false);
const deviceList = common_vendor.ref([]);
const connectedDevice = common_vendor.ref(null);
const currentWeight = common_vendor.ref(0);
const init = async () => {
try {
await utils_bluetooth.initBluetooth();
} catch (error) {
console.error("Bluetooth init failed:", error);
}
};
const startScan = async () => {
isDiscovering.value = true;
deviceList.value = [];
await utils_bluetooth.startDiscovery((devices) => {
deviceList.value = devices;
});
};
const stopScan = () => {
isDiscovering.value = false;
utils_bluetooth.stopDiscovery();
};
const connect = async (deviceId) => {
try {
await utils_bluetooth.connectDevice(deviceId);
const device = deviceList.value.find((d) => d.deviceId === deviceId);
if (device) {
connectedDevice.value = device;
isConnected.value = true;
}
utils_bluetooth.listenWeightData((weight) => {
currentWeight.value = weight;
});
} catch (error) {
console.error("Connect failed:", error);
}
};
const disconnect = async () => {
try {
await utils_bluetooth.disconnectDevice();
isConnected.value = false;
connectedDevice.value = null;
currentWeight.value = 0;
} catch (error) {
console.error("Disconnect failed:", error);
}
};
const resetWeight = () => {
currentWeight.value = 0;
};
return {
isConnected,
isDiscovering,
deviceList,
connectedDevice,
currentWeight,
init,
startScan,
stopScan,
connect,
disconnect,
resetWeight
};
});
exports.useBluetoothStore = useBluetoothStore;