public/Connect-Yeelight.ps1

<#
.SYNOPSIS
    Connects with Yeelight Lightstrip
.DESCRIPTION
    The function connects with Yeelight Lightstrip.
.EXAMPLE
    PS C:\> Connect-Yeelight 10.10.0.13 -Name Office
 
.NOTES
    Author: Mateusz Nadobnik
    Link: akademiapowershell.pl
 
    Date: 14-11-2020
    Version: 0.0.1
    Keywords: connect, yeelight, xiaomi
    Notes:
    Changelog:
#>


function Connect-Yeelight
{
    [cmdletbinding()]
    param(
        [Parameter(Mandatory, Position = 0)]
        [IPAddress]$IpDevice,
        [Parameter(Mandatory, Position = 1)]
        [string]$Name,
        [switch]$PassThru
    )

    try
    {
        # Initialize device and connect
        $Device = [YeelightAPI.Device]::new($IpDevice)
        $Device.Connect().Wait()

        if ($Device.IsConnected)
        {
            if ($null -ne $Name)
            {
                $Device.Name = $Name
            }

            if ($script:connections.Hostname -notmatch $IpDevice)
            {
                $script:connections.Add($Device) | Out-Null
            }
            else
            {
                Write-Verbose "The connection to $IpDevice exists"
            }

            if ($PassThru.IsPresent)
            {
                Write-Output $script:connections
            }
        }
        else
        {
            Write-Warning "The function cannot connect to $IpDevice device"
        }
    }
    catch
    {
        Write-Warning $_
    }
}