Skip to content

Conversation

@chkr1011
Copy link
Collaborator

This PR adds a new project which contains a PowerShell module so that MQTTnet can also be used in PowerShell.

@chkr1011 chkr1011 linked an issue Oct 20, 2025 that may be closed by this pull request
@ArakniD
Copy link

ArakniD commented Dec 1, 2025

consider RegisterMqttMessageHandlerCmdlet to include the following implementation

        EventHandler<PsMqttMessage> handler = (s, e) =>
        // Capture the ScriptBlock and current default runspace (available during cmdlet execution)
        var scriptBlock = Action ?? throw new ArgumentNullException(nameof(Action));
        var capturedRunspace = Runspace.DefaultRunspace ?? throw new InvalidOperationException("No default runspace available during cmdlet execution.");

        EventHandler<PsMqttMessage> handler = null!;
        handler = (sender, e) =>
        {
            //throw new NotImplementedException();
            //InvokeCommand.InvokeScript(Action, false, PipelineResultTypes.Output, null, new object[] { e.Topic, e.Payload });
            // Run asynchronously to avoid blocking the event thread
            Task.Run(() =>
            {
                // Temporarily set the default runspace for this thread
                var originalRunspace = Runspace.DefaultRunspace;
                Runspace.DefaultRunspace = capturedRunspace;
        
                try
                {
                    // Invoke the ScriptBlock directly with arguments (returns Collection<PSObject>)
                    var results = scriptBlock.Invoke(e.Topic, e.Payload, e); // Pass topic, payload, and full message
        
                    // Handle output manually (e.g., write to host/console)
                    foreach (var result in results)
                    {
                        Host.UI.WriteLine(result?.ToString() ?? string.Empty);
                    }
                }
                catch (Exception ex)
                {
                    // Handle errors by writing to host error stream
                    Host.UI.WriteErrorLine($"MQTT handler error: {ex.Message}");
                    // Optionally: Host.UI.WriteVerboseLine(ex.StackTrace); for more details
                }
                finally
                {
                    // Restore the original default runspace for this thread
                    Runspace.DefaultRunspace = originalRunspace;
                }
            });
        };

gives an example usage of

    Register-MqttMessageHandler -Session $session -Action {
           param($topic, $payload, $message)
            try {
                #Write-Host "Received MQTT message on $topic  $payload"
                Add-Content -Path $script:currentFile -Value $payload
            } catch {
                Unsubscribe-MqttTopic -Session $session -Topic $Topic
                Write-Host "Un-Subscripion due to error."
                
                Disconnect-MqttSession -Session $session
                Write-Host "Mqtt disconnec due to error."
            }
    # Or do processing: Send-MqttResponse -Topic $topic -Payload "Ack: $payload"
    }
Write-Host "Registered msg handler added."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FR] Powershell compatibility

3 participants