Skip to content

mtanana/UartTools

Repository files navigation

UART Discovery Tool

A powerful Electron-based desktop application for discovering and debugging UART/serial protocols, with specialized Tuya WiFi Module Emulation for MCU pairing. Perfect for reverse engineering unknown UART communications, analyzing serial data streams, and developing/testing Tuya-based IoT devices.

Features

🔌 Tuya WiFi Module Emulation (NEW!)

Emulate a Tuya WiFi module to pair with Tuya MCUs over serial. Ideal for:

  • Testing Tuya MCU firmware without a real WiFi module
  • Reverse engineering Tuya device protocols
  • Developing custom Tuya-compatible devices
  • Debugging MCU-WiFi module communication

Key Capabilities:

  • Full Auto-Pairing: Complete automated pairing sequence with state machine
  • Dual Protocol Support: Standard MCU protocol + Lock variant (with 2-byte sequence)
  • Product Info Response: Configurable PID and version
  • Network Status Simulation: Simulates WiFi → Cloud connection sequence
  • DP Query/Report: Handles Data Point communication
  • Visual Feedback: Real-time pairing state display
  • Protocol Parser Window: Detailed packet analysis with color-coded fields

📡 Connection Management

  • List and connect to any Windows serial port
  • Configurable parameters:
    • Baud rates: 9600 to 921600
    • Data bits: 5, 6, 7, 8
    • Stop bits: 1, 2
    • Parity: None, Even, Odd, Mark, Space

📊 Real-time Data Display

  • Multiple display formats:
    • Hex (with spacing)
    • ASCII (printable characters)
    • Decimal
    • Binary
    • Mixed (Hex + ASCII side-by-side)
  • Timestamps for every message
  • Color-coded sent vs. received data
  • Auto-scroll option

🔍 Protocol Analysis

  • Pattern Detection: Automatically identifies repeated byte sequences
  • Statistics Tracking:
    • Total bytes and messages
    • Bytes per second rate
    • Most common bytes (frequency analysis)
  • Helps discover message structures and protocol patterns

📤 Data Transmission

  • Send data in multiple formats:
    • Plain text (ASCII)
    • Hexadecimal
    • Decimal byte values
  • Optional line ending control (CR, LF)

💾 Data Export

  • Export complete session logs to text file
  • Includes all metadata and statistics
  • Timestamped entries for both sent and received data

⏸️ Playback Controls

  • Pause/resume data capture
  • Clear display
  • Maintains data for analysis even when paused

Installation

Prerequisites

  • Node.js (v16 or later)
  • npm or yarn
  • Windows (for serial port access)

Setup

  1. Install dependencies:

    npm install
  2. Run the application:

    npm start

    For development mode with DevTools:

    npm run dev

Usage

Tuya WiFi Module Emulation Mode

Quick Start: Auto-Pairing with a Tuya MCU

  1. Physical Setup

    • Connect your Tuya MCU's UART TX to your computer's serial RX
    • Connect your Tuya MCU's UART RX to your computer's serial TX
    • Connect GND between MCU and computer
    • Power on the MCU (typically 3.3V or 5V)
  2. Configure the Tool

    • Select the correct COM port
    • Set baud rate (typically 9600 or 115200 for Tuya)
    • Data bits: 8, Stop bits: 1, Parity: None
    • Click Connect
  3. Enable Tuya Mode

    • Check "Enable TUYA Mode"
    • Select Protocol Variant:
      • "Standard MCU": For most Tuya devices
      • "Lock Variant": For Tuya locks (uses 2-byte sequence field)
    • Enter your Product ID (PID) (e.g., ke0iyratqxuqyv3k)
    • Set Module Version (e.g., 1.0.0)
  4. Start Auto-Pairing

    • Ensure "Auto-Pair with MCU" is checked
    • Reset your MCU or wait for it to send heartbeat
    • Watch the TUYA Status field for pairing progress:
      • Waiting for MCU... → Device not communicating yet
      • Heartbeat received → MCU is alive
      • Product info sent → Responded to MCU query
      • Network status: WiFi connected → Simulating WiFi connection
      • Network status: Cloud connected → Fully paired!
      • Paired - DP query sent → Ready for DP communication
  5. Monitor Communication

    • Packets Received: Count of valid frames from MCU
    • Auto-Responses Sent: Count of automatic responses
    • AUTO-RESPONDED indicator flashes when responding
    • Click "Open Protocol Parser" for detailed packet analysis

Tuya Protocol Details

Frame Format (Standard)

55 AA [Ver] [Cmd] [Len Hi] [Len Lo] [Data...] [Checksum]
  • Header: Always 0x55 0xAA
  • Version: 0x00 (MCU sends) or 0x00/0x03 (Module sends)
  • Command: Command ID (see below)
  • Data Length: Big-endian 16-bit length
  • Data: Variable-length payload
  • Checksum: Sum of all bytes from Version onwards, mod 256

