You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
73 lines
2.7 KiB
73 lines
2.7 KiB
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;
|
|
|
|
/// <summary>
|
|
/// 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 <see cref="RebootEsp32(string)"/> to apply the newly set IP.
|
|
/// </summary>
|
|
/// <param name="hostnameRobot">hostname or IP address of the robot</param>
|
|
/// <param name="brokerIp">ip address of the MQTT broker</param>
|
|
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}");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sends a command via UDP to set the challenge mode of a robot.
|
|
/// </summary>
|
|
/// <param name="hostnameRobot">hostname or IP address of the robot</param>
|
|
/// <param name="brokerIp">ip address of the MQTT broker</param>
|
|
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}");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
/// <param name="hostnameRobot">hostname or IP address of the robot</param>
|
|
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();
|
|
}
|
|
}
|
|
}
|
|
|