--- a +++ b/SimpleSocketExample/main.c @@ -0,0 +1,108 @@ +#include <stdlib.h> +#include <stdio.h> +#include <errno.h> + +#include <unistd.h> +#include <fcntl.h> +#include <sys/stat.h> +#include <arpa/inet.h> +#include <sys/types.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <stdint.h> +#include <string.h> +#include <math.h> + + void printUsage(); + + typedef int bool; + #define true 1 + #define false 0 + +int main( int argc, const char* argv[] ) +{ +/* ******************************************** + * Actual socket code + **********************************************/ + +int socketfd; // socket handle + +// open the socket +// http://man7.org/linux/man-pages/man2/socket.2.html +socketfd = socket(AF_INET, // IPv4 + SOCK_STREAM, // a TCP connection + 6); // protocol. 6 is TCP + +if (!socketfd) +{ + printf("opening socket failed\n"); + return 1; +} + +// no need to bind this one. CODESYS is already bound so it is acting as a server. +// We are a client, so we don't need a fixed address/port to be reached at + +// connect to CODESYS + +// first we need to create the struct where we put the connection info +struct sockaddr_in saCodesys; +// init the struct +bzero((char *) &saCodesys, sizeof(saCodesys)); +// put in the information +saCodesys.sin_family = AF_INET; // IPv4 +saCodesys.sin_port = htons(1200); // CODESYS port + +// Convert IPv4 address from text to binary form + if(inet_pton(AF_INET, "127.0.0.1", (struct sockaddr *)&saCodesys.sin_addr)<=0) + { + printf("Invalid address/ Address not supported \n"); + // close the socket + close(socketfd); + return 2; + } + + if (connect(socketfd, (const struct sockaddr *)&saCodesys, sizeof(saCodesys)) < 0) + { + printf("Connection Failed %d\n", errno); + // close the socket + close(socketfd); + return 3; + } + +/* ************************************* + * Sending data + ***************************************/ + // super smart A.I. algorithm putting out production targets once a second + uint16_t uiProductionTarget = 0; + int counter = 0; + + while (1) + { + uiProductionTarget = (sin(counter / 100.0) + 1) * 100; + + if (send(socketfd, &uiProductionTarget, sizeof(uiProductionTarget), 0 /* no flags */) < 0) + { + printf("send failed. Ending.\n"); + break; + } + else + { + printf("sent target: %d\n", uiProductionTarget); + } + + sleep(1); // wait a ms before doing the math again. + counter ++; + } + + + // close the socket + close(socketfd); + printf("closing down.\n", ); + + return 0; +} + +void printUsage() +{ + printf("just run it\n"); +}