Frame Format (Lock Variant)

55 AA [Ver] [Seq Hi] [Seq Lo] [Cmd] [Len Hi] [Len Lo] [Data...] [Checksum]
  • Adds 2-byte sequence number after Version

Command Reference (Module Perspective)

Command Hex Direction Description Data
Heartbeat 0x00 Bidirectional Keep-alive check 0x00 (first) or 0x01 (reconnect)
Product Info 0x01 MCU → Module Query product info Empty (query) / JSON (response)
Work Mode 0x02 MCU → Module Report work mode Work mode byte
WiFi Reset 0x03 MCU → Module Reset WiFi configuration Empty
WiFi Config 0x04 MCU → Module Set pairing mode 0x00=SmartConfig, 0x01=AP, 0x02=Both
WiFi State 0x05 Module → MCU Report network status Status code (see below)
DP Command 0x06 Module → MCU Send control command (DP data) DP format data
DP Report 0x07 MCU → Module Report status (DP data) DP format data
DP Query 0x08 Module → MCU Query all DP values Empty

WiFi Status Codes (used with command 0x05)

  • 0x00: SmartConfig pairing mode (LED fast blink)
  • 0x01: AP pairing mode (LED slow blink)
  • 0x02: WiFi connected, connecting to cloud
  • 0x03: WiFi + Cloud connected (✅ fully online)
  • 0x04: WiFi connected, cloud not connected
  • 0x05: WiFi not connected

Pairing Sequence (Auto-Pair Mode)

1. MCU → Module: Heartbeat (0x00)
2. Module → MCU: Heartbeat ACK (data=0x00)
3. MCU → Module: Product Info Query (0x01)
4. Module → MCU: Product Info Response with JSON: {"p":"PID","v":"1.0.0","m":0}
5. MCU → Module: Work Mode (0x02) 
6. Module → MCU: ACK
7. Module → MCU: WiFi Status = 0x00 (SmartConfig)
8. Module → MCU: WiFi Status = 0x02 (WiFi connected)
9. Module → MCU: WiFi Status = 0x03 (Cloud connected) ✅
10. Module → MCU: DP Query (0x08)
11. MCU → Module: DP Status Report (0x07) with all DP values
12. Module → MCU: ACK
13. ✅ PAIRING COMPLETE - Device is now "online"

Data Point (DP) Format

[DP_ID][Type][Len_Hi][Len_Lo][Value...]
  • DP_ID: Data Point identifier (1 byte)
  • Type: 0x00=Raw, 0x01=Bool, 0x02=Value(int), 0x03=String, 0x04=Enum, 0x05=Bitmap
  • Length: Big-endian 16-bit value length
  • Value: Depends on type

Manual Mode

Disable "Auto-Pair with MCU" to use manual controls:

  • Auto-respond to heartbeats (0x00): Respond to keep-alive checks
  • Auto-respond to product info (0x01): Send product info when queried
  • Auto-respond to work mode (0x02): Acknowledge work mode reports
  • 🔘 Reset Network: Send WiFi reset command

Manual mode is useful for:

  • Testing individual commands
  • Debugging specific protocol issues
  • Learning the protocol step-by-step

Protocol Parser Window

Click "Open Protocol Parser" for advanced analysis:

  • Color-coded bytes: Visual breakdown of each field
  • Checksum validation: ✅ Valid or ❌ Invalid
  • DP data interpretation: Decoded Data Point values
  • Request/Response pairing: See responses inline with requests
  • Export capability: Save parsed packets

Troubleshooting Tuya Pairing

MCU not responding:

  • ✅ Check baud rate (9600 or 115200 most common)
  • ✅ Verify RX/TX are not swapped
  • ✅ Ensure GND is connected
  • ✅ Try power cycling the MCU
  • ✅ Check if MCU is in pairing mode (may need button press)

Pairing stuck:

  • ✅ Click "Reset Network" to restart pairing
  • ✅ Verify Product ID (PID) matches device
  • ✅ Try opposite protocol variant (Standard ↔ Lock)
  • ✅ Check Module Version format (e.g., "1.0.0")

Checksum errors:

  • ✅ Likely wrong protocol variant selected
  • ✅ Try toggling between Standard and Lock variant
  • ✅ Check for electrical noise (shorter cables, shielding)

No heartbeat:

  • ✅ MCU may use different baud rate
  • ✅ MCU may be waiting for module to send first
  • ✅ Some MCUs require DTR/RTS signals

Basic UART Discovery Workflow

  1. Select Serial Port

    • Click "Refresh" to list available ports
    • Select your target port from the dropdown
  2. Configure Connection

    • Set baud rate (default: 115200)
    • Adjust data bits, stop bits, and parity as needed
  3. Connect

    • Click "Connect" button
    • Status indicator will turn green when connected
  4. Monitor Data

    • Incoming data appears in real-time
    • Watch the Pattern Detection section for protocol insights
    • Check Statistics for byte frequency and data rates
  5. Send Commands

    • Enter data in your preferred format
    • Choose line endings if needed
    • Click "Send"
  6. Export Results

    • Click "Export" to save complete session log
    • File includes all data and timestamps

