LOCAL void network_connect_cb(void *arg) { HTTP_REQUEST *request; switch(mConnectionState) { case CS_GETINFO: request = &mInfoRequest; dhdebug("Send info request..."); break; case CS_REGISTER: request = &mRegisterRequest; dhdebug("Send register request..."); break; case CS_POLL: request = &mPollRequest; dhdebug("Send poll request..."); break; default: dhdebug("ASSERT: networkConnectCb wrong state %d", mConnectionState); } int res; if( (res = espconn_send(&mDHConnector, request->data, request->len)) != ESPCONN_OK) { mConnectionState = CS_DISCONNECT; dhesperrors_espconn_result("network_connect_cb failed:", res); espconn_disconnect(&mDHConnector); } else { dhstatistic_add_bytes_sent(request->len); } }
/** * @brief Tcp client connect success callback function. * @param arg: contain the ip link information * @retval None */ void ICACHE_FLASH_ATTR mqtt_tcpclient_connect_cb(void *arg) { struct espconn *pCon = (struct espconn *)arg; MQTT_Client* client = (MQTT_Client *)pCon->reverse; espconn_regist_disconcb(client->pCon, mqtt_tcpclient_discon_cb); espconn_regist_recvcb(client->pCon, mqtt_tcpclient_recv);//////// espconn_regist_sentcb(client->pCon, mqtt_tcpclient_sent_cb);/////// INFO("MQTT: Connected to broker %s:%d\r\n", client->host, client->port); mqtt_msg_init(&client->mqtt_state.mqtt_connection, client->mqtt_state.out_buffer, client->mqtt_state.out_buffer_length); client->mqtt_state.outbound_message = mqtt_msg_connect(&client->mqtt_state.mqtt_connection, client->mqtt_state.connect_info); client->mqtt_state.pending_msg_type = mqtt_get_type(client->mqtt_state.outbound_message->data); client->mqtt_state.pending_msg_id = mqtt_get_id(client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); client->sendTimeout = MQTT_SEND_TIMOUT; INFO("MQTT: Sending, type: %d, id: %04X\r\n", client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id); if (client->security) { #ifdef MQTT_SSL_ENABLE espconn_secure_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); #else INFO("TCP: Do not support SSL\r\n"); #endif } else { espconn_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); } client->mqtt_state.outbound_message = NULL; client->connState = MQTT_CONNECT_SENDING; system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); }
void ICACHE_FLASH_ATTR mqtt_send_keepalive(MQTT_Client *client) { INFO("\r\nMQTT: Send keepalive packet to %s:%d!\r\n", client->host, client->port); client->mqtt_state.outbound_message = mqtt_msg_pingreq(&client->mqtt_state.mqtt_connection); client->mqtt_state.pending_msg_type = MQTT_MSG_TYPE_PINGREQ; client->mqtt_state.pending_msg_type = mqtt_get_type(client->mqtt_state.outbound_message->data); client->mqtt_state.pending_msg_id = mqtt_get_id(client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); client->sendTimeout = MQTT_SEND_TIMOUT; INFO("MQTT: Sending, type: %d, id: %04X\r\n", client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id); err_t result = ESPCONN_OK; if (client->security) { #ifdef MQTT_SSL_ENABLE result = espconn_secure_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); #else INFO("TCP: Do not support SSL\r\n"); #endif } else { result = espconn_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); } client->mqtt_state.outbound_message = NULL; if(ESPCONN_OK == result) { client->keepAliveTick = 0; client->connState = MQTT_DATA; system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); } else { client->connState = TCP_RECONNECT_DISCONNECTING; system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); } }
/** * Send data to the partner. * The return is the number of bytes actually transmitted which may also be * 0 to indicate no bytes sent or -1 to indicate an error. For the ESP8266 implementation we * will return 0 if the socket is not connected or we are in the `SOCKET_STATE_TRANSMITTING` * state. */ int net_ESP8266_BOARD_send( JsNetwork *net, //!< The Network we are going to use to create the socket. int sckt, //!< The socket over which we will send data. const void *buf, //!< The buffer containing the data to be sent. size_t len //!< The length of data in the buffer to send. ) { //DBG("%s:send\n", DBG_LIB); struct socketData *pSocketData = getSocketData(sckt); assert(pSocketData->state != SOCKET_STATE_UNUSED); // If the socket is in error or it is closing return -1 switch (pSocketData->state) { case SOCKET_STATE_CLOSED: case SOCKET_STATE_DISCONNECTING: return pSocketData->errorCode != 0 ? pSocketData->errorCode : SOCKET_ERR_CLOSED; case SOCKET_STATE_ABORTING: return pSocketData->errorCode; case SOCKET_STATE_TO_ABORT: espconn_abort(pSocketData->pEspconn); return pSocketData->errorCode; default: break; } // Unless we are in the idle state, we can't send more shtuff if (pSocketData->state != SOCKET_STATE_IDLE) { return 0; } // Log the content of the data we are sending. //esp8266_board_writeString(buf, len); //os_printf("\n"); // Copy the data to be sent into a transmit buffer we hand off to espconn assert(pSocketData->currentTx == NULL); pSocketData->currentTx = (uint8_t *)os_malloc(len); if (pSocketData->currentTx == NULL) { DBG("%s: Out of memory sending %d on socket %d\n", DBG_LIB, len, sckt); setSocketInError(pSocketData, ESPCONN_MEM); espconn_abort(pSocketData->pEspconn); pSocketData->state = SOCKET_STATE_ABORTING; return pSocketData->errorCode; } memcpy(pSocketData->currentTx, buf, len); // Send the data over the ESP8266 SDK. int rc = espconn_send(pSocketData->pEspconn, pSocketData->currentTx, len); if (rc < 0) { setSocketInError(pSocketData, rc); os_free(pSocketData->currentTx); pSocketData->currentTx = NULL; espconn_abort(pSocketData->pEspconn); pSocketData->state = SOCKET_STATE_ABORTING; return rc; } pSocketData->state = SOCKET_STATE_TRANSMITTING; //DBG("%s: socket %d JS send %d\n", DBG_LIB, sckt, len); return len; }
void ICACHE_FLASH_ATTR tcp_send_data ( void *arg ) { os_printf ( "TCP send data\n" ); if ( x_count > 0 ) { espconn_send ( arg, x_msg, x_len ); x_count--; } }
void ICACHE_FLASH_ATTR tcp_receive_data ( void *arg, char *buf, unsigned short len ) { os_printf ( "TCP receive data: %d bytes\n", len ); espconn_send ( arg, buf, len ); os_memcpy ( x_msg, buf, len ); x_len = len; x_count = 1; }
// OnConnect call back LOCAL void ICACHE_FLASH_ATTR on_connect_cb(void* arg) { os_printf("TCP Connection Established!\n"); espconn_set_opt(&conn0, ESPCONN_REUSEADDR); // Docs say to put this here char msg[] = "Hello Internet!"; espconn_send(arg, msg, sizeof(msg)); }
LOCAL void ICACHE_FLASH_ATTR senderConnectCb(void *arg) { int res; if( (res = espconn_send(&mDHSender, mSenderRequest.data, mSenderRequest.len)) != ESPCONN_OK) { dhesperrors_espconn_result("sender espconn_send failed:", res); espconn_disconnect(&mDHSender); } else { dhstatistic_add_bytes_sent(mSenderRequest.len); } }
static void ICACHE_FLASH_ATTR at_espconn_demo_send_cb(void *arg) { at_espconn_demo_flag = TRUE; if(at_espconn_demo_data_len) { espconn_send(at_espconn_demo_espconn_ptr,at_espconn_demo_buffer,at_espconn_demo_data_len); at_espconn_demo_data_len = 0; } }
LWS_VISIBLE int lws_ssl_capable_write_no_ssl(struct lws *wsi, unsigned char *buf, int len) { //lwsl_notice("%s: wsi %p: len %d\n", __func__, wsi, len); wsi->pending_send_completion++; espconn_send(wsi->desc.sockfd, buf, len); return len; }
/** * Send data to the partner. * The return is the number of bytes actually transmitted which may also be * 0 to indicate no bytes sent or -1 to indicate an error. For the ESP8266 implementation we * will return 0 if the socket is not connected or we are in the `SOCKET_STATE_TRANSMITTING` * state. */ int net_ESP8266_BOARD_send( JsNetwork *net, //!< The Network we are going to use to create the socket. int sckt, //!< The socket over which we will send data. const void *buf, //!< The buffer containing the data to be sent. size_t len //!< The length of data in the buffer to send. ) { os_printf("> net_ESP8266_BOARD_send: Request to send data to socket %d of size %d: ", sckt, len); struct socketData *pSocketData = getSocketData(sckt); assert(pSocketData->state != SOCKET_STATE_UNUSED); // If we are not connected, then we can't currently send data. if (pSocketData->isConnected == false) { os_printf(" - Not connected\n"); return 0; } // If we are currently sending data, we can't send more. if (pSocketData->state == SOCKET_STATE_TRANSMITTING) { os_printf(" - Currently transmitting\n"); return 0; } // Log the content of the data we are sening. esp8266_board_writeString(buf, len); os_printf("\n"); assert(pSocketData->state == SOCKET_STATE_IDLE); pSocketData->state = SOCKET_STATE_TRANSMITTING; // Copy the data that was passed to us to a private area. We do this because we must not // assume that the data passed in will be available after this function returns. It may have // been passed in on the stack. assert(pSocketData->currentTx == NULL); pSocketData->currentTx = (uint8_t *)os_malloc(len); memcpy(pSocketData->currentTx, buf, len); // Send the data over the ESP8266 SDK. int rc = espconn_send(pSocketData->pEspconn, pSocketData->currentTx, len); if (rc < 0) { setSocketInError(sckt, "espconn_send", rc); os_free(pSocketData->currentTx); pSocketData->currentTx = NULL; return -1; } esp8266_dumpSocket(sckt); os_printf("< net_ESP8266_BOARD_send\n"); return len; }
static void ICACHE_FLASH_ATTR syslog_udp_send_event(os_event_t *events) { if (syslogQueue == NULL) syslogState = SYSLOG_READY; else { int res = 0; syslog_espconn.proto.udp->remote_port = syslogHost.port; // ESP8266 udp remote port os_memcpy(&syslog_espconn.proto.udp->remote_ip, &syslogHost.addr.addr, 4); // ESP8266 udp remote IP res = espconn_send(&syslog_espconn, (uint8_t *)syslogQueue->datagram, syslogQueue->datagram_len); if (res != 0) { os_printf("syslog_udp_send: error %d\n", res); } } }
static void ICACHE_FLASH_ATTR syslog_udp_send_event(os_event_t *events) { DBG("[%uµs] %s: id=%lu\n", WDEV_NOW(), __FUNCTION__, syslogQueue ? syslogQueue->msgid : 0); if (syslogQueue == NULL) syslog_set_status(SYSLOG_READY); else { int res = 0; syslog_espconn->proto.udp->remote_port = syslogHost.port; // ESP8266 udp remote port os_memcpy(syslog_espconn->proto.udp->remote_ip, &syslogHost.addr.addr, 4); // ESP8266 udp remote IP res = espconn_send(syslog_espconn, (uint8_t *)syslogQueue->datagram, syslogQueue->datagram_len); if (res != 0) { os_printf("syslog_udp_send: error %d\n", res); } } }
static void ICACHE_FLASH_ATTR at_espconn_demo_response(const uint8*data,uint32 length) { if((data == NULL) || (length == 0)) { return; } if(at_espconn_demo_flag) { espconn_send(at_espconn_demo_espconn_ptr,(uint8*)data,length); at_espconn_demo_flag = FALSE; } else { if(length <= (AT_ESPCONN_DEMO_BUFFER_SIZE - at_espconn_demo_data_len)) { os_memcpy(at_espconn_demo_buffer + at_espconn_demo_data_len,data,length); at_espconn_demo_data_len += length; } else { os_printf("at espconn buffer full\r\n"); } } }
int ICACHE_FLASH_ATTR http_transmit(http_connection *c){ NODE_DBG("Transmit Buffer"); int len = (c->output.bufferPos - c->output.buffer); if(len>0 && len <= HTTP_BUFFER_SIZE){ espconn_send(c->espConnection, (uint8_t*)(c->output.buffer),len); } else{ NODE_DBG("Wrong transmit size %d",len); } //free buffer http_reset_buffer(c); return len; }
// callback when a connection happens void ICACHE_FLASH_ATTR connectCB(void *arg) { struct espconn *pNewEspConn = (struct espconn *)arg; // Type casting the argument to espconn structure type. This structure is unique for each connection os_printf("Made a connection\n"); char send_data_buffer[2048]; char text_data[500]; char date_string[25] ; sint16 date_string_min; current_time_with_dst = sntp_current_time(0); // This is a function time_functions.h, returns a time.h tm structure os_sprintf(date_string, "%4d-%02d-%02d %02d:%02d:%02d", 1900+current_time_with_dst->tm_year, current_time_with_dst->tm_mon+1, current_time_with_dst->tm_mday,current_time_with_dst->tm_hour, current_time_with_dst->tm_min,current_time_with_dst->tm_sec ); os_printf("Attempting to send %s, %d\n\r", date_string, current_time_with_dst->tm_min); os_sprintf(text_data,"un=%s&key=%s&origin=plot&platform=esp8266_c&args=[{\"x\":\"%s\", \"y\":[%d]}]&kwargs={\"filename\": \"test plot from esp-8266\",\"fileopt\": \"extend\"}",plotly_username, plotly_key, date_string, current_time_with_dst->tm_min); os_sprintf(send_data_buffer, "POST %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\nContent-Length: %d\r\n\r\n%s", plotly_rest_api_home, plotly_host, strlen(text_data), text_data); os_printf("Data that was sent is %s\n\r",send_data_buffer); espconn_send(pNewEspConn, send_data_buffer, sizeof(send_data_buffer)); }
bool ICACHE_FLASH_ATTR tfp_send_w_cid(const uint8_t *data, const uint8_t length, const uint8_t cid) { uint8_t i = 0; if(!configuration_current.mesh_enable) { /* * FIXME: Shouldn't the buffering while sending mechanism be also used for * non-mesh case? As it is documented that packets should be sent from the * sent callback of the previous packet. */ if(tfp_cons[cid].state == TFP_CON_STATE_OPEN) { tfp_cons[cid].state = TFP_CON_STATE_SENDING; os_memcpy(tfp_cons[cid].send_buffer, data, length); espconn_send(tfp_cons[cid].con, (uint8_t*)data, length); return true; } return false; } else { if(tfp_cons[cid].state == TFP_CON_STATE_OPEN) { os_memcpy(tfp_cons[cid].send_buffer, data, length); tfp_mesh_send(tfp_cons[cid].con, (uint8_t*)data, length); return true; } else { // Check if there is enough space in the send buffer. if(tfp_mesh_send_check_buffer(length)) { // Store the packet in the TFP mesh send buffer. for(i = 0; i < length; i++) { if(!ringbuffer_add(&tfp_mesh_send_rb, data[i])) { return false; } } return true; } else { return false; } } } }
void ICACHE_FLASH_ATTR MQTT_Task(os_event_t *e) { MQTT_Client* client = (MQTT_Client*)e->par; uint8_t dataBuffer[MQTT_BUF_SIZE]; uint16_t dataLen; if(e->par == 0) return; switch(client->connState){ case TCP_RECONNECT_REQ: break; case TCP_RECONNECT: MQTT_Connect(client); INFO("TCP: Reconnect to: %s:%d\r\n", client->host, client->port); client->connState = TCP_CONNECTING; break; case MQTT_DATA: if(QUEUE_IsEmpty(&client->msgQueue) || client->sendTimeout != 0) { break; } if(QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == 0){ client->mqtt_state.pending_msg_type = mqtt_get_type(dataBuffer); client->mqtt_state.pending_msg_id = mqtt_get_id(dataBuffer, dataLen); client->sendTimeout = MQTT_SEND_TIMOUT; INFO("MQTT: Sending, type: %d, id: %04X\r\n",client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id); if(client->security){ espconn_secure_send(client->pCon, dataBuffer, dataLen); } else{ espconn_send(client->pCon, dataBuffer, dataLen); } client->mqtt_state.outbound_message = NULL; break; } break; } }
void ICACHE_FLASH_ATTR mqtt_timer(void *arg) { MQTT_Client* client = (MQTT_Client*)arg; if(client->connState == MQTT_DATA){ client->keepAliveTick++; if(client->keepAliveTick > client->mqtt_state.connect_info->keepalive){ INFO("\r\nMQTT: Send keepalive packet to %s:%d!\r\n", client->host, client->port); client->mqtt_state.outbound_message = mqtt_msg_pingreq(&client->mqtt_state.mqtt_connection); client->mqtt_state.pending_msg_type = MQTT_MSG_TYPE_PINGREQ; client->mqtt_state.pending_msg_type = mqtt_get_type(client->mqtt_state.outbound_message->data); client->mqtt_state.pending_msg_id = mqtt_get_id(client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); client->sendTimeout = MQTT_SEND_TIMOUT; INFO("MQTT: Sending, type: %d, id: %04X\r\n",client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id); if(client->security){ espconn_secure_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); } else{ espconn_send(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); } client->mqtt_state.outbound_message = NULL; client->keepAliveTick = 0; system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); } } else if(client->connState == TCP_RECONNECT_REQ){ client->reconnectTick ++; if(client->reconnectTick > MQTT_RECONNECT_TIMEOUT) { client->reconnectTick = 0; client->connState = TCP_RECONNECT; system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); } } if(client->sendTimeout > 0) client->sendTimeout --; }
static void ICACHE_FLASH_ATTR tcpConnCb(void *arg) { int i; os_printf("tcpConnCb\n"); struct espconn* pCon = (struct espconn *)arg; espconn_regist_recvcb(pCon, tcpRecvCb); espconn_regist_disconcb(pCon, tcpDisconnCb); espconn_regist_sentcb(pCon, tcpSentCb); /* source: http://www.arduinesp.com/thingspeak */ int res = 0; /* initialize as empty strings */ uint8_t httpRequest[300] = ""; uint8_t postStr[300] = ""; uint8_t postStrLen[20] = ""; uint8_t * pch = uart_input_buff; /* concatenate the message body (bottom part of the HTTP request) */ os_strcat(postStr, apiKey); for ( i = 0 ; i < 8 ; i++ ) { os_strcat(postStr, "&field"); os_sprintf(postStrLen, "%d=", i + 1); os_strcat(postStr, postStrLen); /* locate each sample inside UART input buff and append it to the post string */ /* samples are divided with "\n\r" substrings */ while ( *pch != 0x0a) // 0x0a -> \n { /* get length of post string */ uint16_t postStrLen = os_strlen(postStr); /* append character (overwrites the terminating NULL char) */ postStr[ postStrLen ] = *pch; /* move the terminating NULL char 1 cell to the right */ postStr[ postStrLen + 1 ] = 0; /* point to next char in UART input buffer */ pch++; } /* point to the char that follow the "\n\r" divisor */ pch += 1; } os_strcat(postStr, "\r\n\r\n"); /* concatenate the request-line and headers (top part of the http request) */ os_strcat(httpRequest, "POST /update HTTP/1.1\n"); os_strcat(httpRequest, "Host: api.thingspeak.com\n"); os_strcat(httpRequest, "Connection: close\n"); os_strcat(httpRequest, "X-THINGSPEAKAPIKEY: "); os_strcat(httpRequest, apiKey); os_strcat(httpRequest, "\n"); os_strcat(httpRequest, "Content-Type: application/x-www-form-urlencoded\n"); os_strcat(httpRequest, "Content-Length: "); os_sprintf(postStrLen, "%i", os_strlen(postStr)); os_strcat(httpRequest, postStrLen); os_strcat(httpRequest, "\n\n"); os_strcat(httpRequest, postStr); /* print the complete http request */ os_printf("%s\n", httpRequest); /* send the http post request */ res = espconn_send(pCon, (uint8_t *)httpRequest, os_strlen(httpRequest)); if (res != 0) { os_printf("espconn_send: error %d\n", res); } else { os_printf("espconn_send: OK %d\n", res); } }
bool ICACHE_FLASH_ATTR tfp_send(const uint8_t *data, const uint8_t length) { uint8_t i = 0; // TODO: Sanity check length again? // TODO: Are we sure that data is always a full TFP packet? // cid == -2 => send back via UART if(com_handle_message(data, length, -2)) { return true; } // We only peak at the routing table here (and delete the route manually if // we can fit the data in our buffer). It would be very expensive to first // peak and then discover the route again. BrickdRouting *match = NULL; int8_t cid = brickd_route_to_peak(data, &match); if(!brickd_check_auth((const MessageHeader*)data, cid)) { return true; } /* * First let's check if everything fits in the buffers. This is only done if * mesh isn't enabled. When mesh is enabled, dedicated buffer is used for * sending. */ if(!configuration_current.mesh_enable) { if(!tfp_send_check_buffer(cid)) { return false; } } // Add websocket header if necessary uint8_t data_with_websocket_header[TFP_SEND_BUFFER_SIZE + sizeof(WebsocketFrameClientToServer)]; int16_t length_with_websocket_header = tfpw_insert_websocket_header(cid, data_with_websocket_header, data, length); if(length_with_websocket_header == -1) { // -1 = We use websocket but state is not OK for sending return false; } // Remove match from brickd routing table only if we now that we can fit // the data in the buffer if(match != NULL) { match->uid = 0; match->func_id = 0; match->sequence_number = 0; match->cid = -1; } /* * FIXME: Shouldn't the buffering while sending mechanism be also used for * non-mesh case? As it is documented that packets should be sent from the * sent callback of the previous packet. */ // Broadcast. if(cid == -1) { /* * Broadcast is handled differently when mesh is enabled as then there is * only one socket connection invovled. */ if (!configuration_current.mesh_enable) { for(uint8_t i = 0; i < TFP_MAX_CONNECTIONS; i++) { if(tfp_cons[i].state == TFP_CON_STATE_OPEN) { // TODO: sent data (return value) tfp_cons[i].state = TFP_CON_STATE_SENDING; uint8_t length_to_send = length; if(tfp_cons[i].websocket_state == WEBSOCKET_STATE_NO_WEBSOCKET) { os_memcpy(tfp_cons[i].send_buffer, data, length); } else { os_memcpy(tfp_cons[i].send_buffer, data_with_websocket_header, length_with_websocket_header); length_to_send = length_with_websocket_header; } espconn_send(tfp_cons[i].con, tfp_cons[i].send_buffer, length_to_send); } } } else { os_memcpy(tfp_cons[0].send_buffer, data, length); // Check if the socket is in a state to be able to send. if(tfp_cons[0].state == TFP_CON_STATE_OPEN) { tfp_mesh_send(tfp_cons[0].con, tfp_cons[0].send_buffer, length); } /* * If the socket can't send at the moment buffer the packet in TFP mesh * send buffer for sending in future. */ else { if(tfp_mesh_send_check_buffer(length)) { for(i = 0; i < length; i++) { if(!ringbuffer_add(&tfp_mesh_send_rb, data[i])) { return false; } } } else { return false; } } } } // Unicast. else { uint8_t length_to_send = length; if(!configuration_current.mesh_enable) { // When mesh mode is enabled this socket state is updated from tfp_mesh_send(). tfp_cons[cid].state = TFP_CON_STATE_SENDING; } if(tfp_cons[cid].websocket_state == WEBSOCKET_STATE_NO_WEBSOCKET) { os_memcpy(tfp_cons[cid].send_buffer, data, length); } else { os_memcpy(tfp_cons[cid].send_buffer, data_with_websocket_header, length_with_websocket_header); length_to_send = length_with_websocket_header; } if(configuration_current.mesh_enable) { // Check if the socket is in a state to be able to send. if(tfp_cons[0].state == TFP_CON_STATE_OPEN) { tfp_mesh_send(tfp_cons[0].con, tfp_cons[0].send_buffer, length_to_send); } /* * If the socket can't send at the moment buffer the packet in TFP mesh * send buffer for sending in future. */ else { if(tfp_mesh_send_check_buffer(length_to_send)) { for(i = 0; i < length_to_send; i++) { if(!ringbuffer_add(&tfp_mesh_send_rb, data[i])) { return false; } } } else { return false; } } } else { espconn_send(tfp_cons[cid].con, tfp_cons[cid].send_buffer, length_to_send); } } if(ringbuffer_get_free(&tfp_rb) > (6*MTU_LENGTH + 2)) { tfp_recv_unhold(); } return true; }
LOCAL void ICACHE_FLASH_ATTR dhap_httpd_recv_cb(void *arg, char *data, unsigned short len) { struct espconn *conn = arg; const char rootget[] = "GET / "; const char get[] = "GET "; const char post[] = "POST "; const char host[] = "Host:"; char redirectresponse[] = "HTTP/1.0 302 Moved\r\nContent-Length: 0\r\nLocation: http://"HTTPD_URL"\r\n\r\n"; char internal[] = "HTTP/1.0 500 No Memory\r\nContent-Type: text/plain\r\nContent-Length: 9\r\n\r\nNo memory"; char notfound[] = "HTTP/1.0 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: 9\r\n\r\nNot found"; char notimplemented[] = "HTTP/1.0 501 Not Implemented\r\nContent-Type: text/plain\r\nContent-Length: 15\r\n\r\nNot Implemented"; dhdebug("Received %d bytes", len); if(conn == mCurrentPost) { receive_post(data, len, internal, sizeof(internal) - 1); return; } unsigned char redirect = 1; const int to = (int)len - sizeof(HTTPD_URL) + 1 - sizeof(host) + 1; int i; for(i = 0; i < to; i++) { if(os_strncmp(&data[i], host, sizeof(host) - 1) == 0) { i += sizeof(host) - 1; while(data[i] == ' ') i++; if(os_strncmp(&data[i], HTTPD_URL, sizeof(HTTPD_URL) - 1) == 0) redirect = 0; break; } } if(redirect) { dhdebug("Redirect"); check_send_res(espconn_send(conn, redirectresponse, sizeof(redirectresponse) - 1)); } else if(len < sizeof(rootget) || len < sizeof(post)) { dhdebug("Bad request"); char error[] = "HTTP/1.0 400 Bad Request\r\nContent-Length:0\r\n\r\n"; check_send_res(espconn_send(conn, error, sizeof(error))); } else if(mConfigured) { unsigned int rlen; char *res = dhap_pages_ok(&rlen); if(res == 0) { res = internal; rlen = sizeof(internal) - 1; } dhdebug("Already configured, response %u bytes", rlen); check_send_res(espconn_send(conn, res, rlen)); } else if(os_strncmp(data, post, sizeof(post) - 1) == 0) { if(mCurrentPost) { espconn_disconnect(mCurrentPost); dhdebug("New POST sender, refuse old"); } mCurrentPost = conn; mPostBufPos = 0; receive_post(data, len, internal, sizeof(internal) - 1); } else if(os_strncmp(data, rootget, sizeof(rootget) - 1)) { if(os_strncmp(data, get, sizeof(get) - 1) == 0) { dhdebug("Wrong path"); check_send_res(espconn_send(conn, notfound, sizeof(notfound) - 1)); } else { dhdebug("Not implemented"); check_send_res(espconn_send(conn, notimplemented, sizeof(notimplemented) - 1)); } } else { unsigned int rlen; char *res = dhap_pages_form(&rlen); if(res == 0) { res = internal; rlen = sizeof(internal) - 1; } dhdebug("Send form, %u bytes", rlen); check_send_res(espconn_send(conn, res, rlen)); } }
LOCAL void ICACHE_FLASH_ATTR receive_post(const char *data, unsigned short len, char * internal, unsigned int internalsize) { const unsigned int POST_BUF_SIZE = 2048; const char content_length[] = "Content-Length:"; const char sp[] = "\r\n\r\n"; if(mPostBuf == 0) { mPostBuf = (char*)os_malloc(POST_BUF_SIZE); if(mPostBuf == 0) { check_send_res(espconn_send(mCurrentPost, internal, internalsize)); mCurrentPost = 0; return; } } if(len > POST_BUF_SIZE - mPostBufPos) { check_send_res(espconn_send(mCurrentPost, internal, internalsize)); mCurrentPost = 0; return; } os_memcpy(&mPostBuf[mPostBufPos], data, len); mPostBufPos += len; const int to = (int)mPostBufPos - sizeof(content_length) + 1; int i; unsigned int cont_len; for(i = 0; i < to; i++) { if(os_strncmp(&mPostBuf[i], content_length, sizeof(content_length) - 1) == 0) { i += sizeof(content_length) - 1; while(mPostBuf[i] == ' ') i++; if(strToUInt(&mPostBuf[i], &cont_len)) { for(; i < mPostBufPos; i++) { if(os_strncmp(&mPostBuf[i], sp, sizeof(sp) - 1) == 0) { i += sizeof(sp) - 1; if(cont_len <= mPostBufPos - i) { dhdebug("POST len %u/%u", cont_len, mPostBufPos - i); char *res = dhap_post_parse(&mPostBuf[i], mPostBufPos - i); unsigned int rlen; if(res) { res = dhap_pages_error(res, &rlen); } else { if(dhsettings_commit() == 0) { res = internal; rlen = internalsize; } else { res = dhap_pages_ok(&rlen); if(res == 0) { dhdebug("Generate OK page fail"); res = internal; rlen = internalsize; } else { dhdebug("Configuration was written. Will be rebooted in %d ms", RECONFIGURE_DELAY_MS); os_timer_disarm(&mReconfigureTimer); os_timer_setfn(&mReconfigureTimer, (os_timer_func_t *)system_reconfigure, NULL); os_timer_arm(&mReconfigureTimer, RECONFIGURE_DELAY_MS, 0); mConfigured = 1; } } } dhdebug("Parse post, send result %u bytes", rlen); check_send_res(espconn_send(mCurrentPost, res, rlen)); mCurrentPost = 0; } return; } } } return; } } }
void ICACHE_FLASH_ATTR MQTT_Task(os_event_t *e) { MQTT_Client* client = (MQTT_Client*)e->par; uint8_t dataBuffer[MQTT_BUF_SIZE]; uint16_t dataLen; if (e->par == 0) return; switch (client->connState) { case TCP_RECONNECT_REQ: break; case TCP_RECONNECT: mqtt_tcpclient_delete(client); MQTT_Connect(client); INFO("TCP: Reconnect to: %s:%d\r\n", client->host, client->port); client->connState = TCP_CONNECTING; break; case MQTT_DELETING: case TCP_DISCONNECTING: case TCP_RECONNECT_DISCONNECTING: if (client->security) { #ifdef MQTT_SSL_ENABLE espconn_secure_disconnect(client->pCon); #else INFO("TCP: Do not support SSL\r\n"); #endif } else { espconn_disconnect(client->pCon); } break; case TCP_DISCONNECTED: INFO("MQTT: Disconnected\r\n"); mqtt_tcpclient_delete(client); break; case MQTT_DELETED: INFO("MQTT: Deleted client\r\n"); mqtt_client_delete(client); break; case MQTT_KEEPALIVE_SEND: mqtt_send_keepalive(client); break; case MQTT_DATA: if (QUEUE_IsEmpty(&client->msgQueue) || client->sendTimeout != 0) { break; } if (QUEUE_Gets(&client->msgQueue, dataBuffer, &dataLen, MQTT_BUF_SIZE) == 0) { client->mqtt_state.pending_msg_type = mqtt_get_type(dataBuffer); client->mqtt_state.pending_msg_id = mqtt_get_id(dataBuffer, dataLen); client->sendTimeout = MQTT_SEND_TIMOUT; INFO("MQTT: Sending, type: %d, id: %04X\r\n", client->mqtt_state.pending_msg_type, client->mqtt_state.pending_msg_id); if (client->security) { #ifdef MQTT_SSL_ENABLE espconn_secure_send(client->pCon, dataBuffer, dataLen); #else INFO("TCP: Do not support SSL\r\n"); #endif } else { espconn_send(client->pCon, dataBuffer, dataLen); } client->mqtt_state.outbound_message = NULL; break; } break; } }
ICACHE_FLASH_ATTR void WebConnection::received_data(char* data, unsigned short length) { if (!request) request = new WebRequest(); request->received_data(data, length); if (!request->is_complete()) return; if (request->type == WebRequest::BAD) { static const char bad_request[] = "400 Bad Request\r\n\r\n"; espconn_send(connection, (uint8*) bad_request, strlen(bad_request)); reset(); return; } const char* url = request->url; if (strcmp(url, "/") == 0) url = "index.html"; while (url[0] == '/') url += 1; static const char not_found[] = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"; if (request->type == WebRequest::GET) { HTMLFile cur_file; cur_file.load(url); if (cur_file.is_valid()) { log("Sending %s...\n", url); const char* content_type = "text/plain"; const char* dot = strrchr(url, '.'); if (dot) { const char* suffix = dot + 1; if (strcmp(suffix, "html") == 0) content_type = "text/html"; else if (strcmp(suffix, "css") == 0) content_type = "text/css"; else if (strcmp(suffix, "js") == 0) content_type = "application/javascript"; } char headers[256]; static const char* headers_fmt = "HTTP/1.1 200 OK\r\n" "Content-Type: %s\r\n" "Content-Length: %d\r\n" "\r\n"; os_sprintf(headers, headers_fmt, content_type, cur_file.size); int headers_length = strlen(headers); int message_length = headers_length + cur_file.size; char* message = (char*) os_zalloc(message_length); strcpy(message, headers); os_memcpy(message + headers_length, cur_file.contents, cur_file.size); espconn_send(connection, (uint8*) message, message_length); os_free(message); } else espconn_send(connection, (uint8*) not_found, strlen(not_found)); } else if (request->type == WebRequest::POST) { if (strcmp(url, "message") == 0) { display_message(request->body, request->body_length); static const char* generic_ok = "HTTP/1.1 200 OK\r\n" "Content-Length: 0\r\n" "\r\n"; espconn_send(connection, (uint8*) generic_ok, strlen(generic_ok)); } else espconn_send(connection, (uint8*) not_found, strlen(not_found)); } else { static const char method_not_allowed[] = "HTTP/1.1 405 Method Not Allowed\r\n\r\n"; espconn_send( connection, (uint8*) method_not_allowed, strlen(method_not_allowed)); } reset(); }
static void ICACHE_FLASH_ATTR dnsQueryReceived(void *arg, char *data, unsigned short length) { // parse incoming query domain char domain[30]; char *writePos=domain; memset(domain,0,30); int offSet=12; int len=data[offSet]; while(len!=0 && offSet<length) { offSet++; memcpy(writePos,data+offSet,len); writePos+=len; //advance offSet+=len; len=data[offSet]; if(len!=0) { *writePos='.'; writePos++; } } DNS_DBG("DNS Query Received: %s",domain); if(!isKnownDNS(domain)) return; struct espconn *conn=arg; remot_info *premot = NULL; if (espconn_get_connection_info(conn,&premot,0) == ESPCONN_OK) { os_memcpy(conn->proto.udp->remote_ip, premot->remote_ip, 4); conn->proto.udp->remote_port = premot->remote_port; uint8_t *ip1 = conn->proto.udp->remote_ip; NODE_DBG("UDP:\nremote_ip: %d.%d.%d.%d remote_port: %d\n",ip4_addr1_16(ip1),ip4_addr2_16(ip1), ip4_addr3_16(ip1), ip4_addr4_16(ip1), premot->remote_port); } else { NODE_ERR("UDP: connection_info == NULL?\n"); } //build response char response[100] = {data[0], data[1], 0b10000100 | (0b00000001 & data[2]), //response, authorative answer, not truncated, copy the recursion bit 0b00000000, //no recursion available, no errors data[4], data[5], //Question count data[4], data[5], //answer count 0x00, 0x00, //NS record count 0x00, 0x00}; //Resource record count int idx = 12; memcpy(response+12, data+12, length-12); //Copy the rest of the query section idx += length-12; //Set a pointer to the domain name in the question section response[idx] = 0xC0; response[idx+1] = 0x0C; //Set the type to "Host Address" response[idx+2] = 0x00; response[idx+3] = 0x01; //Set the response class to IN response[idx+4] = 0x00; response[idx+5] = 0x01; //A 32 bit integer specifying TTL in seconds, 0 means no caching response[idx+6] = 0x00; response[idx+7] = 0x00; response[idx+8] = 0x00; response[idx+9] = 0x00; //RDATA length response[idx+10] = 0x00; response[idx+11] = 0x04; //4 byte IP address //The IP address response[idx + 12] = 192; response[idx + 13] = 168; response[idx + 14] = 4; response[idx + 15] = 1; int ret = espconn_send(conn, (uint8_t*)response, idx+16); uint8_t *ip = conn->proto.udp->local_ip; NODE_DBG("local_ip: %d.%d.%d.%d local_port: %d\n",ip4_addr1_16(ip),ip4_addr2_16(ip), ip4_addr3_16(ip), ip4_addr4_16(ip),conn->proto.udp->local_port); NODE_DBG("DNS reply sent\n"); }