MQTT-Gateway/test/heading.c
2024-01-22 21:20:10 +01:00

106 lines
2.4 KiB
C

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h> // BSD compatible
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>
#define SERVER "::1"
#define PORT 49000
#define COMMAND_BUFFER 256
char *printable(char *str)
{
char *ret = strdup(str);
for (int i = strlen(ret); i >= 0; i--)
{
if (ret[i] == '\r' || ret[i] == '\n')
{
ret[i] = '\0';
}
}
return ret;
}
void sendCommand(int sock, char *cmd)
{
char bytesToSend[COMMAND_BUFFER];
memset(bytesToSend, 0, COMMAND_BUFFER);
strcpy(&bytesToSend[0], "CMND");
strcpy(&bytesToSend[5], cmd);
int numBytesSend = send(sock, bytesToSend, 5 + strlen(cmd), 0);
if (numBytesSend >= 0)
{
// printf("Send %d bytes to %s:%d: %s\n", numBytesSend, SERVER, PORT, printable(bytesToSend));
}
else
{
fprintf(stderr, "Failed to send message to %s:%d (%d): %s", SERVER, PORT, errno, strerror(errno));
exit(EXIT_FAILURE);
}
}
int main(int argc, char *argv[])
{
int xplaneSocket;
struct sockaddr_in6 xplaneAddress;
int err;
// check argument
if (argc != 2 || (strcmp(argv[1], "up") != 0 && strcmp(argv[1], "down") != 0))
{
fprintf(stderr, "Usage: %s <up|down>\n", argv[0]);
exit(EXIT_FAILURE);
}
// create socket
xplaneSocket = socket(AF_INET6, SOCK_DGRAM, 0);
if (xplaneSocket == -1)
{
fprintf(stderr, "Error creating socket (%d): %s\n", errno, strerror(errno));
exit(EXIT_FAILURE);
}
// prepare address struct
xplaneAddress.sin6_family = AF_INET6;
xplaneAddress.sin6_port = htons(PORT);
inet_pton(AF_INET6, SERVER, &xplaneAddress.sin6_addr.s6_addr);
// connect to xplane
err = connect(xplaneSocket, (struct sockaddr *)&xplaneAddress, sizeof(xplaneAddress));
if (err)
{
fprintf(stderr, "Error connecting %s:%d (%d): %s\n", SERVER, PORT, err, gai_strerror(err));
exit(EXIT_FAILURE);
}
// send payload
if (strcmp(argv[1], "up") == 0)
{
sendCommand(xplaneSocket, "sim/autopilot/heading_up");
}
else if (strcmp(argv[1], "down") == 0)
{
sendCommand(xplaneSocket, "sim/autopilot/heading_down");
}
else
{
exit(EXIT_FAILURE);
}
// bye bye (and no, I don't care about error anymore; I'll exit anyway?!)
close(xplaneSocket);
exit(EXIT_SUCCESS);
}