Search code examples
powershelleventhandler

Serial port writing with an eventhandler in Powershell


I'm having an issue with a powershell script that I would like to use for configurating a barcode scanner. I've been able to get most working, but I think because I use rather simple writelines, readexisting etc etc I'm not always getting the right answer of the device (the barcode scanner) nor am I sure that I send all lines.

So when I'm searching stackoverflow (or Google for that matter) I'm getting a lot of stuff about the datareceivedhandler etc, but I'm not sure how to get my script and the eventhandler to work. I've never used any eventhandlers in powershell so my ability to understand those are somewhat limited. I know they are a lot used in .net, but from my understanding I cannot literaly copy paste them from a c# code. Can someone help my on the way (I don't need a whole rewritten script, but just :

  • this is how you start the eventhandler datareceived
  • this is how you do a writeline with above method
  • this is how you do a readline with above method

I'm sorry if the question is out of order, then you may close it off course.

    #requires -version 2
<#
.SYNOPSIS
  <Overview of script>
.DESCRIPTION
  <Brief description of script>
.PARAMETER <Parameter_Name>
    <Brief description of parameter input required. Repeat this attribute if required>
.INPUTS
  <Inputs if any, otherwise state None>
.OUTPUTS
  <Outputs if any, otherwise state None - example: Log file stored in C:\Windows\Temp\<name>.log>
.NOTES
  Version:        1.0
  Author:         <Name>
  Creation Date:  <Date>
  Purpose/Change: Initial script development
  
.EXAMPLE
  <Example goes here. Repeat this attribute for more than one example>
#>

#---------------------------------------------------------[Initialisations]--------------------------------------------------------

#Set Error Action to Silently Continue
$ErrorActionPreference = "SilentlyContinue"

#----------------------------------------------------------[Declarations]----------------------------------------------------------

#Script Version
#$sScriptVersion = "1.0"
#Log File Info
#$ScriptName = "<script_name>.log"


#-----------------------------------------------------------[Functions]------------------------------------------------------------

function PushConfig
{
  try 
  {
    $scanner = (Get-WmiObject Win32_PnPEntity |Where-Object {$_.name -match "Barcode Scanner*" })
    Write-Host "`nScanners gevonden: $(($scanner | Measure-Object).count)" -ForegroundColor DarkMagenta
    if ($scanner)
    {
      $scannerName = $scanner.Name
      #Here I get the com port out of the object
      $posCOM = $ScannerName.IndexOf("COM")
      [int]$posCOM = $posCOM + 2
      $COMNummer = $scannerName.Substring($posCOM+1,1)
      $COMPoort = "COM" + $COMNummer
      Write-Host "We found the datalogic barcode scanner on: $COMPoort" -ForegroundColor DarkMagenta
      #opening com port
      $port = New-Object System.IO.Ports.SerialPort $COMPoort,9600,None,8,one
      try
      {
        $port.Open()
      }
      catch
      {
        $port.PortName.ToString() + "is already open"
      }
      if (-not $port.IsOpen)
      {
        Write-Error "COMpoort $COMPoort cannot be opened";
        Write-Output "Please close the script, and close all programms that might be using the com port"
        $port.Close()
      }
      Write-Host "--------------------------------------------------------------------------------------------------------" -ForegroundColor DarkMagenta
      #scanner geeft teken van leven
      $port.WriteLine("`$+`$!`r")#read out software version from scanner
      Start-Sleep -Milliseconds 500
      $output = $port.ReadExisting()
      Write-Host "SOFTWARE versie:  $output" -ForegroundColor DarkMagenta
      Write-Host "--------------------------------------------------------------------------------------------------------" -ForegroundColor DarkMagenta
      $configuratie = Get-Content -path c:\temp\barcode_dl_4500_config.txt
      $port.WriteLine("`$S`r")#putting the scanner in service mode
      Write-Host "putting the scanner in service mode" -ForegroundColor DarkMagenta
      Write-Host "--------------------------------------------------------------------------------------------------------" -ForegroundColor DarkMagenta
      $output = $port.ReadExisting()
      Start-Sleep -Milliseconds 2500
      write-host $output -ForegroundColor Red
      Write-Host "--------------------------------------------------------------------------------------------------------" -ForegroundColor DarkMage
      Write-Host "Sending the configuration to the scanner" -ForegroundColor DarkMagenta
      Write-Host "--------------------------------------------------------------------------------------------------------" -ForegroundColor DarkMagenta
      foreach ($line in $configuratie) #Sending the configuration to the scanner
      {
        Write-Host "HOST:`$$line" -ForegroundColor DarkMagenta
        $port.Write("`$$line`r")
        $output = $port.ReadExisting()
        Start-Sleep -Milliseconds 80
        Write-Output "DEVICE: $output"
        if ($output -eq "$>`r")
        {
          write-host "Device OK" -ForegroundColor Green
        }
        else {
          write-host "Device NOK" -ForegroundColor Red
        }
      }
      write-host "HOST: Saving the settings"
      $port.WriteLine("`$Ar\x0d`r")#saving settings on barcode scanner
      $output = $port.ReadExisting()
      Write-Host "DEVICE: $output" -ForegroundColor Magenta
      $port.WriteLine("`$s`r")#closing service mode
      $output = $port.ReadExisting()
      Write-Host "DEVICE: $output"
      Start-Sleep -Milliseconds 5000
      Write-Host "HOST:Leaving service mode"
      $output = $port.ReadExisting()
      Write-Host "DEVICE: $output"
    }
    $port.Close()
  }
  catch 
  {
      Write-Host "Something has gone wrong " -ForegroundColor Red
      Write-output $_.ScriptStackTracke
      Write-Output $_.Exception.Message
  }  
}

#-----------------------------------------------------------[Execution]------------------------------------------------------------

Start-Transcript -Path C:\temp\Logs\seding_config_scannedl_4500.log -IncludeInvocationHeader
PushConfig

Stop-Transcript

this is the result I get:

Scanners found: 1
We found the datalogic barcode scanenr on: COM5
--------------------------------------------------------------------------------------------------------
SOFTWARE versie:  WLC4090-BASE-WIRELESS-CHARGER SOFTWARE RELEASE 610116050 BL 38.96fa43e6c 10/Nov/2021
--------------------------------------------------------------------------------------------------------
Putting the scanner in service mode
--------------------------------------------------------------------------------------------------------
$>
--------------------------------------------------------------------------------------------------------
Sending the configuration to the scanner
--------------------------------------------------------------------------------------------------------
HOST:$AE
DEVICE:
Device NOK
HOST:$YF00000000000000000000
DEVICE:
Device NOK
HOST:$M05
DEVICE:
Device NOK
HOST:$CSNOG02
DEVICE:
Device NOK
HOST:$CSLPS03
DEVICE:
Device NOK
HOST:$CSMSD00
DEVICE:
Device NOK
HOST:$CLAGL03
DEVICE:
Device NOK
HOST:$CAB3B01
DEVICE:
Device NOK
HOST:$CBPVO01
DEVICE:
Device NOK
HOST:$As
DEVICE:
Device NOK
HOST:$M47
DEVICE:
Device NOK
HOST:$CIPNR02
DEVICE:
Device NOK
HOST:$CSNOG02
DEVICE:
Device NOK
HOST:$CSLPS03
DEVICE:
Device NOK
HOST:$CI2EN01
DEVICE:
Device NOK
HOST:$CI2L20A
DEVICE:
Device NOK
HOST:$CLADF02
DEVICE:
Device NOK
HOST:$CLADI00
DEVICE:
Device NOK
HOST:$CU2EN01
DEVICE:
Device NOK
HOST:$CU2L102
DEVICE:
Device NOK
HOST:$CLEEN01
DEVICE:
Device NOK
HOST:$CU8AI00
DEVICE:
Device NOK
HOST:$CSMSD00
DEVICE:
Device NOK
HOST:$CLAGL03
DEVICE:
Device NOK
HOST:$CMSCT00
DEVICE:
Device NOK
HOST:$CMSEN01
DEVICE:
Device NOK
HOST:$CPLCT00
DEVICE:
Device NOK
HOST:$CPLEN01
DEVICE:
Device NOK
HOST:$CUSSE00
DEVICE:
Device NOK
HOST:$CI8CE01
DEVICE:
Device NOK
HOST:$CDMDA05
DEVICE:
Device NOK
HOST:$CI8CE00
DEVICE:
Device NOK
HOST:$CABID4A2000
DEVICE:
Device NOK
HOST:$CEBID532000
$>VICE: $>
Device NOK
HOST:$C8BID4D2000
$>VICE: $>
Device NOK
HOST:$C3BID4D2000
DEVICE: $>
Device OK
HOST:$CISID482000
DEVICE:
Device NOK
HOST:$CINID6E2000
$>VICE: $>
Device NOK
HOST:$CC3ID412000
DEVICE: $>
Device OK
HOST:$CP3ID582000
DEVICE: $>
Device OK
HOST:$CI2ID442000
DEVICE: $>
Device OK
HOST:$CS2ID502000
DEVICE: $>
Device OK
HOST:$CF2ID4F2000
DEVICE: $>
Device OK
HOST:$CIAID262000
DEVICE: $>
Device OK
HOST:$CU2ID432000
DEVICE: $>
Device OK
HOST:$CCBID462000
DEVICE: $>
Device OK
HOST:$CACID532000
DEVICE: $>
Device OK
HOST:$CHRID652000
DEVICE: $>
Device OK
HOST:$CC9ID492000
DEVICE: $>
Device OK
HOST:$CC1ID622000
DEVICE: $>
Device OK
HOST:$CC8ID482000
DEVICE: $>
Device OK
HOST:$CU8ID472000
DEVICE: $>
Device OK
HOST:$CMSID562000
DEVICE: $>
Device OK
HOST:$CCFID6D0000
DEVICE: $>
Device OK
HOST:$CI8ID482000
DEVICE: $>
Device OK
HOST:$CM2ID452000
DEVICE: $>
Device OK
HOST:$CCCID592000
DEVICE: $>
Device OK
HOST:$CPLID612000
DEVICE: $>
Device OK
HOST:$CALID6F2000
DEVICE: $>
Device OK
HOST:$CA2ID4A2000
DEVICE: $>
Device OK
HOST:$CA5ID4A2000
DEVICE: $>
Device OK
HOST:$CE2ID532000
DEVICE: $>
Device OK
HOST:$CE5ID532000
DEVICE: $>
Device OK
HOST:$C82ID4D2000
DEVICE: $>
Device OK
HOST:$C85ID4D2000
DEVICE: $>
Device OK
HOST:$C32ID4D2000
DEVICE: $>
Device OK
HOST:$C35ID4D2000
DEVICE: $>
Device OK
HOST:$C4BID472000
DEVICE: $>
Device OK
HOST:$CXBID472000
DEVICE: $>
Device OK
HOST:$CLBID472000
DEVICE: $>
Device OK
HOST:$CDMID632000
DEVICE: $>
Device OK
HOST:$CGBID244100
DEVICE: $>
Device OK
HOST:$CG2ID244200
DEVICE: $>
Device OK
HOST:$CG5ID244300
DEVICE: $>
Device OK
HOST:$CAB3B01
DEVICE: $>
Device OK
HOST:$CBPVO01
DEVICE: $>
Device OK
HOST:$CBCHP02
DEVICE: $>
Device OK
HOST:$As
DEVICE: $>
Device OK
HOST:$AS
DEVICE: $>
Device OK
HOST:$M35
DEVICE: $>
Device OK
HOST:$CSNOG02
DEVICE:
Device NOK
HOST:$CSLPS03
DEVICE:
Device NOK
HOST:$CSMSD00
$>VICE: $>
Device NOK
HOST:$CLAGL03
DEVICE: $>
Device OK
HOST:$AS
DEVICE: $>
Device OK
HOST:$HA05
DEVICE: $>
Device OK
HOST:$HA47
DEVICE:
Device NOK
HOST:$U00000008554C453202F20A0A
DEVICE: $>
Device OK
HOST:$U000800107B0A633D496E74546F537472284F5554
DEVICE:
Device NOK
HOST:$U00180010312E446174614C656E290A443D4F5554
$>VICE: $>
Device NOK
HOST:$U00280010312E446174610A4C3D226320220A0A69
DEVICE: $>
Device OK
HOST:$U003800106628284F5554312E4461746154797065
DEVICE: $>
Device OK
HOST:$U004800103D3D22436F646531323822297C7C284F
DEVICE: $>
Device OK
HOST:$U005800105554312E44617461547970653D3D2249
DEVICE: $>
Device OK
HOST:$U006800105342542229290A7B0A4C3D224820220A
DEVICE: $>
Device OK
HOST:$U007800107D0A6966284F5554312E446174615479
DEVICE: $>
Device OK
HOST:$U0088001070653D3D22436F6465333922290A7B0A
DEVICE: $>
Device OK
HOST:$U00980010653D284F5554312E446174614C656E29
DEVICE: $>
Device OK
HOST:$U00A800102D320A633D496E74546F537472286529
DEVICE: $>
Device OK
HOST:$U00B800100A4F5554312E44617461547970653D22
DEVICE: $>
Device OK
HOST:$U00C80010436F6465313238220A443D4D6964284F
DEVICE: $>
Device OK
HOST:$U00D800105554312E446174612C322C65290A4C3D
DEVICE: $>
Device OK
HOST:$U00E80010224120220A7D0A0A6966284F5554312E
DEVICE: $>
Device OK
HOST:$U00F8001044617461547970653D3D2249326F6635
DEVICE: $>
Device OK
HOST:$U0108001022290A7B0A4C3D224420220A7D0A6966
DEVICE: $>
Device OK
HOST:$U01180010284F5554312E44617461547970653D3D
DEVICE: $>
Device OK
HOST:$U01280010224D5349506C657373657922290A0A7B
DEVICE: $>
Device OK
HOST:$U013800100A0A653D4F5554312E446174614C656E
DEVICE: $>
Device OK
HOST:$U014800102D310A0A633D496E74546F5374722865
DEVICE: $>
Device OK
HOST:$U01580010290A0A4C3D225620220A7D0A6966284F
DEVICE: $>
Device OK
HOST:$U016800105554312E44617461547970653D3D2245
DEVICE: $>
Device OK
HOST:$U01780010414E3822290A7B0A4C3D224D20220A7D
DEVICE: $>
Device OK
HOST:$U018800100A6966284F5554312E44617461547970
DEVICE: $>
Device OK
HOST:$U01980010653D3D2245414E313322290A7B0A4C3D
DEVICE: $>
Device OK
HOST:$U01A80010224D20220A7D0A0A6966284F5554312E
DEVICE: $>
Device OK
HOST:$U01B8001044617461547970653D3D225550434122
DEVICE: $>
Device OK
HOST:$U01C80010290A7B0A4F5554312E44617461547970
DEVICE: $>
Device OK
HOST:$U01D80010653D22436F6465313238220A443D2230
DEVICE: $>
Device OK
HOST:$U01E80010222B4F5554312E446174610A633D496E
DEVICE: $>
Device OK
HOST:$U01F8001074546F537472284F5554312E44617461
DEVICE: $>
Device OK
HOST:$U020800104C656E2B31290A4C3D224D20220A7D0A
DEVICE: $>
Device OK
HOST:$U021800100A6966284F5554312E44617461547970
DEVICE: $>
Device OK
HOST:$U02280010653D3D22446174616D61747269782229
DEVICE: $>
Device OK
HOST:$U023800100A7B0A4C3D226320220A7D0A69662828
DEVICE: $>
Device OK
HOST:$U024800104F5554312E44617461547970653D3D22
DEVICE: $>
Device OK
HOST:$U02580010436F646531323822292626284C656674
DEVICE: $>
Device OK
HOST:$U02680010284F5554312E446174612C32293D3D22
DEVICE: $>
Device OK
HOST:$U027800105C5C5C7838302229290A7B0A653D4F55
DEVICE: $>
Device OK
HOST:$U0288001054312E446174614C656E2D320A633D49
DEVICE: $>
Device OK
HOST:$U029800106E74546F5374722865290A0A4C3D2247
DEVICE: $>
Device OK
HOST:$U02A8001020220A7D0A6966284F5554312E446174
DEVICE: $>
Device OK
HOST:$U02B8001061547970653D3D2245414E3132382229
DEVICE: $>
Device OK
HOST:$U02C800100A7B0A4C3D224720220A7D0A0A4F5554
DEVICE: $>
Device OK
HOST:$U02D80010312E446174613D4C2B632B2220222B44
DEVICE: $>
Device OK
HOST:$U02E800100A446F534C46284F555431290A0A7D0A
DEVICE: $>
Device OK
HOST: saving the settings
DEVICE: $>
DEVICE:
HOST:leaving service mode
$>VICE: $>
Transcript stopped, output file is C:\uz\Logs\naamScript.log

Solution

  • I did not succeed (yet) in using an eventhandler, but solved the problem with me not getting an answert etc... below the new (working)code

    #requires -version 2
    <#
    .SYNOPSIS
      configuration of gm4500 scanner for KWS
    .DESCRIPTION
      see synopsis
    .PARAMETER <Parameter_Name>
        none
    .INPUTS
      none
    .OUTPUTS
      log in c\uz\logs\nameofscript.txt
    .NOTES
      Version:        0.33
      Author:         Chris Vermeijlen
      Creation Date:  27-05-2022
      Purpose/Change: Initial script development
      
    .EXAMPLE
      <Example goes here. Repeat this attribute for more than one example>
    #>
    
    #---------------------------------------------------------[Initialisations]--------------------------------------------------------
    
    #Set Error Action to Silently Continue
    $ErrorActionPreference = "SilentlyContinue"
    # $ScriptFolder = Split-Path -Parent $Script:MyInvocation.MyCommand.Path
    # $ScriptModules = Join-Path -Path $ScriptFolder -ChildPath Modules
    # $env:PSModulePath = "$ScriptModules;$env:PSModulePath"
    
    #----------------------------------------------------------[Declarations]----------------------------------------------------------
    
    #Script Version
    #$sScriptVersion = "1.0"
    #Log File Info
    $ScriptName = "DatalogicGM4500Configr2.log"
    $scanner = ""
    $scannerName =""
    $output = "no input, also no output then (yet)"
    $configuration = Get-Content -path C:\uz\temp\configuratie.txt
    $tel = 0
    $linesInConf = ($configuration).Length
    
    #-----------------------------------------------------------[Functions]------------------------------------------------------------
    function PushConfig
    {
         Write-Host "--------------------------------------------------------------------------------------------------------"
        $scanner = (Get-WmiObject Win32_PnPEntity |Where-Object {$_.name -match "Barcode Scanner*" })
        Write-Host "`nScanners found: $(($scanner | Measure-Object).count)"
        if ((($scanner | Measure-Object).count) -eq 0) 
        {
            Write-Host "No scanner has been found, close programs that are using the comport, or connect a COM-port configured barcodescanner." -ForegroundColor Cyan
            Start-Sleep -Milliseconds 2000
        }
        else 
        {
            $scannerName = $scanner.Name
            #get com port number out of object
            $positionCOM = $scannerName.IndexOf("COM")
            [int]$positionCOM = $positionCOM + 2
            $COMPortNumber = $scannerName.Substring($positionCOM+1,1)
            $COMPort = "COM" + $COMPortNumber
            Write-Host "We found a datalogic scanner on: $COMPort"
            #opening COM-port
            try 
            {
                $port = New-Object System.IO.Ports.SerialPort $COMPort,9600,None,8,One
                $port.Open()
                if (-not $port.IsOpen)
                {
                    Write-Error "COMport $COMPoort cannot be opened";
                    Write-Output "Please close the script and all programs using the COM-port ( KWS, Putty,...) or the scanner for that matter"
                }
                write-output $port
                Write-Host "--------------------------------------------------------------------------------------------------------"
            }
            catch 
            {
                Write-Host "Error trying to open the comport" -ForegroundColor Red
                Write-output $_.ScriptStackTracke
                Write-Output $_.Exception.Message
            }
            #does scanner react? -> read software version
            try
            {
                $port.WriteLine("`$+`$!`r")#reading software version
                Start-Sleep -Milliseconds 500
                $output = $port.ReadExisting()
                Write-Host "SOFTWARE VERSIE: $output"
                Write-Host "--------------------------------------------------------------------------------------------------------"
            }
            catch
            {
                Write-Host "Error while retrieving software version" -ForegroundColor Red
                Write-output $_.ScriptStackTracke
                Write-Output $_.Exception.Message
            }
            #sending configuration to scanner
            try 
            {
                #putting the device into service mode
                $port.WriteLine("`$S`r")
                Start-Sleep -Milliseconds 3000
                $output = $port.ReadExisting()        
                Write-Host "DEVICE: $output"  -foregroundcolor Gray
                if ($output -eq "`$>`r")
                {
                    Write-Host "device is in service mode" -ForegroundColor Cyan
                    $port.Close()
                    Write-Host "Close port $COMPort @ 9600" -ForegroundColor Cyan
                    Start-Sleep -Milliseconds 1000
                    Write-host "Open port $COMPort @ 115200" -ForegroundColor Cyan
                    Start-Sleep -Milliseconds 1000
                    $port2 = New-Object System.IO.Ports.SerialPort $COMPort,115200,None,8,One
                    $port2.Open()
                    Start-Sleep -Milliseconds 1000
                }
                else
                {
                    Write-Host "something went wrong putting the device in service mode"
                    $port.Close()
                    exit
                }
                #sending the configuration, line per line
                foreach ($line in $configuration)
                {
                    $port2.WriteLine("`$$line`r")
                    write-host "HOST: $line" -ForegroundColor DarkGray
                    do 
                    {
                        $output = $port2.ReadExisting()
                    }
                     while ($output -eq "")
                    Write-Host "DEVICE: $output" -ForegroundColor Gray
                    if ($output -eq "`$>`r")
                    {
                        write-Host "Device: OK" -foregroundcolor Green
                        $tel++
                    }
                    else 
                    {
                        write-Host "Device: NOK"
                    }
                    Start-Sleep -Milliseconds 30
                }
                Start-Sleep -Milliseconds 30
                #save settings on device
                Write-host "HOST: saving settings on device" -foregroundcolor DarkGray
                $port2.WriteLine("`$Ar`r")
                Start-Sleep -Milliseconds 30
                $output = $port2.ReadExisting()
                Write-Host "DEVICE: $output"
                Start-Sleep -Milliseconds 4000
                #closing the service mode
                Write-host "HOST: Close Service mode"  -foregroundcolor DarkGray
                $port2.WriteLine("`$s`r")
                Start-Sleep -Milliseconds 4000
                Write-Host "--------------------------------------------------------------------------------------------------------"  -foregroundcolor DarkGray
                Write-Host "HOST: close com port" -foregroundcolor DarkGray
                Write-Host "--------------------------------------------------------------------------------------------------------"  -foregroundcolor DarkGray
                $port2.Close()
                if ($port2.IsOpen)
                {
                    write-host "port is still open :s" -ForegroundColor Red
                }
                else
                {
                    write-host "Port $COMPort is closed" -ForegroundColor Green
                }
                if ($tel -eq $linesInConf)
                {
                    Write-Host "--------------------------------------------------------------------------------------------------------" -foregroundcolor Green
                    write-Host "All lines of configuration are written correctly to device" -foregroundcolor Green
                    Write-Host "--------------------------------------------------------------------------------------------------------" -foregroundcolor Green
                    Start-Sleep -Milliseconds 1000
                }
                else
                {
                    Write-Host "--------------------------------------------------------------------------------------------------------" -foregroundcolor Red
                    write-Host "Something has gone wrong, contact scanner team" -foregroundcolor Red
                    Write-Host "--------------------------------------------------------------------------------------------------------" -foregroundcolor Red
                    Start-Sleep -Milliseconds 1000
                }
            }
            catch 
            {
                Write-Host "Error while sending configuration to scanner" -ForegroundColor Red
                Write-output $_.ScriptStackTracke
                Write-Output $_.Exception.Message
            }        
        }
    }
    
    
    
    
    #-----------------------------------------------------------[Execution]------------------------------------------------------------
    
    Start-Transcript -Path C:\namefolder\Logs\DatalogicGM4500Configr2.log -IncludeInvocationHeader
    Get-CimInstance Win32_OperatingSystem | Select-Object Caption, InstallDate, ServicePackMajorVersion, OSArchitecture, BootDevice, BuildNumber, CSName | Format-List
    PushConfig
    Stop-Transcript