using System.Net; using System.Net.Sockets; using System.Text; namespace RobotLib { public static class IndependentRobotConfigurator { private static readonly NLog.Logger log = NLog.LogManager.GetCurrentClassLogger(); private const int udpPortRobot = 1818; /// /// Sends a command via UDP to set the MQTT broker IP on a robot. /// This serves to adopt a robot (get it to communicate via MQTT). /// Consider rebooting ESP32 with to apply the newly set IP. /// /// hostname or IP address of the robot /// ip address of the MQTT broker public static void Adopt(string hostnameRobot, string brokerIp) { // test if IP valid if (IPAddress.TryParse(brokerIp, out _)) { SendMessageUdp(hostnameRobot, udpPortRobot, $"mqtt setIp {brokerIp}"); } else { log.Error($"Invalid broker IP address: {brokerIp}"); } } /// /// Sends a command via UDP to set the challenge mode of a robot. /// /// hostname or IP address of the robot /// ip address of the MQTT broker public static void SetRobotMode(string hostnameRobot, string mode) { // test if mode is valid if (mode == "stationary" || mode == "s" || mode == "mobile" || mode == "m") { SendMessageUdp(hostnameRobot, udpPortRobot, $"challenge setMode {mode}"); } else { log.Error($"Invalid robot mode: {mode}"); } } /// /// Sends a command via UDP to reboot the ESP32 of a robot. /// For example when a new mqtt broker IP was set, the robot needs to reboot in order to apply the IP and reconnect to a new broker. /// /// hostname or IP address of the robot public static void RebootEsp32(string hostnameRobot) { SendMessageUdp(hostnameRobot, udpPortRobot, $"challenge reboot"); } private static void SendMessageUdp(string hostname, int port, string message) { var udpClient = new UdpClient(); udpClient.Connect(hostname, port); byte[] data = Encoding.ASCII.GetBytes(message); udpClient.Send(data, data.Length); log.Trace($"Msg sent to {udpClient.Client.RemoteEndPoint}: {message}"); udpClient.Close(); } } }