PSZebraSGD.psm1

function ConvertTo-ZebraPropertyName {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Name
    )

    $Aliases = @{
        'appl.name'                  = 'Application'
        'appl.link_os_version'       = 'Firmware'
        'odometer.total_label_count' = 'LabelsPrinted'
        'wlan.mac_addr'              = 'WlanMacAddr'
    }

    if ($Aliases.ContainsKey($Name)) {
        return $Aliases[$Name]
    }

    $NamePart = ($Name -split '\.')[-1]
    $PascalCaseParts = foreach ($Word in ($NamePart -split '_')) {
        $Word.Substring(0, 1).ToUpperInvariant() + $Word.Substring(1).ToLowerInvariant()
    }

    return $PascalCaseParts -join ''
}

function Invoke-ZebraTcpCommand {
    <#
    .SYNOPSIS
        Sends one command over a new TCP connection.
 
    .DESCRIPTION
        Encodes the command as ASCII with a trailing CRLF. Unless NoResponse is set,
        collects response bytes until the peer closes or the stream is quiet for 250 milliseconds.
        Quiet-gap completion is a best-effort heuristic, not a universal SGD response terminator;
        verify response timing against supported printers before relying on it in production.
        The total response deadline is TimeoutMilliseconds after the command is written.
        Decodes the received bytes as UTF-8 and trims leading and trailing whitespace.
 
    .PARAMETER ComputerName
        Printer hostname or IP address.
 
    .PARAMETER Command
        Command text without its terminating CRLF.
 
    .PARAMETER Port
        TCP port from 1 through 65535. Defaults to 9100.
 
    .PARAMETER TimeoutMilliseconds
        Connect and send timeout, and total response deadline in milliseconds, from 100 through
        60000. Defaults to 3000.
 
    .PARAMETER MaxResponseBytes
        Largest accepted reply in bytes, from 1 through 1048576. Defaults to 65536.
        Reading more than this limit raises an error.
 
    .PARAMETER NoResponse
        Returns after the write without reading a reply or confirming acceptance.
 
    .EXAMPLE
        Invoke-ZebraTcpCommand -ComputerName 192.0.2.10 -Command '! U1 getvar "device.unique_id"'
 
    .INPUTS
        None.
 
    .OUTPUTS
        System.String. Returns the trimmed reply unless NoResponse is set, in which case there is
        no output.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$ComputerName,

        [Parameter(Mandatory)]
        [string]$Command,

        [ValidateRange(1, 65535)]
        [int]$Port = 9100,

        [ValidateRange(100, 60000)]
        [int]$TimeoutMilliseconds = 3000,

        [ValidateRange(1, 1048576)]
        [int]$MaxResponseBytes = 65536,

        [switch]$NoResponse
    )

    # Use a fresh connection for each command and bound the connect wait.
    $Client = [System.Net.Sockets.TcpClient]::new()

    try {
        $ConnectTask = $Client.ConnectAsync($ComputerName, $Port)
        if (-not $ConnectTask.Wait($TimeoutMilliseconds)) {
            throw "Connection timed out: ${ComputerName}:$Port"
        }

        $Client.SendTimeout = $TimeoutMilliseconds
        $Client.ReceiveTimeout = $TimeoutMilliseconds
        $Stream = $Client.GetStream()
        $Payload = [System.Text.Encoding]::ASCII.GetBytes($Command + "`r`n")
        $Stream.Write($Payload, 0, $Payload.Length)

        # A write-only command returns without implying that the printer accepted it.
        if ($NoResponse) {
            return
        }

        # With no universal reply terminator, collect bytes until close or a quiet gap
        # after the first byte; the stopwatch still bounds the entire response wait.
        $ResponseTimeoutMilliseconds = 250
        $ResponseTimer = [System.Diagnostics.Stopwatch]::StartNew()
        $Buffer = [byte[]]::new(4096)
        $Response = [System.IO.MemoryStream]::new()

        try {
            while ($true) {
                $RemainingMilliseconds = $TimeoutMilliseconds - $ResponseTimer.ElapsedMilliseconds
                if ($RemainingMilliseconds -le 0) {
                    throw 'Timed out waiting for the printer response.'
                }

                $ReadTimeoutMilliseconds = $RemainingMilliseconds
                if ($Response.Length -gt 0) {
                    $ReadTimeoutMilliseconds = [Math]::Min(
                        $ResponseTimeoutMilliseconds,
                        $RemainingMilliseconds
                    )
                }
                $Stream.ReadTimeout = [int][Math]::Max(1, $ReadTimeoutMilliseconds)

                try {
                    $BytesRead = $Stream.Read($Buffer, 0, $Buffer.Length)
                } catch [System.IO.IOException] {
                    $SocketException = $_.Exception.InnerException
                    $IsReadTimeout = $SocketException -is [System.Net.Sockets.SocketException] -and
                        $SocketException.SocketErrorCode -eq [System.Net.Sockets.SocketError]::TimedOut

                    if (-not $IsReadTimeout) {
                        throw
                    }

                    if ($Response.Length -eq 0 -or
                        $ResponseTimer.ElapsedMilliseconds -ge $TimeoutMilliseconds) {
                        throw 'Timed out waiting for the printer response.'
                    }

                    # Only a quiet-gap timeout after receiving data completes the reply.
                    break
                }

                if ($ResponseTimer.ElapsedMilliseconds -ge $TimeoutMilliseconds) {
                    throw 'Timed out waiting for the printer response.'
                }

                if ($BytesRead -eq 0) {
                    if ($Response.Length -eq 0) {
                        throw 'The printer closed the connection without a response.'
                    }

                    # A peer close ends a response only after at least one byte arrived.
                    break
                }

                # Enforce the response cap before adding another chunk to memory.
                if ($Response.Length + $BytesRead -gt $MaxResponseBytes) {
                    throw 'Response exceeds MaxResponseBytes.'
                }
                $Response.Write($Buffer, 0, $BytesRead)
            }

            return [System.Text.Encoding]::UTF8.GetString($Response.ToArray()).Trim()
        } finally {
            # Release the response buffer even when reading or decoding fails.
            $Response.Dispose()
        }
    } finally {
        # Always close the socket, including write-only and error paths.
        $Client.Dispose()
    }
}

