You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Expo与React Native连接OBD2 Wifi设备的WebSocket问题求助

OBD2 WiFi读取器TCP连接解决方案(Expo/React Native)

核心问题诊断

你用错了通信协议:OBD2 WiFi读取器和ezobd模拟器都是原始TCP套接字服务,而非WebSocket服务。浏览器/React Native的WebSocket API依赖HTTP握手流程,OBD2设备无法识别该协议,因此会出现连接超时或握手失败的错误。

解决方案步骤

1. 替换WebSocket为TCP套接字库

在Expo项目中,使用官方提供的expo-tcp-socket库实现原始TCP连接,无需 eject 项目。
安装依赖:

npx expo install expo-tcp-socket

2. 修改连接代码

替换原WebSocket连接逻辑为TCP连接:

import { Socket } from 'expo-tcp-socket';

let tcpSocket = null;

const connect = () => {
  if (connectionStatus === 'disconnected') {
    setConnectionStatus('connecting');
    const currentTime = new Date().getTime();

    // 建立TCP连接
    tcpSocket = Socket.connect({
      host: ip,
      port: port,
      timeout: 10000, // 设置10秒超时
    }, () => {
      console.log("TCP连接建立成功");
      Alert.alert(`连接成功,耗时${new Date().getTime() - currentTime}ms`);
      setConnectionStatus('connected');
      
      // 发送OBD2初始化指令(示例:重置设备)
      tcpSocket.write('ATZ\r\n');
    });

    // 监听设备返回数据
    tcpSocket.on('data', (data) => {
      const response = data.toString();
      console.log("收到设备数据:", response);
      Alert.alert("收到消息:" + response);
    });

    // 监听连接错误
    tcpSocket.on('error', (error) => {
      console.log("连接错误:", error);
      setConnectionStatus('disconnected');
      Alert.alert("连接失败:" + error.message);
    });

    // 监听连接关闭
    tcpSocket.on('close', () => {
      console.log("连接已关闭");
      setConnectionStatus('disconnected');
      Alert.alert("连接已关闭");
    });
  } else {
    Alert.alert("正在建立连接中,请稍候");
  }
};

// 新增断开连接函数
const disconnect = () => {
  if (tcpSocket) {
    tcpSocket.destroy();
    tcpSocket = null;
  }
};

3. 模拟器连接修复

使用上述TCP代码连接ezobd模拟器,即可正常通信。模拟器会响应标准OBD2指令(如发送ATZ返回OK)。

4. 真实设备连接注意事项

  • 确保iPhone已连接到OBD2设备的WiFi热点
  • 发送OBD2指令时必须添加\r\n作为结束符,符合协议规范
  • 关闭iPhone蜂窝数据,避免网络切换导致连接中断
  • 可先用电脑telnet 192.168.0.10 35000测试设备连通性,确认设备正常后再调试代码

内容的提问来源于stack exchange,提问作者Gil Teixeira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 12:55:01