Files
powershell-scripts/docs/API_INTEGRATION.md
cproudlock 96cb1dd946 Remove all emojis from markdown documentation
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-10 11:03:45 -05:00

10 KiB

API Integration Documentation

Overview

The PowerShell scripts integrate with a centralized Dashboard API to store comprehensive asset data in a MySQL database. This document details the API communication protocols, data structures, and integration patterns.

Dashboard API Architecture

Base URL Structure

Primary:   http://10.48.130.197/dashboard-v2/api.php
Fallback:  http://localhost/dashboard-v2/api.php
Test:      http://10.48.130.197/test/dashboard/api.php

Auto-Discovery Mechanism

function Get-DashboardURL {
    # Priority order:
    # 1. Command-line parameter
    # 2. Environment variable (ASSET_DASHBOARD_URL)
    # 3. Configuration file (dashboard-config.json)
    # 4. Auto-discovery probe
    # 5. Default fallback
}

API Endpoint: updateCompleteAsset

Request Structure

POST /dashboard-v2/api.php HTTP/1.1
Content-Type: application/x-www-form-urlencoded

action=updateCompleteAsset&hostname=H123EXAMPLE&serialNumber=ABC123&...

Complete Payload Structure

Core System Information

$postData = @{
    action = 'updateCompleteAsset'
    
    # Basic System Identification
    hostname = $SystemInfo.Hostname                    # String: Computer name
    serialNumber = $SystemInfo.SerialNumber            # String: Hardware serial
    serviceTag = $SystemInfo.ServiceTag               # String: Dell service tag
    manufacturer = $SystemInfo.Manufacturer           # String: Dell, HP, etc.
    model = $SystemInfo.Model                        # String: OptiPlex 7070, etc.
    
    # System Classification & Context  
    pcType = $SystemInfo.PCType                      # String: Engineer|Shopfloor|Standard
    loggedInUser = $SystemInfo.LoggedInUser          # String: Current user
    machineNo = $SystemInfo.MachineNo               # String: M123 (GE machine number)
    
    # Technical Specifications
    osVersion = $SystemInfo.OSVersion                # String: Windows 10, etc.
    totalPhysicalMemory = $SystemInfo.TotalPhysicalMemory  # Decimal: GB
    domainRole = $SystemInfo.DomainRole             # Integer: Domain membership
    currentTimeZone = $SystemInfo.CurrentTimeZone   # String: Timezone ID
    lastBootUpTime = $SystemInfo.LastBootUpTime     # DateTime: Last boot
}

Manufacturing-Specific Data (Shopfloor PCs Only)

# Network Interface Data (JSON Array)
$postData.networkInterfaces = [
    {
        "InterfaceName": "Ethernet 2",
        "IPAddress": "192.168.1.100",
        "SubnetMask": 24,
        "DefaultGateway": "192.168.1.1",
        "MACAddress": "00-15-5D-A2-33-4F",
        "IsDHCP": 0,
        "IsActive": 1,
        "IsMachineNetwork": 1
    }
] | ConvertTo-Json -Compress

# Communication Configuration Data (JSON Array)
$postData.commConfigs = [
    {
        "PortName": "COM1",
        "BaudRate": 9600,
        "DataBits": 8,
        "Parity": "None",
        "StopBits": 1,
        "IsActive": 1
    }
] | ConvertTo-Json -Compress

# DNC Configuration Data (JSON Object)
$postData.dncConfig = {
    "Site": "WestJefferson",
    "CNC": "Fanuc 30", 
    "NcIF": "EFOCAS",
    "MachineNo": "3109",
    "Debug": "ON",
    "HostType": "WILM"
} | ConvertTo-Json -Compress

GE Registry Architecture Data New in v3.0

# DualPath Communication Settings
$postData.dncDualPathEnabled = $true                    # Boolean: DualPath enabled
$postData.dncPath1Name = "Path1Primary"                 # String: Primary path name
$postData.dncPath2Name = "Path2Secondary"               # String: Secondary path name

# Registry Architecture Detection  
$postData.dncGeRegistry32Bit = $true                    # Boolean: Found in 32-bit registry
$postData.dncGeRegistry64Bit = $false                   # Boolean: Found in 64-bit registry

# Additional Registry Metadata (JSON Object)
$postData.dncGeRegistryNotes = {
    "32bit": {
        "BasePath": "HKLM:\\SOFTWARE\\GE Aircraft Engines",
        "SubKeys": "DNC, Enhanced DNC, MarkZebra, PPDCS",
        "Found": "2025-09-06 14:30:00"
    },
    "32bit-eFocas": {
        "DualPath": "YES",
        "Path1Name": "Path1Primary", 
        "Path2Name": "Path2Secondary",
        "IpAddr": "192.168.1.1",
        "SocketNo": "8192"
    }
} | ConvertTo-Json -Compress

Warranty Information (Dell Systems Only)

# Currently disabled but structure available
$postData.warrantyEndDate = $WarrantyData.warrantyEndDate        # Date: YYYY-MM-DD
$postData.warrantyStatus = $WarrantyData.warrantyStatus          # String: Active|Expired
$postData.warrantyServiceLevel = $WarrantyData.serviceLevel      # String: Service level
$postData.warrantyDaysRemaining = $WarrantyData.daysRemaining    # Integer: Days remaining

API Response Handling

Success Response Structure

{
    "success": true,
    "data": {
        "success": true,
        "message": "Complete asset data updated successfully",
        "pcid": 221,
        "hostname": "H123EXAMPLE",
        "operation": "complete_asset_update",
        "recordsAffected": 3,
        "pcType": "Shopfloor",
        "warrantyStatus": null,
        "machineNo": "M123",
        "timestamp": "2025-09-06 14:30:45",
        "debugMsg": "PCType=Shopfloor, DNC=YES, Net=YES"
    },
    "timestamp": "2025-09-06 14:30:45"
}