Tips for Protocol Discovery

  1. Start with Common Baud Rates: Try 9600, 115200, or 57600 first
  2. Watch for Patterns: The pattern detector highlights repeated sequences
  3. Check Byte Frequency: Common bytes often indicate delimiters or commands
  4. Try Different Formats: Switch between Hex and Mixed view to spot ASCII strings
  5. Send Test Data: Try common commands like:
    • 0x00, 0xFF (boundary values)
    • ASCII: ?, AT, help, version
    • Sequences: 0xAA 0x55 (common sync patterns)

Project Structure

uartjavascript/
├── main.js              # Electron main process & serial port management
├── preload.js           # IPC bridge for main window (security layer)
├── preload-parser.js    # IPC bridge for parser window
├── renderer.js          # Main window logic, UARTDiscoveryTool class, Tuya state machine
├── parser.js            # Protocol parser window logic, ProtocolParser class
├── index.html           # Main window UI structure
├── parser.html          # Parser window UI structure
├── styles.css           # Main window styling
├── parser.css           # Parser window styling
├── package.json         # Dependencies & scripts
└── README.md            # This file

Architecture

Security Model

  • Uses Electron's contextIsolation and contextBridge
  • Renderer process has no direct access to Node.js
  • All serial operations via secure IPC channels

Key Components

Main Process (main.js)

  • Manages Electron window lifecycle
  • Handles serial port operations via serialport library
  • Provides IPC handlers for port control
  • Forwards parsed packets between main window and parser window

Renderer Process (renderer.js)

  • UARTDiscoveryTool class manages UI and analysis
  • TuyaProtocolParser class for fallback parsing
  • Tuya pairing state machine with full auto-pairing logic
  • Pattern detection algorithm
  • Byte frequency tracking
  • Real-time statistics calculation

Parser Window (parser.js)

  • ProtocolParser class for dedicated packet analysis
  • Visual packet breakdown with color-coded fields
  • Checksum validation
  • DP (Data Point) interpretation
  • Request/response correlation

Preload Scripts

  • preload.js: Exposes window.serialAPI for main window
  • preload-parser.js: Exposes IPC for parser window
  • Provides secure API: listPorts, openPort, closePort, sendData
  • Events: onSerialData, onSerialError, onPortClosed, onParsedPacket

Dependencies

  • electron: Desktop app framework
  • serialport: Serial port communication library

Troubleshooting

Serial Port Latency Issues (Out-of-Order Data)

If you see data arriving out of sequence, you may need to reduce USB-Serial latency at the Windows driver level:

For FTDI Devices (FT232, FT2232, etc.):

  1. Open Device Manager (Win+X, then select Device Manager)
  2. Expand Ports (COM & LPT)
  3. Right-click your COM port → Properties
  4. Go to Port Settings tab → Advanced
  5. Set Latency Timer (msec) to 1 or 2 (default is 16)
  6. Click OK and reconnect

For CH340/CH341 Devices:

  1. Open Device Manager
  2. Right-click COM port → PropertiesPort Settings
  3. Set Receive Buffer and Transmit Buffer to lowest values (4096 or lower)
  4. Click OK and reconnect

For All USB-Serial Adapters:

  1. Try a different physical USB port (prefer USB 2.0 ports over USB 3.0 for serial)
  2. Use a shorter USB cable (< 6 feet / 2 meters)
  3. Avoid USB hubs - connect directly to computer
  4. Lower baud rate if possible (9600 instead of 115200)

Port Access Issues

  • Ensure no other application is using the port
  • On Windows, check Device Manager for COM port availability
  • Try disconnecting and reconnecting the device

Data Not Appearing

  • Verify baud rate matches device configuration
  • Check data bits, stop bits, and parity settings
  • Try different baud rates if unknown

Build Errors

  • Run npm install to ensure all dependencies are installed
  • Delete node_modules and reinstall if needed
  • Check Node.js version (requires v16+)

License

MIT

Contributing

Contributions welcome! Areas for enhancement:

  • Additional Tuya commands (OTA updates, time sync)
  • Other protocol analyzers (Modbus, MQTT-SN)
  • Save/load device profiles (PID, baud rate, protocol variant)
  • Scripting/automation for testing
  • Custom DP definitions
  • Graphical timeline view
  • Packet filtering and search

References

Tuya Protocol Documentation

Serial Communication

Acknowledgments

  • Tuya protocol reverse engineering community
  • Electron and Node-Serialport maintainers
  • All contributors and testers

About

Tools for Decoding Uart Protocols

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages