如何在智能家居示例中创建持久化虚拟设备?相关问题咨询
Hey there, let's tackle your smart home sample issues one by one—sounds like you're working through some common kinks with persistence and front-end loading. Here's how I'd approach each problem:
1. Fix Slow Load Times & Excessive "/bower_components" Requests
The flood of requests to /bower_components is almost certainly the culprit behind your slow site. Here's how to fix it:
- First, make sure you've installed all front-end dependencies locally. Run
bower installin your project root—this pulls down all required libraries into the/bower_componentsfolder, so your server can serve them directly instead of trying to fetch them from remote sources (which causes delays or failures). - If you already ran
bower install, double-check your Node.js server setup. You need to explicitly tell Express to serve the/bower_componentsdirectory. Add this line to your server code if it's missing:app.use('/bower_components', express.static(__dirname + '/bower_components')); - Verify with your browser's DevTools (Network tab) that these requests are now returning 200 OK instead of 404s or slow responses. Ngrok adds minor latency, but the main issue here is almost certainly missing local dependencies.
2. Stop Devices From Disappearing After Login
Your devices vanishing when you log back in means they're stored in in-memory storage (which resets when the server restarts or sessions end). This ties directly into your persistence question, but here's the immediate fix:
- Check your
datastore.js—it's likely using a simple JavaScript object to hold devices, which gets wiped when the server stops. We'll modify this to use persistent storage next, but first ensure your device data is tied to the logged-in user's account (so Rick only sees his own devices).
3. Implement a Persistent Virtual Light with datastore.js
Since you mentioned missing docs for datastore.js, let's build a simple file-based persistence layer using a JSON file (no extra databases needed):
Step 1: Rewrite datastore.js for File Persistence
Replace the existing in-memory code with this, which reads/writes devices to a devices.json file:
const fs = require('fs'); const path = require('path'); // Path to our persistent data file const DATA_FILE = path.join(__dirname, 'devices.json'); // Load existing devices on server startup let devices = {}; try { const savedData = fs.readFileSync(DATA_FILE, 'utf8'); devices = JSON.parse(savedData); } catch (err) { // If file doesn't exist, start with empty storage console.log('No existing device data found, starting fresh'); } // Helper to save changes to the file function saveDevices() { fs.writeFileSync(DATA_FILE, JSON.stringify(devices, null, 2)); } // Export modified datastore methods with persistence module.exports = { getDevice: (deviceId) => devices[deviceId], getDevices: () => Object.values(devices), addDevice: (device) => { devices[device.id] = device; saveDevices(); // Save after adding return device; }, updateDevice: (deviceId, updates) => { if (!devices[deviceId]) return null; devices[deviceId] = {...devices[deviceId], ...updates}; saveDevices(); // Save after updating return devices[deviceId]; }, deleteDevice: (deviceId) => { const device = devices[deviceId]; if (device) { delete devices[deviceId]; saveDevices(); // Save after deleting } return device; } };
Step 2: Add a Persistent Virtual Light
Add this code somewhere in your server initialization (like a setup.js file or directly in your main server script) to create a virtual light that persists across restarts:
const datastore = require('./datastore'); // Only add the light if it doesn't already exist const persistentLightId = 'rick-virtual-light'; if (!datastore.getDevice(persistentLightId)) { datastore.addDevice({ id: persistentLightId, name: 'Rick\'s Persistent Virtual Light', type: 'light', state: { on: false, brightness: 75 }, owner: 'rick' // Tie the device to Rick's account }); }
Step 3: Filter Devices by User Account
Make sure your API routes return only the devices belonging to the logged-in user. For example, in the route that fetches devices:
app.get('/api/devices', (req, res) => { // Assuming req.user holds the logged-in user's data (e.g., { username: 'rick' }) const userDevices = datastore.getDevices().filter(device => device.owner === req.user.username); res.json(userDevices); });
This ensures when Rick logs in, he only sees his devices, and they'll stay around even after server restarts or logging out/in.
内容的提问来源于stack exchange,提问作者Damn Vegetables

