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 ?
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);
}
}
}
}