function Get-ZebraConfiguration {
    <#
    .SYNOPSIS
        Reads named SGD settings from a Zebra printer.
 
    .DESCRIPTION
        Queries the requested names in order and returns one object with a property for each name.
        Property names use ConvertTo-ZebraPropertyName. A failed query warns and leaves that
        property's value null while the remaining names are queried.
 
    .PARAMETER ComputerName
        Printer hostname or IP address.
 
    .PARAMETER Name
        One or more SGD variable names that map to unique output property names.
 
    .PARAMETER Port
        Printer TCP port. Defaults to 9100.
 
    .EXAMPLE
        $SGDVariables = @(
            'device.product_name'
            'device.unique_id'
            'appl.name'
        )
        Get-ZebraConfiguration -ComputerName 192.0.2.10 -Name $SGDVariables
 
    .INPUTS
        None.
 
    .OUTPUTS
        System.Management.Automation.PSCustomObject. Contains ComputerName and one property per
        requested SGD variable. Empty input or duplicate output property names are rejected.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$ComputerName,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string[]]$Name,

        [int]$Port = 9100
    )

    $SeenPropertyNames = @{ ComputerName = $true }
    foreach ($SettingName in $Name) {
        $PropertyName = ConvertTo-ZebraPropertyName -Name $SettingName
        if ($SeenPropertyNames.ContainsKey($PropertyName)) {
            throw "SGD variable '$SettingName' maps to duplicate output property '$PropertyName'."
        }

        $SeenPropertyNames[$PropertyName] = $true
    }

    $Properties = [ordered]@{
        ComputerName = $ComputerName
    }

    foreach ($SettingName in $Name) {
        $PropertyName = ConvertTo-ZebraPropertyName -Name $SettingName
        $ReadParameters = @{
            ComputerName = $ComputerName
            Operation    = 'Get'
            Name         = $SettingName
            Port         = $Port
        }

        try {
            $Properties[$PropertyName] = Invoke-ZebraSGD @ReadParameters
        } catch {
            Write-Warning "${SettingName}: $_"
            $Properties[$PropertyName] = $null
        }
    }

    [PSCustomObject]$Properties
}

function Get-ZebraPrinter {
    <#
    .SYNOPSIS
        Reads identification and firmware information from a Zebra printer.
 
    .DESCRIPTION
        Reads the standard printer fields through Get-ZebraConfiguration. If a query throws,
        the command warns, leaves that property null and continues with the remaining variables.
 
    .PARAMETER ComputerName
        Printer hostname or IP address.
 
    .PARAMETER Port
        Printer TCP port. Defaults to 9100.
 
    .EXAMPLE
        Get-ZebraPrinter -ComputerName 192.0.2.10
 
    .INPUTS
        None.
 
    .OUTPUTS
        System.Management.Automation.PSCustomObject. Contains ComputerName, ProductName, UniqueId,
        FriendlyName, Application, Firmware, ActiveNetwork, MacAddr and LabelsPrinted.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$ComputerName,

        [int]$Port = 9100
    )

    $Fields = @(
        'device.product_name'
        'device.unique_id'
        'device.friendly_name'
        'appl.name'
        'appl.link_os_version'
        'ip.active_network'
        'interface.network.active.mac_addr'
        'odometer.total_label_count'
    )

    Get-ZebraConfiguration -ComputerName $ComputerName -Name $Fields -Port $Port
}

