Highlight a phrase and click this icon to search it on Swyx-Forum    Highlight a phrase and click this icon to search it within the Swyx Knowledgebase    Highlight a phrase and click this icon to search it using Goolge    Highlight a phrase and click this icon to search it using Wikipedia

List of Blogs
Search Blogs

Blog Archive

Most recent blog entries

 

Jun24

Written by:Martin
24.06.2011 15:00 

For my PowerShell session at Swyx Technology Conference I prepared an additional demo. I didn’t show it, because there was no time and most of the audience had little experience with PowerShell anyway. This demo uses the APIs described in the SwyxIt! Client SDK to consume events from SwyxIt! and uses that to display state changes of every speed dial key the current user has configured.

In order to do this you first have to create a .NET runtime callable wrapper for the API using tlbimp.exe from the Microsoft .Net Framework SDK. Using the ClientLineManager object via this interop assembly, SwyxIt! events can easily be consumed using PowerShell’s eventing support. To do so you

  1. Create a new ClientlineManager object (demo3.ps1, line  12)
  2. Subscribe to an event, in this case the DispOnLineMgrNotification event on the ClientLineMgr object (demo3.ps1, line 15)
  3. Wait for events (clmgr-utilities.ps1, line 103)
  4. Check for type of event and handle it accordingly

This is a proof of concept. I did it, because I can, not because it’s the best way to program against the ClMgr-API. That being said: Enjoy Smile

demo3.ps1
  1. $ScriptFolder = (split-path $MyInvocation.MyCommand.Path -Parent)
  2. . (join-path $ScriptFolder "clmgr-utilities.ps1")
  3.  
  4. import-module ippbx
  5.  
  6. function get-SpeedDialKeyStateChange
  7. {
  8.    param([string[]]$SpeedDialKeyNames,
  9.          [Clmgr.CLMgrNameKeyStates[]]$States = $null)
  10.  
  11.    BEGIN {
  12.        $clmgr = new-object "CLMgr.ClientLineMgrClass"
  13.  
  14.        # register for line manager events    
  15.        Register-ObjectEvent -InputObject $clmgr -EventName DispOnLineMgrNotification
  16.  
  17.        # get speed dial key definitions
  18.        $blob = new-object "IpPbxBlob.UserSettings"
  19.        $Bytes = $clmgr.DispClientConfig.ConfigBuffer
  20.        if ($Bytes) { [void]$Blob.SetBLOB($Bytes) }
  21.        $SpeedDialKeys = $Blob.m_NameKeySettings
  22.    }
  23.    
  24.    PROCESS {
  25.        do {
  26.            $event = wait-ClmgrEvent -MessageTypes "NameKeyStateChangedMessage","ClientShutDownRequest"
  27.            if ($Event.sourceargs[0] -eq [clmgr.clmgrmessage]::NameKeyStateChangedMessage)
  28.            {
  29.                # $message parameter is speed dial key index which has changed, get state
  30.                $idx = $Event.SourceArgs[1]
  31.                $SpeedDialKeyState = 0
  32.                if ($idx -gt 0)    
  33.                {
  34.                    $clmgr.GetNamekeyState($Event.SourceArgs[1], [ref] $SpeedDialKeyState)
  35.                    $Name = $SpeedDialKeys[$idx].Title
  36.                    if (!$Name) { $Name = $SpeedDialKeys[$idx].DialNumber }
  37.                    if ((!$SpeedDialKeyNames -or $SpeedDialKeyNames -contains $Name) -and (!$States -or $States -contains $SpeedDialKeyState))
  38.                    {
  39.                        new-object "PSObject" |
  40.                            Add-Member -Name "Index" -Value $idx -MemberType NoteProperty -PassThru |
  41.                            Add-Member -Name "Title" -Value $Name -MemberType NoteProperty -PassThru |
  42.                            Add-Member -Name "State" -Value $SpeedDialKeyState -MemberType NoteProperty -PassThru
  43.                    }
  44.                }
  45.            }             
  46.            $Event | remove-event
  47.        } while ($Event.sourceargs[0] -ne [clmgr.clmgrmessage]::ClientShutDownRequest)
  48.    }
  49.    
  50.    END {
  51.        Get-EventSubscriber | Where-Object { $_.EventName -eq "DispOnLineMgrNotification" } | Unregister-Event
  52.        $clmgr = $null
  53.    }
  54. }
  55.  
  56. get-SpeedDialKeyStateChange | format-table

 

 

