Author Topic: Start/stop listening (using UDP)  (Read 724 times)

IvanS

  • Newbie
  • *
  • Posts: 16
Start/stop listening (using UDP)
« on: March 03, 2025, 02:14:49 PM »
I've created an inline function to monitor incoming UDP, so I can send commands to VA from within my app.

It works partially.  The commands I send appear in the log, however trying to turn listening on/off with it don't work.  It even blocks further inputs being logged.  So in the below code, if the SetListeningEnabled statements are uncommented, it doesn't turn on/off listening AND makes further UDP input not to be displayed anymore.

Can anyone spot the issue ?


Code: [Select]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

public class VAInline
{

    private static bool isListening = false;

    public void main()
    {
        // Get the path to the folder from the VoiceAttack variable
        string icaFolder = VA.GetText("icaFolder");
       
        // Combine the folder path with the settings.json file name
        string filePath = Path.Combine(icaFolder, "icaCOM.json");

       // Check if the file exists
        if (File.Exists(filePath))
        {
            VA.WriteToLog("Setting up UDP listener", "blue");
       
            // Read the entire content of the JSON file
            string jsonContent = File.ReadAllText(filePath);
           
            Match match;
            string patternToDev = "\"UDPtoDev\"\\s*:\\s*\"?(\\d+)\"?";
           
            match = Regex.Match(jsonContent, patternToDev);
            if (match.Success)
            {
                // Parse the extracted value to an integer
                int portToDev = int.Parse(match.Groups[1].Value);
               
                // Output the value or assign it to a VoiceAttack variable
                VA.SetInt("portToDev", portToDev);
                VA.WriteToLog("Set UDP port (icarus to device): " + portToDev, "green");
            }
            else
            {
                VA.WriteToLog("UDP port for receiving data not found.", "red");
            }
        }
        else
        {
            VA.WriteToLog("The file " + filePath + " does not exist. UDP ports could not be set!", "red");
            return;
        }
       
        // port found, so proceed to set up listener
        VA.WriteToLog("STARTING UP LISTENER (code not fully implemented yet)", "red");
       
        if (!isListening)
        {
          VA.WriteToLog("START UDP LISTENER", "red");
          isListening = true;
          Task.Run( () => ListenForUdp(VA) );
        }
    }
   
    // Method that listens for UDP packets (for now only turning listening on/off)
    private static async Task ListenForUdp(dynamic vaProxy)
    {
        using (UdpClient udpListener = new UdpClient(vaProxy.GetInt("portToDev"))) // Change port if needed
        {
        vaProxy.WriteToLog("STARTED LISTENING TO PORT: " + vaProxy.GetInt("portToDev"), "green");
            while (true)
            {
                // Listen for incoming UDP packets
                UdpReceiveResult result = await udpListener.ReceiveAsync();
                string message = Encoding.UTF8.GetString(result.Buffer);

                // Check the message
                vaProxy.WriteToLog("Received UDP: " + message, "pink");
//                if (message == "!LISTEN!0") vaProxy.SetListeningEnabled(0);
//                if (message == "!LISTEN!1") vaProxy.SetListeningEnabled(1);
            }
        }
    }
}
 

IvanS

  • Newbie
  • *
  • Posts: 16
Re: Start/stop listening (using UDP)
« Reply #1 on: March 04, 2025, 03:42:39 AM »
OK, I figured it out.  Instead of launching a Task, just loop in main().

Should someone need something similar, here is the code:

Code: [Select]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

public class VAInline
{

    private static bool isListening = false;

    public void main()
    {
       // Set port to listen to
       int portToDev = 5555;
               
                // Output the value or assign it to a VoiceAttack variable
                VA.SetInt("portToDev", portToDev);
                VA.WriteToLog("UDP input bound to port: " + portToDev, "green");
            }
            else
            {
                VA.WriteToLog("UDP port for receiving data not found.", "red");
            }
        }
        else
        {
            VA.WriteToLog("The file " + filePath + " does not exist. UDP ports could not be set!", "red");
            return;
        }
       
        // port found, so proceed to set up listener
        //VA.WriteToLog("Listening for UDP input on port " + portToDev, "blue");
       

        UdpClient udpClient = new UdpClient(6464); // Specify the port to listen on
        IPEndPoint remoteEP = new IPEndPoint("127.0.0.1", 0);

        while (true)
        {
            try
            {
                byte[] receivedData = udpClient.Receive(ref remoteEP);
                string receivedMessage = Encoding.ASCII.GetString(receivedData);

                VA.WriteToLog("Received data: " + receivedMessage + " from " + remoteEP, "pink");
                if (receivedMessage == "!EXIT!") break;
                ProcessInput(receivedMessage);
            }
            catch (Exception e)
            {
                VA.WriteToLog("An error occurred: " + e.Message, "red");
                Thread.Sleep(250);
            }
        }       
       
        udpClient.Close();
        VA.WriteToLog("CLOSED UDP", "red");
               
    }
   
    public void ProcessInput(string msg)
    {
        if (msg == "!LISTEN0!") VA.State.SetListeningEnabled(false);
        if (msg == "!LISTEN1!") VA.State.SetListeningEnabled(true);
    }
   
}

Just code in the port you want to use, and place appropriate statements in ProcessInput(...).