function Invoke-ZebraSGD {
    <#
    .SYNOPSIS
        Sends a Get, Set or Do SGD command to a Zebra printer.
    .DESCRIPTION
        Get reads the reply, even under WhatIf. Set and Do support confirmation and WhatIf.
        Neither waits for a reply or verifies printer acceptance.
    .PARAMETER ComputerName
        Printer hostname or IP address.
    .PARAMETER Operation
        Get reads a variable, Set writes a variable and Do requests an action.
    .PARAMETER Name
        SGD variable or action name, such as device.friendly_name.
    .PARAMETER Value
        Argument for Set or Do. Defaults to an empty string. Double quotes, carriage returns and
        line feeds are rejected for all operations, even though Get does not send a value.
    .PARAMETER Port
        Printer TCP port. Defaults to 9100.
    .PARAMETER TimeoutMilliseconds
        Timeout for connecting and for individual socket operations. Defaults to 3000 milliseconds.
    .EXAMPLE
        Invoke-ZebraSGD -ComputerName 192.0.2.10 -Operation Get -Name device.friendly_name
    .INPUTS
        None.
    .OUTPUTS
        System.String. Get returns the trimmed reply. Set and Do return no output.
    #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param(
        [Parameter(Mandatory)]
        [string]$ComputerName,

        [Parameter(Mandatory)]
        [ValidateSet('Get', 'Set', 'Do')]
        [string]$Operation,

        [Parameter(Mandatory)]
        [ValidatePattern('^[a-zA-Z][a-zA-Z0-9_.-]*$')]
        [string]$Name,

        [string]$Value = '',

        [int]$Port = 9100,

        [int]$TimeoutMilliseconds = 3000
    )

    if ($Value.Contains('"') -or $Value.Contains("`r") -or $Value.Contains("`n")) {
        throw 'Value contains unsupported quote or newline characters.'
    }

    $Command = switch ($Operation) {
        'Get' {
            '! U1 getvar "{0}"' -f $Name
        }
        'Set' {
            '! U1 setvar "{0}" "{1}"' -f $Name, $Value
        }
        'Do' {
            '! U1 do "{0}" "{1}"' -f $Name, $Value
        }
    }

    $TcpParameters = @{
        ComputerName        = $ComputerName
        Command             = $Command
        Port                = $Port
        TimeoutMilliseconds = $TimeoutMilliseconds
    }

    if ($Operation -eq 'Get') {
        return Invoke-ZebraTcpCommand @TcpParameters
    }

    if ($PSCmdlet.ShouldProcess($ComputerName, "$Operation SGD $Name")) {
        Invoke-ZebraTcpCommand @TcpParameters -NoResponse
    }
}

function Set-ZebraConfiguration {
    <#
    .SYNOPSIS
        Writes one or more SGD settings to a Zebra printer.
 
    .DESCRIPTION
        Sends each setvar command after confirmation without waiting for a reply. Configuration
        entries are sent sequentially; if a write fails, earlier settings may already be applied.
        A successful write does not confirm that the printer accepted the value.
 
    .PARAMETER ComputerName
        Printer hostname or IP address.
 
    .PARAMETER Name
        SGD variable to set when using the NameValue parameter set.
 
    .PARAMETER Value
        Setting value when using the NameValue parameter set. Double quotes, carriage returns
        and line feeds are unsupported.
 
    .PARAMETER Configuration
        Hashtable of SGD variable names and values to set sequentially. Use an ordered hashtable
        when the setting order matters. Double quotes, carriage returns and line feeds are
        unsupported.
 
    .PARAMETER Port
        Printer TCP port. Defaults to 9100.
 
    .EXAMPLE
        Set-ZebraConfiguration -ComputerName 192.0.2.10 -Name device.friendly_name -Value 'West Desk' -WhatIf
 
    .EXAMPLE
        $Configuration = [ordered]@{
            'ezpl.media_type' = 'gap/notch'
            'ezpl.tear_off' = '2'
        }
        Set-ZebraConfiguration -ComputerName 192.0.2.10 -Configuration $Configuration -WhatIf
 
    .INPUTS
        None.
 
    .OUTPUTS
        None.
    #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High', DefaultParameterSetName = 'NameValue')]
    param(
        [Parameter(Mandatory)]
        [string]$ComputerName,

        [Parameter(Mandatory, ParameterSetName = 'NameValue')]
        [string]$Name,

        [Parameter(Mandatory, ParameterSetName = 'NameValue')]
        [string]$Value,

        [Parameter(Mandatory, ParameterSetName = 'Configuration')]
        [System.Collections.IDictionary]$Configuration,

        [int]$Port = 9100
    )

    if ($PSCmdlet.ParameterSetName -eq 'NameValue') {
        $Settings = @{ $Name = $Value }
    } else {
        if ($Configuration.Count -eq 0) {
            throw 'Configuration must contain at least one SGD setting.'
        }

        $Settings = $Configuration
    }

    foreach ($SettingName in $Settings.Keys) {
        $SettingValue = $Settings[$SettingName]
        if ($PSCmdlet.ShouldProcess($ComputerName, "Set SGD $SettingName")) {
            $SetParameters = @{
                ComputerName = $ComputerName
                Operation    = 'Set'
                Name         = $SettingName
                Value        = $SettingValue
                Port         = $Port
                Confirm      = $false
            }

            Invoke-ZebraSGD @SetParameters
        }
    }
}