Error Response Structure

{
    "success": false,
    "error": "hostname and serial number are required",
    "timestamp": "2025-09-06 14:30:45"
}

Response Processing Logic

$response = Invoke-RestMethod -Uri $DashboardURL -Method Post -Body $postData -Headers $headers -TimeoutSec 30

if ($response.success) {
    Write-Host "[OK] Complete asset data stored in database!" -ForegroundColor Green
    $data = $response.data
    Write-Host "  PCID: $($data.pcid)"
    Write-Host "  Operation: $($data.operation)" 
    Write-Host "  Records affected: $($data.recordsAffected)"
    return $true
} else {
    Write-Host "[FAIL] Dashboard could not store data: $($response.error)" -ForegroundColor Red
    return $false
}

Database Schema Integration

Primary Tables Updated

pc Table (Core System Information)

UPDATE pc SET 
    hostname = ?, serialnumber = ?, modelnumberid = ?,
    pctypeid = ?, loggedinuser = ?, machinenumber = ?, 
    operatingsystem = ?, warrantyenddate = ?, warrantystatus = ?,
    warrantyservicelevel = ?, warrantydaysremaining = ?,
    warrantylastchecked = IF(? IS NOT NULL, NOW(), warrantylastchecked),
    lastupdated = NOW()
WHERE pcid = ?

pc_dnc_config Table (Manufacturing Configuration) Enhanced in v3.0

INSERT INTO pc_dnc_config (
    pcid, site, cnc, ncif, machinenumber, hosttype, 
    ftphostprimary, ftphostsecondary, ftpaccount,
    debug, uploads, scanner, dripfeed, additionalsettings,
    dualpath_enabled, path1_name, path2_name,              -- DualPath settings
    ge_registry_32bit, ge_registry_64bit, ge_registry_notes, -- Registry architecture
    lastupdated
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
ON DUPLICATE KEY UPDATE ...

machines Table (Auto-Population) New in v3.2

-- Machine records created from PC data
INSERT INTO machines (
    machinenumber, alias, machinetypeid, isactive,
    businessunitid, modelnumberid, printerid,
    ipaddress1, machinenotes
)
SELECT DISTINCT
    p.machinenumber,
    CONCAT('Machine ', p.machinenumber),
    1, 1, 1, 1, 1,
    ni.ipaddress,
    CONCAT('Auto-discovered | Connected PCs: ', GROUP_CONCAT(p.hostname))
FROM pc p
LEFT JOIN pc_network_interfaces ni ON p.pcid = ni.pcid
WHERE p.machinenumber IS NOT NULL
GROUP BY p.machinenumber;

-- PC-Machine relationship tracking
INSERT INTO machine_pc_relationships (
    machine_id, pc_id, pc_hostname, pc_role, is_primary
)
SELECT 
    m.machineid, p.pcid, p.hostname,
    CASE 
        WHEN p.hostname LIKE '%HMI%' THEN 'hmi'
        WHEN p.hostname LIKE '%CONTROL%' THEN 'control'
        ELSE 'unknown'
    END,
    (p.lastupdated = MAX(p.lastupdated) OVER (PARTITION BY p.machinenumber))
FROM machines m
JOIN pc p ON m.machinenumber = p.machinenumber;

Connection Management

URL Auto-Discovery Process

# Test candidate URLs in priority order
$candidates = @(
    "http://10.48.130.197/dashboard-v2/api.php",      # Production primary
    "http://10.48.130.197/test/dashboard/api.php",    # Test environment
    "http://localhost/dashboard-v2/api.php"           # Local development
)

foreach ($url in $candidates) {
    $testResponse = Invoke-RestMethod -Uri "$url?action=getDashboardData" -Method Get -TimeoutSec 5
    if ($testResponse.success) {
        return $url  # First successful connection wins
    }
}

Error Handling & Retries

# HTTP timeout and error handling
try {
    $response = Invoke-RestMethod -Uri $DashboardURL -Method Post -Body $postData -Headers $headers -TimeoutSec 30
} 
catch [System.Net.WebException] {
    Write-Host "[FAIL] Network error: $($_.Exception.Message)" -ForegroundColor Red
    return $false
}
catch {
    Write-Host "[FAIL] Unexpected error: $($_.Exception.Message)" -ForegroundColor Red  
    return $false
}

Data Validation & Integrity

Required Fields Validation

# API enforces required fields
if (empty($hostname) || empty($serialnumber)) {
    $this->sendError('hostname and serial number are required');
    return;
}

Data Type Conversion

# Boolean conversion for registry flags
$dncDualPathEnabled = isset($_POST['dncDualPathEnabled']) ? 
    (($_POST['dncDualPathEnabled'] === 'true' || $_POST['dncDualPathEnabled'] === '1' || 
      $_POST['dncDualPathEnabled'] === 1 || $_POST['dncDualPathEnabled'] === true) ? 1 : 0) : null;

JSON Serialization

# Complex objects serialized as JSON
$postData.networkInterfaces = $ShopfloorInfo.NetworkInterfaces | ConvertTo-Json -Compress
$postData.dncGeRegistryNotes = $geInfo.RegistryNotes | ConvertTo-Json -Compress

Performance Optimization

Payload Compression

  • JSON objects compressed with -Compress flag
  • Minimal redundant data transmission
  • Efficient HTTP POST encoding

Connection Pooling

  • Reuses HTTP connections where possible
  • Configurable timeout values
  • Graceful connection cleanup

Batch Processing Capability

  • Single API call handles complete asset profile
  • Atomic database transactions
  • Rollback capability on failures

API Integration designed for reliable, efficient, and comprehensive asset data management in enterprise manufacturing environments.