OK, a small amount of hackery required this time to get your example running.
There were a few issues with your example code. I’ve hacked it around a bit and the modified example below quite happily shows a regular heartbeat for a SITL instance running on the same machine. Suggest you use diff
to see the changes I’ve made to your NavControl.cpp
#include "NavControl.h"
#include <sys/time.h>
void timer_start(std::function<void(void)> func, unsigned int interval)
{
std::thread([func, interval]()
{
while (true)
{
auto x = std::chrono::steady_clock::now() + std::chrono::milliseconds(interval);
func();
std::this_thread::sleep_until(x);
}
}).detach();
}
struct sockaddr_in src_addr;
void mavSendHeartbeat(void)
{
if (src_addr.sin_family == 0) {
printf("No source address yet\n");
return;
}
mavlink_msg_heartbeat_pack(mavlink_system.sysid, mavlink_system.compid, &msg, MAV_TYPE_ONBOARD_CONTROLLER,
MAV_AUTOPILOT_INVALID, 0, 0, 0);
len = mavlink_msg_to_send_buffer(buf, &msg);
printf("Heartbeat sent\n");
sendto(clientSocket,buf,len,0,(struct sockaddr *)&src_addr,addr_size);
}
struct timeval last_received;
void heartbeat_received()
{
struct timeval now;
gettimeofday(&now, NULL);
struct timeval delta;
timersub(&now, &last_received, &delta);
char ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(src_addr.sin_addr), ip, sizeof(ip));
printf("Hearbeat received from (%s:%u).. (delta=%f)\n", ip,src_addr.sin_port, (delta.tv_sec+delta.tv_usec/1000000.0));
last_received = now;
}
uint8_t mavReceive(void)
{
while (true) {
bufIndex = 0;
bytesReceived = 0;
socklen_t socklen = sizeof(sizeof(src_addr));
bytesReceived = recvfrom(clientSocket, rxBuf, 1024, 0, (struct sockaddr*)&src_addr, &socklen);
// bytesReceived = recvfrom(clientSocket, rxBuf, 1024, 0, NULL, NULL);
if(bytesReceived < 0)
{
printf("Error receiveing UDP\n");
continue;
}
// Process the received bytes to form a message
while(bufIndex < bytesReceived)
{
ch = rxBuf[bufIndex++];
if(mavlink_parse_char(MAVLINK_COMM_0, ch, &msg, &status))
{
switch(msg.msgid)
{
case MAVLINK_MSG_ID_HEARTBEAT:
heartbeat_received();
break;
default:
// printf("Received .. MSG ID = %d\n", msg.msgid);
break;
}
}
}
}
return 1;
}
int main(void)
{
mavlink_system.sysid = 20;
mavlink_system.compid = 20;
clientSocket = socket(PF_INET, SOCK_DGRAM, 0);
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(14551);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);
addr_size = sizeof serverAddr;
if (bind(clientSocket, (struct sockaddr*)&serverAddr, addr_size) < 0) {
printf("Bind failed: %m");
exit(1);
}
gettimeofday(&last_received, NULL);
// Start a timer to send heartbeat signal each second
timer_start(mavSendHeartbeat, 1000);
// Start a timer to receive messages from the other side each second
timer_start(mavReceive, 10);
while(1);
}
Note that this is just hackery to get something that works