clmgr-utilities.ps1
  1. $ScriptFolder = (split-path $MyInvocation.MyCommand.Path -Parent)
  2. . (join-path $ScriptFolder "custom-enum.ps1")
  3.  
  4. add-type -path (join-path $ScriptFolder "Interop.Clmgr.dll")
  5.  
  6. # clmgr event type
  7. Add-Enum -erroraction SilentlyContinue -nameSpace Clmgr -name ClMgrMessage -values @(
  8.    "LineStateChangedMessage";   # state of a line has changed"
  9.    "LineSelectionChangedMessage";  # line selection has changed = "; new line in focus"
  10.    "LineDetailsChangedMessage";   # details of line has changed"
  11.    "UserDataChangedMessage";    # user configuration has changed"
  12.    "CallDetailsMessage";     # details of last call are available = "; after disconnect = "; for logging purpose"
  13.    "ServerDownMessage";     # server is down = "; will be rebooted = "; ..."
  14.    "ServerUpMessage";     # server is up again -> keep interfaces to line manger
  15.    "WaveDeviceChanged";     # speaker and / or micro has been switched on or off
  16.    "GroupCallNotificationMessage";  # notification about signaled call we could pick up now
  17.    "NameKeyStateChangedMessage";   # notification about changed namekey state
  18.    "NumberOfLinesChangedMessage";  # the number of lines has changed
  19.    "ClientShutDownRequest";    # Client Line Manager requests client to shutdown and release all interfaces
  20.    "PowerSuspendMessage";    # client machine goes to hibernate or suspend mode
  21.    "PowerResumeMessage";     # client machine has returned from suspend mode -> keep interfaces to line manager
  22.    "HandsetStateChangedMessage";   # state of handset has changed
  23.    "SkinPhoneCommandMessage";   # for forwarding commands from PlugIn to SwyxIt!.exe.
  24.    "SkinActionAreaStateChangedMessage"; # informing clients about a changed action area state.
  25.    "SkinInfoDetailChangedMessage";  # informing clients about changed information area details.
  26.    "CallbackOnBusyNotification";   # informing clients about available callback on busy
  27.    "AsyncMessage";      # message for reporting success or problems that occured within state machine / were reported by server
  28.    "CtiPairingStateChanged";    # informing clients about changed state of CTI pairing process
  29.    "ChatMessage";      # for call clients that have registered as chat message receiver: new message available
  30.    "ChatMessageAck";      # for call clients that have registered as chat message receiver:
  31.    "RecordingError";      # Error on recording conversation
  32.    "VolumeChanged";      # Volume of sound device has changed
  33.    "AudioModeChanged";     # Current audio mode has changed
  34.    "MicAdjustLevelMeter";    # Peak level meter during microphone adjustment
  35.    "MicAdjustProceedMeter";    # Proceed level during microphone adjustment
  36.    "LineStateChangedMessageEx";   # state of at least line has changed
  37.    "PlaySoundFileDxProceedMeter";  # Proceed level during PlaySoundFileDx playback
  38.    "SIPRegistrationStateChanged";     # registration state of SIP account has changed
  39.    "WaveFilePlayed";      # wave file playback finished
  40.    "FirstDataReceived";     # wave file playback finished
  41.    "RegisteredSipDeviceListChanged";  # number of registered dialer mode compatible (SIP) devices for own user changed
  42.    "DialerStartCallResult";    # message for reporting start call success or failure in dialer mode
  43.    "LineStateChangedMessageEx2";   # state of at least line has changed
  44.    "MediaEncryptionStatusChanged"; # media encryption state has changed
  45. )
  46.  
  47. Add-Enum -erroraction SilentlyContinue -namespace Clmgr -name ClMgrLineState -values @(
  48.    "Inactive";                 # line is inactive
  49.    "HookOffInternal";          # off hook, internal dialtone
  50.    "HookOffExternal";          # off hook, external dialtone
  51.    "Ringing";                  # incoming call, ringing
  52.    "Dialing";                  # outgoing call, we are dialing"; no sound
  53.    "Alerting";                 # outgoing call, alerting = ringing on destination
  54.    "Knocking";                 # outgoing call, knocking = second call ringing on destination
  55.    "Busy";                     # outgoing call, destination is busy
  56.    "Active";                   # incoming / outgoing call, logical and physical connection is established
  57.    "OnHold";                   # incoming / outgoing call, logical connection is established"; destination gets music on hold
  58.    "ConferenceActive";         # incoming / outgoing conference, logical and physical connection is established
  59.    "ConferenceOnHold";         # incoming / outgoing conference, logical connection is established"; not physcically connected
  60.    "Terminated";               # incoming / outgoing connection / call has been disconnected
  61.    "Transferring";             # special LSOnHold, call is awaiting to be transferred"; peer gets special music on hold
  62.    "Disabled";                 # special LSInactive, wrap up time"; we will temporary not allow calls on that line
  63.    "DirectCall"                # incoming call logical and physical connection is established micro is muted
  64. )
  65.  
  66. Add-enum -erroraction SilentlyContinue -namespace Clmgr -name ClmgrDisconnectReason -values @(
  67.    "Normal";                 # nothing special
  68.    "Busy";                   # peer was busy
  69.    "Rejected";               # peer rejected call
  70.    "Cancelled";              # call was cancelled
  71.    "Transferred";            # call was transferred (connect to peers with "PubTransferCall")
  72.    "JoinedConference";       # call was added to conference on other line with "PubJoinConference"
  73.    "NoAnswer";               # peer did not pick up"; timeout
  74.    "TooLate";                # call was already picked up from other phone
  75.    "DirectCallImpossible";   # direct call to peer was not allowed
  76.    "WrongNumber";            # invalid number was dialed
  77.    "Unreachable";            # destination is unreachable
  78.    "CallDiverted";           # call was redirected
  79.    "CallRoutingFailed";      # call routing failed"; possible script error (script of peer)
  80.    "PermissionDenied";       # permission for call was denied due to call restrictions (e.g. no long distance call allowed)
  81.    "NetworkCongestion";      # no line available (within ISDN network)
  82.    "NoChannelAvailable";     # no gateway channel available
  83.    "NumberChanged";          # the number of the called party has changed
  84.    "IncompatibleDestination";# the device type of the called party is incompatible
  85.    "BadAddressFormat";       # wrong phone number format"; e.g. bad character
  86. )
  87.  
  88.  
  89. <#
  90. .Synopsis
  91.    Wait for client line manager event
  92. .Description
  93.    Wait for an event send from clmgr.exe via the client API
  94. .Parameter Eventfilter
  95.    ScriptBlock to filter events. If it returns $true event will be returned. ScriptBlock gets two int parameter $Message and $MessageParam.
  96.    The first defines the type of event, the second is an event specific parameter. See Client SDK for details
  97. .Example
  98.    wait-event
  99. #>
  100. function wait-ClmgrEvent
  101. {
  102.    param([System.Management.Automation.ScriptBlock]$EventFilter = { $true },
  103.          [Clmgr.ClmgrMessage[]]$MessageTypes = $null,
  104.          [int]$Timeout = -1
  105.         )
  106.         
  107.    $SourceID = (Get-EventSubscriber | Where-Object { $_.EventName -eq "DispOnLineMgrNotification" } | select -first 1).SourceIdentifier
  108.  
  109.    $StartTime = get-date
  110.    $TimeoutExceeded = $false
  111.    do
  112.    {
  113.        $event = wait-event -SourceIdentifier $SourceID -Timeout 1
  114.        if ($event)
  115.        {
  116.            $Message = $Event.SourceArgs[0]
  117.            $MessageParam = $Event.SourceArgs[1]
  118.  
  119.            if ($MessageTypes)
  120.            {
  121.                $EventMatches = $MessageTypes -contains $Message
  122.            }
  123.            else
  124.            {
  125.                $EventMatches = $EventFilter.Invoke(@($Message,$MessageParam))
  126.            }
  127.        }
  128.        
  129.        if ($Timeout -ne -1)
  130.        {
  131.            $TimeoutExceeded = (((get-date) - $StartTime).TotalSeconds) -gt $timeout
  132.        }
  133.        
  134.        if ($Event -and !$EventMatches)
  135.        {
  136.            $Event | remove-event
  137.        }
  138.    } while ( !$EventMatches -and !$TimeoutExceeded)
  139.    
  140.    if (!$TimeoutExceeded)
  141.    {
  142.        $event
  143.    }
  144. }

 

Download the whole demo here:

 

 

Tags:

 


Your name:
Your email:
(Optional) Email used only to show Gravatar.
Title:
Comment:
Security Code
Enter the code shown above in the box below
Add Comment  Cancel 
Blog Help
Sponsors