### List Business Entities Source: https://context7.com/hyperviewhq/sample_code/llms.txt Retrieve a paginated list of business entities using the advanced collection endpoint. ```APIDOC ## GET /api/asset/businessEntities/advancedCollection ### Description Retrieves a paginated list of business entities. Supports skipping a certain number of entities and taking a specified quantity. ### Method GET ### Endpoint `/api/asset/businessEntities/advancedCollection` ### Parameters #### Query Parameters - **skip** (integer) - Optional - The number of entities to skip from the beginning of the list. - **take** (integer) - Optional - The maximum number of entities to return. ### Request Example ```python import requests instance_url = "https://your-instance.hyperview.com" access_token = "your_access_token" headers = { "Authorization": f"Bearer {access_token}" } params = { "skip": 0, "take": 100 } response = requests.get(f"{instance_url}/api/asset/businessEntities/advancedCollection", headers=headers, params=params) ``` ### Response #### Success Response (200) - **data** (array) - A list of business entity objects. - **id** (string) - The unique identifier of the business entity. - **name** (string) - The name of the business entity. - **businessEntityTypeValue** (string) - The type of the business entity. - **_metadata** (object) - Metadata about the response, such as pagination information. #### Response Example ```json { "data": [ { "id": "entity-123", "name": "Example Business Entity", "businessEntityTypeValue": "Customer" } ], "_metadata": { "totalCount": 500, "skip": 0, "take": 100 } } ``` ``` -------------------------------- ### Query Assets by Type (Python) Source: https://context7.com/hyperviewhq/sample_code/llms.txt Retrieves a list of assets from Hyperview filtered by asset type. It supports pagination and includes parameters for filtering and sorting. Dependencies include the 'requests' library. ```python import requests def get_asset_list(instance_url, access_token): asset_endpoint = f"{instance_url}/api/asset/assets" req_headers = { "Content-Type": "application/json", "Authorization": f"Bearer {access_token}" } # Query parameters - fetch first 10 CRAC units req_params = { "assetType": "crac", "includeDimensions": "false", "(after)": "0", "(limit)": "10", "(sort)": "+Id" } try: resp = requests.get(url=asset_endpoint, params=req_params, headers=req_headers) resp.raise_for_status() resp_json = resp.json() # Process asset list asset_list = resp_json.get("data") metadata = resp_json.get("_metadata") print(f"Retrieved {len(asset_list)} assets") for asset in asset_list: print(f"Asset ID: {asset['id']}, Name: {asset['name']}, Parent: {asset['parentName']}") return asset_list except requests.exceptions.RequestException as e: print(f"Failed to fetch assets: {e}") exit(1) # Usage access_token = "your_access_token_here" instance_url = "https://your-instance.hyperview.com" assets = get_asset_list(instance_url, access_token) ``` -------------------------------- ### List Assets with PowerShell Source: https://context7.com/hyperviewhq/sample_code/llms.txt Query and export assets by type to JSON format with detailed information using PowerShell. This script retrieves DNS names, OS details, and power associations for assets. ```APIDOC ## GET /api/asset/assets (with related lookups) ### Description Query and export assets by type to JSON format with detailed information. This script retrieves DNS names, OS details, and power associations for assets. ### Method GET (for core asset and then subsequent calls for details) ### Endpoint /api/asset/assets (and related detail endpoints like /api/asset/discoveredDnsName, /api/asset/discoveredOs, /api/asset/powerAssociations) ### Query Parameters - **Type** (string) - Required - The type of asset to filter by (e.g., 'Server'). - **AccessToken** (string) - Required - Your Hyperview API access token. - **ApiHost** (string) - Required - The hostname of your Hyperview instance. ### Request Example ```powershell # Configuration $AssetType = "Server" $OutFileName = "output.json" $HostName = "your-instance.hyperview.com" $accessToken = "your_access_token" # Assuming Get-AssetsByType, Get-DiscoveredDnsName, Get-DiscoveredOs, Get-PowerAssociations are defined cmdlets $Assets = Get-AssetsByType -AccessToken $accessToken -ApiHost $HostName -Type $AssetType $records = @() foreach ($asset in $Assets) { $DiscoveredDnsName = Get-DiscoveredDnsName -AccessToken $accessToken -ApiHost $HostName -AssetId $asset.Id $OperatingSystem = Get-DiscoveredOs -AccessToken $accessToken -ApiHost $HostName -AssetId $asset.Id $powerAssociations = Get-PowerAssociations -AccessToken $accessToken -ApiHost $HostName -AssetId $asset.Id $mappedAsset = @{ "u_dns_hostname" = $DiscoveredDnsName.value; "u_hyperview_asset_type" = $asset.assetType; "u_hyperview_id" = $asset.id; "u_serial_number" = $asset.assetProperty_serialNumber; "u_lifecycle_state" = $asset.assetLifecycleState; "u_manufacturer" = $asset.manufacturerName; "u_model" = $asset.productName; "u_name" = $asset.displayName; "u_operating_system" = $OperatingSystem.name; "u_power_providing_assets" = $powerAssociations.by_name; "u_rack_elevation" = $asset.rackULocation; "u_rack_side" = $asset.rackSide; } $records += $mappedAsset } # Export to JSON $output = @{ "records" = $records } $output | ConvertTo-Json -Depth 9 | Out-File -FilePath $OutFileName -NoClobber Write-Host "Exported $($records.Count) assets to $OutFileName" ``` ### Response #### Success Response (200) - The script outputs a JSON file named `output.json` containing an array of asset records with mapped details. #### Response Example ```json { "records": [ { "u_dns_hostname": "server1.example.com", "u_hyperview_asset_type": "Server", "u_hyperview_id": "server_abc", "u_serial_number": "SN12345", "u_lifecycle_state": "In Service", "u_manufacturer": "Dell", "u_model": "PowerEdge R740", "u_name": "Web Server 1", "u_operating_system": "Windows Server 2019", "u_power_providing_assets": [ "PDU-A-1", "UPS-Main" ], "u_rack_elevation": 10, "u_rack_side": "Front" } ] } ``` ``` -------------------------------- ### OAuth2 Client Credentials Authentication (Python) Source: https://context7.com/hyperviewhq/sample_code/llms.txt Authenticates with the Hyperview API using OAuth2 client credentials flow in Python and retrieves an access token. ```APIDOC ## POST /connect/token ### Description Authenticates with the Hyperview API using OAuth2 client credentials flow and retrieves an access token for subsequent API requests. ### Method POST ### Endpoint `/connect/token` ### Parameters #### Query Parameters - **grant_type** (string) - Required - Must be 'client_credentials'. - **client_id** (string) - Required - Your OAuth2 client ID. - **client_secret** (string) - Required - Your OAuth2 client secret. ### Request Example ```json { "grant_type": "client_credentials", "client_id": "your_client_id", "client_secret": "your_client_secret" } ``` ### Response #### Success Response (200) - **access_token** (string) - The obtained access token. - **expires_in** (integer) - The lifetime in seconds of the access token. - **token_type** (string) - The type of token issued, typically 'Bearer'. #### Response Example ```json { "access_token": "eyJ...", "expires_in": 3600, "token_type": "Bearer" } ``` ``` -------------------------------- ### OAuth2 Client Credentials Authentication (PowerShell) Source: https://context7.com/hyperviewhq/sample_code/llms.txt Authenticates with the Hyperview API using OAuth2 client credentials flow in PowerShell and retrieves an access token. ```APIDOC ## POST /connect/token ### Description Authenticates with the Hyperview API using OAuth2 client credentials flow in PowerShell and retrieves an access token. ### Method POST ### Endpoint `/connect/token` ### Parameters #### Query Parameters - **grant_type** (string) - Required - Must be 'client_credentials'. - **client_id** (string) - Required - Your OAuth2 client ID. - **client_secret** (string) - Required - Your OAuth2 client secret. ### Request Example ```json { "grant_type": "client_credentials", "client_id": "your_client_id", "client_secret": "your_client_secret" } ``` ### Response #### Success Response (200) - **access_token** (string) - The obtained access token. - **expires_in** (integer) - The lifetime in seconds of the access token. - **token_type** (string) - The type of token issued, typically 'Bearer'. #### Response Example ```json { "access_token": "eyJ...", "expires_in": 3600, "token_type": "Bearer" } ``` ``` -------------------------------- ### List Business Entities with Pagination (Python) Source: https://context7.com/hyperviewhq/sample_code/llms.txt Retrieves a paginated list of business entities using the advanced collection endpoint. Requires instance URL and access token. Outputs a formatted list of entities. ```python import requests import json def list_business_entities(instance_url, access_token, skip=0, take=100): be_endpoint = f"{instance_url}/api/asset/businessEntities/advancedCollection" req_headers = { "Content-Type": "application/json", "Authorization": f"Bearer {access_token}" } req_params = { "skip": skip, "take": take } try: resp = requests.get(url=be_endpoint, params=req_params, headers=req_headers) resp.raise_for_status() resp_json = resp.json() be_list = resp_json.get("data") metadata = resp_json.get("_metadata") print(f"Retrieved {len(be_list)} business entities") print(f"{'ID':<10} {'Name':<40} {'Type':<30}") print("-" * 80) for be in be_list: be_id = be.get('id', 'N/A') name = be.get('name', 'N/A') be_type = be.get('businessEntityTypeValue', 'N/A') print(f"{be_id:<10} {name:<40} {be_type:<30}") return be_list except requests.exceptions.RequestException as e: print(f"Failed to fetch business entities: {e}") exit(1) # Usage access_token = "your_access_token" instance_url = "https://your-instance.hyperview.com" entities = list_business_entities(instance_url, access_token, skip=0, take=100) ``` -------------------------------- ### OAuth2 Client Credentials Authentication (Java) Source: https://context7.com/hyperviewhq/sample_code/llms.txt Authenticates with the Hyperview API using OAuth2 client credentials flow in Java and retrieves an access token. ```APIDOC ## POST /connect/token ### Description Authenticates with the Hyperview API using OAuth2 client credentials flow in Java and retrieves an access token. ### Method POST ### Endpoint `/connect/token` ### Parameters #### Query Parameters - **grant_type** (string) - Required - Must be 'client_credentials'. - **client_id** (string) - Required - Your OAuth2 client ID. - **client_secret** (string) - Required - Your OAuth2 client secret. ### Request Example ```json { "grant_type": "client_credentials", "client_id": "your_client_id", "client_secret": "your_client_secret" } ``` ### Response #### Success Response (200) - **access_token** (string) - The obtained access token. - **expires_in** (integer) - The lifetime in seconds of the access token. - **token_type** (string) - The type of token issued, typically 'Bearer'. #### Response Example ```json { "access_token": "eyJ...", "expires_in": 3600, "token_type": "Bearer" } ``` ``` -------------------------------- ### Acknowledge Alarm Events API Source: https://context7.com/hyperviewhq/sample_code/llms.txt Acknowledge specific alarm events by providing their IDs. ```APIDOC ## POST /api/asset/alarmEvents/{alarmEventId}/acknowledge ### Description Acknowledge one or more specific alarm events by sending a POST request to their respective endpoints. ### Method POST ### Endpoint `/api/asset/alarmEvents/{alarmEventId}/acknowledge` ### Parameters #### Path Parameters - **alarmEventId** (string) - Required - The unique identifier of the alarm event to acknowledge. ### Request Example ```powershell $HostName = "https://your-instance.hyperview.com" $accessToken = "your_access_token" $AlarmEventIds = @("alarm-id-1", "alarm-id-2") $Headers = @{ "Content-Type" = "application/json" "Authorization" = "Bearer $accessToken" } foreach ($AlarmId in $AlarmEventIds) { $Uri = "$HostName/api/asset/alarmEvents/$AlarmId/acknowledge" try { Invoke-RestMethod -Uri $Uri -Method Post -Headers $Headers Write-Host "Successfully acknowledged alarm $AlarmId" } catch { Write-Host "Failed to acknowledge alarm $AlarmId : $_" } } ``` ### Response #### Success Response (200) Typically returns an empty body or a success confirmation. #### Response Example (No specific JSON body provided for success, often an HTTP 200 OK status is sufficient confirmation.) ``` -------------------------------- ### List Alarm Events API Source: https://context7.com/hyperviewhq/sample_code/llms.txt Query alarm events with filtering options, including acknowledged/unacknowledged status and pagination. ```APIDOC ## GET /api/asset/alarmEvents/allAssets/advancedCollection ### Description Retrieves a list of alarm events. Allows filtering by acknowledgement status and pagination. ### Method GET ### Endpoint `/api/asset/alarmEvents/allAssets/advancedCollection` ### Parameters #### Query Parameters - **skip** (integer) - Optional - The number of alarm events to skip. - **take** (integer) - Optional - The maximum number of alarm events to return. - **filter** (string) - Optional - A JSON string representing filter criteria. Example: `["acknowledgementState","=","unacknowledged"]` to filter for unacknowledged events. ### Request Example ```powershell $HostName = "https://your-instance.hyperview.com" $accessToken = "your_access_token" $Headers = @{ "Content-Type" = "application/json" "Authorization" = "Bearer $accessToken" } $Parameters = [System.Web.HttpUtility]::ParseQueryString([String]::Empty) $Parameters['skip'] = 0 $Parameters['take'] = 100 # To get only unacknowledged events: # $Parameters['filter'] = '["acknowledgementState","=","unacknowledged"]' $BaseUri = "$HostName/api/asset/alarmEvents/allAssets/advancedCollection" $Request = New-Object System.UriBuilder($BaseUri) $Request.Query = $Parameters.ToString() $Response = Invoke-RestMethod -Uri $Request.Uri -Method Get -Headers $Headers ``` ### Response #### Success Response (200) - **data** (array) - A list of alarm event objects. - **id** (string) - The unique identifier of the alarm event. - **acknowledgementState** (string) - The acknowledgement status of the alarm (e.g., 'acknowledged', 'unacknowledged'). - **state** (string) - The current state of the alarm (e.g., 'active'). - **_metadata** (object) - Metadata about the response. #### Response Example ```json { "data": [ { "id": "alarm-event-xyz", "acknowledgementState": "unacknowledged", "state": "active" } ], "_metadata": {} } ``` ``` -------------------------------- ### Upload Floor-Mounted Assets Source: https://context7.com/hyperviewhq/sample_code/llms.txt Create new floor-mounted assets in Hyperview from CSV data. This endpoint allows for bulk creation of assets by specifying details like name, location, type, and model. ```APIDOC ## POST /api/asset/assets ### Description Create new floor-mounted assets in Hyperview from CSV data. This endpoint allows for bulk creation of assets by specifying details like name, location, type, and model. ### Method POST ### Endpoint /api/asset/assets ### Parameters #### Query Parameters - **AccessToken** (string) - Required - Your Hyperview API access token. - **ApiHost** (string) - Required - The hostname of your Hyperview instance. #### Request Body - **AssetObject** (object) - Required - An object containing the details of the asset to be created. - **name** (string) - Required - The name of the asset. - **status** (integer) - Required - The status of the asset (e.g., 0 for active). - **assetTypeId** (string) - Required - The ID of the asset type. - **parentId** (string) - Required - The ID of the parent location. - **creatableAssetProperties** (array) - Required - An array of asset properties. - **type** (string) - Required - The type of property (e.g., 'serialNumber', 'assetTrackerId'). - **value** (string) - Required - The value of the property. - **assetLifecycleState** (integer) - Required - The lifecycle state of the asset (e.g., 0 for operational). - **productId** (string) - Required - The ID of the product model. *CSV Headers* - Name - Location - AssetType - SerialNumber - ModelId - AssetTrackerId (Optional) ### Request Example ```powershell # Assuming Get-LocationId and Add-Asset are defined cmdlets $accessToken = "your_access_token" $HostName = "your-instance.hyperview.com" # Import CSV file with asset data $CsvData = Import-Csv -Path ./data/floor_mounted.csv foreach ($line in $CsvData) { # Get location ID from location name $LocationId = Get-LocationId -AccessToken $accessToken -Location $line.Location -ApiHost $HostName -Type "Location" # Build asset object $AssetObject = @{ "name" = $line.Name; "status" = 0; "assetTypeId" = $line.AssetType; "parentId" = $LocationId; "creatableAssetProperties" = @( @{ "type" = "serialNumber"; "value" = $line.SerialNumber } ); "assetLifecycleState" = 0; "productId" = $line.ModelId; } # Add optional asset tracker ID if (-not ([string]::IsNullOrEmpty($line.AssetTrackerId))) { $AssetObject.creatableAssetProperties += @{ "type" = 147; "value" = $line.AssetTrackerId } } Write-Host "Creating Asset: $($line.Name) at Location: $($line.Location)" # Create asset via API $Response = Add-Asset -AssetObject $AssetObject -ApiHost $HostName -AccessToken $accessToken Write-Host "Response: $Response" } ``` ### Response #### Success Response (200) - The response indicates the success or failure of the asset creation operation. A typical success response might contain the ID of the newly created asset or a confirmation message. #### Response Example ```json { "message": "Asset created successfully", "assetId": "new_asset_id_456" } ``` ``` -------------------------------- ### Close Active Alarm Events API Source: https://context7.com/hyperviewhq/sample_code/llms.txt Retrieve and close active alarm events. ```APIDOC ## POST /api/asset/alarmEvents/{alarmEventId}/close (Implicit) ### Description This operation involves first listing active alarm events and then potentially closing them. The provided script fetches active alarms. Closing an alarm would typically involve a POST or PUT request to a specific alarm endpoint, potentially with a 'close' action. ### Method GET (to list active alarms) followed by POST (to close, implied) ### Endpoint - List Active Alarms: `/api/asset/alarmEvents/allAssets/advancedCollection` (with filter for state='active') - Close Alarm: `/api/asset/alarmEvents/{alarmEventId}/close` (Hypothetical endpoint, specific implementation may vary) ### Parameters #### Query Parameters (for listing active alarms) - **filter** (string) - Required - To filter for active alarms, e.g., `["state","=","active"]`. - **take** (integer) - Optional - Maximum number of alarms to retrieve. ### Request Example (Listing active alarms) ```powershell $HostName = "https://your-instance.hyperview.com" $accessToken = "your_access_token" $Headers = @{ "Content-Type" = "application/json" "Authorization" = "Bearer $accessToken" } $Parameters = [System.Web.HttpUtility]::ParseQueryString([String]::Empty) $Parameters['filter'] = '["state","=","active"]' $Parameters['take'] = '100' $BaseUri = "$HostName/api/asset/alarmEvents/allAssets/advancedCollection" $Request = New-Object System.UriBuilder($BaseUri) $Request.Query = $Parameters.ToString() $Response = Invoke-RestMethod -Uri $Request.Uri -Method Get -Headers $Headers # To close each active alarm, you would iterate through $Response.data # and make a POST request to a /close endpoint for each alarm ID. # Example (conceptual): # foreach ($alarm in $Response.data) { # $CloseUri = "$HostName/api/asset/alarmEvents/$($alarm.id)/close" # Invoke-RestMethod -Uri $CloseUri -Method Post -Headers $Headers # } ``` ### Response #### Success Response (200) (for listing active alarms) - **data** (array) - A list of active alarm event objects. #### Response Example (for listing active alarms) ```json { "data": [ { "id": "active-alarm-1", "state": "active", "severity": "critical" } ], "_metadata": {} } ``` ``` -------------------------------- ### List Assets by Type and Export to JSON (PowerShell) Source: https://context7.com/hyperviewhq/sample_code/llms.txt Queries assets by a specified type using PowerShell and exports the detailed information to a JSON file. This script retrieves DNS names, OS information, and power associations for each asset. It relies on custom cmdlets like Get-AssetsByType, Get-DiscoveredDnsName, etc. ```powershell # Configuration $AssetType = "Server" $OutFileName = "output.json" $HostName = "your-instance.hyperview.com" $accessToken = "your_access_token" # Get assets by type $Assets = Get-AssetsByType -AccessToken $accessToken -ApiHost $HostName -Type $AssetType $records = @() foreach ($asset in $Assets) { $DiscoveredDnsName = Get-DiscoveredDnsName -AccessToken $accessToken -ApiHost $HostName -AssetId $asset.Id $OperatingSystem = Get-DiscoveredOs -AccessToken $accessToken -ApiHost $HostName -AssetId $asset.Id $powerAssociations = Get-PowerAssociations -AccessToken $accessToken -ApiHost $HostName -AssetId $asset.Id $mappedAsset = @{ "u_dns_hostname" = $DiscoveredDnsName.value; "u_hyperview_asset_type" = $asset.assetType; "u_hyperview_id" = $asset.id; "u_serial_number" = $asset.assetProperty_serialNumber; "u_lifecycle_state" = $asset.assetLifecycleState; "u_manufacturer" = $asset.manufacturerName; "u_model" = $asset.productName; "u_name" = $asset.displayName; "u_operating_system" = $OperatingSystem.name; "u_power_providing_assets" = $powerAssociations.by_name; "u_rack_elevation" = $asset.rackULocation; "u_rack_side" = $asset.rackSide; } $records += $mappedAsset } # Export to JSON $output = @{ "records" = $records } $output | ConvertTo-Json -Depth 9 | Out-File -FilePath $OutFileName -NoClobber Write-Host "Exported $($records.Count) assets to $OutFileName" ``` -------------------------------- ### Query Assets by Type Source: https://context7.com/hyperviewhq/sample_code/llms.txt Retrieve assets from Hyperview filtered by asset type with pagination support. This endpoint allows fetching assets such as CRAC units, with options for sorting and limiting the results. ```APIDOC ## GET /api/asset/assets ### Description Retrieve assets from Hyperview filtered by asset type with pagination support. ### Method GET ### Endpoint /api/asset/assets ### Query Parameters - **assetType** (string) - Required - The type of asset to filter by (e.g., 'crac', 'Server'). - **includeDimensions** (boolean) - Optional - Whether to include dimensional data for assets. - **(after)** (string) - Optional - Pagination cursor for fetching assets after a specific point. - **(limit)** (integer) - Optional - The maximum number of assets to return per page. - **(sort)** (string) - Optional - Field and direction to sort assets by (e.g., '+Id'). ### Request Example ```python import requests instance_url = "https://your-instance.hyperview.com" access_token = "your_access_token_here" asset_endpoint = f"{instance_url}/api/asset/assets" req_headers = { "Content-Type": "application/json", "Authorization": f"Bearer {access_token}" } req_params = { "assetType": "crac", "includeDimensions": "false", "(after)": "0", "(limit)": "10", "(sort)": "+Id" } resp = requests.get(url=asset_endpoint, params=req_params, headers=req_headers) print(resp.json()) ``` ### Response #### Success Response (200) - **data** (array) - An array of asset objects. - **_metadata** (object) - Metadata related to the query, such as pagination info. *Asset Object Example* ```json { "id": "asset_id_123", "name": "Example CRAC Unit", "assetType": "crac", "parentName": "Datacenter A", "...other_fields": "..." } ``` #### Response Example ```json { "data": [ { "id": "crac_unit_001", "name": "CRAC Unit 1", "assetType": "crac", "parentName": "Row 5" } ], "_metadata": { "totalCount": 15, "nextCursor": "10" } } ``` ``` -------------------------------- ### Upload Floor-Mounted Assets from CSV (PowerShell) Source: https://context7.com/hyperviewhq/sample_code/llms.txt Creates new floor-mounted assets in Hyperview by reading data from a CSV file. The script maps CSV columns to asset properties and uses API calls to add each asset. It requires a CSV file with specific headers like Name, Location, AssetType, etc., and relies on custom cmdlets like Get-LocationId and Add-Asset. ```powershell # Import CSV file with asset data $CsvData = Import-Csv -Path ./data/floor_mounted.csv # Headers: Name, Location, AssetType, SerialNumber, ModelId, AssetTrackerId foreach ($line in $CsvData) { # Get location ID from location name $LocationId = Get-LocationId -AccessToken $accessToken -Location $line.Location -ApiHost $HostName -Type "Location" # Build asset object $AssetObject = @{ "name" = $line.Name; "status" = 0; "assetTypeId" = $line.AssetType; "parentId" = $LocationId; "creatableAssetProperties" = @( @{ "type" = "serialNumber"; "value" = $line.SerialNumber; } ); "assetLifecycleState" = 0; "productId" = $line.ModelId; } # Add optional asset tracker ID if (-not ([string]::IsNullOrEmpty($line.AssetTrackerId))) { $AssetObject.creatableAssetProperties += @{ "type" = 147; "value" = $line.AssetTrackerId; } } Write-Host "Creating Asset: $($line.Name) at Location: $($line.Location)" # Create asset via API $Response = Add-Asset -AssetObject $AssetObject -ApiHost $HostName -AccessToken $accessToken Write-Host "Response: $Response" } ``` -------------------------------- ### List Alarm Events with Filtering (PowerShell) Source: https://context7.com/hyperviewhq/sample_code/llms.txt Queries alarm events, allowing filtering for acknowledged or unacknowledged status. Takes skip, limit, and a switch for including all events. Outputs results as CSV. ```powershell # Parameters param( [int]$Skip = 0, [int]$Limit = 100, [switch]$AllEvents # Include acknowledged events ) $HostName = "https://your-instance.hyperview.com" $accessToken = "your_access_token" $Headers = @{ "Content-Type" = "application/json" "Authorization" = "Bearer $accessToken" } # Build query parameters $Parameters = [System.Web.HttpUtility]::ParseQueryString([String]::Empty) $Parameters['skip'] = $Skip $Parameters['take'] = $Limit # Filter for unacknowledged only if AllEvents not specified if (-not $AllEvents) { $Parameters['filter'] = '["acknowledgementState","=","unacknowledged"]' } # Build request URI $BaseUri = [string]::Format("{0}/api/asset/alarmEvents/allAssets/advancedCollection", $HostName) $Request = [System.UriBuilder]$BaseUri $Request.Query = $Parameters.ToString() # Fetch alarm events Write-Host "Fetching alarm events from: $($Request.Uri)" $Response = Invoke-RestMethod -Uri $Request.Uri -Method Get -Headers $Headers # Output results if ($null -ne $Response.data) { Write-Host "`nFound $($Response.data.Count) alarm events" $Response.data | ConvertTo-Csv } else { Write-Host "No alarm events found" } ``` -------------------------------- ### Acknowledge Alarm Events by ID (PowerShell) Source: https://context7.com/hyperviewhq/sample_code/llms.txt Acknowledges specific alarm events by their IDs. Iterates through a list of provided alarm event IDs and sends a POST request for each. Includes error handling. ```powershell # Alarm event IDs to acknowledge $AlarmEventIds = @("alarm-id-1", "alarm-id-2", "alarm-id-3") $HostName = "https://your-instance.hyperview.com" $accessToken = "your_access_token" $Headers = @{ "Content-Type" = "application/json" "Authorization" = "Bearer $accessToken" } foreach ($AlarmId in $AlarmEventIds) { $Uri = [string]::Format("{0}/api/asset/alarmEvents/{1}/acknowledge", $HostName, $AlarmId) try { Write-Host "Acknowledging alarm event: $AlarmId" $Response = Invoke-RestMethod -Uri $Uri -Method Post -Headers $Headers Write-Host "Successfully acknowledged alarm $AlarmId" -ForegroundColor Green } catch { Write-Host "Failed to acknowledge alarm $AlarmId : $_" -ForegroundColor Red } Start-Sleep -Milliseconds 100 } Write-Host "`nCompleted acknowledging $($AlarmEventIds.Count) alarm events" ``` -------------------------------- ### Retrieve Asset Sensors in Python Source: https://context7.com/hyperviewhq/sample_code/llms.txt Fetches sensor data for a specified asset, including values, timestamps, and units. It requires an access token, instance URL, and asset ID as input. The function handles potential request errors and prints formatted sensor information. ```python import requests def get_asset_sensors(asset_id, access_token, instance_url): sensor_endpoint = f"{instance_url}/api/asset/sensors/{asset_id}" req_headers = { "Content-Type": "application/json", "Authorization": f"Bearer {access_token}" } try: resp = requests.get(url=sensor_endpoint, headers=req_headers) resp.raise_for_status() sensor_list = resp.json() print(f"\nSensors for Asset ID: {asset_id}") print(f"{'Sensor ID':<40} {'Name':<30} {'Value':<15} {'Unit':<15} {'Timestamp':<25}") print("-" * 125) for sensor in sensor_list: sensor_id = sensor.get('id', 'N/A') name = sensor.get('name', 'N/A') value = sensor.get('value', 'N/A') unit = sensor.get('unitString', 'N/A') timestamp = sensor.get('lastValueUpdate', 'N/A') print(f"{sensor_id:<40} {name:<30} {value:<15} {unit:<15} {timestamp:<25}") return sensor_list except requests.exceptions.RequestException as e: print(f"Failed to fetch sensor data: {e}") return [] # Usage example access_token = "your_access_token" instance_url = "https://your-instance.hyperview.com" asset_id = "12345" sensors = get_asset_sensors(asset_id, access_token, instance_url) ``` -------------------------------- ### Export Sensor List to CSV using PowerShell Source: https://context7.com/hyperviewhq/sample_code/llms.txt Fetches sensors for multiple assets up to a specified limit and exports the data to a CSV file. This script uses PowerShell's `Invoke-RestMethod` to interact with the API and `ConvertTo-Csv` for output. It includes parameters for asset limit and output file path. ```powershell # Parameters param( [int]$AssetLimit = 10, [string]$OutputFile = "sensors_output.csv" ) $HostName = "https://your-instance.hyperview.com" $accessToken = "your_access_token" # Headers for API requests $Headers = @{ "Content-Type" = "application/json" "Authorization" = "Bearer $accessToken" } # Fetch assets $Uri = [string]::Format("{0}/api/asset/assets?(limit)={1}&(sort)=%2BId", $HostName, $AssetLimit) $Response = Invoke-RestMethod -Uri $Uri -Method Get -Headers $Headers $Assets = $Response.data $AllSensors = @() $Counter = 0 foreach ($Asset in $Assets) { $Counter++ $PercentComplete = ($Counter / $Assets.Count) * 100 Write-Progress -Activity "Fetching sensors" -Status "Asset $Counter of $($Assets.Count)" -PercentComplete $PercentComplete $Id = $Asset.id $SensorsUri = [string]::Format("{0}/api/asset/sensors/{1}", $HostName, $Id) $Sensors = Invoke-RestMethod -Method Get -Headers $Headers -Uri $SensorsUri $AllSensors += $Sensors Start-Sleep -Milliseconds 50 } Write-Progress -Activity "Fetching sensors" -Completed # Export to CSV $AllSensors | ConvertTo-Csv | Out-File -FilePath $OutputFile Write-Host "Exported sensors to $OutputFile" ``` -------------------------------- ### Batch Export Sensor Data to CSV in Python Source: https://context7.com/hyperviewhq/sample_code/llms.txt Retrieves sensors for multiple assets and exports the combined data into a timestamped CSV file. It first fetches sensor data for each asset in the provided list and then organizes it for CSV export. Dependencies include the `csv` and `requests` modules. ```python from datetime import datetime import csv import requests def get_sensors_for_assets(asset_list, access_token, instance_url): all_sensors = [] for asset_id in asset_list: sensor_endpoint = f"{instance_url}/api/asset/sensors/{asset_id}" req_headers = { "Content-Type": "application/json", "Authorization": f"Bearer {access_token}" } try: resp = requests.get(url=sensor_endpoint, headers=req_headers) resp.raise_for_status() sensors = resp.json() # Add asset ID to each sensor for sensor in sensors: sensor["assetId"] = asset_id all_sensors.extend(sensors) except requests.exceptions.RequestException as e: print(f"Failed to fetch sensors for asset {asset_id}: {e}") return all_sensors def export_sensors_to_csv(sensor_list): timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"sensor_export_{timestamp}.csv" header = ["assetId", "sensorId", "name", "timestamp", "value", "unit"] with open(filename, "w", newline="") as csvfile: writer = csv.DictWriter(csvfile, fieldnames=header) writer.writeheader() for sensor in sensor_list: writer.writerow({ "assetId": sensor.get('assetId'), "sensorId": sensor.get('id'), "name": sensor.get('name'), "timestamp": sensor.get('lastValueUpdate'), "value": sensor.get('value'), "unit": sensor.get('unitString') }) print(f"Exported {len(sensor_list)} sensors to {filename}") return filename # Usage example asset_ids = ["asset-123", "asset-456", "asset-789"] sensors = get_sensors_for_assets(asset_ids, access_token, instance_url) export_sensors_to_csv(sensors) ``` -------------------------------- ### Authenticate with Hyperview API using OAuth2 Client Credentials Source: https://context7.com/hyperviewhq/sample_code/llms.txt Authenticates with the Hyperview API using OAuth2 client credentials flow to obtain an access token. This is a prerequisite for making authenticated API requests. It requires client ID, client secret, and the instance URL. ```python import requests import json # Authentication configuration client_id = "your_client_id" client_secret = "your_client_secret" instance_url = "https://your-instance.hyperview.com" # Prepare authentication payload auth_payload = { "grant_type": "client_credentials", "client_id": client_id, "client_secret": client_secret } token_endpoint = f"{instance_url}/connect/token" try: # Request access token resp = requests.post(url=token_endpoint, data=auth_payload) resp.raise_for_status() resp_json = resp.json() access_token = resp_json.get("access_token") print(f"Successfully authenticated. Token: {access_token[:20]}...") except requests.exceptions.RequestException as e: print(f"Authentication failed: {e}") exit(1) except json.JSONDecodeError: print("Failed to decode authentication response") exit(1) ``` ```powershell # Read configuration from JSON files $ClientConfiguration = Get-Content -Raw -Path ./conf/client_credential.json | ConvertFrom-Json $HyperviewHost = Get-Content -Raw -Path ./conf/hostname.json | ConvertFrom-Json # Prepare authentication payload $PayloadBody = @{ grant_type = "client_credentials" client_id = $ClientConfiguration.ClientId client_secret = $ClientConfiguration.ClientSecret } $HostName = [string]::Format("https://{0}", $HyperviewHost.Hostname) $TokenUrl = [string]::Format("{0}/connect/token", $HostName) $FetchTokenHeaders = @{ "Content-Type" = "application/x-www-form-urlencoded" } try { $resp = Invoke-RestMethod -Method Post -Headers $FetchTokenHeaders -Body $PayloadBody -Uri $TokenUrl $accessToken = $resp.access_token Write-Host "Authentication successful" } catch { Write-Output "Failed to authenticate. Exiting..." Exit $LASTEXITCODE } ``` ```java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; // Configuration String clientId = "your_client_id"; String clientSecret = "your_client_secret"; String instanceUrl = "https://your-instance.hyperview.com"; // Create HTTP client HttpClient httpClient = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(30)) .build(); // Build authentication payload String payload = "grant_type=client_credentials&client_id=" + clientId + "&client_secret=" + clientSecret; String tokenEndpoint = instanceUrl + "/connect/token"; HttpRequest request = HttpRequest.newBuilder() .POST(HttpRequest.BodyPublishers.ofString(payload)) .uri(URI.create(tokenEndpoint)) .header("Content-Type", "application/x-www-form-urlencoded") .header("Accept", "application/json") .timeout(Duration.ofSeconds(30)) .build(); try { HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); ObjectMapper mapper = new ObjectMapper(); JsonNode jsonResponse = mapper.readTree(response.body()); String accessToken = jsonResponse.get("access_token").asText(); System.out.println("Authentication successful"); } catch (Exception e) { System.err.println("Authentication failed: " + e.getMessage()); } ``` -------------------------------- ### Close Active Alarm Events (PowerShell) Source: https://context7.com/hyperviewhq/sample_code/llms.txt Fetches currently active alarm events and initiates their closure. It first retrieves active alarms using a filter and then proceeds with the closure process (closure logic not fully shown in this snippet). ```powershell # Get active alarm events and close them $HostName = "https://your-instance.hyperview.com" $accessToken = "your_access_token" $Headers = @{ "Content-Type" = "application/json" "Authorization" = "Bearer $accessToken" } # Fetch active alarms $Parameters = [System.Web.HttpUtility]::ParseQueryString([String]::Empty) $Parameters['filter'] = '["state","=","active"]' $Parameters['take'] = '100' $BaseUri = [string]::Format("{0}/api/asset/alarmEvents/allAssets/advancedCollection", $HostName) $Request = [System.UriBuilder]$BaseUri $Request.Query = $Parameters.ToString() $Response = Invoke-RestMethod -Uri $Request.Uri -Method Get -Headers $Headers Write-Host "Found $($Response.data.Count) active alarm events" ``` -------------------------------- ### Close Each Active Alarm - PowerShell Source: https://context7.com/hyperviewhq/sample_code/llms.txt Iterates through active alarms from an API response and attempts to close each one using a POST request. It includes error handling and provides console output for success or failure. This script requires the API host name, alarm data, and authentication headers. ```powershell # Close each active alarm foreach ($Alarm in $Response.data) { $CloseUri = [string]::Format("{0}/api/asset/alarmEvents/{1}/close", $HostName, $Alarm.id) try { Write-Host "Closing alarm: $($Alarm.id) - $($Alarm.message)" Invoke-RestMethod -Uri $CloseUri -Method Post -Headers $Headers Write-Host "Successfully closed" -ForegroundColor Green } catch { Write-Host "Failed to close: $_" -ForegroundColor Red } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.