Tcp::Tcp() { socketInit(); errno = 0; _socket = socket(AF_INET, SOCK_STREAM, 0); #ifndef NDEBUG char optval = 1; setsockopt(_socket, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval); log::debug << "Socket set to reusse addr" << log::endl; #endif if (_socket == -1) throw std::runtime_error(strerror(errno)); }
/** * \brief Main application function. * * Initializing the board and connect to wireless router. * And event handling the Wi-Fi and SW timer. */ int main(void) { tstrWifiInitParam param; int8_t ret; /* Initialize the board. */ system_init(); /* Initialize the UART console. */ configure_console(); /* Initialize the Timer. */ configure_timer(); /* Initialize the HTTP client service. */ configure_http_client(); /* Initialize the BSP. */ nm_bsp_init(); /* Output example information */ printf(STRING_HEADER); /* Initialize Wi-Fi driver with data and Wi-Fi status callbacks. */ param.pfAppWifiCb = wifi_callback; /* Set Wi-Fi event callback. */ ret = m2m_wifi_init(¶m); if (M2M_SUCCESS != ret) { printf("main: m2m_wifi_init call error!(%d)\r\n", ret); while (1) { /* Loop forever. */ } } /* Initialize Socket module */ socketInit(); registerSocketCallback(socket_event_handler, socket_resolve_handler); /* Connect to router. */ ret = m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL); if (M2M_SUCCESS != ret) { printf("main: failed to connect access point!\r\n"); while (1) { } } while (1) { /* Handle pending events from network controller. */ m2m_wifi_handle_events(NULL); /* Checks the timer timeout. */ sw_timer_task(&swt_module_inst); } }
/** * \brief Main application function. * * Application entry point. * * \return program return value. */ int main(void) { tstrWifiInitParam param; int8_t ret; /* Initialize the board. */ system_init(); /* Initialize the UART console. */ configure_console(); printf(STRING_HEADER); /* Initialize the BSP. */ nm_bsp_init(); /* Initialize Wi-Fi parameters structure. */ memset((uint8_t *)¶m, 0, sizeof(tstrWifiInitParam)); /* Initialize Wi-Fi driver with data and status callbacks. */ param.pfAppWifiCb = wifi_cb; ret = m2m_wifi_init(¶m); if (M2M_SUCCESS != ret) { printf("main: m2m_wifi_init call error!(%d)\r\n", ret); while (1) { } } /* Initialize Socket module */ socketInit(); registerSocketCallback(socket_cb, resolve_cb); /* Connect to router. */ m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL); while (1) { m2m_wifi_handle_events(NULL); if (gbConnectedWifi && gbHostIpByName) { if (gu8SocketStatus == SocketInit) { if (tcp_client_socket < 0) { gu8SocketStatus = SocketWaiting; if (sslConnect() != SOCK_ERR_NO_ERROR) { gu8SocketStatus = SocketInit; } } } } } return 0; }
void OsSocket::getHostIp(UtlString* hostAddress) { socketInit(); UtlString thisHost; #ifdef _VXWORKS /* [ */ char ipAddr[100]; ipAddr[0] = '\0'; hostAddress->remove(0); if(!ifAddrGet("csp0", ipAddr)) hostAddress->append(ipAddr); #elif defined(__pingtel_on_posix__) /* ] [ */ #ifdef __linux__ char ipAddr[100]; unsigned int ip_int = ntohl(getExternalHostAddressLinux()); sprintf(ipAddr, "%d.%d.%d.%d", ip_int >> 24, (ip_int >> 16) & 255, (ip_int >> 8) & 255, ip_int & 255); hostAddress->remove(0); hostAddress->append(ipAddr); #else getHostName(&thisHost); getHostIpByName(thisHost.data(), hostAddress); #endif /* __linux__ */ #elif defined(_WIN32) /* ] [ */ unsigned long address_val = OsSocket::getDefaultBindAddress(); if (address_val == htonl(INADDR_ANY)) { getHostName(&thisHost); getHostIpByName(thisHost.data(), hostAddress); } else { struct in_addr in; char tmp[50]; in.S_un.S_addr = address_val; strcpy(tmp,inet_ntoa(in)); *hostAddress = tmp; } #else /* ] [ */ #error Unsupported target platform. #endif /* ] */ thisHost.remove(0); }
status_t HeadSetDetect::init() { int state = readStateFromFile(); if(state == -1) return NO_INIT; bool on= headsetConnect(state); if(mOn != on) { mCblk(mObserver,on); mOn = on; } if(!socketInit()) return NO_INIT; return NO_ERROR; }
int main(int argc, char *argv[]) { pthread_t pth; socketInit(); pthread_create(&pth, NULL, socketListener, 0); //usleep(10000000); while (1) { printf("I'm alive!\n"); fflush(stdout); usleep(5000000); } return 0; }
int main(int argc, char const *argv[]) { unsigned short port; int listenfd, connfd; char send_buf[BUFLEN]; time_t ticks; if (argc != 2) { if (argc == 1) { port = DEFAULT_PORT; printf("Using default port %d\n", port); } else { printf("Usage: %s <port>\n", argv[0]); exit(EXIT_FAILURE); } } else { port = atoi(argv[1]); } listenfd = socketInit(port); // Main loop for(EVER) { // Accept a client from the listening fd if ((connfd = accept(listenfd, NULL, NULL)) < 0) { printf("ERROR: Accept client error\n"); close(listenfd); exit(EXIT_FAILURE); } ticks = time(NULL); //sprintf(send_buf, "%.24s\n", ctime(&ticks)); snprintf(send_buf, sizeof(send_buf), "%.24s\n", ctime(&ticks)); write(connfd, send_buf, strlen(send_buf)); close(connfd); } close(listenfd); return 0; }
int WiFiClass::init() { tstrWifiInitParam param; int8_t ret; // Initialize the WiFi BSP: nm_bsp_init(); // Initialize WiFi module and register status callback: param.pfAppWifiCb = wifi_cb; ret = m2m_wifi_init(¶m); if (M2M_SUCCESS != ret) { // Error led ON (rev A then rev B). m2m_periph_gpio_set_val(M2M_PERIPH_GPIO18, 0); m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO6, 1); return ret; } // Initialize socket API and register socket callback: socketInit(); socketBufferInit(); registerSocketCallback(socketBufferCb, resolve_cb); _init = 1; _status = WL_IDLE_STATUS; _localip = 0; _submask = 0; _gateway = 0; _dhcp = 1; memset(_client, 0, sizeof(WiFiClient *) * TCP_SOCK_MAX); // Initialize IO expander LED control (rev A then rev B).. m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 1); m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); m2m_periph_gpio_set_val(M2M_PERIPH_GPIO18, 1); m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO15, 1); m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO16, 1); m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO18, 1); m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 1); m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); m2m_periph_gpio_set_val(M2M_PERIPH_GPIO6, 1); m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO4, 1); m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO5, 1); m2m_periph_gpio_set_dir(M2M_PERIPH_GPIO6, 1); return ret; }
RoomListDialog::RoomListDialog(QWidget *parent) : QDialog(parent), ui(new Ui::RoomListDialog), dataPort_(0), msgPort_(0), historySize_(0), socket(nullptr), newRoomWindow(new NewRoomWindow(this)) { ui->setupUi(this); connect(ui->pushButton_4,&QPushButton::clicked, this, &RoomListDialog::reject); connect(ui->pushButton_4,&QPushButton::clicked, this, &RoomListDialog::saveNick); connect(ui->pushButton_3,&QPushButton::clicked, this, &RoomListDialog::requestRoomList); connect(ui->pushButton_2,&QPushButton::clicked, this, &RoomListDialog::requestJoin); connect(ui->tableWidget,&QTableWidget::cellDoubleClicked, this,&RoomListDialog::requestJoin); connect(ui->checkBox, &QCheckBox::clicked, this,&RoomListDialog::filterRoomList); connect(ui->pushButton, &QPushButton::clicked, newRoomWindow, &NewRoomWindow::show); connect(newRoomWindow, &NewRoomWindow::newRoom, this,&RoomListDialog::requestNewRoom); connect(newRoomWindow, &NewRoomWindow::finished, this,&RoomListDialog::requestRoomList); connect(&Singleton<CommandSocket>::instance(), &CommandSocket::connected, this, &RoomListDialog::onCmdServerConnected); connect(&Singleton<CommandSocket>::instance(), &CommandSocket::newData, this, &RoomListDialog::onCmdServerData); tableInit(); socketInit(); timer = new QTimer(this); connect(timer,&QTimer::timeout, this,&RoomListDialog::requestRoomList); timer->start(10000); loadNick(); clientId_ = loadClientId(); }
UtlBoolean OsSocket::getHostIpByName(const char* hostName, UtlString* hostAddress) { UtlBoolean bSuccess = FALSE; struct hostent* server; socketInit(); // If this is aleady an IP address if (isIp4Address(hostName)) { *hostAddress = hostName; bSuccess = TRUE ; } else if (strcmp(hostName, "localhost") == 0) { *hostAddress = "127.0.0.1"; bSuccess = TRUE ; } // if no default domain name and host name not fully qualified else if (!hasDefaultDnsDomain() && (strchr(hostName, '.') == NULL)) { *hostAddress = "0.0.0.0"; } else { #if defined(_WIN32) || defined(__pingtel_on_posix__) server = gethostbyname(hostName); #else #error Unsupported target platform. #endif if(server) { inet_ntoa_pt(*((in_addr*) (server->h_addr)), *hostAddress); bSuccess = TRUE ; } else { *hostAddress = "0.0.0.0"; } } return bSuccess ; }
error_t tcpIpStackInit(void) { error_t error; uint_t i; OsTask *task; //Memory pool initialization error = memPoolInit(); //Any error to report? if(error) return error; //Clear configuration data for each interface memset(netInterface, 0, sizeof(netInterface)); //Loop through network interfaces for(i = 0; i < NET_INTERFACE_COUNT; i++) { //Default interface identifier netInterface[i].identifier = i; //Default name sprintf(netInterface[i].name, "eth%u", i); } //Socket related initialization error = socketInit(); //Any error to report? if(error) return error; //Create task to handle periodic operations task = osTaskCreate("TCP/IP Stack (Tick)", tcpIpStackTickTask, NULL, TCP_IP_TICK_STACK_SIZE, TCP_IP_TICK_PRIORITY); //Unable to create the task? if(task == OS_INVALID_HANDLE) return ERROR_OUT_OF_RESOURCES; //The handle can be used for further referencing for(i = 0; i < NET_INTERFACE_COUNT; i++) netInterface[i].tickTask = task; //Return status code return error; }
/** * @brief Initializes mcu sockets layer */ bool winc1500_socket_layer_init(void) { int i; if (!cb_registered) { socketInit(); registerSocketCallback(socket_layer_cb, NULL); cb_registered = true; for (i=0; i<NO_OF_SOCKETS; ++i) sockets[i].sock = -1; } /* if (!winc1500_is_wifi_connected()) */ /* return false; */ if (winc1500_is_socket_layer_active()) return true; return false; }
/// Call just before returning to idle loop. This checks for errors and tries to recover. Returns true if no errors. bool net_cc3000_checkError(JsNetwork *net) { bool hadErrors = false; while (jspIsInterrupted()) { hadErrors = true; jsiConsolePrint("CC3000 WiFi is not responding. Power cycling...\n"); jspSetInterrupted(false); // remove all existing connections networkState = NETWORKSTATE_OFFLINE; // ensure we don't try and send the CC3k anything socketKill(net); socketInit(); // power cycle JsVar *wlan = jsvObjectGetChild(execInfo.hiddenRoot, CC3000_OBJ_NAME, 0); if (wlan) { jswrap_wlan_reconnect(wlan); jsvUnLock(wlan); } else jsExceptionHere(JSET_INTERNALERROR, "No CC3000 object!\n"); // jswrap_wlan_reconnect could fail, which would mean we have to do this all over again } return hadErrors; }
/** * \brief Main application function. * * Application entry point. * * \return program return value. */ int main(void) { tstrWifiInitParam param; int8_t ret; init_state(); /* Initialize the board. */ sysclk_init(); board_init(); /* Initialize the UART console. */ configure_console(); printf(STRING_HEADER); printf("This example may not work as it requires internet connectivity.\r\n"); /* Initialize the Timer. */ configure_timer(); /* Initialize the HTTP client service. */ configure_http_client(); /* Initialize the BSP. */ nm_bsp_init(); /* Initialize SD/MMC storage. */ init_storage(); /* Initialize Wi-Fi parameters structure. */ memset((uint8_t *)¶m, 0, sizeof(tstrWifiInitParam)); /* Initialize Wi-Fi driver with data and status callbacks. */ param.pfAppWifiCb = wifi_cb; ret = m2m_wifi_init(¶m); if (M2M_SUCCESS != ret) { printf("main: m2m_wifi_init call error!(%d)\r\n", ret); while (1) { } } /* Initialize socket module. */ socketInit(); /* Register socket callback function. */ registerSocketCallback(socket_cb, resolve_cb); /* Connect to router. */ printf("main: Waiting for Wi-Fi connection. AP:%s\r\n", (char *)MAIN_WLAN_SSID); m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL); while (!(is_state_set(COMPLETED) || is_state_set(CANCELED))) { /* Handle pending events from network controller. */ m2m_wifi_handle_events(NULL); /* Checks the timer timeout. */ sw_timer_task(&swt_module_inst); } printf("main: Exit program. Please unplug the card.\r\n"); while (1) { } /* Loop forever. */ return 0; }
/** * \brief Main application function. * * Initialize system, UART console, network then start function of UDP socket. * * \return program return value. */ int main(void) { tstrWifiInitParam param; int8_t ret; struct sockaddr_in addr; /* Initialize the board. */ sysclk_init(); board_init(); /* Initialize the UART console. */ configure_console(); printf(STRING_HEADER); /* Initialize the BSP. */ nm_bsp_init(); /* Initialize socket address structure. */ addr.sin_family = AF_INET; addr.sin_port = _htons(MAIN_WIFI_M2M_SERVER_PORT); addr.sin_addr.s_addr = _htonl(MAIN_WIFI_M2M_SERVER_IP); /* Initialize Wi-Fi parameters structure. */ memset((uint8_t *)¶m, 0, sizeof(tstrWifiInitParam)); /* Initialize Wi-Fi driver with data and status callbacks. */ param.pfAppWifiCb = wifi_cb; ret = m2m_wifi_init(¶m); if (M2M_SUCCESS != ret) { printf("main: m2m_wifi_init call error!(%d)\r\n", ret); while (1) { } } /* Initialize socket module */ socketInit(); registerSocketCallback(socket_cb, NULL); /* Connect to router. */ m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL); packetCnt = 0; while (1) { if (packetCnt >= MAIN_WIFI_M2M_PACKET_COUNT) { printf("UDP Server test Complete!\r\n"); close(rx_socket); rx_socket = -1; break; } m2m_wifi_handle_events(NULL); if (wifi_connected == M2M_WIFI_CONNECTED) { /* Create socket for Rx UDP */ if (rx_socket < 0) { if ((rx_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { printf("main : failed to create RX UDP Client socket error!\r\n"); continue; } /* Socket bind */ bind(rx_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)); } } } return 0; }
void main( void ) { u8 i, ucChar, *ucEeproms, ucBuffer[ 40 ]; sysInit(); socketInit(); rfInit(); print( COM3, "\rV2 RFID: 0x%X", socketGetID()); //mpl115a2Init( TX1, RX1, NONE, NONE ); //print( COM3, "\rPressure: %f", mpl115a2ReadkPa() ); //print( COM3, "\rTemp: %f", mpl115a2ReadTemp() ); //i2cConfig( &globalGasSensorDigipot, DIGIPOT_BASEADDRESS|3, TX1, RX1, I2CSPEEDFAST ); //digipotSetWiper( &globalGasSensorDigipot, 2, 0 ); //eepromOpen( 0x2F, TX1, RX1, NONE ); //eepromPutString( 0, "Test" ); pinConfig( MCO, OUT ); pinSet( MCO, HIGH ); gasSensorInit(); //print( COM3, "\rGas Sensor: %f", gasSensorRead() ); //gasSensorSetGain( 0,0 ); //print( COM3, "\rGas Sensor: %f", gasSensorRead() ); //gasSensorSetGain( 200,200 ); //print( COM3, "\rGas Sensor: %f", gasSensorRead() ); //eepromGetBuffer( 0, ucBuffer, len( "test" ) ); //print( COM3, "\rEeprom: ucBuffer ); //print( COM3, "\rEEPROM Direct Read: " ); /*for( i = 0; i < len( "test" ); i++ ){ ucChar = eepromGetChar( i ); if( isAlphaOrNumeric( ucChar ) ) { print( COM3, "%c", ucChar ); } else{ print( COM3, "(%d)", ucChar );//ucBuffer, len( "humidity" ) ); } // else } // for */ /* // Test for LCD code if( isStringSame( ucBuffer, "<shield lcd>" ) ){ print( COM3, "\rLCD Shield Detected" ); fileOpenResource( &fileFont, (u8*)PYGMY_orbitron18 ); fontLoad( &fileFont, &fontOrbitron18 ); fontSetAll( &fontOrbitron18 ); pinConfig( A0, PULLUP ); pinConfig( D3, PULLUP ); pinConfig( TA0, PULLUP ); pinConfig( DAC1, PULLUP ); pinConfig( DAC2, PULLUP ); pinConfig( TX2, PULLUP ); pinConfig( RX2, PULLUP ); drawMainMenu(); } else{ hih5030Init( A2, A3 ); } // else */ //taskNewSimple( "humidity", 1000, (void*)threadRFHumiditySave ); //gemInit(); //fileOpen( &pygmyFile, "picon128", READ ); //drawImage( 0,0, &pygmyFile, 0 ); /*ucBuffer = sysAllocate( 5 ); copyString( "Test", ucBuffer ); ucBuffer = sysReallocate( ucBuffer, 20 ); appendString( "ThisToo", ucBuffer ); print( COM3, "\rTest String: %s", ucBuffer );*/ //pinConfig( SHIELD_CENTER, PULLUP ); //pinInterrupt( gemClickMenu, SHIELD_CENTER, TRIGGER_RISING|TRIGGER_FALLING ); //drawRect( 0, 20, 127, 40, VISIBLE|BORDER|ROUNDED, 8); //gemDrawMenu(); //drawWidget( &btnOK ); //gemInit(); //sysFree( ucBuffer ); //fileOpen( &pygmyFile, "jpeg", READ ); //drawJPEG( &pygmyFile, 0, 0 ); //drawPNG( &pygmyFile, 0, 0 ); /*mstatsTemp mstats(); print( COM3, "\rbytes_total: %d", bytes_total ); print( COM3, "\rchunks_used: %d", chunks_used ); print( COM3, "\rbytes_used: %d", bytes_used ); print( COM3, "\rchunks_free: %d", chunks_free ); print( COM3, "\rbytes_free: %d", bytes_free );*/ while(1){;} }
/** * \brief Main application function. * * Initialize system, UART console, network then start time client. * * \return Program return value. */ int main(void) { tstrWifiInitParam param; int8_t ret; struct sockaddr_in addr_in; /* Initialize the board. */ system_init(); /* Initialize the UART console. */ configure_console(); printf(STRING_HEADER); /* Initialize the BSP. */ nm_bsp_init(); /* Initialize Wi-Fi parameters structure. */ memset((uint8_t *)¶m, 0, sizeof(tstrWifiInitParam)); /* Initialize Wi-Fi driver with data and status callbacks. */ param.pfAppWifiCb = wifi_cb; ret = m2m_wifi_init(¶m); if (M2M_SUCCESS != ret) { printf("main: m2m_wifi_init call error!(%d)\r\n", ret); while (1) { } } /* Turn LED0 off initially. */ port_pin_set_output_level(LED_0_PIN, true); /* Initialize Socket module */ socketInit(); /* Register socket handler, resolve handler */ registerSocketCallback(socket_cb, resolve_cb); /* Connect to router. */ m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL); while (1) { /* Handle pending events from network controller. */ m2m_wifi_handle_events(NULL); if (gbConnectedWifi) { /* * Create the socket for the first time. */ if (udp_socket < 0) { udp_socket = socket(AF_INET, SOCK_DGRAM, 0); if (udp_socket < 0) { printf("main: UDP Client Socket Creation Failed.\r\n"); continue; } /* Initialize default socket address structure. */ addr_in.sin_family = AF_INET; addr_in.sin_addr.s_addr = _htonl(MAIN_DEFAULT_ADDRESS); addr_in.sin_port = _htons(MAIN_DEFAULT_PORT); bind(udp_socket, (struct sockaddr *)&addr_in, sizeof(struct sockaddr_in)); } } } return 0; }
// Constructor OsMulticastSocket::OsMulticastSocket(int multicastPortNum, const char* multicastHost, int localHostPortNum, const char* localHost) { int error = 0; struct sockaddr_in localAddr; struct hostent* server = NULL; int iTmp = TRUE; socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; localHostPort = localHostPortNum; if(localHost) { localHostName.append(localHost); } remoteHostPort = multicastPortNum; if(multicastHost) { remoteHostName.append(multicastHost); } if(!socketInit()) { goto EXIT; } # ifdef _VXWORKS char hostentBuf[512]; # endif // Create the socket socketDescriptor = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if(socketDescriptor == OS_INVALID_SOCKET_DESCRIPTOR) { error = OsSocketGetERRNO(); close(); perror("call to socket failed in OsMulticastSocket::OsMulticastSocket\n"); osPrintf("socket call failed with error in OsMulticastSocket::OsMulticastSocket: 0x%x\n", error); goto EXIT; } /* avoid EADDRINUSE error on bind() */ iTmp = TRUE; if(setsockopt(socketDescriptor, SOL_SOCKET, SO_REUSEADDR, (char *)&iTmp, sizeof(iTmp))) { error = OsSocketGetERRNO(); close(); perror("call to setsockopt failed\n"); osPrintf("setsockopt SO_REUSEADDR call failed with error: %d\n", error); goto EXIT; } localAddr.sin_family = AF_INET; localAddr.sin_port = htons(multicastPortNum); if(localHost == NULL) { localAddr.sin_addr.s_addr=OsSocket::getDefaultBindAddress(); // localAddr.sin_addr.s_addr=htonl(INADDR_ANY); // Allow IP in on // any of this hosts addresses or NICs. } else { // Should use host address specified, for now use any localAddr.sin_addr.s_addr=OsSocket::getDefaultBindAddress(); // localAddr.sin_addr.s_addr=htonl(INADDR_ANY); // Allow IP in on // any of this hosts addresses or NICs. } # if defined(_WIN32) error = bind( socketDescriptor, (const struct sockaddr*) &localAddr, sizeof(localAddr)); # elif defined(_VXWORKS) || defined(__pingtel_on_posix__) error = bind( socketDescriptor, (struct sockaddr*) &localAddr, sizeof(localAddr)); # else # error Unsupported target platform. # endif if(error == OS_INVALID_SOCKET_DESCRIPTOR) { // error = OsSocketGetERRNO(); close(); // perror("bind to socket failed\n"); goto EXIT; } // Setup multicast options # if defined(_WIN32) || defined(__pingtel_on_posix__) server = gethostbyname(multicastHost); # elif defined(_VXWORKS) server = resolvGetHostByName((char*) multicastHost, hostentBuf, sizeof(hostentBuf)); # else # error Unsupported target platform. # endif //_VXWORKS if(server == NULL) { error = OsSocketGetERRNO(); close(); perror("call to gethostbyname failed\n"); osPrintf("gethostbyname(%s) call failed with error: %d\n",multicastHost, error); goto EXIT; } struct ip_mreq mreq; mreq.imr_multiaddr = *((in_addr*) (server->h_addr)); mreq.imr_interface.s_addr = OsSocket::getDefaultBindAddress(); // mreq.imr_interface.s_addr = htonl(INADDR_ANY); if(setsockopt(socketDescriptor, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*) &mreq, sizeof(mreq))) { error = OsSocketGetERRNO(); close(); perror("call to setsockopt failed\n"); osPrintf("setsockopt call failed with error: %d\n", error); goto EXIT; } joinMulticast(multicastPortNum, multicastHost); EXIT: ; }
/** * \brief Main application function. * * Initialize system, UART console, network then start function of SMTP email client. * * \return Program return value. */ int main(void) { tstrWifiInitParam param; int8_t ret; /* Initialize the board. */ system_init(); /* Initialize the UART console. */ configure_console(); printf(STRING_HEADER); /* Initialize the BSP. */ nm_bsp_init(); /* Initialize Wi-Fi parameters structure. */ memset((uint8_t *)¶m, 0, sizeof(tstrWifiInitParam)); /* Initialize Wi-Fi driver with data and status callbacks. */ param.pfAppWifiCb = wifi_cb; ret = m2m_wifi_init(¶m); if (M2M_SUCCESS != ret) { printf("main: m2m_wifi_init call error!(%d)\r\n", ret); while (1) { } } /* Initialize Socket module */ socketInit(); registerSocketCallback(socket_cb, resolve_cb); /* Connect to router. */ m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL); while (1) { m2m_wifi_handle_events(NULL); if (gbConnectedWifi && gbHostIpByName) { if (gu8SocketStatus == SocketInit) { if (tcp_client_socket < 0) { gu8SocketStatus = SocketWaiting; if (smtpConnect() != SOCK_ERR_NO_ERROR) { gu8SocketStatus = SocketInit; } } } else if (gu8SocketStatus == SocketConnect) { gu8SocketStatus = SocketWaiting; if (smtpStateHandler() != MAIN_EMAIL_ERROR_NONE) { if (gs8EmailError == MAIN_EMAIL_ERROR_INIT) { gu8SocketStatus = SocketError; } else { close_socket(); break; } } } else if (gu8SocketStatus == SocketComplete) { printf("main: Email was successfully sent.\r\n"); port_pin_set_output_level(LED_0_PIN, false); close_socket(); break; } else if (gu8SocketStatus == SocketError) { if (gu8RetryCount < MAIN_RETRY_COUNT) { gu8RetryCount++; printf("main: Waiting to connect server.(30 seconds)\r\n\r\n"); retry_smtp_server(); } else { printf("main: Failed retry to server. Press reset your board.\r\n"); gu8RetryCount = 0; close_socket(); break; } } } } return 0; }
/*JSON{ "type" : "init", "generate" : "jswrap_net_init" }*/ void jswrap_net_init() { socketInit(); }
/** * \brief Main application function. * * Application entry point. * * \return program return value. */ int main(void) { tstrWifiInitParam param; int8_t ret; char topic[strlen(MAIN_CHAT_TOPIC) + MAIN_CHAT_USER_NAME_SIZE + 1]; /* Initialize the board. */ system_init(); /* Initialize the UART console. */ configure_console(); /* Output example information */ printf(STRING_HEADER); /* Initialize the Timer. */ configure_timer(); /* Initialize the MQTT service. */ configure_mqtt(); /* Initialize the BSP. */ nm_bsp_init(); /* Setup user name first */ printf("Enter the user name (Max %d characters)\r\n", MAIN_CHAT_USER_NAME_SIZE); scanf("%64s", mqtt_user); printf("User : %s\r\n", mqtt_user); sprintf(topic, "%s%s", MAIN_CHAT_TOPIC, mqtt_user); /* Initialize Wi-Fi parameters structure. */ memset((uint8_t *)¶m, 0, sizeof(tstrWifiInitParam)); /* Initialize Wi-Fi driver with data and status callbacks. */ param.pfAppWifiCb = wifi_callback; /* Set Wi-Fi event callback. */ ret = m2m_wifi_init(¶m); if (M2M_SUCCESS != ret) { printf("main: m2m_wifi_init call error!(%d)\r\n", ret); while (1) { /* Loop forever. */ } } /* Initialize socket interface. */ socketInit(); registerSocketCallback(socket_event_handler, socket_resolve_handler); /* Connect to router. */ m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL); while (1) { /* Handle pending events from network controller. */ m2m_wifi_handle_events(NULL); /* Try to read user input from USART. */ usart_read_job(&cdc_uart_module, &uart_ch_buffer); /* Checks the timer timeout. */ sw_timer_task(&swt_module_inst); /* Checks the USART buffer. */ check_usart_buffer(topic); } }
void main(int argc, char **argv) { ULONG ulSignal; debugInit(); xplInit(); if ( !_getOpt( argc, argv ) ) { debugDone(); xplDone(); exit( 1 ); } if ( !logInit() || !socketInit() || !sqInit() || !dfInit() || !reqInit() || !statInit() || !ifsockInit() ) { puts( "Initialization failed." ); debugDone(); xplDone(); exit( 2 ); } ifpipeInit(); if ( pConfig->fWeaselLogPipe ) weaselInit( pConfig->fWeaselLogToScreen ); signal( SIGINT, sigBreak ); signal( SIGTERM, sigBreak ); sqSetTimer( SIG_CLEANING, 1000 * 3 ); // Internal data clean up. sqSetTimer( SIG_LISTS_STORE, 1000 * 60 * 2 ); // Save data files. sqSetTimer( SIG_POSTPONDED_BACKUP, 1000 ); // Delayed rename tasks. while( ( ulSignal = sqWait() ) != SIG_SHUTDOWN ) { switch( ulSignal ) { case SIG_CLEANING: reqClean(); break; case SIG_LISTS_STORE: reqStoreLists(); break; case SIG_POSTPONDED_BACKUP: dfExecPostpond( FALSE ); break; case SIG_RECONFIGURE: cfgReconfigure(); reqReconfigured(); break; } weaselListenLog(); } weaselDone(); reqStoreLists(); statDone(); socketDone(); // Closes sockets ==> cancel waits... reqDone(); ifpipeDone(); ifsockDone(); dfDone(); sqDone(); logDone(); cfgDone(); debugDone(); xplDone(); #ifdef DEBUG_FILE puts( "Done." ); #endif }
// Constructor OsDatagramSocket::OsDatagramSocket(int remoteHostPortNum, const char* remoteHost, int localHostPortNum, const char* localHost) : mNumTotalWriteErrors(0), mNumRecentWriteErrors(0), mSimulatedConnect(FALSE) // Simulated connection is off until // activated in doConnect. { Os::Logger::instance().log(FAC_SIP, PRI_DEBUG, "OsDatagramSocket::_ attempt %s:%d" ,remoteHost != NULL ? remoteHost : "[null]", remoteHostPortNum); int error = 0; #ifdef IP_MTU_DISCOVER int pmtuDiscover; #endif struct sockaddr_in localAddr; // Verify socket layer is initialized. if(!socketInit()) { goto EXIT; } // Obtain time for throttling logging of write errors time(&mLastWriteErrorTime); // Initialize state settings mToSockaddrValid = FALSE; mpToSockaddr = (struct sockaddr_in*) malloc(sizeof(struct sockaddr_in)); assert(NULL != mpToSockaddr); memset(mpToSockaddr, 0, sizeof(struct sockaddr_in)); socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; localHostPort = localHostPortNum; if(localHost) { localHostName = localHost ; } // Create the socket socketDescriptor = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if(socketDescriptor == OS_INVALID_SOCKET_DESCRIPTOR) { error = OsSocketGetERRNO(); close(); Os::Logger::instance().log(FAC_KERNEL, PRI_WARNING, "OsDatagramSocket::_ socket(%d, %d, %d) failed w/ errno %d '%s')", AF_INET, SOCK_DGRAM, IPPROTO_UDP, error, strerror(error)); goto EXIT; } // Set Socket Options: IP_MTU_DISCOVER to DONT: Do not set dontfrag bit in // IP header #ifdef IP_MTU_DISCOVER pmtuDiscover = IP_PMTUDISC_DONT ; error = setsockopt(socketDescriptor, IPPROTO_IP, IP_MTU_DISCOVER, &pmtuDiscover, sizeof(pmtuDiscover)) ; if (error != 0) { static bool bReported = false ; // Failure to set the socket option isn't a show-stopper, but should // be noted (and not spammed). if (!bReported) { bReported = true ; Os::Logger::instance().log(FAC_KERNEL, PRI_WARNING, "OsDatagramSocket::_ socket %d failed to set IP_MTU_DISCOVER (rc=%d, errno=%d)", socketDescriptor, error, OsSocketGetERRNO()); } } #endif // Bind to the socket memset(&localAddr, 0, sizeof(localAddr)); localAddr.sin_family = AF_INET; localAddr.sin_port = htons(localHostPort == PORT_DEFAULT ? 0 : localHostPort); // Should use host address (if specified in localHost) but for now use any if (!localHost) { localAddr.sin_addr.s_addr=OsSocket::getDefaultBindAddress(); // $$$ mLocalIp = inet_ntoa(localAddr.sin_addr); } else { struct in_addr ipAddr; ipAddr.s_addr = inet_addr (localHost); localAddr.sin_addr.s_addr= ipAddr.s_addr; mLocalIp = localHost; } # if defined(_WIN32) error = bind( socketDescriptor, (const struct sockaddr*) &localAddr, sizeof(localAddr)); # elif defined(__pingtel_on_posix__) error = bind( socketDescriptor, (struct sockaddr*) &localAddr, sizeof(localAddr)); # endif if(error == OS_INVALID_SOCKET_DESCRIPTOR) { error = OsSocketGetERRNO(); close(); // Extract the address and port we were trying to bind() to. const char *addr = inet_ntoa(localAddr.sin_addr); int port = ntohs(localAddr.sin_port); Os::Logger::instance().log(FAC_KERNEL, PRI_WARNING, "OsDatagramSocket::_ %d (%s:%d %s:%d) bind(%d, %s:%d) failed w/ errno %d '%s')", socketDescriptor, remoteHost, remoteHostPortNum, localHost, localHostPortNum, socketDescriptor, addr, port, error, strerror(error)); goto EXIT; } else { sockaddr_in addr ; int addrSize = sizeof(struct sockaddr_in); error = getsockname(socketDescriptor, (struct sockaddr*) &addr, SOCKET_LEN_TYPE& addrSize); localHostPort = htons(addr.sin_port); } Os::Logger::instance().log(FAC_KERNEL, PRI_DEBUG, "OsDatagramSocket::_ %d (%s:%d %s:%d) socket and bind succeeded", socketDescriptor, remoteHost, remoteHostPortNum, localHost, localHostPortNum); // Kick off connection mSimulatedConnect = FALSE; doConnect(remoteHostPortNum, remoteHost, mSimulatedConnect) ; EXIT: return; }
Tcp::Tcp(int socketDescriptor) : _socket(socketDescriptor) { socketInit(); }
// Constructor OsDatagramSocket::OsDatagramSocket(int remoteHostPortNum, const char* remoteHost, int localHostPortNum, const char* localHost) : mNumTotalWriteErrors(0), mNumRecentWriteErrors(0) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "OsDatagramSocket::_ attempt %s:%d" ,remoteHost, remoteHostPortNum); int error = 0; UtlBoolean isIp = FALSE; struct sockaddr_in localAddr; struct hostent* server = NULL; // Verify socket layer is initialized. if(!socketInit()) { goto EXIT; } // Obtain time for throttling logging of write errors time(&mLastWriteErrorTime); // Initialize state settings mToSockaddrValid = FALSE; mpToSockaddr = (struct sockaddr_in*) malloc(sizeof(struct sockaddr_in)); assert(NULL != mpToSockaddr); memset(mpToSockaddr, 0, sizeof(struct sockaddr_in)); socketDescriptor = OS_INVALID_SOCKET_DESCRIPTOR; localHostPort = localHostPortNum; if(localHost) { localHostName = localHost ; } // Create the socket socketDescriptor = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if(socketDescriptor == OS_INVALID_SOCKET_DESCRIPTOR) { error = OsSocketGetERRNO(); close(); OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsDatagramSocket::OsDatagramSocket( %s:%d %s:%d) failed w/ errno %d)", remoteHost, remoteHostPortNum, localHost, localHostPortNum, error); goto EXIT; } // Bind to the socket localAddr.sin_family = AF_INET; localAddr.sin_port = htons(localHostPort == PORT_DEFAULT ? 0 : localHostPort); // Should use host address (if specified in localHost) but for now use any if (!localHost) { localAddr.sin_addr.s_addr=OsSocket::getDefaultBindAddress(); // $$$ mLocalIp = inet_ntoa(localAddr.sin_addr); } else { struct in_addr ipAddr; ipAddr.s_addr = inet_addr (localHost); localAddr.sin_addr.s_addr= ipAddr.s_addr; mLocalIp = localHost; } # if defined(_WIN32) error = bind( socketDescriptor, (const struct sockaddr*) &localAddr, sizeof(localAddr)); # elif defined(__pingtel_on_posix__) error = bind( socketDescriptor, (struct sockaddr*) &localAddr, sizeof(localAddr)); # endif if(error == OS_INVALID_SOCKET_DESCRIPTOR) { close(); goto EXIT; } else { sockaddr_in addr ; int addrSize = sizeof(struct sockaddr_in); error = getsockname(socketDescriptor, (struct sockaddr*) &addr, SOCKET_LEN_TYPE& addrSize); localHostPort = htons(addr.sin_port); } // Kick off connection mSimulatedConnect = FALSE; doConnect(remoteHostPortNum, remoteHost, mSimulatedConnect) ; EXIT: return; }
/** * \brief Main application function. * * Application entry point. * Initialize board and WINC1500 Wi-Fi module. * Read input data from serial interface and sent it to the remote device. * * \return program return value. */ int main(void) { tstrWifiInitParam param; int8_t ret; /* Initialize the board. */ system_init(); /* Initialize the UART console. */ configure_console(); printf(STRING_HEADER); /* Initialize the BSP. */ nm_bsp_init(); /* Initialize Wi-Fi parameters structure. */ memset((uint8_t *)¶m, 0, sizeof(tstrWifiInitParam)); /* Initialize Wi-Fi driver with data and status callbacks. */ param.pfAppWifiCb = wifi_cb; ret = m2m_wifi_init(¶m); if (M2M_SUCCESS != ret) { printf("main: m2m_wifi_init call error!(%d)\r\n", ret); while (1) { } } /* Initialize socket interface. */ socketInit(); registerSocketCallback(socket_cb, NULL); /* Connect to router. */ m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL); while (1) { if (wifi_connected == M2M_WIFI_CONNECTED && tcp_server_socket < 0) { struct sockaddr_in addr; /* Create TCP server socket. */ if ((tcp_server_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("Failed to create TCP server socket!\r\n"); continue; } /* Initialize socket address structure and bind service. */ addr.sin_family = AF_INET; addr.sin_port = _htons(MAIN_WIFI_M2M_SERVER_PORT); addr.sin_addr.s_addr = 0; bind(tcp_server_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)); } /* Handle pending events from network controller. */ m2m_wifi_handle_events(NULL); /* Try to read user input from EDBG. */ usart_read_job(&cdc_uart_module, &uart_ch_buffer); /* Handle user message from EDBG. */ handle_input_message(); } return 0; }