Greatings,
I am trying to establish a raw socket connection between my windows 10 pc (which has a service waiting for incoming connections) and the tiva board (client)
Pc and Board are connected to a hub which is connected to my router.
I have the Ip of my pc as destination, the port on which the pc is accepting is the port the client is trying to connect to.
I am using RTOS on the tiva board and the whole connection is in a task function.
I configured static ip for the board which has the same mask and gateway as the pc (both devices on the same hub).
/* * rtos base-system configuration for TI-RTOS 2.16 and above * (c) DIScoVER 2015, 2016 */ /* * ======== application.cfg ======== */ var Types = xdc.useModule('xdc.runtime.Types'); /* * This module defines basic constants and types used throughout the * xdc.runtime package. */ var mwConfig = xdc.useModule('ti.mw.Config'); /* * Include TI-RTOS middleware libraries */ /* ================ General configuration ================ */ var Defaults = xdc.useModule('xdc.runtime.Defaults'); /* Allow object view tools to display names of instance objects. */ Defaults.common$.namedInstance = true; /* * A flag to allow module names to be loaded on the target. Module name * strings are placed in the .const section for debugging purposes. * * Pick one: * - true (default) * Setting this parameter to true will include name strings in the .const * section so that Errors and Asserts are easier to debug. * - false * Setting this parameter to false will reduce footprint in the .const * section. As a result, Error and Assert messages will contain an * "unknown module" prefix instead of the actual module name. */ Defaults.common$.namedModule = true; var Mailbox = xdc.useModule('ti.sysbios.knl.Mailbox'); var Event = xdc.useModule('ti.sysbios.knl.Event'); var HeapBuf = xdc.useModule('ti.sysbios.heaps.HeapBuf'); var Timer = xdc.useModule('ti.sysbios.hal.Timer'); var LoggingSetup = xdc.useModule('ti.uia.sysbios.LoggingSetup'); var LogSnapshot = xdc.useModule('ti.uia.runtime.LogSnapshot'); /* ================ Error configuration ================ */ var Error = xdc.useModule('xdc.runtime.Error'); /* * This function is called to handle all raised errors, but unlike * Error.raiseHook, this function is responsible for completely handling the * error with an appropriately initialized Error_Block. * * Pick one: * - Error.policyDefault (default) * Calls Error.raiseHook with an initialized Error_Block structure and logs * the error using the module's logger. * - Error.policySpin * Simple alternative that traps on a while(1) loop for minimized target * footprint. * Using Error.policySpin, the Error.raiseHook will NOT called. */ Error.policyFxn = Error.policyDefault; //Error.policyFxn = Error.policySpin; /* * If Error.policyFxn is set to Error.policyDefault, this function is called * whenever an error is raised by the Error module. * * Pick one: * - Error.print (default) * Errors are formatted and output via System_printf() for easier * debugging. * - null * Errors are not formatted or logged. This option reduces code footprint. * - non-null function * Errors invoke custom user function. See the Error module documentation * for more details. */ Error.raiseHook = Error.print; //Error.raiseHook = null; //Error.raiseHook = "&myErrorFxn"; /* * If Error.policyFxn is set to Error.policyDefault, this option applies to the * maximum number of times the Error.raiseHook function can be recursively * invoked. This option limits the possibility of an infinite recursion that * could lead to a stack overflow. * The default value is 16. */ Error.maxDepth = 2; var Diags = xdc.useModule('xdc.runtime.Diags'); var Log = xdc.useModule('xdc.runtime.Log'); var Main = xdc.useModule('xdc.runtime.Main'); var System = xdc.useModule('xdc.runtime.System'); var xdc_runtime_Timestamp = xdc.useModule('xdc.runtime.Timestamp'); var HeapMem = xdc.useModule('ti.sysbios.heaps.HeapMem'); //var FatFS = xdc.useModule('ti.sysbios.fatfs.FatFS'); /* ================ Hwi configuration ================ */ var halHwi = xdc.useModule('ti.sysbios.hal.Hwi'); var m3Hwi = xdc.useModule('ti.sysbios.family.arm.m3.Hwi'); /* * Checks for Hwi (system) stack overruns while in the Idle loop. * * Pick one: * - true (default) * Checks the top word for system stack overflows during the idle loop and * raises an Error if one is detected. * - false * Disabling the runtime check improves runtime performance and yields a * reduced flash footprint. */ halHwi.checkStackFlag = true; //halHwi.checkStackFlag = false; /* * The following options alter the system's behavior when a hardware exception * is detected. * * Pick one: * - Hwi.enableException = true * This option causes the default m3Hwi.excHandlerFunc function to fully * decode an exception and dump the registers to the system console. * This option raises errors in the Error module and displays the * exception in ROV. * - Hwi.enableException = false * This option reduces code footprint by not decoding or printing the * exception to the system console. * It however still raises errors in the Error module and displays the * exception in ROV. * - Hwi.excHandlerFunc = null * This is the most aggressive option for code footprint savings; but it * can difficult to debug exceptions. It reduces flash footprint by * plugging in a default while(1) trap when exception occur. This option * does not raise an error with the Error module. */ m3Hwi.enableException = true; //m3Hwi.enableException = false; //m3Hwi.excHandlerFunc = null; /* * Enable hardware exception generation when dividing by zero. * * Pick one: * - 0 (default) * Disables hardware exceptions when dividing by zero * - 1 * Enables hardware exceptions when dividing by zero */ m3Hwi.nvicCCR.DIV_0_TRP = 0; //m3Hwi.nvicCCR.DIV_0_TRP = 1; /* * Enable hardware exception generation for invalid data alignment. * * Pick one: * - 0 (default) * Disables hardware exceptions for data alignment * - 1 * Enables hardware exceptions for data alignment */ m3Hwi.nvicCCR.UNALIGN_TRP = 0; //m3Hwi.nvicCCR.UNALIGN_TRP = 1; /* ================ Idle configuration ================ */ var Idle = xdc.useModule('ti.sysbios.knl.Idle'); /* * The Idle module is used to specify a list of functions to be called when no * other tasks are running in the system. * * Functions added here will be run continuously within the idle task. * * Function signature: * Void func(Void); */ //Idle.addFunc("&myIdleFunc"); /* ================ Clock configuration ================ */ var Clock = xdc.useModule('ti.sysbios.knl.Clock'); /* * Default value is family dependent. For example, Linux systems often only * support a minimum period of 10000 us and multiples of 10000 us. * TI platforms have a default of 1000 us. */ Clock.tickPeriod = 1000; /* ================ System configuration ================ */ var System = xdc.useModule('xdc.runtime.System'); System.extendedFormats = "%$L%$S%$F%f"; /* * The Abort handler is called when the system exits abnormally. * * Pick one: * - System.abortStd (default) * Call the ANSI C Standard 'abort()' to terminate the application. * - System.abortSpin * A lightweight abort function that loops indefinitely in a while(1) trap * function. * - A custom abort handler * A user-defined function. See the System module documentation for * details. */ //System.abortFxn = System.abortStd; /* * The Exit handler is called when the system exits normally. * * Pick one: * - System.exitStd (default) * Call the ANSI C Standard 'exit()' to terminate the application. * - System.exitSpin * A lightweight exit function that loops indefinitely in a while(1) trap * function. * - A custom exit function * A user-defined function. See the System module documentation for * details. */ // System.exitFxn = System.exitStd; /* * Minimize exit handler array in the System module. The System module includes * an array of functions that are registered with System_atexit() which is * called by System_exit(). The default value is 8. */ System.maxAtexitHandlers = 2; /* * The System.SupportProxy defines a low-level implementation of System * functions such as System_printf(), System_flush(), etc. * * Pick one pair: * - SysMin * This module maintains an internal configurable circular buffer that * stores the output until System_flush() is called. * The size of the circular buffer is set via SysMin.bufSize. * - SysCallback * SysCallback allows for user-defined implementations for System APIs. * The SysCallback support proxy has a smaller code footprint and can be * used to supply custom System_printf services. * The default SysCallback functions point to stub functions. See the * SysCallback module's documentation. */ var SysMin = xdc.useModule('xdc.runtime.SysMin'); SysMin.bufSize = 1024; System.SupportProxy = SysMin; //var SysCallback = xdc.useModule('xdc.runtime.SysCallback'); //System.SupportProxy = SysCallback; //SysCallback.abortFxn = "&myUserAbort"; //SysCallback.exitFxn = "&myUserExit"; //SysCallback.flushFxn = "&myUserFlush"; //SysCallback.putchFxn = "&myUserPutch"; //SysCallback.readyFxn = "&myUserReady"; /* ================ Kernel (SYS/BIOS) configuration ================ */ var BIOS = xdc.useModule('ti.sysbios.BIOS'); /* * Enable asserts in the BIOS library. * * Pick one: * - true (default) * Enables asserts for debugging purposes. * - false * Disables asserts for a reduced code footprint and better performance. */ //BIOS.assertsEnabled = false; /* * Specify default heap size for BIOS. */ BIOS.heapSize = 1024*10*2; /* * A flag to determine if xdc.runtime sources are to be included in a custom * built BIOS library. * * Pick one: * - false (default) * The pre-built xdc.runtime library is provided by the respective target * used to build the application. * - true * xdc.runtime library sources are to be included in the custom BIOS * library. This option yields the most efficient library in both code * footprint and runtime performance. */ BIOS.includeXdcRuntime = true; /* * The SYS/BIOS runtime is provided in the form of a library that is linked * with the application. Several forms of this library are provided with the * SYS/BIOS product. * * Pick one: * - BIOS.LibType_Custom * Custom built library that is highly optimized for code footprint and * runtime performance. * - BIOS.LibType_Debug * Custom built library that is non-optimized that can be used to * single-step through APIs with a debugger. * */ BIOS.libType = BIOS.LibType_Custom; /* * Runtime instance creation enable flag. * * Pick one: * - true (default) * Allows Mod_create() and Mod_delete() to be called at runtime which * requires a default heap for dynamic memory allocation. * - false * Reduces code footprint by disallowing Mod_create() and Mod_delete() to * be called at runtime. Object instances are constructed via * Mod_construct() and destructed via Mod_destruct(). */ BIOS.runtimeCreatesEnabled = true; //BIOS.runtimeCreatesEnabled = false; /* * Enable logs in the BIOS library. * * Pick one: * - true (default) * Enables logs for debugging purposes. * - false * Disables logging for reduced code footprint and improved runtime * performance. */ //BIOS.logsEnabled = false; /* ================ Memory configuration ================ */ var Memory = xdc.useModule('xdc.runtime.Memory'); /* * The Memory module itself simply provides a common interface for any * variety of system and application specific memory management policies * implemented by the IHeap modules(Ex. HeapMem, HeapBuf). */ /* ================ Task configuration ================ */ var Task = xdc.useModule('ti.sysbios.knl.Task'); /* * Check task stacks for overflow conditions. * * Pick one: * - true (default) * Enables runtime checks for task stack overflow conditions during * context switching ("from" and "to") * - false * Disables runtime checks for task stack overflow conditions. */ Task.checkStackFlag = true; //Task.checkStackFlag = false; /* * Set the default task stack size when creating tasks. * * The default is dependent on the device being used. Reducing the default stack * size yields greater memory savings. */ Task.defaultStackSize = 512; /* * Enables the idle task. * * Pick one: * - true (default) * Creates a task with priority of 0 which calls idle hook functions. This * option must be set to true to gain power savings provided by the Power * module. * - false * No idle task is created. This option consumes less memory as no * additional default task stack is needed. * To gain power savings by the Power module without having the idle task, * add Idle.run as the Task.allBlockedFunc. */ Task.enableIdleTask = true; //Task.enableIdleTask = false; //Task.allBlockedFunc = Idle.run; /* * If Task.enableIdleTask is set to true, this option sets the idle task's * stack size. * * Reducing the idle stack size yields greater memory savings. */ Task.idleTaskStackSize = 512; /* * Reduce the number of task priorities. * The default is 16. * Decreasing the number of task priorities yield memory savings. */ Task.numPriorities = 16; /* ================ Semaphore configuration ================ */ var Semaphore = xdc.useModule('ti.sysbios.knl.Semaphore'); /* * Enables global support for Task priority pend queuing. * * Pick one: * - true (default) * This allows pending tasks to be serviced based on their task priority. * - false * Pending tasks are services based on first in, first out basis. * * When using BIOS in ROM: * This option must be set to false. */ Semaphore.supportsPriority = true; //Semaphore.supportsPriority = false; /* * Allows for the implicit posting of events through the semaphore, * disable for additional code saving. * * Pick one: * - true * This allows the Semaphore module to post semaphores and events * simultaneously. * - false (default) * Events must be explicitly posted to unblock tasks. * */ //Semaphore.supportsEvents = true; /* ================ Text configuration ================ */ var Text = xdc.useModule('xdc.runtime.Text'); /* * These strings are placed in the .const section. Setting this parameter to * false will save space in the .const section. Error, Assert and Log messages * will print raw ids and args instead of a formatted message. * * Pick one: * - true (default) * This option loads test string into the .const for easier debugging. * - false * This option reduces the .const footprint. */ Text.isLoaded = true; //Text.isLoaded = false; /* ================ TI-RTOS drivers' configuration ================ */ var driversConfig = xdc.useModule('ti.drivers.Config'); /* * Include TI-RTOS drivers * * Pick one: * - driversConfig.LibType_NonInstrumented (default) * Use TI-RTOS drivers library optimized for footprint and performance * without asserts or logs. * - driversConfig.LibType_Instrumented * Use TI-RTOS drivers library for debugging with asserts and logs enabled. */ //driversConfig.libType = driversConfig.LibType_Instrumented; /* =========== Instrumentation configuration =========== */ /* Deactivate RTOS assertions */ BIOS.assertsEnabled = false; /* Deactivate assertions and logging for drivers */ driversConfig.libType = driversConfig.LibType_NonInstrumented; /* Add hooks for UIA to monitor task creation and task switches */ Task.addHookSet ({ createFxn: '&tskCreateHook', }); LoggingSetup.snapshotLogging = true /* ================ NDK configuration ================ */ var Ndk = xdc.loadPackage('ti.ndk.config'); var Global = xdc.useModule('ti.ndk.config.Global'); var Ip = xdc.useModule('ti.ndk.config.Ip'); var Tcp = xdc.useModule('ti.ndk.config.Tcp'); Tcp.transmitBufSize = 16384; Tcp.receiveBufSize = 65536; Tcp.receiveBufLimit = 65536; Global.ndkTickPeriod = 100; Global.kernTaskPriLevel = 11; Global.serviceReportHook = null; Global.IPv6 = false; /* Settings for static IP configuration */ Ip.ResolveIP = false; Ip.CallByIP = false; Ip.autoIp = false; Ip.address = "192.168.178.99"; Ip.mask = "255.255.255.0"; Ip.gatewayIpAddr = "192.168.178.1";
Code:
#define TCPPACKETSIZE 255 extern int inet_addr(const char *str); int setup_Network_Task(int prio, uint32_t wait_ticks) { Task_Params taskParams; Task_Handle task; Error_Block eb; Error_init(&eb); Task_Params_init(&taskParams); taskParams.stackSize = 1024; taskParams.priority = prio; taskParams.arg0 = (UArg)wait_ticks; task = Task_create((Task_FuncPtr)networkFxn, &taskParams, &eb); if(task == NULL) { System_abort("Task create failed"); } return (0); } static int tryCounter = 0; void networkFxn(UArg arg0) { uint32_t wait_ticks = (uint32_t) arg0; SOCKET clientfd; struct sockaddr_in sLocalAddr; int nbytes; bool flag = true; char *buffer; Error_Block eb; clientfd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP); if (clientfd < 0) { if(DEBUG) { System_printf("tcpHandler: socket failed\n"); System_flush(); } Task_exit(); return; } if(DEBUG) { System_printf("socket success\n"); System_flush(); } memset((char *)&sLocalAddr, 0, sizeof(sLocalAddr)); sLocalAddr.sin_family = AF_INET; // sLocalAddr.sin_len = sizeof(sLocalAddr); sLocalAddr.sin_addr.s_addr = inet_addr("192.168.178.170"); sLocalAddr.sin_port = htons(11000); Task_sleep(2000); int connectStatus = connect(clientfd, (struct sockaddr *)&sLocalAddr, sizeof(sLocalAddr)); if(DEBUG) { System_printf("Connection status: %d \n", connectStatus); System_flush(); } if(connectStatus < 0) { if(DEBUG) { System_printf("Connection failed %d \n", fdError()); System_flush(); } if(tryCounter > 5) { Task_exit(); return; } tryCounter++; Task_sleep(1000); networkFxn(wait_ticks); } if (DEBUG) { System_printf("Connected!\n"); System_flush(); } fdOpenSession(TaskSelf()); if (DEBUG) { System_printf("tcpWorker: start clientfd = 0x%x\n", clientfd); System_flush(); } /* Make sure Error_Block is initialized */ Error_init(&eb); /* Get a buffer to receive incoming packets. Use the default heap. */ buffer = Memory_alloc(NULL, TCPPACKETSIZE, 0, &eb); if (buffer == NULL) { if (DEBUG) { System_printf("tcpWorker: failed to alloc memory\n"); System_flush(); } Task_exit(); } /* Loop while we receive data */ while (flag) { nbytes = recv(clientfd, (char *)buffer, TCPPACKETSIZE, 0); if (nbytes > 0) { /* Echo the data back */ nbytes = 15; char *sendBuffer = "I like turtles."; send(clientfd, (char *)sendBuffer, sizeof(sendBuffer), 0 ); } else { fdClose(clientfd); flag = false; } Task_sleep(wait_ticks); } if(DEBUG) { System_printf("tcpWorker stop clientfd = 0x%x\n", clientfd); System_flush(); } /* Free the buffer back to the heap */ Memory_free(NULL, buffer, TCPPACKETSIZE); fdCloseSession(TaskSelf()); /* * Since deleteTerminatedTasks is set in the cfg file, * the Task will be deleted when the idle task runs. */ Task_exit(); }
Basically the connect gets me -1 and fdError() gives me -1 too, I m not sure what -1 means because the doc describes:
" If it succeeds, the function returns 0. Otherwise, a value of -1 is returned and the function fdError() can be called to determine the error:"
I m unsure what I m doing wrong, what is missing.