### Install xmihome Node.js Package Source: https://github.com/alex2844/node-xmihome/blob/main/packages/node/README.md Installs the xmihome library using npm. For Linux users with Bluetooth, additional steps may be required during or after installation to configure D-Bus permissions. ```bash npm install xmihome ``` -------------------------------- ### Install Node-Xmihome Dependencies with Bun Source: https://github.com/alex2844/node-xmihome/blob/main/docs/README.md Installs all project dependencies and sets up symlinks between packages within the monorepo. This command requires Bun to be installed. ```bash bun install ``` -------------------------------- ### xmihome-setup-bluetooth Source: https://github.com/alex2844/node-xmihome/blob/main/packages/node/docs/en-US/CLI.md A utility to simplify Bluetooth configuration on Linux systems, including D-Bus policy generation and remote access setup. ```APIDOC ## POST /cli/xmihome-setup-bluetooth ### Description Configures Bluetooth on Linux systems, including D-Bus policies and optional remote access setup. ### Method POST ### Endpoint /cli/xmihome-setup-bluetooth ### Parameters #### Query Parameters - **remote** (boolean) - Optional - Generate configuration for remote D-Bus access via TCP proxy. - **port** (integer) - Optional - Port for remote access (default: 55555). - **host** (string) - Optional - Host to listen on for remote access (default: 0.0.0.0). ### Request Example ```bash xmihome-setup-bluetooth --remote --port 55556 ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message of successful Bluetooth setup. #### Response Example ```json { "message": "Bluetooth setup complete. D-Bus policies generated." } ``` ``` -------------------------------- ### Get and Set Device Properties with Node-XMIHome Source: https://context7.com/alex2844/node-xmihome/llms.txt Demonstrates how to read and write device properties using human-readable names or MiOT specification siid/piid values. Supports fetching all properties at once, single properties by name or ID, and setting properties. Includes examples for generic devices and kettle-specific properties. ```javascript import { XiaomiMiHome } from 'xmihome'; const miHome = new XiaomiMiHome({ credentials: { username: 'user@example.com', password: 'pass', country: 'sg' } }); const devices = await miHome.getDevices(); const device = await miHome.getDevice(devices[0]); await device.connect(); // Get all readable properties at once const allProperties = await device.getProperties(); console.log('All properties:', allProperties); // Output for humidifier: { on: true, current_humidity: 45, target_humidity: 50, fan_level: 2, ... } // Get single property by name (for supported models) const isOn = await device.getProperty('on'); const humidity = await device.getProperty('current_humidity'); console.log(`Power: ${isOn}, Humidity: ${humidity}%`); // Get property using MiOT spec (siid/piid) for any device const tempValue = await device.getProperty({ siid: 3, piid: 7 }); console.log(`Temperature: ${tempValue}`); // Set property by name await device.setProperty('on', true); await device.setProperty('target_humidity', 60); await device.setProperty('fan_level', 3); // Set property using MiOT spec await device.setProperty({ siid: 2, piid: 6 }, 55); // Set target humidity to 55% // Kettle-specific properties (Bluetooth device) const kettleDevice = await miHome.getDevice({ mac: 'AA:BB:CC:DD:EE:FF', model: 'yunmi.kettle.v2', token: 'your-kettle-token' }); await kettleDevice.connect(); // Set keep warm temperature await kettleDevice.setProperty('keep_warm_settings', { temperature: 80, type: 'heat_to_temperature' // or 'boil_and_cool_down' }); // Set keep warm duration (1-12 hours) await kettleDevice.setProperty('keep_warm_duration', 6); await device.disconnect(); await miHome.destroy(); ``` -------------------------------- ### CLI Commands: Authentication and Discovery Source: https://context7.com/alex2844/node-xmihome/llms.txt Provides command-line tools for initial setup, authentication, and device discovery without requiring code. Includes commands for logging into Xiaomi Cloud (saving credentials), interactive login, discovering devices by type (all, cloud, miio, bluetooth), forcing new discovery, and setting up Bluetooth permissions or remote access on Linux systems. Offers help options for each command. ```bash # Login to Xiaomi Cloud (saves credentials to ~/.config/xmihome/credentials.json) xmihome login -u your-email@example.com -p your-password -c sg # Interactive login (prompts for credentials) xmihome login # Discover all devices (cloud + local) xmihome devices --type all # Discover only cloud devices xmihome devices --type cloud # Discover only local MiIO (Wi-Fi) devices xmihome devices --type miio # Discover only Bluetooth LE devices xmihome devices --type bluetooth # Force new discovery (ignore cache) xmihome devices --type all --force # Setup Bluetooth permissions on Linux xmihome-setup-bluetooth # Setup remote Bluetooth access via TCP proxy xmihome-setup-bluetooth --remote --host 0.0.0.0 --port 55555 # Show help xmihome --help xmihome-setup-bluetooth --help ``` -------------------------------- ### Setup Bluetooth for Xiaomi Devices CLI Source: https://github.com/alex2844/node-xmihome/blob/main/packages/node/docs/en-US/CLI.md Simplifies Bluetooth configuration on Linux by generating D-Bus policy files and optionally setting up a proxy for remote access. Supports specifying remote port and host. ```bash xmihome-setup-bluetooth --remote --port 55555 --host 0.0.0.0 ``` ```bash xmihome-setup-bluetooth ``` -------------------------------- ### Create and Connect Device Instance (Node.js) Source: https://context7.com/alex2844/node-xmihome/llms.txt Creates or retrieves a cached Device instance for controlling a specific Xiaomi device. It can connect via cloud, MiIO, or Bluetooth, automatically detecting the best connection type or allowing explicit specification. Provides methods to get device name and model. ```javascript import { XiaomiMiHome } from 'xmihome'; const miHome = new XiaomiMiHome({ credentials: { username: 'user@example.com', password: 'pass', country: 'sg' } }); // Get devices first const devices = await miHome.getDevices(); const humidifierConfig = devices.find(d => d.model === 'deerma.humidifier.jsq2w'); // Create device instance from discovered config const device = await miHome.getDevice(humidifierConfig); // Or create from manual configuration const manualDevice = await miHome.getDevice({ id: 'device-cloud-id', address: '192.168.1.100', token: 'ffffffffffffffffffffffffffffffff', model: 'deerma.humidifier.jsq2w', name: 'Bedroom Humidifier' }); // Connect to device (auto-detects best connection type) await device.connect(); console.log(`Connected via: ${device.connectionType}`); // 'miio', 'bluetooth', or 'cloud' console.log(`Device name: ${device.getName()}`); console.log(`Device model: ${device.getModel()}`); // Explicit connection type await manualDevice.connect('miio'); // Force MiIO connection await miHome.destroy(); ``` -------------------------------- ### Build Node-Xmihome Packages with Bun Source: https://github.com/alex2844/node-xmihome/blob/main/docs/README.md Builds all packages in the monorepo that require a build step, such as node-red-contrib-xmihome. This command is used after installing dependencies. ```bash bun run build ``` -------------------------------- ### Control Xiaomi Mi Home Devices with xmihome (JavaScript) Source: https://github.com/alex2844/node-xmihome/blob/main/packages/node/README.md Demonstrates how to use the xmihome library in Node.js to connect to Xiaomi devices via the cloud, discover devices, get their properties, set new property values, and disconnect. It requires Xiaomi cloud credentials and handles device connection and disconnection. ```javascript import { XiaomiMiHome } from 'xmihome'; async function main() { const miHome = new XiaomiMiHome({ credentials: { username: process.env.XIAOMI_USERNAME, password: process.env.XIAOMI_PASSWORD, country: 'sg' }, connectionType: 'cloud', logLevel: 'error' }); try { const devices = await miHome.getDevices({ timeout: 30000, onDeviceFound: (device, devices, type) => { // Return true to include the device, false to ignore, or // an object { include?: boolean, stop?: boolean } to control discovery. return true; } }); console.log('Found devices:', devices); if (devices.length === 0) throw new Error('Device not found'); // Select a device to control const device = await miHome.getDevice(devices[0]); // Connect to the device (connection type will be determined automatically) await device.connect(); console.log(`Connected to "${device.getName()}" via: ${device.connectionType}`); // Get the current properties of the device const properties = await device.getProperties(); console.log('Current properties:', properties); // Set a new property value if (!properties.on) { await device.setProperty('on', true); console.log('Device turned on'); } // Disconnect from the device await device.disconnect(); console.log('Disconnected from device'); } catch (error) { console.error('Error:', error); } finally { // Release resources miHome.destroy(); } } main(); ``` -------------------------------- ### Get Specific Xiaomi Device Instance Source: https://github.com/alex2844/node-xmihome/blob/main/packages/node/docs/en-US/api/XiaomiMiHome.md Retrieves a cached or creates a new Device instance for a specific Xiaomi device. Requires device configuration including at least an ID, address, or MAC address. Returns a promise that resolves to a Device instance. ```javascript const deviceConfig = { id: '1234567890', address: '192.168.1.100' }; const device = await miHome.getDevice(deviceConfig); console.log('Device instance:', device); ``` -------------------------------- ### Call Device Actions with Node-XMIHome Source: https://context7.com/alex2844/node-xmihome/llms.txt Enables execution of device-specific actions such as starting/stopping operations, triggering behaviors, or invoking custom methods. Supports calling actions by name or using MiOT specification siid/aiid. Includes examples for vacuum cleaner actions. ```javascript import { XiaomiMiHome } from 'xmihome'; const miHome = new XiaomiMiHome({ credentials: { username: 'user@example.com', password: 'pass', country: 'sg' } }); const devices = await miHome.getDevices(); const vacuum = await miHome.getDevice(devices.find(d => d.model?.includes('vacuum'))); await vacuum.connect(); // Call action by name (for supported models) await vacuum.callAction('start_sweep'); await vacuum.callAction('stop_sweeping'); await vacuum.callAction('start_charge'); // Call action with parameters await vacuum.callAction('start_room_sweep', [101, 102]); // Clean specific rooms // Call action using MiOT spec (siid/aiid) await vacuum.callAction({ siid: 2, aiid: 1 }, []); // Start cleaning // Call method directly on device class (advanced usage) const rooms = await vacuum.callAction('getRooms'); // Custom method for some vacuums await vacuum.disconnect(); await miHome.destroy(); ``` -------------------------------- ### Start Bluetooth Monitoring (Node.js) Source: https://github.com/alex2844/node-xmihome/blob/main/packages/node/docs/en-US/api/Device.md Initiates passive monitoring of Bluetooth advertisement packets. This feature is specific to Bluetooth devices. A callback function is provided to process the parsed advertisement data. Returns a Promise that resolves when monitoring begins. ```javascript device.startMonitoring((data) => { console.log('Advertisement data received:', data); }); ``` -------------------------------- ### Subscribe to Device Events with Node-XMIHome Source: https://context7.com/alex2844/node-xmihome/llms.txt Allows subscribing to real-time property changes and device events, crucial for monitoring sensors and tracking device states. Covers listening for connection events, property updates, and passive advertisement monitoring for Bluetooth sensors. Includes methods to start and stop notifications. ```javascript import { XiaomiMiHome } from 'xmihome'; const miHome = new XiaomiMiHome({ credentials: { username: 'user@example.com', password: 'pass', country: 'sg' } }); const devices = await miHome.getDevices(); const kettle = await miHome.getDevice(devices.find(d => d.model === 'yunmi.kettle.v2')); // Listen for connection events kettle.on('connected', (type) => { console.log(`Kettle connected via ${type}`); }); kettle.on('disconnect', () => { console.log('Kettle disconnected'); }); kettle.on('reconnecting', ({ reason }) => { console.log(`Reconnecting due to: ${reason}`); }); kettle.on('reconnect_failed', ({ attempts }) => { console.log(`Reconnection failed after ${attempts} attempts`); }); kettle.on('properties', (props) => { console.log('Properties changed:', props); }); await kettle.connect(); // Subscribe to property notifications await kettle.startNotify('status', (value) => { console.log('Kettle status update:', value); // Output: { action: 'heating', mode: 'keep_warm', current_temperature: 65, keep_warm_set_temperature: 80, ... } if (value.current_temperature >= value.keep_warm_set_temperature) { console.log('Target temperature reached!'); } }); // For Bluetooth sensors - passive advertisement monitoring const sensor = await miHome.getDevice({ mac: 'AA:BB:CC:DD:EE:FF', model: 'miaomiaoce.sensor_ht' }); await sensor.startMonitoring((data) => { console.log('Sensor advertisement:', data); // Output: { temperature: 23.5, humidity: 45, battery: 98 } }); // Stop notifications // await kettle.stopNotify('status'); // await sensor.stopMonitoring(); // Keep running to receive events setTimeout(async () => { await kettle.disconnect(); await miHome.destroy(); }, 60000); ``` -------------------------------- ### Node-RED Discover Xiaomi Devices Source: https://context7.com/alex2844/node-xmihome/llms.txt The xmihome-devices node discovers available Xiaomi devices and outputs them as an array. This is useful for dynamically selecting devices within Node-RED flows. The example flow shows how to trigger discovery and process the results to filter for specific device types like humidifiers. ```json [ { "id": "discover-devices", "type": "inject", "name": "Discover", "topic": "discover", "wires": [["xmihome-devices-node"]] }, { "id": "xmihome-devices-node", "type": "xmihome-devices", "name": "Find Devices", "settings": "xmihome-config-node", "connectionType": "cloud", "wires": [["process-devices"]] }, { "id": "process-devices", "type": "function", "name": "Process Devices", "func": "// msg.payload contains array of discovered devices\nconst devices = msg.payload;\nconst humidifiers = devices.filter(d => d.model?.includes('humidifier'));\nreturn { payload: humidifiers };", "wires": [["debug"]] } ] ``` -------------------------------- ### Bluetooth Class: Low-Level BLE Operations Source: https://context7.com/alex2844/node-xmihome/llms.txt Enables direct Bluetooth LE operations for device discovery, connection management, and advertisement monitoring, specifically on Linux systems. It supports checking BlueZ service availability, registering bindkeys for encrypted MiBeacon devices, starting/stopping discovery and monitoring, listening for discovered devices and advertisements, waiting for specific devices, getting device proxies for direct interaction, and cleaning up resources. Requires a Linux environment with Bluetooth capabilities. ```javascript import { Bluetooth } from 'xmihome'; // Create standalone Bluetooth instance const bluetooth = await Bluetooth.createBluetooth(); // Check BlueZ service availability const serviceAvailable = await bluetooth.checkBlueZService(); console.log('BlueZ available:', serviceAvailable); // Register bindkey for encrypted MiBeacon devices bluetooth.registerBindKey('AA:BB:CC:DD:EE:FF', 'your-16-byte-hex-bindkey'); // Start device discovery with service UUID filter const started = await bluetooth.startDiscovery([ 'fe95', // Xiaomi MiBeacon service '01344736-0000-1000-8000-262837236156' // Kettle service ]); console.log('Discovery started:', started); // Listen for discovered devices bluetooth.on('available', (device) => { console.log('Found device:', device.name, device.mac); }); // Wait for specific device const deviceConfig = await bluetooth.waitDevice('AA:BB:CC:DD:EE:FF', 30000); console.log('Device found:', deviceConfig); // Get device proxy for direct interaction const deviceProxy = await bluetooth.getDevice('AA:BB:CC:DD:EE:FF'); await deviceProxy.connect(); // Start passive advertisement monitoring (for sensors) await bluetooth.startMonitoring(); bluetooth.on('advertisement', (data) => { console.log('BLE advertisement:', data); }); bluetooth.on('advertisement:AA:BB:CC:DD:EE:FF', (data) => { console.log('Specific device advertisement:', data); }); // Stop discovery await bluetooth.stopDiscovery(); await bluetooth.stopMonitoring(); // Remove device from cache await bluetooth.removeDevice('AA:BB:CC:DD:EE:FF'); // Clean up await bluetooth.destroy(); ``` -------------------------------- ### Node-RED Control Individual Xiaomi Devices Source: https://context7.com/alex2844/node-xmihome/llms.txt The xmihome-device node allows for controlling individual Xiaomi devices. It supports getting and setting properties, calling device actions, and subscribing to notifications. The examples demonstrate getting device status, turning a humidifier on, subscribing to kettle status updates, and dynamically preparing commands. ```json [ { "id": "get-properties", "type": "xmihome-device", "name": "Get Humidifier Status", "settings": "xmihome-config-node", "device": "discovered-device-config", "action": "getProperties", "wires": [["debug"], ["connection-status"]] }, { "id": "set-property", "type": "xmihome-device", "name": "Turn On Humidifier", "settings": "xmihome-config-node", "device": "discovered-device-config", "action": "setProperty", "property": "on", "value": "true", "wires": [[], ["connection-status"]] }, { "id": "subscribe-notifications", "type": "xmihome-device", "name": "Subscribe to Kettle", "settings": "xmihome-config-node", "device": "device", "deviceType": "msg", "action": "subscribe", "property": "status", "wires": [["kettle-logic"], ["connection-status"]] }, { "id": "dynamic-control", "type": "function", "name": "Prepare Command", "func": "// Dynamic device control via msg.device\nmsg.device = {\n mac: env.get('KETTLE_MAC'),\n token: env.get('KETTLE_TOKEN'),\n model: 'yunmi.kettle.v2'\n};\nmsg.payload = {\n property: 'keep_warm_settings',\n value: { temperature: 80, type: 'heat_to_temperature' }\n};\nreturn msg;", "wires": [["xmihome-device-node"]] } ] ``` -------------------------------- ### Instantiate XiaomiMiHome Client Source: https://github.com/alex2844/node-xmihome/blob/main/packages/node/docs/en-US/api/XiaomiMiHome.md Creates a new instance of the XiaomiMiHome client with provided configuration. Supports cloud credentials, connection types, predefined devices, and logging levels. Credentials can be provided directly or via a file path. ```javascript import { XiaomiMiHome } from 'xmihome'; const miHome = new XiaomiMiHome({ credentials: { username: 'your-email@example.com', password: 'your-password', country: 'sg' }, logLevel: 'info' }); ``` -------------------------------- ### Methods Source: https://github.com/alex2844/node-xmihome/blob/main/packages/node/docs/en-US/api/Miot.md Instance methods for interacting with Xiaomi Cloud and devices. ```APIDOC ## Methods ### `login(handlers)` Logs into the Xiaomi account to obtain tokens. Supports two-factor authentication (2FA) and Captcha via callbacks. #### Parameters - **handlers** (`object`) - Optional - An object with handlers for interactive steps. - **handlers.on2fa** (`(url: str) => Promise`) - Optional - Async function that receives verification URL and returns confirmation code. - **handlers.onCaptcha** (`(img: str) => Promise`) - Optional - Async function that receives captcha image (base64) and returns the text. #### Returns - `Promise`: A promise that resolves with an object containing the tokens (`userId`, `ssecurity`, `serviceToken`). ``` ```APIDOC ### `request(path, data)` Executes a signed request to the Xiaomi Cloud API. #### Parameters - **path** (`string`) - Required - The API endpoint path (e.g., `/home/device_list`). - **data** (`object`) - Required - The data object to send. #### Returns - `Promise`: A promise that resolves with the JSON response from the server. ``` ```APIDOC ### `parseJson(str)` Parses a JSON string, removing the `&&&START&&&` prefix if present. #### Parameters - **str** (`string`) - Required - The JSON string. #### Returns - `object`: The parsed JSON object. ``` ```APIDOC ### `getApiUrl(country)` Returns the API URL for the specified country. #### Parameters - **country** (`string`) - Required - The country code (e.g., `ru`, `cn`). #### Returns - `string`: The API URL. ``` ```APIDOC ### `generateSignature(path, _signedNonce, nonce, params)` Generates a request signature for the Xiaomi Cloud API. #### Parameters - **path** (`string`) - Required - The API request path. - **_signedNonce** (`string`) - Required - The signed nonce. - **nonce** (`string`) - Required - The nonce. - **params** (`object`) - Required - The request parameters. #### Returns - `string`: The request signature in base64. ``` ```APIDOC ### `generateNonce()` Generates a nonce for Xiaomi Cloud API requests. #### Returns - `string`: The nonce in base64. ``` ```APIDOC ### `signedNonce(ssecret, nonce)` Generates a signed nonce. #### Parameters - **ssecret** (`string`) - Required - The `ssecurity` token. - **nonce** (`string`) - Required - The nonce. #### Returns - `string`: The signed nonce in base64. ``` -------------------------------- ### XiaomiMiHome Constructor Source: https://github.com/alex2844/node-xmihome/blob/main/packages/node/docs/en-US/api/XiaomiMiHome.md Initializes a new instance of the XiaomiMiHome client with configuration options for credentials, connection type, and logging. ```APIDOC ## Constructor XiaomiMiHome ### Description Creates a new instance of the `XiaomiMiHome` client. ### Method `new XiaomiMiHome(config)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **config** (object) - Required - The configuration object. - **config.credentials** (object) - Optional - Credentials for Xiaomi Cloud. Required for cloud operations. - **config.credentials.username** (string) - Required - Xiaomi account username. - **config.credentials.password** (string) - Required - Xiaomi account password. - **config.credentials.country** (string) - Required - Xiaomi account region (e.g., `ru`, `cn`, `us`). - **config.credentialsFile** (string) - Optional - Path to a JSON file with credentials. - **config.connectionType** (string) - Optional - The default connection type to use for device discovery and connection (`'cloud'`, `'miio'`, `'bluetooth'`). - **config.devices** (object[]) - Optional - An array of predefined device configurations. - **config.logLevel** (string) - Optional - The logging level for the console output (`'none'`, `'error'`, `'warn'`, `'info'`, `'debug'`). Default: `'none'`. ### Request Example ```javascript import { XiaomiMiHome } from 'xmihome'; const miHome = new XiaomiMiHome({ credentials: { username: 'your-email@example.com', password: 'your-password', country: 'sg' }, logLevel: 'info' }); ``` ### Response #### Success Response (200) N/A (Constructor does not return a value directly, it creates an instance) #### Response Example N/A ``` -------------------------------- ### Get Device Model (Node.js) Source: https://github.com/alex2844/node-xmihome/blob/main/packages/node/docs/en-US/api/Device.md Retrieves the model identifier of the smart device. This function returns a Promise that resolves with the device's model string. ```javascript const model = await device.getModel(); console.log(model); ``` -------------------------------- ### Get Device Name (Node.js) Source: https://github.com/alex2844/node-xmihome/blob/main/packages/node/docs/en-US/api/Device.md Retrieves the human-readable name of the smart device. This function returns a Promise that resolves with the device's name as a string. ```javascript const name = await device.getName(); console.log(name); ``` -------------------------------- ### Initialize XiaomiMiHome Client (Node.js) Source: https://context7.com/alex2844/node-xmihome/llms.txt Initializes the main XiaomiMiHome client, which manages device connections and discovery. It can be configured for cloud, MiIO, or Bluetooth connections, with options for credentials, connection type, and logging level. Includes cleanup logic for graceful shutdown. ```javascript import { XiaomiMiHome } from 'xmihome'; // Initialize with cloud credentials const miHome = new XiaomiMiHome({ credentials: { username: 'your-email@example.com', password: 'your-password', country: 'sg' // 'ru', 'cn', 'us', etc. }, connectionType: 'cloud', // 'miio', 'bluetooth', or 'cloud' logLevel: 'info' // 'none', 'error', 'warn', 'info', 'debug' }); // Alternative: Initialize for local-only discovery (no credentials) const localMiHome = new XiaomiMiHome({ connectionType: 'miio', // Will only discover MiIO devices on local network devices: [ // Pre-configured devices with known tokens { address: '192.168.1.100', token: 'your-device-token', model: 'deerma.humidifier.jsq2w' } ], logLevel: 'debug' }); // Clean up when done process.on('SIGINT', async () => { await miHome.destroy(); process.exit(0); }); ``` -------------------------------- ### Get Environmental Data for a Home Source: https://github.com/alex2844/node-xmihome/blob/main/packages/node/docs/en-US/api/XiaomiMiHome.md Fetches the environmental data for a specified home from the Xiaomi Cloud. This endpoint requires a `home_id` to identify the target location. ```APIDOC ## GET /api/homes/{home_id}/environment ### Description Fetches the environmental data for a specified home from the Xiaomi Cloud. ### Method GET ### Endpoint /api/homes/{home_id}/environment ### Parameters #### Path Parameters - **home_id** (number) - Required - The ID of the home for which to fetch data. #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **environment** (object) - An object containing environmental data (e.g., temperature, humidity). #### Response Example ```json { "environment": { "temperature": 22.5, "humidity": 45.2 } } ``` ``` -------------------------------- ### Get User's Homes Source: https://github.com/alex2844/node-xmihome/blob/main/packages/node/docs/en-US/api/XiaomiMiHome.md Fetches the user's list of homes from the Xiaomi Cloud. This is useful for retrieving all available home locations associated with the user's account. ```APIDOC ## GET /api/homes ### Description Fetches the user's list of homes from the Xiaomi Cloud. ### Method GET ### Endpoint /api/homes ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **homes** (object[]) - An array of home objects. #### Response Example ```json { "homes": [ { "id": 123, "name": "My Home" }, { "id": 456, "name": "Vacation House" } ] } ``` ``` -------------------------------- ### XiaomiMiHome Class - Initialization Source: https://context7.com/alex2844/node-xmihome/llms.txt Initializes the main client for interacting with Xiaomi Mi Home devices. Supports cloud credentials, local MiIO discovery, and Bluetooth LE. ```APIDOC ## Initialization ### Description Initializes the main client for interacting with Xiaomi Mi Home devices. Supports cloud credentials, local MiIO discovery, and Bluetooth LE. ### Method `new XiaomiMiHome(options)` ### Parameters #### Options Object - **credentials** (object) - Optional - Cloud credentials. - **username** (string) - Required if using cloud connection - Your Xiaomi account username. - **password** (string) - Required if using cloud connection - Your Xiaomi account password. - **country** (string) - Required if using cloud connection - Your country code (e.g., 'sg', 'ru', 'cn', 'us'). - **connectionType** (string) - Optional - Specifies the connection type. Defaults to 'cloud'. Options: 'miio', 'bluetooth', 'cloud', 'miio+bluetooth'. - **devices** (array) - Optional - Pre-configured devices with known tokens for local-only discovery. - **address** (string) - Required - Device IP address. - **token** (string) - Required - Device token. - **model** (string) - Required - Device model identifier. - **logLevel** (string) - Optional - Sets the logging level. Defaults to 'info'. Options: 'none', 'error', 'warn', 'info', 'debug'. ### Request Example ```javascript import { XiaomiMiHome } from 'xmihome'; // Initialize with cloud credentials const miHome = new XiaomiMiHome({ credentials: { username: 'your-email@example.com', password: 'your-password', country: 'sg' }, connectionType: 'cloud', logLevel: 'info' }); // Alternative: Initialize for local-only discovery const localMiHome = new XiaomiMiHome({ connectionType: 'miio', devices: [ { address: '192.168.1.100', token: 'your-device-token', model: 'deerma.humidifier.jsq2w' } ], logLevel: 'debug' }); // Clean up when done process.on('SIGINT', async () => { await miHome.destroy(); process.exit(0); }); ``` ### Response N/A (Constructor does not return a value, but initializes the client object.) ``` -------------------------------- ### Get Single Property Value (Node.js) Source: https://github.com/alex2844/node-xmihome/blob/main/packages/node/docs/en-US/api/Device.md Fetches the current value of a specific property from the device. The property can be identified by its name (string) or a property definition object. Returns a Promise that resolves with the property's value. ```javascript const brightness = await device.getProperty('brightness'); console.log(brightness); ``` -------------------------------- ### Get Multiple Property Values (Node.js) Source: https://github.com/alex2844/node-xmihome/blob/main/packages/node/docs/en-US/api/Device.md Fetches the current values of multiple properties from the device. An optional array of property names or definition objects can be provided. Returns a Promise that resolves to an object containing key-value pairs of the requested properties. ```javascript const properties = await device.getProperties(['brightness', 'color_mode']); console.log(properties); ``` -------------------------------- ### Configure Bluetooth Permissions on Linux Source: https://github.com/alex2844/node-xmihome/blob/main/packages/node/README.md Copies the generated Bluetooth configuration file to the system's D-Bus directory and restarts the Bluetooth service to ensure proper Bluetooth LE functionality on Linux systems. ```bash sudo cp node_modules/xmihome/xmihome_bluetooth.conf /etc/dbus-1/system.d/ sudo systemctl restart bluetooth ``` -------------------------------- ### Bluetooth Class - Static Methods Source: https://github.com/alex2844/node-xmihome/blob/main/packages/node/docs/en-US/api/Bluetooth.md Methods for creating and initializing instances of the Bluetooth class. ```APIDOC ## Static Methods ### `createBluetooth()` Creates and initializes a new instance of the Bluetooth class. This is the recommended way to create a standalone instance. **Returns:** - `Promise`: A promise that resolves with the initialized Bluetooth instance. ``` -------------------------------- ### Device Class Static Methods Source: https://github.com/alex2844/node-xmihome/blob/main/packages/node/docs/en-US/api/Device.md Provides documentation for the static methods available on the Device class, used for managing device models and creating device instances. ```APIDOC ## Device Class Static Methods ### `registerModels(models)` Registers device classes from the `xmihome-devices` package, making them available to `findModel` and `create`. **Parameters:** | Name | Type | Description | | -------- | -------- | ------------------------------------------------------------ | | `models` | `object` | An object where keys are models and values are device classes. | ### `getModels()` Gets a list of all registered registered models. **Returns:** - `string[]`: An array of model strings. ### `findModel(device)` Finds the appropriate class for a device based on its `model` or `name`. **Parameters:** | Name | Type | Description | | -------- | -------- | -------------------------------- | | `device` | `object` | The device configuration object. | **Returns:** - `typeof Device | undefined`: The found device class or `undefined`. ### `valid(device, model)` Checks if the provided device configuration matches a specific model class. **Parameters:** | Name | Type | Description | | -------- | -------- | ------------------------------------ | | `device` | `object` | The device configuration object. | | `model` | `class` | The device class (constructor). | **Returns:** - `boolean`: `true` if it matches, `false` otherwise. ### `create(device, client)` Creates an instance of the correct device class (`Device` or a subclass) based on the model. If no specific class is found for the model, it attempts to load the specification from the MiOT cloud. **Parameters:** | Name | Type | Description | | -------- | -------------- | ------------------------------ | | `device` | `object` | The device configuration object. | | `client` | `XiaomiMiHome` | The main client instance. | **Returns:** - `Promise`: A promise that resolves to a `Device` instance. ### `getDeviceId(device)` Generates a unique string identifier for a device instance based on its configuration. **Parameters:** | Name | Type | Description | | -------- | -------- | -------------------------------- | | `device` | `object` | The device configuration object. | **Returns:** - `string`: A unique key for the device. ### `getDeviceType(device, credentials)` Determines the most likely connection type (`miio`, `bluetooth`, `cloud`) based on the available fields in the device configuration. **Parameters:** | Name | Type | Description | | ------------- | -------- | ----------------------------- | | `device` | `object` | The device configuration object. | | `credentials` | `object` | (Optional) Cloud credentials. | **Returns:** - `'miio' | 'bluetooth' | 'cloud' | undefined`: A string with the connection type. ``` -------------------------------- ### Node.js Smart Home Automation with XMiHome Source: https://context7.com/alex2844/node-xmihome/llms.txt This JavaScript code demonstrates how to use the XMiHome library to discover Xiaomi Mi Home devices, connect to them, retrieve their status, control properties like power and target humidity, and subscribe to real-time property changes. It includes error handling and graceful shutdown. ```javascript import { XiaomiMiHome } from 'xmihome'; async function main() { const miHome = new XiaomiMiHome({ credentials: { username: process.env.XIAOMI_USERNAME, password: process.env.XIAOMI_PASSWORD, country: 'sg' }, logLevel: 'info' }); try { // Discover all devices console.log('Discovering devices...'); const devices = await miHome.getDevices({ timeout: 30000, onDeviceFound: (device, allDevices, type) => { console.log(`[${type}] Found: ${device.name || device.model} (${device.address || device.mac})`); return true; } }); console.log(`\nFound ${devices.length} devices total`); if (devices.length === 0) { console.log('No devices found'); return; } // Find and control a humidifier const humidifierConfig = devices.find(d => d.model?.includes('humidifier')); if (humidifierConfig) { const humidifier = await miHome.getDevice(humidifierConfig); humidifier.on('connected', (type) => console.log(`Humidifier connected via ${type}`)); humidifier.on('properties', (props) => console.log('Humidifier properties updated:', props)); await humidifier.connect(); const status = await humidifier.getProperties(); console.log('\nHumidifier status:', status); if (!status.on) { console.log('Turning on humidifier...'); await humidifier.setProperty('on', true); await humidifier.setProperty('target_humidity', 50); } // Subscribe to humidity changes await humidifier.startNotify('current_humidity', (humidity) => { console.log(`Current humidity: ${humidity}%`); if (humidity >= 55) { console.log('Target humidity reached, turning off...'); humidifier.setProperty('on', false); } }); } // Find and monitor a kettle const kettleConfig = devices.find(d => d.model === 'yunmi.kettle.v2'); if (kettleConfig) { const kettle = await miHome.getDevice(kettleConfig); await kettle.connect(); console.log('\nKettle connected, subscribing to status...'); await kettle.startNotify('status', (status) => { console.log(`Kettle: ${status.action} | ${status.current_temperature}°C | Mode: ${status.mode}`); }); } // Keep running for monitoring console.log('\nMonitoring devices... Press Ctrl+C to exit'); process.on('SIGINT', async () => { console.log('\nShutting down...'); await miHome.destroy(); process.exit(0); }); } catch (error) { console.error('Error:', error.message); await miHome.destroy(); process.exit(1); } } main(); ``` -------------------------------- ### Clone Node-Xmihome Repository Source: https://github.com/alex2844/node-xmihome/blob/main/docs/README.md This command clones the node-xmihome repository from GitHub. It is the first step in setting up the development environment for the project. ```bash git clone https://github.com/alex2844/node-xmihome.git cd node-xmihome ``` -------------------------------- ### Discover Xiaomi Devices CLI Source: https://github.com/alex2844/node-xmihome/blob/main/packages/node/docs/en-US/CLI.md Lists Xiaomi devices by discovering them from local network (miIO, Bluetooth) and/or Xiaomi Cloud. Supports filtering by discovery type and forcing a new discovery. ```bash xmihome devices --type all --force ``` ```bash xmihome devices --type miio ``` ```bash xmihome devices --type bluetooth ``` ```bash xmihome devices --type cloud ``` -------------------------------- ### Connect to Device (Node.js) Source: https://github.com/alex2844/node-xmihome/blob/main/packages/node/docs/en-US/api/Device.md Establishes a connection to a smart device. The connection type can be specified or will be automatically determined. This function returns a Promise that resolves when the connection is established. ```javascript device.connect(connectionType); // Example with optional connectionType: device.connect('miio'); ``` -------------------------------- ### getDevice() - Device Instance Creation Source: https://context7.com/alex2844/node-xmihome/llms.txt Creates or retrieves a cached Device instance for controlling a specific device. Supports connection via cloud, MiIO, or Bluetooth. ```APIDOC ## getDevice() ### Description Creates or retrieves a cached Device instance for controlling a specific device. The device can be connected via cloud, MiIO, or Bluetooth based on available configuration data. ### Method `miHome.getDevice(deviceConfig)` ### Parameters #### deviceConfig Object - **id** (string) - Optional - Unique device identifier (often cloud-based). - **address** (string) - Optional - IP address of the device (required for MiIO). - **token** (string) - Optional - Device token (required for MiIO). - **model** (string) - Optional - Device model identifier (required for MiIO and Bluetooth). - **name** (string) - Optional - User-friendly name of the device. - **connectionType** (string) - Optional - Explicitly set the connection type ('miio', 'bluetooth', 'cloud'). If not provided, it will be auto-detected. ### Request Example ```javascript import { XiaomiMiHome } from 'xmihome'; const miHome = new XiaomiMiHome({ credentials: { username: 'user@example.com', password: 'pass', country: 'sg' } }); // Get devices first to find configuration const devices = await miHome.getDevices(); const humidifierConfig = devices.find(d => d.model === 'deerma.humidifier.jsq2w'); // Create device instance from discovered config const device = await miHome.getDevice(humidifierConfig); // Or create from manual configuration const manualDevice = await miHome.getDevice({ id: 'device-cloud-id', address: '192.168.1.100', token: 'ffffffffffffffffffffffffffffffff', model: 'deerma.humidifier.jsq2w', name: 'Bedroom Humidifier' }); // Connect to device (auto-detects best connection type) await device.connect(); console.log(`Connected via: ${device.connectionType}`); // Explicit connection type await manualDevice.connect('miio'); // Force MiIO connection await miHome.destroy(); ``` ### Response #### Success Response (200) - **deviceInstance** (object) - An instance of the device class, ready for control. - **connectionType** (string) - The active connection type ('miio', 'bluetooth', 'cloud'). - **getName()** (function) - Returns the device name. - **getModel()** (function) - Returns the device model. - **connect(connectionType?)** (function) - Establishes a connection to the device. - **destroy()** (function) - Closes the connection and cleans up resources. #### Response Example ```javascript // Assuming 'device' is the returned instance from getDevice() console.log(device.connectionType); // e.g., 'miio' console.log(device.getName()); // e.g., 'Bedroom Humidifier' ``` ``` -------------------------------- ### JavaScript Define Custom Xiaomi Device Classes Source: https://context7.com/alex2844/node-xmihome/llms.txt This JavaScript code defines custom device classes for the xmihome project, allowing for optimized support of specific Xiaomi models. It includes human-readable property names, MiOT SIID/PIID mapping, value aliases, and custom methods. The example shows how to define properties, actions, and register the custom device class for use within the xmihome framework. ```javascript // packages/devices/src/devices/my-device.js import Device from 'xmihome/device.js'; export default class MyCustomDevice extends Device { // Display name for the device static name = 'My Custom Smart Device'; // Model identifiers this class handles static models = [ 'vendor.device.model1', 'vendor.device.model2' ]; // Aliases for device name matching (Bluetooth discovery) static alias = ['CustomDevice', 'MyDevice-V1']; // Property definitions with MiOT siid/piid mapping properties = { 'on': { siid: 2, piid: 1, format: 'bool', access: ['read', 'write', 'notify'] }, 'mode': { siid: 2, piid: 2, format: 'uint8', access: ['read', 'write'], // Optional value mapping values: { 0: 'auto', 1: 'manual', 2: 'sleep' } }, 'temperature': { siid: 3, piid: 1, format: 'float', access: ['read', 'notify'] } }; // Action definitions actions = { 'start': { siid: 2, aiid: 1 }, 'stop': { siid: 2, aiid: 2 }, 'reset': { siid: 2, aiid: 3, in: [{ piid: 1, value: true }] } }; // Custom methods async turnOnWithMode(mode) { await this.setProperty('mode', mode); await this.setProperty('on', true); } } // Register custom device import { Device } from 'xmihome'; import MyCustomDevice from './my-device.js'; Device.registerModels({ 'vendor.device.model1': MyCustomDevice, 'vendor.device.model2': MyCustomDevice }); ``` -------------------------------- ### Discover Devices with XiaomiMiHome (Node.js) Source: https://context7.com/alex2844/node-xmihome/llms.txt Discovers available Xiaomi devices using various connection types: cloud, local MiIO network scanning, Bluetooth LE scanning, or a combination. It returns device configurations and supports filtering devices during discovery via a callback function. ```javascript import { XiaomiMiHome } from 'xmihome'; const miHome = new XiaomiMiHome({ credentials: { username: 'user@example.com', password: 'pass', country: 'sg' } }); // Discover all devices from cloud const cloudDevices = await miHome.getDevices({ connectionType: 'cloud', timeout: 30000 }); console.log('Cloud devices:', cloudDevices); // Output: [{ id: 'blt.3.xxx', name: 'Mi Kettle', model: 'yunmi.kettle.v2', mac: 'AA:BB:CC:DD:EE:FF', ... }] // Discover local MiIO devices only const miioDevices = await miHome.getDevices({ connectionType: 'miio', timeout: 10000 }); // Discover Bluetooth LE devices only const bleDevices = await miHome.getDevices({ connectionType: 'bluetooth', timeout: 15000 }); // Combined MiIO + Bluetooth discovery const localDevices = await miHome.getDevices({ connectionType: 'miio+bluetooth', timeout: 20000 }); // Filter devices during discovery with callback const filteredDevices = await miHome.getDevices({ timeout: 30000, onDeviceFound: (device, devices, type) => { console.log(`Found ${type} device: ${device.model} at ${device.address || device.mac}`); // Return true to include device, false to skip if (device.model?.includes('humidifier')) { return { include: true, stop: false }; // Include and continue searching } if (devices.length >= 5) { return { include: true, stop: true }; // Include and stop searching } return false; // Skip this device } }); await miHome.destroy(); ```