//Template code for the led page. void ICACHE_FLASH_ATTR tplLed(HttpdConnData *connData, char *token, void **arg) { char buff[128]; if (token==NULL) return; os_strcpy(buff, "Unknown"); if (os_strcmp(token, "ledstate")==0) { if (currLedState) { os_strcpy(buff, "on"); } else { os_strcpy(buff, "off"); } } espconn_sent(connData->conn, (uint8 *)buff, os_strlen(buff)); }
/* cgiReadFlash */ int ICACHE_FLASH_ATTR cgiReadFlash(HttpdConnection * ptConnection) { /* initialization */ int iRet = 0; int * iFlashOffset = NULL; iFlashOffset = (int *)&ptConnection->pbCgiData; if (NULL == ptConnection->ptEspConnection) { /* connection aborted - clean up */ iRet = HTTPD_CGI_DONE; goto lblCleanup; } if (0 == *iFlashOffset) { #ifdef CGIFLASH_DEBUG os_printf("cgiReadFlash: begin flash download\n"); #endif httpdStartResponse(ptConnection, 200); httpdHeader(ptConnection, "Content-Type", "application/bin"); httpdEndHeaders(ptConnection); /* update offset */ *iFlashOffset = 0x40200000; iRet = HTTPD_CGI_MORE; goto lblCleanup; } /* send 1K of flash per call, will be called again if haven't sent 512K yet */ espconn_sent(ptConnection->ptEspConnection, (uint8 *)(*iFlashOffset), 1024); *iFlashOffset += 1024; if (*iFlashOffset >= 0x40200000 + (512 * 1024)) { iRet = HTTPD_CGI_DONE; goto lblCleanup; } else { iRet = HTTPD_CGI_MORE; goto lblCleanup; } lblCleanup: return iRet; }
/** * @brief Send out top message in queue onto socket */ static void ICACHE_FLASH_ATTR mqtt_send_message(MQTT_Client* client) { //DBG_MQTT("MQTT: Send_message\n"); PktBuf *buf = client->msgQueue; if (buf == NULL || client->sending) return; // ahem... client->msgQueue = PktBuf_Shift(client->msgQueue); // get some details about the message uint16_t msg_type = mqtt_get_type(buf->data); uint8_t msg_id = mqtt_get_id(buf->data, buf->filled); msg_id = msg_id; #ifdef MQTT_DBG os_printf("MQTT: Send type=%s id=%04X len=%d\n", mqtt_msg_type[msg_type], msg_id, buf->filled); #if 0 for (int i=0; i<buf->filled; i++) { if (buf->data[i] >= ' ' && buf->data[i] <= '~') os_printf("%c", buf->data[i]); else os_printf("\\x%02X", buf->data[i]); } os_printf("\n"); #endif #endif // send the message out if (client->security) espconn_secure_sent(client->pCon, buf->data, buf->filled); else espconn_sent(client->pCon, buf->data, buf->filled); client->sending = true; // depending on whether it needs an ack we need to hold on to the message bool needsAck = (msg_type == MQTT_MSG_TYPE_PUBLISH && mqtt_get_qos(buf->data) > 0) || msg_type == MQTT_MSG_TYPE_PUBREL || msg_type == MQTT_MSG_TYPE_PUBREC || msg_type == MQTT_MSG_TYPE_SUBSCRIBE || msg_type == MQTT_MSG_TYPE_UNSUBSCRIBE || msg_type == MQTT_MSG_TYPE_PINGREQ; if (msg_type == MQTT_MSG_TYPE_PINGREQ) { client->pending_buffer = NULL; // we don't need to rexmit this one client->sending_buffer = buf; } else if (needsAck) { client->pending_buffer = buf; // remeber for rexmit on disconnect/reconnect client->sending_buffer = NULL; client->timeoutTick = client->sendTimeout+1; // +1 to ensure full sendTireout seconds } else { client->pending_buffer = NULL; client->sending_buffer = buf; client->timeoutTick = 0; } client->keepAliveTick = client->connect_info.keepalive > 0 ? client->connect_info.keepalive+1 : 0; }
//Template code for the Tcp server status void ICACHE_FLASH_ATTR tplTcpServerStatus(HttpdConnData *connData, char *token, void **arg) { char buff[512]; static struct station_config stconf; if (token==NULL) return; wifi_station_get_config(&stconf); os_strcpy(buff, "Unknown"); if (os_strcmp(token, "WiFiSettings")==0) { os_printf("-%s-%s Getting ip settings to replace token: %s \r\n", __FILE__, __func__, token); char ipSettings[256] = { 0}; GetTcpServerStatus(ipSettings); os_strcpy(buff, ipSettings); os_printf("-%s-%s Found ip settings: %s \r\n", __FILE__, __func__, buff); } espconn_sent(connData->conn, (uint8 *)buff, os_strlen(buff)); }
/****************************************************************************** * FunctionName : upgrade_connect * Description : client connected with a host successfully * Parameters : arg -- Additional argument to pass to the callback function * Returns : none *******************************************************************************/ LOCAL void ICACHE_FLASH_ATTR upgrade_connect_cb(void *arg){ struct espconn *pespconn = arg; UPGRADE_DBG("upgrade_connect_cb\n"); os_timer_disarm(&upgrade_connect_timer); espconn_regist_disconcb(pespconn, upgrade_disconcb); espconn_regist_sentcb(pespconn, upgrade_datasent); if (pbuf != NULL) { UPGRADE_DBG("%s\n", pbuf); espconn_sent(pespconn, pbuf, os_strlen(pbuf)); } }
// method socket.send(bytes) STATIC mp_obj_t esp_socket_send(mp_obj_t self_in, mp_obj_t buf_in) { esp_socket_obj_t *s = self_in; if (s->espconn->state == ESPCONN_NONE || s->espconn->state == ESPCONN_CLOSE) { nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "not connected")); } mp_buffer_info_t bufinfo; mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_READ); espconn_sent(s->espconn, bufinfo.buf, bufinfo.len); return mp_obj_new_int(bufinfo.len); }
// Send the next buffer (assumes that the connection is in a state that allows it) static void ICACHE_FLASH_ATTR tcpDoSend(TcpConn *tci) { sint8 err = espconn_sent(tci->conn, (uint8*)tci->txBuf, tci->txBufLen); if (err == ESPCONN_OK) { // send successful os_printf("TCP sent (%p %p)\n", tci->conn, tci); tci->txBuf[tci->txBufLen] = 0; os_printf("TCP data: %s\n", tci->txBuf); tci->txBufSent = tci->txBuf; tci->txBuf = NULL; tci->txBufLen = 0; } else { // send error, leave as-is and try again later... os_printf("TCP send err (%p %p) %d\n", tci->conn, tci, err); } }
void ICACHE_FLASH_ATTR ssSentCb(void *arg) { struct espconn *pespconn = (struct espconn *)arg; struct HttpConnection *c = getHttpConnection(pespconn); if (c->r.complete == 1) { espconn_disconnect(pespconn); return; } ureq_run(&c->r); espconn_sent(pespconn, c->r.response.data, c->r.len); if (c->r.len < 1024) { espconn_disconnect(pespconn); } }
static void ICACHE_FLASH_ATTR replyOK(struct espconn *conn) { char bfr[2048]; int l; l = os_sprintf(bfr, "HTTP/1.0 %d OK\r\nServer: esp8266-http/0.4\r\nConnection: close\r\n\r\n", 200); l += os_sprintf(&bfr[l], "<html><body>"); l += os_sprintf(&bfr[l], "<h3>MQTT Setup</h3><form action=\"/setup\">"); l += os_sprintf(&bfr[l], "<p>MQTT host: <input type=\"text\" name=\"MQTThost\" value=\"%s\"></p>", sysCfg.mqtt_host); l += os_sprintf(&bfr[l], "<p>MQTT Port: <input type=\"text\" name=\"MQTTport\" value=\"%d\" size=\"4\"></p>", sysCfg.mqtt_port); l += os_sprintf(&bfr[l], "<p>MQTT UserID: <input type=\"text\" name=\"MQTTuser\" value=\"%s\"></p>", sysCfg.mqtt_user); l += os_sprintf(&bfr[l], "<p>MQTT Pwd: <input type=\"text\" name=\"MQTTpass\" value=\"%s\"></p>", sysCfg.mqtt_pass); l += os_sprintf(&bfr[l], "<p>Device ID prefix: <input type=\"text\" name=\"DevPrefix\" value=\"%s\"></p>", sysCfg.deviceID_prefix); l += os_sprintf(&bfr[l], "Reboot: <input type=\"checkbox\" name=\"reboot\" value=\"yes\" %s> ", reboot ? "checked" : ""); l += os_sprintf(&bfr[l], "<input type=\"submit\" name=\"Action\" value=\"Update\" style=\"border-radius: 8px; background-color: #CAD0E6\">"); l += os_sprintf(&bfr[l], "</form></body></html>"); espconn_sent(conn, bfr, l); }
static void ICACHE_FLASH_ATTR tcpclient_sent_cb(void *arg) { struct espconn *pCon = (struct espconn *)arg; RestClient* client = (RestClient *)pCon->reverse; DBG("REST: Sent\n"); if (client->data_sent != client->data_len) { // we only sent part of the buffer, send the rest espconn_sent(client->pCon, (uint8_t*)(client->data+client->data_sent), client->data_len-client->data_sent); client->data_sent = client->data_len; } else { // we're done sending, free the memory if (client->data) os_free(client->data); client->data = 0; } }
static void ICACHE_FLASH_ATTR sent_callback(void * arg) { struct espconn * conn = (struct espconn *)arg; request_args * req = (request_args *)conn->reverse; if (req->post_data == NULL) { PRINTF("All sent\n"); } else { // The headers were sent, now send the contents. PRINTF("Sending request body\n"); espconn_sent(conn, (uint8_t *)req->post_data, strlen(req->post_data)); os_free(req->post_data); req->post_data = NULL; } }
void ESP_RestClient::_send() { String data; switch (m_commandType) { case GET: data += "GET "; break; case PUT: data += "PUT "; break; case POST: data += "POST "; break; } // Build the start line of the request. data += String(m_path) + String(" HTTP/1.1\r\n"); // Add the headers to the HTTP request int size = m_headers.size(); for (int i = 0; i < size; i++) { Header *pHeader = (Header *) m_headers.get(i); data += pHeader->getName() + String(": ") + pHeader->getValue() + String("\r\n"); } // Add the payload length if the type is PUT or POST. if (m_commandType == PUT || m_commandType == POST) { data += "Content-Length: " + String(strlen(m_payload)) + String("\r\n"); } // Add the data separator line. data += String("\r\n"); // Add the payload if we have any. if (m_payload != NULL) { data += m_payload; } // Send the buffer. int length = data.length() + 1; m_pSendBuffer = (uint8_t *) malloc(length); data.getBytes(m_pSendBuffer, length, 0); int rc = espconn_sent(&m_conn, m_pSendBuffer, length); if (rc != 0) { // Error LOG("Error with send: %d\n", rc); return; } } // End of _send
//This is a catch-all cgi function. It takes the url passed to it, looks up the corresponding //path in the filesystem and if it exists, passes the file through. This simulates what a normal //webserver would do with static files. int ICACHE_FLASH_ATTR cgiEspFsHook(HttpdConnData *connData) { EspFsFile *file=connData->cgiData; int len; char buff[1024]; #ifdef GZIP_COMPRESSION const char *gzipSendResult = NULL; #endif if (connData->conn==NULL) { //Connection aborted. Clean up. espFsClose(file); return HTTPD_CGI_DONE; } if (file==NULL) { //First call to this cgi. Open the file so we can read it. file=espFsOpen(connData->url); if (file==NULL) { return HTTPD_CGI_NOTFOUND; } connData->cgiData=file; httpdStartResponse(connData, 200); httpdHeader(connData, "Content-Type", httpdGetMimetype(connData->url)); #ifdef GZIP_COMPRESSION gzipSendResult = sendGZIPEncodingIfNeeded(connData); if (gzipSendResult != NULL) { httpdEndHeaders(connData); httpdSend(connData, gzipSendResult, os_strlen(gzipSendResult)); return HTTPD_CGI_DONE; } #endif httpdHeader(connData, "Cache-Control", "max-age=3600, must-revalidate"); httpdEndHeaders(connData); return HTTPD_CGI_MORE; } len=espFsRead(file, buff, 1024); if (len>0) espconn_sent(connData->conn, (uint8 *)buff, len); if (len!=1024) { //We're done. espFsClose(file); return HTTPD_CGI_DONE; } else { //Ok, till next time. return HTTPD_CGI_MORE; } }
static void server_serve(struct espconn *c, void *p, unsigned short len) { int res; char *buf = NULL; char *filename; const char *ok = "HTTP/1.1 200 OK\r\n\r\n"; const char *ok_gzip = "HTTP/1.1 200 OK\r\nContent-Encoding: gzip\n\r\n"; const char *resp = ok; const char not_found[] = "HTTP/1.1 404 Not Found\r\n\r\n"; const char server_error[] = "HTTP/1.1 500 Internal error\r\n\r\n"; spiffs_stat stat; spiffs_file fd = 0; (void) p; (void) len; if (len >= 16 && strncmp(p, "GET /favicon.ico", 16) == 0) { espconn_sent(c, (char *) not_found, sizeof(not_found)); return; } else { filename = "index.html"; } if ((res = SPIFFS_stat(&fs, filename, &stat)) < 0) { espconn_sent(c, (char *) server_error, sizeof(server_error)); return; } if ((fd = SPIFFS_open(&fs, filename, SPIFFS_RDONLY, 0)) < 0) { espconn_sent(c, (char *) server_error, sizeof(server_error)); return; } int resp_size = strlen(resp) + stat.size; buf = malloc(resp_size + 1); if (buf == NULL) { espconn_sent(c, (char *) server_error, sizeof(server_error)); goto cleanup; } memcpy(buf, resp, strlen(resp)); if ((res = SPIFFS_read(&fs, fd, buf + strlen(resp), stat.size)) < 0) { espconn_sent(c, (char *) server_error, sizeof(server_error)); goto cleanup; } buf[resp_size] = '\0'; espconn_sent(c, (char *) buf, resp_size); cleanup: if (buf) free(buf); SPIFFS_close(&fs, fd); return; }
void procfn_ledtest_req(struct espconn* pconn, char* pdata, unsigned short len) { os_printf("Enter %s, pconn: [%p], buf: [%p], len:[%d]\n", __func__, pconn, pdata, len); uint8 buf[2]; led_glint* led = (led_glint*)os_zalloc(sizeof(led_glint)); PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTDI_U, FUNC_GPIO12); led->pin = BIT12; led->interval = 100; led->limit_count = 100; led_glint_control(led); buf[0] = sizeof(buf); buf[1] = LEDTEST_RSP; espconn_sent(pconn, buf, 2); }
void procfn_rst_req(struct espconn* pconn, char* pdata, unsigned short len) { os_printf("Enter %s, pconn: [%p], buf: [%p], len:[%d]\n", __func__, pconn, pdata, len); uint8 buf[2]; buf[0] = sizeof(buf); buf[1] = RST_RSP; espconn_sent(pconn, buf, 2); espconn_disconnect(pconn); //直接调用restart总是故障,改用定时器,100毫秒后重启,顺带也可以把网络数据发出去 ETSTimer* ptimer = (ETSTimer*)os_zalloc(sizeof(ETSTimer)); os_timer_disarm(ptimer); os_timer_setfn(ptimer, restart_timer_cb, ptimer); os_timer_arm(ptimer, 100, 0); }
void ICACHE_FLASH_ATTR tcpclient_connect_cb(void *arg) { struct espconn *pCon = (struct espconn *)arg; REST_CLIENT* client = (REST_CLIENT *)pCon->reverse; espconn_regist_disconcb(client->pCon, tcpclient_discon_cb); espconn_regist_recvcb(client->pCon, tcpclient_recv);//////// espconn_regist_sentcb(client->pCon, tcpclient_sent_cb);/////// if(client->security){ espconn_secure_sent(client->pCon, client->data, client->data_len); } else{ espconn_sent(client->pCon, client->data, client->data_len); } }
void httpd_set_error_state(struct HttpdConnectionSlot *slot, uint16_t code, char *codemessage, char *message) { char strTemp[32]; uint16_t messagelen=strlen(message); slot->bufferLen = 0; httpd_add_buffer_string(slot,"HTTP/1.0 "); os_sprintf(strTemp,"%d ",code); httpd_add_buffer_string(slot,strTemp); httpd_add_buffer_string(slot,codemessage); httpd_add_buffer_string(slot,"\r\nContent-Length: "); os_sprintf(strTemp,"%d ",messagelen); httpd_add_buffer_string(slot,strTemp); httpd_add_buffer_string(slot,"\r\nContent-Type: text/plain\r\n\r\n"); httpd_add_buffer_string(slot,message); slot->state = HTTPD_STATE_RESPONDING; espconn_sent(slot->conn, slot->buffer, slot->bufferLen); }
static void ICACHE_FLASH_ATTR at_tcpclient_connect_cb(void *arg) { struct espconn *pespconn = (struct espconn *)arg; #ifdef PLATFORM_DEBUG ets_uart_printf("TCP client connect\r\n"); #endif espconn_regist_sentcb(pespconn, at_tcpclient_sent_cb); //espconn_regist_recvcb(pespconn, at_tcpclient_recv); espconn_regist_disconcb(pespconn, at_tcpclient_discon_cb); char payload[128]; os_sprintf(payload, MACSTR ",%s\r\n", MAC2STR(macaddr), "ESP8266"); #ifdef PLATFORM_DEBUG ets_uart_printf(payload); #endif espconn_sent(pespconn, payload, strlen(payload)); }
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_sent(client->pCon, dataBuffer, dataLen); } else{ espconn_sent(client->pCon, dataBuffer, dataLen); } client->mqtt_state.outbound_message = NULL; break; } break; case TCP_CONNECTING_ERROR: MQTT_Disconnect(client); MQTT_exit(client); break; } }
LOCAL void ICACHE_FLASH_ATTR clientConnectedCallback(void *arg) { struct espconn *pespconn = arg; connState = TCP_CONNECTED; espconn_regist_sentcb(pespconn, clientSentCallback); espconn_regist_recvcb(pespconn, clientReceiveCallback); sint8 sentStatus = espconn_sent(pespconn, txPayload, os_strlen(txPayload)); if (sentStatus == ESPCONN_OK) { connState = TCP_SENDING; ets_uart_printf("TCP connected, sending request: %s\r\n", txPayload); } else { connState = TCP_SEND_ERROR; ets_uart_printf("ERROR: TCP send failed, disconnecting ...\r\n"); espconn_disconnect(pespconn); } }
static void ICACHE_FLASH_ATTR tcpclient_connect_cb(void *arg) { struct espconn *pCon = (struct espconn *)arg; RestClient* client = (RestClient *)pCon->reverse; DBG("REST #%d: connected\n", client-restClient); espconn_regist_disconcb(client->pCon, tcpclient_discon_cb); espconn_regist_recvcb(client->pCon, tcpclient_recv); espconn_regist_sentcb(client->pCon, tcpclient_sent_cb); client->data_sent = client->data_len <= 1400 ? client->data_len : 1400; DBG("REST #%d: sending %d\n", client-restClient, client->data_sent); //if(client->security){ // espconn_secure_sent(client->pCon, client->data, client->data_sent); //} //else{ espconn_sent(client->pCon, (uint8_t*)client->data, client->data_sent); //} }
/*** * Send data if in Idle state */ static void ICACHE_FLASH_ATTR my_sent_next() { if (my_send_state == Idle && !fifo_is_empty(msg_queue)) { my_send_state = WaitingForSend; my_send_queue_item_t *i = (my_send_queue_item_t *) fifo_first(msg_queue); // when the connection is closed do not send the data if (i->l->free) { remove_first(); my_sent_next(); } else { espconn_sent(i->l->pCon, i->data, i->length); } } }
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_sent(client->pCon, client->mqtt_state.outbound_message->data, client->mqtt_state.outbound_message->length); } else{ espconn_sent(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); } }else if(client->connState == TCP_CONNECTING){ client->connState = TCP_CONNECTING_ERROR; system_os_post(MQTT_TASK_PRIO, 0, (os_param_t)client); } if(client->sendTimeout > 0) client->sendTimeout --; }
//Cgi that reads the SPI flash. Assumes 512KByte flash. int ICACHE_FLASH_ATTR cgiReadFlash(HttpdConnData *connData) { int *pos=(int *)&connData->cgiData; if (connData->conn==NULL) { //Connection aborted. Clean up. return HTTPD_CGI_DONE; } if (*pos==0) { //os_printf("Start flash download.\n"); httpdStartResponse(connData, 200); httpdHeader(connData, "Content-Type", "application/bin"); httpdEndHeaders(connData); *pos=0x40200000; return HTTPD_CGI_MORE; } espconn_sent(connData->conn, (uint8 *)(*pos), 1024); *pos+=1024; if (*pos>=0x40200000+(512*1024)) return HTTPD_CGI_DONE; else return HTTPD_CGI_MORE; }
// ---------------------------------------------------------------------------- // Callback Function. // When you call the function wifi_station_scan() below, the ESP8266 goes off // and starts scanning. When it is done, this function is called automatically. // ---------------------------------------------------------------------------- void ICACHE_FLASH_ATTR wifiSendCb(void *arg, STATUS status) { char payload[1024], *ptr; int n, noAps; struct bss_info *bss_link = (struct bss_info *)arg; os_printf("wifi scan send done %d\n", status); if(status != OK) { scanInProgress = 0; // clear scanning in progress flag return; } noAps = 0; // variable for count of AP's found while(bss_link != NULL) { // Count amount of access points found. bss_link = bss_link->next.stqe_next; noAps++; } os_printf("Scan done: found %d AP's, sending...\n", noAps); ptr = payload; os_sprintf(ptr,">APs_found:%d,", noAps); ptr = &payload[strlen(payload)]; os_sprintf(ptr,"BSSID;SSID;RSSI;Auth,"); ptr = &payload[strlen(payload)];; n = 0; bss_link = (struct bss_info *)arg; while(bss_link != NULL) { if(n >= noAps) { os_printf("Warning: I have more than the allocated %d aps!\n", noAps); break; } if(bss_link->rssi != 0) { os_sprintf(ptr,"%02X:%02X:%02X:%02X:%02X:%02X;",bss_link->bssid[0],bss_link->bssid[1],bss_link->bssid[2],bss_link->bssid[3],bss_link->bssid[4],bss_link->bssid[5]); ptr = payload + strlen(payload); os_sprintf(ptr,"%s;%d;%x,", (char*)bss_link->ssid, bss_link->rssi, bss_link->authmode); ptr = payload + strlen(payload); } bss_link = bss_link->next.stqe_next; // linked list, step to next link n++; } scanInProgress = 0; // clear scanning in progress flag os_sprintf(ptr,"AP_list_end,\n"); os_printf("UDP sending list...\n"); espconn_sent(&Conn, (uint8 *)payload, os_strlen(payload)); }
/** * @brief Get version connection version * @param arg: contain the ip link information * @retval None */ void ICACHE_FLASH_ATTR get_version_connect_cb(void *arg) { struct espconn *pespconn = (struct espconn *)arg; fota_client_t *fota_client = (fota_client_t *)pespconn->reverse; espconn_regist_recvcb(pespconn, get_version_recv); espconn_regist_sentcb(pespconn, get_version_sent_cb); uint8_t user_bin[12] = {0}; if(system_upgrade_userbin_check() == UPGRADE_FW_BIN1) { os_memcpy(user_bin, "image2", os_strlen("image2")); } else if(system_upgrade_userbin_check() == UPGRADE_FW_BIN2) { os_memcpy(user_bin, "image1", os_strlen("image1")); } char *temp = NULL; temp = (uint8 *) os_zalloc(512); os_sprintf(temp, "GET /api/%s/versions/%s HTTP/1.0\r\nHost: %s\r\n"pHeadStatic""pHeadAuthen"\r\n", PROJECT, user_bin, fota_client->host, // fota_client->uuid, //pHeaderAuthen fota_client->token // FOTA_CLIENT // VERSION ); // INFO("request: %s\n", temp); if (FOTA_SECURE) espconn_secure_sent(pespconn, temp, os_strlen(temp)); else espconn_sent(pespconn, temp, os_strlen(temp)); FREE(temp); // prepare to get response get_version_body_len = -1; }
LOCAL void yeelinkget(void) { // struct espconn ptrespconn; // LOCAL esp_tcp esptcp; static u8_t i = 0; static u16_t length; // static char buf[8]={"led"}; char str_tmp[128] = {0}; char remote_server[] = "api.yeelink.net"; static char apikey[] = "fa93b17ce5d3b8bfae0988b503d0b4fa"; static char http_request[DATA_BUF_SIZE] = {0}; //声明为静态变量,防止堆栈溢出 //http://api.yeelink.net/v1.0/device/20857/sensor/36576/datapoints os_sprintf(str_tmp, "/v1.1/device/20857/sensor/36576/datapoints"); os_sprintf(http_request , "POST %s HTTP/1.1\r\n", str_tmp); os_sprintf(str_tmp , "Host:%s\r\n" , remote_server); os_strcat(http_request , str_tmp); os_strcat(http_request , "Accept: */*\r\n"); os_sprintf(str_tmp , "U-ApiKey:%s\r\n" , apikey); //需要替换为自己的APIKey os_strcat(http_request , str_tmp); os_strcat(http_request , "Content-Length: 12\r\n"); os_strcat(http_request , "Content-Type: application/x-www-form-urlencoded\r\n"); os_strcat(http_request , "Connection: close\r\n"); os_strcat(http_request , "\r\n"); os_strcat(http_request , "{\"value\":31}"); length = os_strlen(http_request); os_printf("%s", http_request); espconn_regist_recvcb(&esp_conn, webserver_recv); // espconn_regist_sentcb(&esp_conn, sentcb); espconn_connect(&esp_conn); if (0 == espconn_sent(&esp_conn, http_request, length)) { os_printf("sent ok\n"); } if ((i++) & 0x01) { GPIO_OUTPUT_SET(GPIO_ID_PIN(0), LED_ON); } else { GPIO_OUTPUT_SET(GPIO_ID_PIN(0), LED_OFF); } }
int ICACHE_FLASH_ATTR authBasic(HttpdConnData *connData) { const char *forbidden="401 Forbidden."; int no=0; int r; char hdr[(AUTH_MAX_USER_LEN+AUTH_MAX_PASS_LEN+2)*10]; char userpass[AUTH_MAX_USER_LEN+AUTH_MAX_PASS_LEN+2]; char user[AUTH_MAX_USER_LEN]; char pass[AUTH_MAX_PASS_LEN]; if (connData->conn==NULL) { //Connection aborted. Clean up. return HTTPD_CGI_DONE; } r=httpdGetHeader(connData, "Authorization", hdr, sizeof(hdr)); if (r && strncmp(hdr, "Basic", 5)==0) { r=base64_decode(strlen(hdr)-6, hdr+6, sizeof(userpass), (unsigned char *)userpass); if (r<0) r=0; //just clean out string on decode error userpass[r]=0; //zero-terminate user:pass string // os_printf("Auth: %s\n", userpass); while (((AuthGetUserPw)(connData->cgiArg))(connData, no, user, AUTH_MAX_USER_LEN, pass, AUTH_MAX_PASS_LEN)) { //Check user/pass against auth header if (strlen(userpass)==strlen(user)+strlen(pass)+1 && os_strncmp(userpass, user, strlen(user))==0 && userpass[strlen(user)]==':' && os_strcmp(userpass+strlen(user)+1, pass)==0) { //Authenticated. Yay! return HTTPD_CGI_AUTHENTICATED; } no++; //Not authenticated with this user/pass. Check next user/pass combo. } } //Not authenticated. Go bug user with login screen. httpdStartResponse(connData, 401); httpdHeader(connData, "Content-Type", "text/plain"); httpdHeader(connData, "WWW-Authenticate", "Basic realm=\""HTTP_AUTH_REALM"\""); httpdEndHeaders(connData); espconn_sent(connData->conn, (uint8 *)forbidden, os_strlen(forbidden)); //Okay, all done. return HTTPD_CGI_DONE; }
/****************************************************************************** * FunctionName : upgrade_connect * Description : client connected with a host successfully * Parameters : arg -- Additional argument to pass to the callback function * Returns : none *******************************************************************************/ LOCAL void ICACHE_FLASH_ATTR upgrade_connect_cb(void *arg) { struct espconn *pespconn = arg; UPGRADE_DBG("upgrade_connect_cb\n"); os_timer_disarm(&upgrade_10s); espconn_regist_disconcb(pespconn, upgrade_disconcb); espconn_regist_sentcb(pespconn, upgrade_datasent); if (pbuf != NULL) { UPGRADE_DBG(pbuf); #ifdef UPGRADE_SSL_ENABLE espconn_secure_sent(pespconn, pbuf, os_strlen(pbuf)); #else espconn_sent(pespconn, pbuf, os_strlen(pbuf)); #endif } }