ESP8266 AP模式TCP server 串口透传

背景:Linux设备装整机后出问题需要调试必须拆壳,不方便,预留调试线影响设备密封性,所以想到使用无线模块把调试串口透传到PC。

解决方案:

1、ESP8266开机进入AP模式,AP的SSID关联设备SN,调试人员根据SSID关联的SN可以知道需要接入的待调试产品。

2、ESP8266开机启动TCP server,该SERVER只能接入一个客户端,当客户端接入后循环接收串口数据发给客户端,接收客户端数据发给串口,实现数据透传。

实现代码如下,AP SSID关联SN部分因涉及公司产品细节已略去,一个简单的demo,待完善。

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <WiFiServer.h>

#ifndef APSSID
#define APSSID "ESP8266ap"
#define APPSK  "12345678"
#endif

/* Set these to your desired credentials. */
const char *ssid = APSSID;
const char *password = APPSK;

WiFiServer server(22333); //声明服务器对象

void setup() {
  delay(1000);
  Serial.begin(115200);
  Serial.println();
  Serial.print("Configuring access point...");
  /* You can remove the password parameter if you want the AP to be open. */
  WiFi.softAP(ssid, password);

  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);

  server.begin(); //服务器启动监听端口号22333
}

void loop()
{
    WiFiClient client = server.available(); //尝试建立客户对象
    if (client) //如果当前客户可用
    {
        Serial.println("[Client connected]");
        uint8_t readBuf[256];

        //!!!注意:此处为处理一次接收大于256字节情况

        while (client.connected()) //如果客户端处于连接状态
        {
            int inComingBytes = client.available();  //接收客户端数据转发给串口
            if(inComingBytes && inComingBytes < 256){
              client.read(readBuf, inComingBytes);
              Serial.write(readBuf, inComingBytes);
            }
   
            inComingBytes = Serial.available();  //接收串口数据转发给客户端
            if(inComingBytes && inComingBytes < 256){
              Serial.read((char*)readBuf, inComingBytes);
              client.write(readBuf, inComingBytes);
            }
        }
        client.stop(); //结束当前连接:
        Serial.println("[Client disconnected]");
    }
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值