I tried to send signal processing parameters to RPi by socket communication, so when I copied and pasted the Internets code in the first socket communication, the accept function threw an ʻInvalid argument` error and did not work. So, I found out that accept is a function used when the protocol is TCP, and the client side sends it by UDP.
For an understanding of the outline of the UDP protocol and the server code, refer to the following site. Using UDP: Geek Page From the explanation of the above site, it seems that UDP is good if immediacy is required and the parameter is short to some extent, so I decided to rewrite the server reception to UDP. Below is the code that processes the signal in the main routine and receives the parameters in another thread. The part that acquires audio data is omitted.
main.c
#include <netinet/in.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#define PORT_NO 12345
/*Structure to store receive parameters*/
typedef struct {
/*Appropriate parameter variable group*/
} socket_data_struct;
int serverSock;
struct sockaddr_in serverAddress;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
/*Socket initialization function*/
int socketInit();
/*Function for threads that receives parameters in socket communication*/
void* parameterReceive(void* pParam);
int socketInit()
{
serverSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(serverSocket < 0) {
return -1;
}
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(PORT_NO);
/*Receive data addressed to all IP addresses*/
serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(serverSocket, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) != 0) {
return -1;
}
return 0;
}
void* parameterReceive(void* pParam)
{
socket_data_struct data;
struct sockaddr_in senderInfo;
socklen_t addressLength;
while (1) {
recvfrom(serverSock, &data, sizeof(socket_data_struct), 0, (struct sockaddr *)&senderInfo, &addressLength);
pthread_mutex_lock(&m);
/*Processing of received parameters*/
pthread_mutex_unlock(&m);
/*Echo received data to client*/
sendto(serverSocket, (char *)&data, sizeof(socket_data_struct), 0, (struct sockaddr *)&senderInfo, addressLength);
usleep(500);
}
close(serverSocket);
}
int main(void)
{
pthread_t threadIdSocket;
if(socketInit()){
return -1;
}
pthread_mutex_init(&m, NULL);
pthread_create(&threadIdSocket, NULL, parameterReceive, NULL);
while(1){
/*Contains the DSP code*/
}
pthread_join(threadIdSocket, NULL);
pthread_mutex_destroy(&m);
return 0;
}
As a precaution when performing signal processing and socket communication in parallel, do not pthread_join
the socket communication thread before the main while loop, put sleep
in the while loop of the socket communication thread, Is it about? Also, of course, the port to be used must be opened with ufw or something. You can now receive signal processing parameters while performing signal processing.
Recommended Posts