### Wrap Existing Connection with New Source: https://context7.com/mdlayher/apcupsd/llms.txt Creates an apcupsd Client from an existing `io.ReadWriteCloser`. This is useful for integrating with custom network setups or existing connections. ```go package main import ( "fmt" "log" "net" "github.com/mdlayher/apcupsd" ) func main() { // Establish your own connection conn, err := net.Dial("tcp", "localhost:3551") if err != nil { log.Fatalf("failed to dial: %v", err) } // Wrap the connection with the apcupsd client client := apcupsd.New(conn) defer client.Close() fmt.Println("Created apcupsd client from existing connection") } ``` -------------------------------- ### Implement UPS Monitoring Loop in Go Source: https://context7.com/mdlayher/apcupsd/llms.txt This example demonstrates a complete monitoring loop that periodically checks UPS status, logs important events, and alerts on critical conditions. It requires connecting to the apcupsd daemon and uses a ticker for periodic polling. ```go package main import ( "context" "fmt" "log" "time" "github.com/mdlayher/apcupsd" ) func main() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() client, err := apcupsd.DialContext(ctx, "tcp", "localhost:3551") if err != nil { log.Fatalf("failed to connect: %v", err) } defer client.Close() // Poll every 30 seconds ticker := time.NewTicker(30 * time.Second) defer ticker.Stop() var lastStatus string for { status, err := client.Status() if err != nil { log.Printf("error getting status: %v", err) continue } // Log status changes if status.Status != lastStatus { log.Printf("Status changed: %s -> %s", lastStatus, status.Status) lastStatus = status.Status } // Log current metrics fmt.Printf("[%s] Status: %s | Load: %.1f%% | Battery: %.1f%% | Time Left: %v\n", time.Now().Format("15:04:05"), status.Status, status.LoadPercent, status.BatteryChargePercent, status.TimeLeft, ) // Alert on critical conditions if status.Status == "ONBATT" { log.Printf("ALERT: Running on battery! Estimated runtime: %v", status.TimeLeft) } if status.BatteryChargePercent < 20 { log.Printf("WARNING: Battery charge critical: %.1f%%", status.BatteryChargePercent) } <-ticker.C } } ``` -------------------------------- ### New - Wrap Existing Connection Source: https://context7.com/mdlayher/apcupsd/llms.txt Creates a Client from an existing `io.ReadWriteCloser`. This is useful when you need custom connection handling or want to wrap an existing network connection with the apcupsd protocol. ```APIDOC ## New - Wrap Existing Connection ### Description Creates a Client from an existing `io.ReadWriteCloser`. This is useful when you need custom connection handling or want to wrap an existing network connection with the apcupsd protocol. ### Method New ### Endpoint N/A (This is a client library function, not a direct HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "log" "net" "github.com/mdlayher/apcupsd" ) func main() { // Establish your own connection conn, err := net.Dial("tcp", "localhost:3551") if err != nil { log.Fatalf("failed to dial: %v", err) } // Wrap the connection with the apcupsd client client := apcupsd.New(conn) defer client.Close() fmt.Println("Created apcupsd client from existing connection") } ``` ### Response #### Success Response (Client) - **client** (*apcupsd.Client) - A client instance for interacting with the NIS. #### Response Example (See Go code example for usage) ``` -------------------------------- ### Connect to apcupsd NIS with Dial Source: https://context7.com/mdlayher/apcupsd/llms.txt Establishes a TCP connection to an apcupsd NIS. Use this for basic connections to the default port. ```go package main import ( "fmt" "log" "github.com/mdlayher/apcupsd" ) func main() { // Connect to apcupsd NIS running on localhost port 3551 (default port) client, err := apcupsd.Dial("tcp", "localhost:3551") if err != nil { log.Fatalf("failed to connect to apcupsd: %v", err) } defer client.Close() fmt.Println("Connected to apcupsd NIS") } ``` -------------------------------- ### Connect to apcupsd NIS with DialContext Source: https://context7.com/mdlayher/apcupsd/llms.txt Connects to an apcupsd NIS with context support for timeouts and cancellation. Useful for managing connection lifecycles in concurrent applications. ```go package main import ( "context" "fmt" "log" "time" "github.com/mdlayher/apcupsd" ) func main() { // Create a context with 5 second timeout ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() // Connect to apcupsd NIS with timeout client, err := apcupsd.DialContext(ctx, "tcp", "192.168.1.100:3551") if err != nil { log.Fatalf("failed to connect to apcupsd: %v", err) } defer client.Close() fmt.Println("Connected to apcupsd NIS with timeout") } ``` -------------------------------- ### DialContext - Connect with Context and Timeout Source: https://context7.com/mdlayher/apcupsd/llms.txt Connects to an apcupsd NIS with a context for timeout and cancellation support. If the context expires before the connection is established, an error is returned. ```APIDOC ## DialContext - Connect with Context and Timeout ### Description Connects to an apcupsd NIS with a context for timeout and cancellation support. If the context expires before the connection is established, an error is returned. Once connected, context expiration does not affect the connection. ### Method DialContext ### Endpoint N/A (This is a client library function, not a direct HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "context" "fmt" "log" "time" "github.com/mdlayher/apcupsd" ) func main() { // Create a context with 5 second timeout ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() // Connect to apcupsd NIS with timeout client, err := apcupsd.DialContext(ctx, "tcp", "192.168.1.100:3551") if err != nil { log.Fatalf("failed to connect to apcupsd: %v", err) } defer client.Close() fmt.Println("Connected to apcupsd NIS with timeout") } ``` ### Response #### Success Response (Client) - **client** (*apcupsd.Client) - A client instance for interacting with the NIS. #### Response Example (See Go code example for usage) ``` -------------------------------- ### Retrieve UPS Status with Status Source: https://context7.com/mdlayher/apcupsd/llms.txt Queries the NIS for the current UPS status and returns a Status struct. Access comprehensive UPS metrics like battery charge, load, voltage, and transfer events. ```go package main import ( "fmt" "log" "github.com/mdlayher/apcupsd" ) func main() { client, err := apcupsd.Dial("tcp", "localhost:3551") if err != nil { log.Fatalf("failed to connect: %v", err) } defer client.Close() // Get current UPS status status, err := client.Status() if err != nil { log.Fatalf("failed to get status: %v", err) } // Access UPS information fmt.Printf("UPS Model: %s\n", status.Model) fmt.Printf("UPS Name: %s\n", status.UPSName) fmt.Printf("Status: %s\n", status.Status) fmt.Printf("Line Voltage: %.1f V\n", status.LineVoltage) fmt.Printf("Load: %.1f%%\n", status.LoadPercent) fmt.Printf("Battery Charge: %.1f%%\n", status.BatteryChargePercent) fmt.Printf("Battery Voltage: %.1f V\n", status.BatteryVoltage) fmt.Printf("Time Left: %v\n", status.TimeLeft) fmt.Printf("Internal Temp: %.1f°C\n", status.InternalTemp) fmt.Printf("Number of Transfers: %d\n", status.NumberTransfers) fmt.Printf("Time on Battery: %v\n", status.TimeOnBattery) fmt.Printf("Cumulative Time on Battery: %v\n", status.CumulativeTimeOnBattery) fmt.Printf("Last Transfer Reason: %s\n", status.LastTransfer) fmt.Printf("Nominal Power: %d W\n", status.NominalPower) fmt.Printf("Firmware: %s\n", status.Firmware) fmt.Printf("Serial Number: %s\n", status.SerialNumber) // Check for battery operation if status.Status == "ONBATT" { fmt.Printf("WARNING: Running on battery! Time remaining: %v\n", status.TimeLeft) } } ``` -------------------------------- ### Connect and Retrieve UPS Status Source: https://context7.com/mdlayher/apcupsd/llms.txt Connects to the apcupsd NIS and retrieves the UPS status. Ensure apcupsd is running and accessible on localhost:3551. The defer client.Close() ensures the connection is closed when the function exits. ```go package main import ( "fmt" "log" "time" "github.com/mdlayher/apcupsd" ) func main() { client, err := apcupsd.Dial("tcp", "localhost:3551") if err != nil { log.Fatalf("failed to connect: %v", err) } defer client.Close() status, err := client.Status() if err != nil { log.Fatalf("failed to get status: %v", err) } // Status struct fields available: // Identification _ = status.APC // Header record with format revision _ = status.Hostname // Machine name collecting UPS data _ = status.Version // apcupsd version info _ = status.UPSName // UPS name from EEPROM or config _ = status.Model // UPS model _ = status.SerialNumber // UPS serial number _ = status.Firmware // Firmware revision // Configuration _ = status.Cable // Cable type from config _ = status.Driver // Driver communicating with UPS _ = status.UPSMode // Operating mode from config // Voltage readings _ = status.LineVoltage // Current line voltage _ = status.BatteryVoltage // Battery voltage _ = status.OutputVoltage // Output voltage _ = status.NominalInputVoltage // Expected input voltage _ = status.NominalBatteryVoltage // Nominal battery voltage _ = status.LowTransferVoltage // Switch to battery below this _ = status.HighTransferVoltage // Switch to battery above this // Load and battery _ = status.LoadPercent // Load capacity percentage _ = status.BatteryChargePercent // Battery charge percentage _ = status.MinimumBatteryChargePercent // Shutdown threshold _ = status.NominalPower // Max power in Watts // Timing _ = status.TimeLeft // Estimated runtime on battery _ = status.MinimumTimeLeft // Shutdown if runtime below this _ = status.MaximumTime // Shutdown if on battery exceeds _ = status.TimeOnBattery // Current time on battery _ = status.CumulativeTimeOnBattery // Total time on battery // Timestamps _ = status.Date // When info was last obtained _ = status.StartTime // When apcupsd was started _ = status.EndAPC // When STATUS record was written // Transfer events _ = status.NumberTransfers // Transfers since startup _ = status.LastTransfer // Reason for last transfer _ = status.XOnBattery // Time of last switch to battery _ = status.XOffBattery // Time of last switch from battery // Other _ = status.Status // Current status (ONLINE, ONBATT, etc.) _ = status.StatusFlags // Raw status flags _ = status.Sense // Sensitivity level _ = status.InternalTemp // Ambient temperature _ = status.LineFrequency // Line frequency _ = status.OutputAmps // Output current _ = status.Selftest // Self test results _ = status.LastSelftest // Last self test time _ = status.AlarmDel // Alarm delay period _ = status.BatteryDate // Battery replacement date // Example: Monitor for low battery if status.BatteryChargePercent < status.MinimumBatteryChargePercent { fmt.Println("CRITICAL: Battery below minimum threshold!") } // Example: Check if UPS was recently on battery if !status.XOnBattery.IsZero() && time.Since(status.XOnBattery) < 24*time.Hour { fmt.Printf("UPS switched to battery within last 24h at %v\n", status.XOnBattery) fmt.Printf("Reason: %s\n", status.LastTransfer) } } ``` -------------------------------- ### Dial - Connect to apcupsd NIS Source: https://context7.com/mdlayher/apcupsd/llms.txt Establishes a TCP connection to an apcupsd Network Information Server and returns a Client for querying UPS status. Accepts network type and address. ```APIDOC ## Dial - Connect to apcupsd NIS ### Description Establishes a TCP connection to an apcupsd Network Information Server and returns a Client for querying UPS status. The function accepts a network type (typically "tcp", "tcp4", or "tcp6") and an address in host:port format. ### Method Dial ### Endpoint N/A (This is a client library function, not a direct HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "log" "github.com/mdlayher/apcupsd" ) func main() { // Connect to apcupsd NIS running on localhost port 3551 (default port) client, err := apcupsd.Dial("tcp", "localhost:3551") if err != nil { log.Fatalf("failed to connect to apcupsd: %v", err) } defer client.Close() fmt.Println("Connected to apcupsd NIS") } ``` ### Response #### Success Response (Client) - **client** (*apcupsd.Client) - A client instance for interacting with the NIS. #### Response Example (See Go code example for usage) ``` -------------------------------- ### Status - Retrieve UPS Status Source: https://context7.com/mdlayher/apcupsd/llms.txt Queries the NIS for the current UPS status and returns a Status struct containing all available UPS metrics. ```APIDOC ## Status - Retrieve UPS Status ### Description Queries the NIS for the current UPS status and returns a Status struct containing all available UPS metrics. The Status struct includes battery charge, load percentage, voltage readings, timing information, and transfer event history. ### Method Status ### Endpoint N/A (This is a client library function, not a direct HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "log" "github.com/mdlayher/apcupsd" ) func main() { client, err := apcupsd.Dial("tcp", "localhost:3551") if err != nil { log.Fatalf("failed to connect: %v", err) } defer client.Close() // Get current UPS status status, err := client.Status() if err != nil { log.Fatalf("failed to get status: %v", err) } // Access UPS information fmt.Printf("UPS Model: %s\n", status.Model) fmt.Printf("UPS Name: %s\n", status.UPSName) fmt.Printf("Status: %s\n", status.Status) fmt.Printf("Line Voltage: %.1f V\n", status.LineVoltage) fmt.Printf("Load: %.1f%%\n", status.LoadPercent) fmt.Printf("Battery Charge: %.1f%%\n", status.BatteryChargePercent) fmt.Printf("Battery Voltage: %.1f V\n", status.BatteryVoltage) fmt.Printf("Time Left: %v\n", status.TimeLeft) fmt.Printf("Internal Temp: %.1f°C\n", status.InternalTemp) fmt.Printf("Number of Transfers: %d\n", status.NumberTransfers) fmt.Printf("Time on Battery: %v\n", status.TimeOnBattery) fmt.Printf("Cumulative Time on Battery: %v\n", status.CumulativeTimeOnBattery) fmt.Printf("Last Transfer Reason: %s\n", status.LastTransfer) fmt.Printf("Nominal Power: %d W\n", status.NominalPower) fmt.Printf("Firmware: %s\n", status.Firmware) fmt.Printf("Serial Number: %s\n", status.SerialNumber) // Check for battery operation if status.Status == "ONBATT" { fmt.Printf("WARNING: Running on battery! Time remaining: %v\n", status.TimeLeft) } } ``` ### Response #### Success Response (200) - **status** (*apcupsd.Status) - A struct containing comprehensive UPS metrics. - **Model** (string) - The UPS model name. - **UPSName** (string) - The name of the UPS. - **Status** (string) - The current status of the UPS (e.g., "ONLINE", "ONBATT"). - **LineVoltage** (float64) - The current line voltage in Volts. - **LoadPercent** (float64) - The current load percentage. - **BatteryChargePercent** (float64) - The current battery charge percentage. - **BatteryVoltage** (float64) - The current battery voltage in Volts. - **TimeLeft** (time.Duration) - The estimated time remaining on battery. - **InternalTemp** (float64) - The internal temperature of the UPS in Celsius. - **NumberTransfers** (int) - The total number of power transfers. - **TimeOnBattery** (time.Duration) - The duration the UPS has been on battery power during the current outage. - **CumulativeTimeOnBattery** (time.Duration) - The cumulative time the UPS has spent on battery power. - **LastTransfer** (string) - The reason for the last power transfer. - **NominalPower** (int) - The nominal power rating of the UPS in Watts. - **Firmware** (string) - The UPS firmware version. - **SerialNumber** (string) - The UPS serial number. #### Response Example ```json { "Model": "Back-UPS Pro", "UPSName": "MyUPS", "Status": "ONLINE", "LineVoltage": 120.5, "LoadPercent": 25.5, "BatteryChargePercent": 98.0, "BatteryVoltage": 13.8, "TimeLeft": "0h30m0s", "InternalTemp": 35.2, "NumberTransfers": 5, "TimeOnBattery": "0h0m0s", "CumulativeTimeOnBattery": "0h15m0s", "LastTransfer": "LOWBATT", "NominalPower": 1500, "Firmware": "v1.2.3", "SerialNumber": "1234567890ABC" } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.