### Basic NUT Client Connection and Device Listing in Dart Source: https://github.com/jandrop/nut_client/blob/main/README.md Demonstrates establishing a simple TCP connection to a NUT server, listing available UPS devices, and retrieving their descriptions. This is a foundational example for interacting with the NUT protocol using the nut_client library. ```dart import 'package:nut_client/nut_client.dart'; void main() async { // Create a client final client = NutTcpClient.simple('192.168.1.10'); try { // Connect to the NUT server await client.connect(); // List all UPS devices final devices = await client.listUps(); for (final device in devices) { print('${device.name}: ${device.description}'); } // Get variables for a UPS final variables = await client.listVariables('ups1'); for (final variable in variables) { print('${variable.name} = ${variable.value}'); } // Get a specific variable final status = await client.getVariable('ups1', 'ups.status'); print('UPS Status: ${status.value}'); final charge = await client.getVariable('ups1', 'battery.charge'); print('Battery: ${charge.intValue}%'); } finally { await client.dispose(); } } ``` -------------------------------- ### Execute Instant UPS Commands (Dart) Source: https://context7.com/jandrop/nut_client/llms.txt Allows running instant commands on UPS devices, which also requires authentication. This code lists available commands, executes a 'beeper.toggle' command, starts and stops a battery test. It depends on the 'nut_client' package and valid credentials. ```dart import 'package:nut_client/nut_client.dart'; void main() async { final client = NutTcpClient( NutClientConfig( host: '192.168.1.10', credentials: Credentials( username: 'admin', password: 'secret', ), ), ); try { await client.connect(); // List available commands final commands = await client.listCommands('ups1'); print('Available commands for ups1:'); for (final cmd in commands) { final desc = cmd.description ?? 'No description'; print(' ${cmd.name}: $desc'); } // Execute a command print(' Toggling beeper...'); await client.runCommand('ups1', 'beeper.toggle'); print('Beeper toggled successfully'); // Start a battery test print(' Starting battery test...'); await client.runCommand('ups1', 'test.battery.start'); print('Battery test started'); // Wait a moment await Future.delayed(Duration(seconds: 5)); // Stop the battery test print(' Stopping battery test...'); await client.runCommand('ups1', 'test.battery.stop'); print('Battery test stopped'); } on AuthenticationException catch (e) { print('Authentication error: ${e.userMessage}'); } on CommandException catch (e) { print('Command error: ${e.userMessage} (code: ${e.errorCode})'); } finally { await client.dispose(); } } ``` -------------------------------- ### NUT Client Error Handling in Dart Source: https://github.com/jandrop/nut_client/blob/main/README.md Provides examples of how to handle various exceptions that can occur when interacting with a NUT server using the nut_client library. This includes connection, authentication, command, and timeout errors. ```dart try { await client.connect(); final status = await client.getVariable('ups1', 'ups.status'); } on ConnectionException catch (e) { print('Connection failed: ${e.userMessage}'); } on AuthenticationException catch (e) { print('Authentication failed: ${e.userMessage}'); } on CommandException catch (e) { print('Command failed: ${e.userMessage}'); print('Error code: ${e.errorCode}'); } on NutTimeoutException catch (e) { print('Timeout: ${e.userMessage}'); } ``` -------------------------------- ### Get UPS Variables (Dart) Source: https://context7.com/jandrop/nut_client/llms.txt Connects to a NUT server and demonstrates how to read various variables from a UPS device, performing type conversions where applicable. It fetches and prints the UPS status, battery charge (as integer), input voltage (as double), estimated runtime, and load. Includes error handling for command execution. ```dart import 'package:nut_client/nut_client.dart'; void main() async { final client = NutTcpClient.simple('192.168.1.10'); try { await client.connect(); // Get specific variables final status = await client.getVariable('ups1', 'ups.status'); print('UPS Status: ${status.value}'); // e.g., "OL" for Online final charge = await client.getVariable('ups1', 'battery.charge'); print('Battery Charge: ${charge.intValue}%'); // Parsed as integer final voltage = await client.getVariable('ups1', 'input.voltage'); print('Input Voltage: ${voltage.doubleValue}V'); // Parsed as double final runtime = await client.getVariable('ups1', 'battery.runtime'); final minutes = (runtime.intValue ?? 0) ~/ 60; print('Estimated Runtime: $minutes minutes'); final load = await client.getVariable('ups1', 'ups.load'); print('Load: ${load.intValue}%'); } on CommandException catch (e) { print('Error: ${e.userMessage}'); } finally { await client.dispose(); } } ``` -------------------------------- ### Monitor Connection State Changes (Dart) Source: https://context7.com/jandrop/nut_client/llms.txt Tracks the connection state of the NUT client using reactive streams. It subscribes to the `connectionStateStream` to receive real-time updates on connection status (disconnected, connecting, connected, etc.). The example demonstrates connecting, checking connection status, performing a basic operation (`listUps`), and disconnecting. ```dart import 'package:nut_client/nut_client.dart'; void main() async { final client = NutTcpClient.simple('192.168.1.10'); // Subscribe to connection state changes final stateSubscription = client.connectionStateStream.listen( (state) { switch (state) { case ConnectionState.disconnected: print('Status: Disconnected'); break; case ConnectionState.connecting: print('Status: Connecting...'); break; case ConnectionState.connected: print('Status: Connected'); break; case ConnectionState.authenticating: print('Status: Authenticating...'); break; case ConnectionState.ready: print('Status: Ready for commands'); break; case ConnectionState.error: print('Status: Error occurred'); break; } }, ); try { await client.connect(); // Check current state print('Current connection state: ${client.connectionState}'); print('Is connected: ${client.isConnected}'); // Perform some operations await client.listUps(); await Future.delayed(Duration(seconds: 2)); await client.disconnect(); } finally { await stateSubscription.cancel(); await client.dispose(); } } ``` -------------------------------- ### Get UPS Variable Source: https://context7.com/jandrop/nut_client/llms.txt Reads a specific variable from a UPS device and returns its value, with type conversion support. ```APIDOC ## Get UPS Variable ### Description Reads a specific variable from a UPS device and returns its value, with type conversion support. ### Method Get UPS Variable ### Endpoint N/A (Client-side command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart import 'package:nut_client/nut_client.dart'; void main() async { final client = NutTcpClient.simple('192.168.1.10'); try { await client.connect(); // Get specific variables final status = await client.getVariable('ups1', 'ups.status'); print('UPS Status: ${status.value}'); // e.g., "OL" for Online final charge = await client.getVariable('ups1', 'battery.charge'); print('Battery Charge: ${charge.intValue}%'); // Parsed as integer final voltage = await client.getVariable('ups1', 'input.voltage'); print('Input Voltage: ${voltage.doubleValue}V'); // Parsed as double final runtime = await client.getVariable('ups1', 'battery.runtime'); final minutes = (runtime.intValue ?? 0) ~/ 60; print('Estimated Runtime: $minutes minutes'); final load = await client.getVariable('ups1', 'ups.load'); print('Load: ${load.intValue}%'); } on CommandException catch (e) { print('Error: ${e.userMessage}'); } finally { await client.dispose(); } } ``` ### Response #### Success Response (200) Returns a `Variable` object containing the variable's value and type conversion properties. **`Variable` Object Structure:** - **value** (String) - The raw string value of the variable. - **intValue** (int?) - The value parsed as an integer, if applicable. - **doubleValue** (double?) - The value parsed as a double, if applicable. - **boolValue** (bool?) - The value parsed as a boolean, if applicable. #### Response Example ```json { "value": "OL", "intValue": null, "doubleValue": null, "boolValue": null } ``` Or for a numeric value: ```json { "value": "50", "intValue": 50, "doubleValue": 50.0, "boolValue": null } ``` ``` -------------------------------- ### Watch Single UPS Variable with Polling (Dart) Source: https://context7.com/jandrop/nut_client/llms.txt Monitors a specific UPS variable ('battery.charge') using automatic polling at a defined interval. This snippet shows how to set up a listener for variable changes, with an example of alerting on low battery levels. It uses the 'nut_client' package and requires a connection to the UPS server. ```dart import 'package:nut_client/nut_client.dart'; void main() async { final client = NutTcpClient.simple('192.168.1.10'); try { await client.connect(); print('Connected, starting to watch battery.charge...\n'); // Watch a single variable with 5-second polling interval final subscription = client.watchVariable( 'ups1', 'battery.charge', interval: Duration(seconds: 5), ).listen( (variable) { final timestamp = DateTime.now().toIso8601String(); print('[$timestamp] Battery charge: ${variable.intValue}%'); // Alert on low battery if (variable.intValue != null && variable.intValue! < 20) { print(' WARNING: Low battery!'); } }, onError: (error) { print('Watch error: $error'); }, onDone: () { print('Watch stream closed'); }, ); // Let it run for 30 seconds await Future.delayed(Duration(seconds: 30)); // Stop watching await subscription.cancel(); print(' Stopped watching battery.charge'); } on ConnectionException catch (e) { print('Connection failed: ${e.userMessage}'); } finally { await client.dispose(); } } ``` -------------------------------- ### Connect to NUT Server (Simple) Source: https://context7.com/jandrop/nut_client/llms.txt Establishes a basic TCP connection to a NUT server using default settings. ```APIDOC ## Connect to NUT Server (Simple) ### Description Establishes a basic TCP connection to a NUT server using default settings. ### Method Connect to NUT Server ### Endpoint N/A (Client-side connection) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart import 'package:nut_client/nut_client.dart'; void main() async { final client = NutTcpClient.simple('192.168.1.10'); try { await client.connect(); print('Connected to NUT server'); final devices = await client.listUps(); for (final device in devices) { print('${device.name}: ${device.description}'); } } on ConnectionException catch (e) { print('Connection failed: ${e.userMessage}'); } finally { await client.dispose(); } } ``` ### Response #### Success Response (200) Connection established. No direct response data, but subsequent commands can be executed. #### Response Example ```json { "message": "Connected to NUT server" } ``` ``` -------------------------------- ### Connect to NUT Server (Dart) Source: https://context7.com/jandrop/nut_client/llms.txt Establishes a basic TCP connection to a NUT server using default settings. It then lists available UPS devices and prints their names and descriptions. Handles potential connection exceptions and ensures the client is disposed. ```dart import 'package:nut_client/nut_client.dart'; void main() async { final client = NutTcpClient.simple('192.168.1.10'); try { await client.connect(); print('Connected to NUT server'); final devices = await client.listUps(); for (final device in devices) { print('${device.name}: ${device.description}'); } } on ConnectionException catch (e) { print('Connection failed: ${e.userMessage}'); } finally { await client.dispose(); } } ``` -------------------------------- ### Connect with TLS and Authentication Source: https://context7.com/jandrop/nut_client/llms.txt Establishes a secure connection with TLS encryption and authenticates using provided credentials. ```APIDOC ## Connect with TLS and Authentication ### Description Establishes a secure connection with TLS encryption and authenticates using provided credentials. Supports configurable timeouts and TLS negotiation. ### Method Connect with TLS and Authentication ### Endpoint N/A (Client-side connection) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart import 'package:nut_client/nut_client.dart'; void main() async { final client = NutTcpClient( NutClientConfig( host: '192.168.1.10', port: 3493, useTls: true, credentials: Credentials( username: 'admin', password: 'secret', ), connectionTimeout: Duration(seconds: 10), commandTimeout: Duration(seconds: 30), ), ); try { await client.connect(); print('Connected with TLS and authenticated'); // Now you can use privileged commands await client.setVariable('ups1', 'ups.delay.shutdown', '120'); await client.runCommand('ups1', 'beeper.toggle'); print('Commands executed successfully'); } on AuthenticationException catch (e) { print('Authentication failed: ${e.userMessage}'); } on ConnectionException catch (e) { print('Connection failed: ${e.userMessage}'); } finally { await client.dispose(); } } ``` ### Response #### Success Response (200) Connection established and authenticated. Allows execution of privileged commands. #### Response Example ```json { "message": "Connected with TLS and authenticated" } ``` ``` -------------------------------- ### Set UPS Variable Values (Dart) Source: https://context7.com/jandrop/nut_client/llms.txt Modifies writable variables on a UPS device, requiring authentication. This snippet demonstrates listing writable variables, setting a specific variable's value, and verifying the change. It uses 'nut_client' and requires valid credentials. ```dart import 'package:nut_client/nut_client.dart'; void main() async { final client = NutTcpClient( NutClientConfig( host: '192.168.1.10', credentials: Credentials( username: 'admin', password: 'secret', ), ), ); try { await client.connect(); // List writable variables first final writableVars = await client.listWritableVariables('ups1'); print('Writable variables:'); for (final v in writableVars) { print(' ${v.name} = ${v.value}'); if (v.enumValues != null) { print(' Allowed values: ${v.enumValues!.join(", ") }'); } if (v.minimum != null && v.maximum != null) { print(' Range: ${v.minimum} - ${v.maximum}'); } } // Set a variable value await client.setVariable('ups1', 'ups.delay.shutdown', '120'); print(' Shutdown delay set to 120 seconds'); // Verify the change final updated = await client.getVariable('ups1', 'ups.delay.shutdown'); print('New value: ${updated.value}'); } on AuthenticationException catch (e) { print('Authentication error: ${e.userMessage}'); } on CommandException catch (e) { print('Command error: ${e.userMessage}'); } finally { await client.dispose(); } } ``` -------------------------------- ### Dart: Comprehensive Error Handling with NUT Client Source: https://context7.com/jandrop/nut_client/llms.txt Demonstrates how to handle various exceptions like CommandException, AuthenticationException, ConnectionException, ProtocolException, and NutTimeoutException when interacting with the NUT server. It covers scenarios such as unknown UPS devices, unknown variables, unauthorized access, and timeouts. ```dart import 'package:nut_client/nut_client.dart'; void main() async { final client = NutTcpClient.simple('192.168.1.10'); try { await client.connect(); print('Connected successfully\n'); // Test 1: Unknown UPS device try { await client.getVariable('nonexistent_ups', 'ups.status'); } on CommandException catch (e) { print('Test 1 - Unknown UPS:'); print(' Error code: ${e.errorCode}'); print(' Message: ${e.userMessage}'); print(' Technical: ${e.technicalMessage}\n'); } // Test 2: Unknown variable try { await client.getVariable('ups1', 'nonexistent.variable'); } on CommandException catch (e) { print('Test 2 - Unknown variable:'); print(' Error code: ${e.errorCode}'); print(' Message: ${e.userMessage}\n'); } // Test 3: Unauthorized access (without authentication) try { await client.setVariable('ups1', 'ups.delay.shutdown', '120'); } on AuthenticationException catch (e) { print('Test 3 - Unauthorized access:'); print(' Error code: ${e.errorCode}'); print(' Message: ${e.userMessage}\n'); } on CommandException catch (e) { print('Test 3 - Command error instead:'); print(' Message: ${e.userMessage}\n'); } // Test 4: Timeout scenario final timeoutClient = NutTcpClient( NutClientConfig( host: '192.168.1.10', commandTimeout: Duration(milliseconds: 1), ), ); try { await timeoutClient.connect(); await timeoutClient.listUps(); } on NutTimeoutException catch (e) { print('Test 4 - Timeout:'); print(' Message: ${e.userMessage}\n'); } finally { await timeoutClient.dispose(); } } on ConnectionException catch (e) { print('Connection error: ${e.userMessage}'); } on ProtocolException catch (e) { print('Protocol error: ${e.userMessage}'); } on NutException catch (e) { print('General NUT error: ${e.userMessage}'); } finally { await client.dispose(); print('Cleanup completed'); } } ``` -------------------------------- ### Connect with TLS and Authentication (Dart) Source: https://context7.com/jandrop/nut_client/llms.txt Establishes a secure connection to a NUT server using TLS encryption and authenticates using provided credentials. After connecting, it demonstrates executing privileged commands like setting a UPS variable and toggling the beeper. Includes error handling for authentication and connection issues. ```dart import 'package:nut_client/nut_client.dart'; void main() async { final client = NutTcpClient( NutClientConfig( host: '192.168.1.10', port: 3493, useTls: true, credentials: Credentials( username: 'admin', password: 'secret', ), connectionTimeout: Duration(seconds: 10), commandTimeout: Duration(seconds: 30), ), ); try { await client.connect(); print('Connected with TLS and authenticated'); // Now you can use privileged commands await client.setVariable('ups1', 'ups.delay.shutdown', '120'); await client.runCommand('ups1', 'beeper.toggle'); print('Commands executed successfully'); } on AuthenticationException catch (e) { print('Authentication failed: ${e.userMessage}'); } on ConnectionException catch (e) { print('Connection failed: ${e.userMessage}'); } finally { await client.dispose(); } } ``` -------------------------------- ### List All UPS Variables (Dart) Source: https://context7.com/jandrop/nut_client/llms.txt Retrieves all available variables for a specified UPS device using the NUT client. It connects to the UPS server, fetches the variables, and prints their names, values, types, and writability. Requires the 'nut_client' package. ```dart import 'package:nut_client/nut_client.dart'; void main() async { final client = NutTcpClient.simple('192.168.1.10'); try { await client.connect(); final variables = await client.listVariables('ups1'); print('All variables for ups1 (${variables.length} total):'); for (final variable in variables) { final line = StringBuffer('${variable.name} = ${variable.value}'); if (variable.type != null) { line.write(' [${variable.type}]'); } if (variable.isWritable) { line.write(' (writable)'); } print(line.toString()); } } on CommandException catch (e) { print('Command failed: ${e.userMessage}'); } finally { await client.dispose(); } } ``` -------------------------------- ### Test NUT Client with Mock Connection (Dart) Source: https://github.com/jandrop/nut_client/blob/main/README.md Demonstrates how to test the NutTcpClient by injecting a mock NutConnection using the mocktail package. This allows for isolated testing of client logic without a real network connection, verifying interactions with the mock and validating the parsing of mock responses. ```dart import 'package:mocktail/mocktail'; class MockConnection extends Mock implements NutConnection {} void main() { test('lists UPS devices', () async { final mockConnection = MockConnection(); final client = NutTcpClient.withConnection(mockConnection); when(() => mockConnection.isConnected).thenReturn(true); when(() => mockConnection.send(any())).thenAnswer((_) async {}); when(() => mockConnection.readMultiLine()).thenAnswer( (_) async => [ 'BEGIN LIST UPS', 'UPS myups "My UPS"', 'END LIST UPS', ], ); final devices = await client.listUps(); expect(devices.length, equals(1)); expect(devices.first.name, equals('myups')); }); } ``` -------------------------------- ### Real-time UPS Variable Monitoring with Streams in Dart Source: https://github.com/jandrop/nut_client/blob/main/README.md Illustrates how to use the nut_client library's Stream capabilities to monitor UPS variables for changes at specified intervals. This includes watching a single variable or all variables for a given UPS. ```dart // Watch a single variable final subscription = client.watchVariable( 'ups1', 'battery.charge', interval: Duration(seconds: 5), ).listen((variable) { print('Battery: ${variable.value}%'); }); // Later: stop watching await subscription.cancel(); // Watch all variables client.watchVariables( 'ups1', interval: Duration(seconds: 10), ).listen((variables) { for (final v in variables) { print('${v.name}: ${v.value}'); } }); ``` -------------------------------- ### List UPS Devices Source: https://context7.com/jandrop/nut_client/llms.txt Retrieves a list of all UPS devices connected to the NUT server. ```APIDOC ## List UPS Devices ### Description Retrieves a list of all UPS devices connected to the NUT server. ### Method List UPS Devices ### Endpoint N/A (Client-side command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart import 'package:nut_client/nut_client.dart'; void main() async { final client = NutTcpClient.simple('192.168.1.10'); try { await client.connect(); final devices = await client.listUps(); print('Found ${devices.length} UPS device(s):'); for (final device in devices) { print('Name: ${device.name}'); print('Description: ${device.description}'); print('---'); } } on CommandException catch (e) { print('Command failed: ${e.userMessage} (Error code: ${e.errorCode})'); } finally { await client.dispose(); } } ``` ### Response #### Success Response (200) Returns a list of `UpsInfo` objects, each containing the name and description of a UPS device. **`UpsInfo` Object Structure:** - **name** (String) - The unique identifier for the UPS device. - **description** (String) - A human-readable description of the UPS device. #### Response Example ```json [ { "name": "ups1", "description": "APC Back-UPS 650" }, { "name": "ups2", "description": "CyberPower CP1500PFCLCD" } ] ``` ``` -------------------------------- ### List UPS Devices (Dart) Source: https://context7.com/jandrop/nut_client/llms.txt Connects to a NUT server and retrieves a list of all available UPS devices. It iterates through the devices and prints their names and descriptions. This function is useful for discovering the UPS units managed by the server. Includes error handling for command execution failures. ```dart import 'package:nut_client/nut_client.dart'; void main() async { final client = NutTcpClient.simple('192.168.1.10'); try { await client.connect(); final devices = await client.listUps(); print('Found ${devices.length} UPS device(s):'); for (final device in devices) { print('Name: ${device.name}'); print('Description: ${device.description}'); print('---'); } } on CommandException catch (e) { print('Command failed: ${e.userMessage} (Error code: ${e.errorCode})'); } finally { await client.dispose(); } } ``` -------------------------------- ### NUT Client with TLS and Authentication in Dart Source: https://github.com/jandrop/nut_client/blob/main/README.md Shows how to configure and connect a NUT client using TLS encryption and username/password authentication. This allows for secure communication and access to privileged commands on the NUT server. ```dart final client = NutTcpClient( NutClientConfig( host: '192.168.1.10', port: 3493, useTls: true, credentials: Credentials( username: 'admin', password: 'secret', ), ), ); await client.connect(); // Client will automatically use TLS and authenticate // Now you can use privileged commands await client.setVariable('ups1', 'ups.delay.shutdown', '120'); await client.runCommand('ups1', 'beeper.toggle'); ``` -------------------------------- ### Common UPS Variables and Status Flags Source: https://github.com/jandrop/nut_client/blob/main/README.md This section details commonly used UPS variables and their descriptions, along with the meaning of various UPS status flags. ```APIDOC ## Common UPS Variables These are some frequently used variables for monitoring and controlling UPS devices. | Variable | Description | Type | |---|---|---| | `ups.status` | UPS status flags (e.g., OL, OB, LB). | String | | `battery.charge` | Current battery charge percentage (0-100). | Integer | | `battery.runtime` | Estimated remaining battery runtime in seconds. | Integer | | `input.voltage` | The current input voltage from the utility power. | Double | | `ups.load` | The current load on the UPS as a percentage (0-100). | Integer | | `ups.temperature` | The internal temperature of the UPS unit. | Double | ## UPS Status Flags These flags provide insights into the current operational state of the UPS. | Flag | Meaning | |---|---| | `OL` | Online: The UPS is running on utility power. | | `OB` | On Battery: The UPS is currently running on battery power. | | `LB` | Low Battery: The battery charge is critically low. | | `RB` | Replace Battery: The UPS battery needs to be replaced. | | `CHRG` | Charging: The UPS battery is currently being charged. | | `DISCHRG` | Discharging: The UPS battery is currently discharging. | | `ALARM` | Alarm: The UPS has an active alarm condition. | ``` -------------------------------- ### NutClient Interface Source: https://github.com/jandrop/nut_client/blob/main/README.md The NutClient provides the primary interface for interacting with NUT servers. It supports connection, authentication, device listing, variable management, command execution, and real-time variable monitoring. ```APIDOC ## NutClient API Reference The `NutClient` class offers methods for interacting with a NUT server. ### Methods | Method | Description | |---|---| | `connect()` | Connect to the NUT server. | | `disconnect()` | Disconnect from the NUT server. | | `authenticate(Credentials credentials)` | Authenticate with the NUT server using provided credentials. | | `startTls()` | Upgrade the current connection to use TLS encryption. | | `listUps()` | Retrieves a list of all UPS devices known to the server. Returns a `Future>`. | | `listVariables(String upsName)` | Lists all available variables for a specified UPS device. Returns a `Future>`. | | `getVariable(String upsName, String varName)` | Retrieves the value of a specific variable for a given UPS device. Returns a `Future`. | | `setVariable(String upsName, String varName, String value)` | Sets the value of a specific variable for a given UPS device. Returns a `Future`. | | `listCommands(String upsName)` | Lists all available instant commands for a specified UPS device. Returns a `Future>`. | | `listWritableVariables(String upsName)` | Lists all variables that can be written to for a specified UPS device. Returns a `Future>`. | | `runCommand(String upsName, String cmdName)` | Executes an instant command on a specified UPS device. Returns a `Future`. | | `watchVariable(String upsName, String varName, {Duration interval})` | Creates a stream that emits updates for a specific variable at a given interval. Returns a `Stream`. | | `watchVariables(String upsName, {Duration interval})` | Creates a stream that emits updates for all variables of a UPS device at a given interval. Returns a `Stream>`. | | `dispose()` | Releases any resources held by the client. | ### Error Handling The following exceptions can be thrown during client operations: - `ConnectionException`: For issues establishing or maintaining a connection. - `AuthenticationException`: For failed authentication attempts. - `CommandException`: For errors during command execution or variable manipulation. - `NutTimeoutException`: If an operation exceeds the allowed timeout period. #### Example Error Handling Block ```dart try { await client.connect(); final status = await client.getVariable('ups1', 'ups.status'); } on ConnectionException catch (e) { print('Connection failed: ${e.userMessage}'); } on AuthenticationException catch (e) { print('Authentication failed: ${e.userMessage}'); } on CommandException catch (e) { print('Command failed: ${e.userMessage}'); print('Error code: ${e.errorCode}'); } on NutTimeoutException catch (e) { print('Timeout: ${e.userMessage}'); } ``` ``` -------------------------------- ### Watch All UPS Variables with Polling (Dart) Source: https://context7.com/jandrop/nut_client/llms.txt Monitors all UPS variables by automatically polling at a specified interval. It connects to the NUT server, subscribes to variable changes, and prints key metrics like status, battery charge, and load. The function handles connection, polling, error reporting, and graceful disconnection. ```dart import 'package:nut_client/nut_client.dart'; void main() async { final client = NutTcpClient.simple('192.168.1.10'); try { await client.connect(); print('Connected, watching all variables...\n'); // Watch all variables with 10-second polling interval final subscription = client.watchVariables( 'ups1', interval: Duration(seconds: 10), ).listen( (variables) { final timestamp = DateTime.now().toIso8601String(); print('[$timestamp] Received ${variables.length} variables:'); // Extract key metrics final status = variables.firstWhere( (v) => v.name == 'ups.status', orElse: () => UpsVariable(name: 'ups.status', value: 'unknown'), ); final charge = variables.firstWhere( (v) => v.name == 'battery.charge', orElse: () => UpsVariable(name: 'battery.charge', value: '0'), ); final load = variables.firstWhere( (v) => v.name == 'ups.load', orElse: () => UpsVariable(name: 'ups.load', value: '0'), ); print(' Status: ${status.value}'); print(' Battery: ${charge.intValue}%'); print(' Load: ${load.intValue}%'); print('---'); }, onError: (error) { print('Watch error: $error'); }, ); // Let it run for 35 seconds await Future.delayed(Duration(seconds: 35)); // Stop watching await subscription.cancel(); print('\nStopped watching variables'); } finally { await client.dispose(); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.