edatahub ED-BLE

Industrial Debugging

The edatahub ED-N2 secondary development documentation: developers do not need to worry about underlying hardware circuits, interface drivers, power adaptation, or the Bluetooth hardware protocol stack. Based solely on the device's open software interfaces, communication protocols, and parameter configuration rules, you can quickly develop and ship software features such as mobile apps, IoT host computers, embedded applications, data acquisition systems, and device management platforms.

TL;DR

The edatahub ED-N2 secondary development documentation is for device-maker developers: without touching underlying hardware circuits, interface drivers, or the Bluetooth protocol stack, you can build WeChat mini programs, IoT host computers, and other software features on the open BLE characteristics, RS485 serial parameters, and data transparent-transmission protocol — with complete code samples and parameter quick references included.

BLE BluetoothRS485Secondary development

What does the edatahub ED-N2 secondary development documentation cover?

Developer-oriented ED-N2 secondary development guide: it applies to the ED-N2-RS485 serial debugger and is designed to let developers ship the software side without touching hardware circuits.

edatahub ED Secondary Development edatahub ED-N2 Secondary Development Documentation Applicable device: edatahub ED-N2-RS485 serial debugger Purpose: developers do not need to worry about underlying hardware circuits, interface drivers, power adaptation, or the Bluetooth hardware protocol stack. Based solely on the device's open software interfaces, communication protocols, and parameter configuration rules, you can quickly develop and ship software features such as mobile apps, IoT host computers, embedded applications, data acquisition systems, and device management platforms. Attribution: this document was compiled by Wuhan Shuentropy Technology Co., Ltd. specifically for its edatahub ED-N2-RS485 serial debugger. Official website: edatahub.cn. Compiled: 2026-08-09

What chapters does the secondary development documentation include?

The documentation has 9 chapters: device overview, BLE characteristics, RS485 serial parameters, data transparent transmission, serial configuration write, line state control, UART status notification, code samples, and the parameter quick reference.

  • Device overview
  • BLE characteristic definitions
  • RS485 serial parameter definitions
  • BLE data transparent transmission protocol
  • Serial configuration write protocol
  • Line state control protocol
  • UART status notification protocol
  • Secondary development code samples
  • Appendix: parameter quick reference

1. Device overview: what is the edatahub ED-N2?

The overview table gives the ED-N2-RS485 product model, communication interface, power supply, and battery life — a quick reference for confirming hardware capabilities before integration.

ItemValue
Product modeledatahub ED-N2
Product nameBluetooth serial debugger (RS485 + BLE)
BLE device nameedatahub ED-N2-RS485
Communication interfaceRS485 half-duplex serial port
Connection methodBLE (mobile app / mini program / host computer)

1.1 Channel numbering

The ED-N2 uses the RS485 channel only:

Channel valueChannel nameDescription
0x00RS485RS485 half-duplex serial port

2. How are the BLE characteristics defined?

Defines the BLE device name (edatahub ED-N2-RS485) and the service/characteristic UUIDs; the phone app establishes the connection and data channel by these characteristics.

2.1 BLE device name

Plaintext
数熵ED-N2-RS485

2.2 BLE service overview

The device exposes 3 BLE services. All UUIDs are 128-bit custom UUIDs sharing the suffix -B5A3-F393-E0A9-E50E24DCCA9E; only the prefix differs:

Service nameService UUIDUUID prefixPurpose
Nordic UART Service6E400001-B5A3-F393-E0A9-E50E24DCCA9E6E40RS485 raw data transparent transmission (send/receive business data)
Serial Config Service8E400001-B5A3-F393-E0A9-E50E24DCCA9E8E40RS485 serial parameter configuration, line state control, UART status notification
Wi-Fi Provisioning Service9E400001-B5A3-F393-E0A9-E50E24DCCA9E9E40Battery/device status reading

2.3 Complete characteristic definitions

2.3.1 Nordic UART Service — RS485 data transparent transmission

CharacteristicUUIDPropertiesPurpose
RX Characteristic6E400002-B5A3-F393-E0A9-E50E24DCCA9EWrite / Write Without ResponsePhone → device: written bytes are forwarded as-is to the RS485 bus
TX Characteristic6E400003-B5A3-F393-E0A9-E50E24DCCA9ENotifyDevice → phone: RS485 return data is reported via Notify

2.3.2 Serial Config Service — RS485 serial configuration

CharacteristicUUIDPropertiesPurpose
UART Config8E400002-B5A3-F393-E0A9-E50E24DCCA9EWrite / Write Without ResponseConfigure RS485 baud rate, data bits, stop bits, and parity
Line State8E400003-B5A3-F393-E0A9-E50E24DCCA9EWrite / Write Without ResponseConfigure DTR / RTS / Break line states
UART Status8E400004-B5A3-F393-E0A9-E50E24DCCA9ENotifyReport UART status mask and error counters

2.3.3 Wi-Fi Provisioning Service — battery status

CharacteristicUUIDPropertiesPurpose
Status Characteristic9E400003-B5A3-F393-E0A9-E50E24DCCA9ERead / NotifyRead/subscribe device status and battery data (UTF-8 text)

3. How are the RS485 serial parameters defined?

The parameter table lists the options and descriptions for baud rate, data bits, stop bits, and parity; match the slave device protocol for stable communication.

3.1 Parameter overview

ParameterFieldOptionsDescription
Baud ratebaud1200 ~ 2000000Serial baud rate (bps)
Data bitsdata_bits5 / 6 / 7 / 8Data bit length
Stop bitsstop_bits0 / 1 / 20 = 1 stop bit, 1 = 1.5 stop bits, 2 = 2 stop bits
Parityparity0 / 1 / 2 / 3 / 40 = None, 1 = Odd, 2 = Even; 3/4 degrade to None

3.2 Common configurations

Serial configbauddata_bitsstop_bitsparity
9600 8N1 (most common)9600800
19200 8N119200800
38400 8N138400800
115200 8N1115200800
9600 8E1 (even parity)9600802
9600 8O1 (odd parity)9600801
9600 7N19600700

3.3 Parameter encoding

Plaintext
data_bits:  5=0x05  6=0x06  7=0x07  8=0x08
stop_bits:  1 bit=0x00  1.5 bits=0x01  2 bits=0x02
parity:     None=0x00  Odd=0x01  Even=0x02  (3/4 degrade to None)

4. How does the BLE data transparent transmission protocol work?

Data flow: bytes written to the RX characteristic are sent to the RS485 bus; bus return data is reported via the TX characteristic — bidirectional transparent transmission between phone and device.

4.1 Data flow

Plaintext
┌──────────┐   Write NUS RX     ┌──────────┐   RS485      ┌──────────┐
│  Phone   │ ──────────────────→ │  ED-N2   │ ─────────→ │RS485 slave│
│          │ ←────────────────── │          │ ←───────── │          │
└──────────┘  Notify NUS TX      └──────────┘   RS485      └──────────┘

4.2 Data rules

RuleDescription
No frame headerThe data link uses no frame header; written bytes are forwarded as-is to RS485
Transparent writeBytes written to NUS RX are written as-is to the RS485 bus
Transparent reportRS485 return data is reported as-is via NUS TX Notify
BinaryAll data is binary bytes, not text
No packetizationThe device does not frame protocols such as Modbus; the host computer handles it

4.3 NUS RX write (phone → device)

Write raw bytes to 6E400002-B5A3-F393-E0A9-E50E24DCCA9E, e.g. a Modbus RTU request frame:

Plaintext
01 03 00 00 00 02 C4 0B

On receipt, the device writes the bytes as-is to the RS485 bus.

4.4 NUS TX Notify (device → phone)

Subscribe to Notify on 6E400003-B5A3-F393-E0A9-E50E24DCCA9E; the device pushes RS485 return data as-is. Example slave response:

Plaintext
01 03 04 00 64 00 C8 BA 7A

5. How do I use the serial configuration write protocol?

Write the baud rate, data bits, stop bits, and parity via the UART Config characteristic; the ED-N2 supports the default 8-byte write format, and settings take effect immediately.

Write via the UART Config characteristic (8E400002-B5A3-F393-E0A9-E50E24DCCA9E) of the Serial Config Service.

5.1 Write formats

The ED-N2 is a pure RS485 product and supports the following two write formats:

Format 1: 8 bytes (default RS485)

Plaintext
baud_le32(4) + data_bits(1) + stop_bits(1) + parity(1) + reserved(1)

baud_le32

Baud rate, 4 bytes little-endian

reserved

Reserved byte, fill with 0x00

Example: 9600 8N1

Plaintext
80 25 00 00  08  00  00  00
└─baud_le32┘ └db┘└sb┘└pr┘└rs┘

9600 = 0x2580, little-endian = 80 25 00 00

Format 2: 9 bytes (with channel identifier)

Plaintext
channel(1, fixed 0x00) + baud_le32(4) + data_bits(1) + stop_bits(1) + parity(1) + reserved(1)
  • channel is fixed at 0x00 (RS485)

Example: 115200 8N1

Plaintext
00  00 C2 01 00  08  00  00  00
└ch┘└─baud_le32┘ └db┘└sb┘└pr┘└rs┘

115200 = 0x01C200, little-endian = 00 C2 01 00

5.2 Little-endian encoding of common baud rates

Baud rateHexadecimalLittle-endian bytes
12000x04B0B0 04 00 00
24000x096060 09 00 00
48000x12C0C0 12 00 00
96000x258080 25 00 00
192000x4B0000 4B 00 00
384000x960000 96 00 00
576000xE10000 E1 00 00
1152000x1C20000 C2 01 00
2304000x3840000 84 03 00
4608000x7080000 08 07 00
9216000xE100000 10 0E 00

6. How do I use the line state control protocol?

Write DTR and RTS state bytes via the Line State characteristic to control device line-state signals, covering slave scenarios that need handshake signals.

Write via the Line State characteristic (8E400003-B5A3-F393-E0A9-E50E24DCCA9E) of the Serial Config Service.

6.1 Write formats

Format 1: 2 bytes

Plaintext
DTR(1) + RTS(1)

Format 2: 4 bytes (with Break)

Plaintext
DTR(1) + RTS(1) + BreakCmd(1) + BreakDuration100ms(1)

6.2 Parameter description

ParameterValueDescription
DTR0 / 1DTR level state
RTS0 / 1RTS level state
BreakCmd0x00 / 0x01 / 0xFF0x00 = stop/none, 0x01 = start Break, 0xFF = hold Break
BreakDuration100ms0~255Break duration in units of 100ms

7. What does the UART status notification protocol return?

The UART Status characteristic reports an 8-byte status mask with frame error counters; the app can use it to diagnose RS485 communication quality.

Reported via Notify on the UART Status characteristic (8E400004-B5A3-F393-E0A9-E50E24DCCA9E) of the Serial Config Service.

7.1 Data format (8 bytes)

Plaintext
status_mask(1) + frame_err_count(1) + parity_err_count(1) + overrun_err_count(1) + 00 + 00 + 00 + 00

7.2 status_mask bit definitions

BitHexadecimalDescription
bit00x01DCD
bit10x02DSR
bit20x04BREAK
bit30x08RI
bit40x10Frame Error
bit50x20Parity Error
bit60x40Overrun Error
bit70x80CTS

8. What secondary development code samples are provided?

Complete WeChat mini program samples for BLE connection and RS485 transparent transmission, usable directly as integration templates.

8.1 WeChat mini program — BLE connection + RS485 transparent transmission

JavaScript
// ===== edatahub ED-N2 BLE constants =====
const BLE_DEVICE_NAME = '数熵ED-N2-RS485'

// Nordic UART Service (RS485 data transparent transmission)
const NUS_SERVICE_UUID = '6E400001-B5A3-F393-E0A9-E50E24DCCA9E'
const NUS_RX_CHAR_UUID = '6E400002-B5A3-F393-E0A9-E50E24DCCA9E' // Write
const NUS_TX_CHAR_UUID = '6E400003-B5A3-F393-E0A9-E50E24DCCA9E' // Subscribe Notify

// Serial Config Service (RS485 serial configuration)
const CFG_SERVICE_UUID     = '8E400001-B5A3-F393-E0A9-E50E24DCCA9E'
const CFG_UART_CONFIG_UUID = '8E400002-B5A3-F393-E0A9-E50E24DCCA9E' // Write serial parameters
const CFG_LINE_STATE_UUID  = '8E400003-B5A3-F393-E0A9-E50E24DCCA9E' // Write line state
const CFG_UART_STATUS_UUID = '8E400004-B5A3-F393-E0A9-E50E24DCCA9E' // Subscribe status

// Wi-Fi Provisioning Service (battery status)
const WF_SERVICE_UUID = '9E400001-B5A3-F393-E0A9-E50E24DCCA9E'
const WF_STATUS_UUID  = '9E400003-B5A3-F393-E0A9-E50E24DCCA9E' // Read battery

// RS485 channel
const CHANNEL_RS485 = 0x00

let deviceId = ''

// ===== 1. Initialize the Bluetooth adapter =====
function initBLE() {
  return new Promise((resolve, reject) => {
    wx.openBluetoothAdapter({
      success: resolve,
      fail: reject
    })
  })
}

// ===== 2. Scan for and connect the device =====
function scanAndConnect() {
  return new Promise((resolve, reject) => {
    wx.startBluetoothDevicesDiscovery({
      success: () => {
        wx.onBluetoothDeviceFound((res) => {
          const device = res.devices[0]
          if (device.name === BLE_DEVICE_NAME) {
            wx.stopBluetoothDevicesDiscovery()
            wx.createBLEConnection({
              deviceId: device.deviceId,
              success: () => {
                deviceId = device.deviceId
                console.log('Device connected:', device.name)
                resolve(deviceId)
              },
              fail: reject
            })
          }
        })
      },
      fail: reject
    })
  })
}

// ===== 3. Configure RS485 serial parameters =====
// baud=9600, data_bits=8, stop_bits=0 (1 bit), parity=0 (None)
function configRS485(baud = 9600, dataBits = 8, stopBits = 0, parity = 0) {
  // 8-byte format: baud_le32 + data_bits + stop_bits + parity + reserved
  const buffer = new ArrayBuffer(8)
  const view = new DataView(buffer)
  view.setUint32(0, baud, true)   // baud little-endian
  view.setUint8(4, dataBits)       // data_bits
  view.setUint8(5, stopBits)       // stop_bits
  view.setUint8(6, parity)         // parity
  view.setUint8(7, 0x00)           // reserved

  return new Promise((resolve, reject) => {
    wx.writeBLECharacteristicValue({
      deviceId,
      serviceId: CFG_SERVICE_UUID,
      characteristicId: CFG_UART_CONFIG_UUID,
      value: buffer,
      success: () => {
        const parityStr = ['N', 'O', 'E'][parity] || 'N'
        const stopStr = stopBits === 0 ? '1' : stopBits === 1 ? '1.5' : '2'
        console.log(`RS485 configured: ${baud} ${dataBits}${parityStr}${stopStr}`)
        resolve()
      },
      fail: reject
    })
  })
}

// ===== 4. Subscribe to NUS TX (receive RS485 return data) =====
function subscribeNusTx(onData) {
  return new Promise((resolve, reject) => {
    wx.notifyBLECharacteristicValueChange({
      deviceId,
      serviceId: NUS_SERVICE_UUID,
      characteristicId: NUS_TX_CHAR_UUID,
      state: true,
      success: () => {
        wx.onBLECharacteristicValueChange((res) => {
          if (res.characteristicId === NUS_TX_CHAR_UUID) {
            onData(new Uint8Array(res.value))
          }
        })
        console.log('Subscribed to NUS TX Notify')
        resolve()
      },
      fail: reject
    })
  })
}

// ===== 5. Send data to RS485 (write NUS RX) =====
function sendToRS485(bytes) {
  const buffer = new ArrayBuffer(bytes.length)
  const view = new Uint8Array(buffer)
  for (let i = 0; i < bytes.length; i++) {
    view[i] = bytes[i]
  }

  return new Promise((resolve, reject) => {
    wx.writeBLECharacteristicValue({
      deviceId,
      serviceId: NUS_SERVICE_UUID,
      characteristicId: NUS_RX_CHAR_UUID,
      value: buffer,
      success: resolve,
      fail: reject
    })
  })
}

// ===== 6. Read battery status =====
function readBatteryStatus() {
  return new Promise((resolve, reject) => {
    wx.readBLECharacteristicValue({
      deviceId,
      serviceId: WF_SERVICE_UUID,
      characteristicId: WF_STATUS_UUID,
      success: () => {
        wx.onBLECharacteristicValueChange((res) => {
          if (res.characteristicId === WF_STATUS_UUID) {
            const text = arrayBufferToUtf8(res.value)
            resolve(parseStatusText(text))
          }
        })
      },
      fail: reject
    })
  })
}

// ===== Utility functions =====
function arrayBufferToUtf8(buffer) {
  return decodeURIComponent(escape(String.fromCharCode(...new Uint8Array(buffer))))
}

function parseStatusText(text) {
  const result = {}
  text.split(';').forEach(pair => {
    const [key, val] = pair.split('=')
    result[key] = val
  })
  return result
}

// ===== Full usage example =====
async function demo() {
  try {
    await initBLE()
    await scanAndConnect()

    // Configure RS485: 9600 8N1
    await configRS485(9600, 8, 0, 0)

    // Subscribe to receive RS485 return data
    await subscribeNusTx((data) => {
      const hex = Array.from(data).map(b => b.toString(16).padStart(2, '0')).join(' ')
      console.log('RS485 RX:', hex)
    })

    // Send Modbus RTU: read holding registers, slave 01, start address 0, quantity 2
    await sendToRS485([0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC4, 0x0B])

    // Read battery
    const battery = await readBatteryStatus()
    console.log('Battery:', battery.BAT_P + '%', battery.BAT_V + 'V')
  } catch (err) {
    console.error('Operation failed:', err)
  }
}

8.2 Android (Kotlin) — BLE connection + RS485 transparent transmission

Kotlin
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattDescriptor
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.UUID

class EdN2BLE {

    companion object {
        const val DEVICE_NAME = "数熵ED-Slink"

        // Nordic UART Service (RS485 data transparent transmission)
        val NUS_SERVICE_UUID     = UUID.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")
        val NUS_RX_CHAR_UUID     = UUID.fromString("6E400002-B5A3-F393-E0A9-E50E24DCCA9E") // Write
        val NUS_TX_CHAR_UUID     = UUID.fromString("6E400003-B5A3-F393-E0A9-E50E24DCCA9E") // Notify

        // Serial Config Service (RS485 serial configuration)
        val CFG_SERVICE_UUID     = UUID.fromString("8E400001-B5A3-F393-E0A9-E50E24DCCA9E")
        val CFG_UART_CONFIG_UUID = UUID.fromString("8E400002-B5A3-F393-E0A9-E50E24DCCA9E") // Write
        val CFG_UART_STATUS_UUID = UUID.fromString("8E400004-B5A3-F393-E0A9-E50E24DCCA9E") // Notify

        // Wi-Fi Provisioning Service (battery status)
        val WF_SERVICE_UUID      = UUID.fromString("9E400001-B5A3-F393-E0A9-E50E24DCCA9E")
        val WF_STATUS_UUID       = UUID.fromString("9E400003-B5A3-F393-E0A9-E50E24DCCA9E") // Read/Notify

        // CCCD Descriptor (enable Notify)
        val CCCD_UUID            = UUID.fromString("00002902-0000-1000-8000-00805F9B34FB")
    }

    private var gatt: BluetoothGatt? = null
    private var onDataReceived: ((ByteArray) -> Unit)? = null

    /**
     * Configure RS485 serial parameters (8-byte format)
     * @param baud Baud rate, e.g. 9600
     * @param dataBits Data bits 5/6/7/8
     * @param stopBits Stop bits 0=1 bit, 1=1.5 bits, 2=2 bits
     * @param parity Parity 0=None, 1=Odd, 2=Even
     */
    fun configRS485(baud: Int, dataBits: Int = 8, stopBits: Int = 0, parity: Int = 0) {
        val buffer = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN)
        buffer.putInt(baud)                // baud (little-endian)
        buffer.put(dataBits.toByte())      // data_bits
        buffer.put(stopBits.toByte())      // stop_bits
        buffer.put(parity.toByte())        // parity
        buffer.put(0x00)                   // reserved

        writeCharacteristic(CFG_UART_CONFIG_UUID, buffer.array(), CFG_SERVICE_UUID)
    }

    /**
     * Send data to RS485 (via NUS RX write)
     */
    fun sendToRS485(data: ByteArray) {
        writeCharacteristic(NUS_RX_CHAR_UUID, data, NUS_SERVICE_UUID)
    }

    /**
     * Subscribe to NUS TX Notify (receive RS485 return data)
     */
    fun subscribeNusTx(callback: (ByteArray) -> Unit) {
        onDataReceived = callback
        enableNotify(NUS_TX_CHAR_UUID, NUS_SERVICE_UUID)
    }

    /**
     * Send a Modbus RTU read holding registers request
     * @param slaveAddr Slave address
     * @param startAddr Start register address
     * @param quantity Register quantity
     */
    fun sendModbusReadHoldingRegisters(slaveAddr: Int, startAddr: Int, quantity: Int) {
        val frame = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN)
        frame.put(slaveAddr.toByte())          // Slave address
        frame.put(0x03)                         // Function code: read holding registers
        frame.putShort(startAddr.toShort())     // Start address
        frame.putShort(quantity.toShort())       // Register quantity

        // Compute Modbus CRC16
        val crc = calculateCRC16(frame.array(), 6)
        frame.putShort(crc.toShort())

        sendToRS485(frame.array())
    }

    private fun writeCharacteristic(uuid: UUID, data: ByteArray, serviceUuid: UUID) {
        val service = gatt?.getService(serviceUuid) ?: return
        val char = service.getCharacteristic(uuid) ?: return
        char.value = data
        char.writeType = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
        gatt?.writeCharacteristic(char)
    }

    private fun enableNotify(uuid: UUID, serviceUuid: UUID) {
        val service = gatt?.getService(serviceUuid) ?: return
        val char = service.getCharacteristic(uuid) ?: return
        gatt?.setCharacteristicNotification(char, true)
        val descriptor = char.getDescriptor(CCCD_UUID)
        descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
        gatt?.writeDescriptor(descriptor)
    }

    /**
     * Modbus CRC16 computation
     */
    private fun calculateCRC16(data: ByteArray, length: Int): Int {
        var crc = 0xFFFF
        for (i in 0 until length) {
            crc = crc xor (data[i].toInt() and 0xFF)
            for (j in 0 until 8) {
                crc = if (crc and 0x0001 != 0) (crc shr 1) xor 0xA001 else crc shr 1
            }
        }
        return crc
    }
}

8.3 Python — BLE connection + RS485 transparent transmission (bleak)

Python
"""
edatahub ED-N2 portable debugger BLE secondary development example (Python + bleak)
Dependency: pip install bleak
"""
import asyncio
import struct
from bleak import BleakClient, BleakScanner

# ===== BLE constants =====
DEVICE_NAME = "数熵ED-N2-RS485"

# Nordic UART Service (RS485 data transparent transmission)
NUS_SERVICE_UUID     = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
NUS_RX_CHAR_UUID     = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"  # Write
NUS_TX_CHAR_UUID     = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"  # Notify

# Serial Config Service (RS485 serial configuration)
CFG_SERVICE_UUID     = "8E400001-B5A3-F393-E0A9-E50E24DCCA9E"
CFG_UART_CONFIG_UUID = "8E400002-B5A3-F393-E0A9-E50E24DCCA9E"  # Write
CFG_LINE_STATE_UUID  = "8E400003-B5A3-F393-E0A9-E50E24DCCA9E"  # Write
CFG_UART_STATUS_UUID = "8E400004-B5A3-F393-E0A9-E50E24DCCA9E"  # Notify

# Wi-Fi Provisioning Service (battery status)
WF_SERVICE_UUID      = "9E400001-B5A3-F393-E0A9-E50E24DCCA9E"
WF_STATUS_UUID       = "9E400003-B5A3-F393-E0A9-E50E24DCCA9E"  # Read/Notify


# ===== Modbus CRC16 computation =====
def crc16(data: bytes) -> int:
    crc = 0xFFFF
    for byte in data:
        crc ^= byte
        for _ in range(8):
            crc = (crc >> 1) ^ 0xA001 if (crc & 0x0001) else (crc >> 1)
    return crc


# ===== Build the RS485 serial configuration command (8-byte format) =====
def build_uart_config(baud: int, data_bits: int = 8,
                      stop_bits: int = 0, parity: int = 0) -> bytes:
    """
    Build the RS485 serial configuration bytes
    baud:      1200~2000000
    data_bits: 5/6/7/8
    stop_bits: 0=1 bit, 1=1.5 bits, 2=2 bits
    parity:    0=None, 1=Odd, 2=Even
    """
    return struct.pack('<IBBBB', baud, data_bits, stop_bits, parity, 0x00)


# ===== Build a Modbus RTU read holding registers request =====
def build_modbus_read_holding(slave: int, start_addr: int, quantity: int) -> bytes:
    """Build a Modbus RTU function code 03 request frame"""
    frame = struct.pack('>BBHH', slave, 0x03, start_addr, quantity)
    crc = crc16(frame)
    return frame + struct.pack('<H', crc)


class EdN2BLE:
    """edatahub ED-N2 BLE device wrapper"""

    def __init__(self, address: str = None):
        self.address = address
        self.client = None

    async def scan(self) -> str:
        """Scan for the device and return its address"""
        print(f"Searching for {DEVICE_NAME} ...")
        device = await BleakScanner.find_device_by_name(DEVICE_NAME)
        if device:
            self.address = device.address
            print(f"Device found: {device.name} ({device.address})")
            return device.address
        raise FileNotFoundError(f"Device not found: {DEVICE_NAME}")

    async def connect(self):
        """Connect to the device"""
        if not self.address:
            await self.scan()
        self.client = BleakClient(self.address)
        await self.client.connect()
        print(f"Connected: {self.address}")
        # Subscribe to NUS TX Notify (receive RS485 return data)
        await self.client.start_notify(NUS_TX_CHAR_UUID, self._on_nus_tx)

    async def disconnect(self):
        """Disconnect"""
        if self.client and self.client.is_connected:
            await self.client.disconnect()
            print("Disconnected")

    def _on_nus_tx(self, sender, data: bytearray):
        """NUS TX Notify callback: receive RS485 return data"""
        hex_str = ' '.join(f'{b:02X}' for b in data)
        print(f"[RX] {hex_str}")

    async def config_rs485(self, baud: int = 9600, data_bits: int = 8,
                           stop_bits: int = 0, parity: int = 0):
        """Configure RS485 serial parameters"""
        payload = build_uart_config(baud, data_bits, stop_bits, parity)
        await self.client.write_gatt_char(CFG_UART_CONFIG_UUID, payload, response=False)
        parity_str = ['N', 'O', 'E'][parity] if parity < 3 else 'N'
        stop_str = str(stop_bits) if stop_bits != 1 else '1.5'
        print(f"[CFG] RS485: {baud} {data_bits}{parity_str}{stop_str}")

    async def send_to_rs485(self, data: bytes):
        """Send data to RS485"""
        await self.client.write_gatt_char(NUS_RX_CHAR_UUID, data, response=False)
        hex_str = ' '.join(f'{b:02X}' for b in data)
        print(f"[TX] {hex_str}")

    async def send_modbus_read(self, slave: int = 1, start_addr: int = 0, quantity: int = 2):
        """Send a Modbus RTU read holding registers request"""
        frame = build_modbus_read_holding(slave, start_addr, quantity)
        await self.send_to_rs485(frame)

    async def read_battery_status(self) -> dict:
        """Read battery/device status"""
        data = await self.client.read_gatt_char(WF_STATUS_UUID)
        text = data.decode('utf-8')
        return self._parse_status(text)

    @staticmethod
    def _parse_status(text: str) -> dict:
        """Parse status text V=1;BAT_V=3.987;..."""
        result = {}
        for pair in text.split(';'):
            if '=' in pair:
                key, val = pair.split('=', 1)
                result[key] = val
        return result


# ===== Full usage example =====
async def main():
    ed = EdN2BLE()
    try:
        # 1. Connect to the device
        await ed.connect()

        # 2. Configure RS485: 9600 8N1
        await ed.config_rs485(baud=9600, data_bits=8, stop_bits=0, parity=0)

        # 3. Read battery status
        status = await ed.read_battery_status()
        print(f"Battery: {status.get('BAT_P', '?')}%  {status.get('BAT_V', '?')}V  charging:{status.get('BAT_CHG', '0')}")

        # 4. Send a Modbus RTU request and wait for the response
        #    Slave address=1, function code=03 (read holding registers), start address=0, quantity=2
        await ed.send_modbus_read(slave=1, start_addr=0, quantity=2)

        # 5. Wait for RS485 return data (the NUS TX Notify callback prints automatically)
        await asyncio.sleep(2)
    finally:
        await ed.disconnect()


if __name__ == "__main__":
    asyncio.run(main())

8.4 JavaScript (Web Bluetooth API) — browser connection

JavaScript
// ===== edatahub ED-N2 BLE constants =====
const NUS_SERVICE_UUID     = '6e400001-b5a3-f393-e0a9-e50e24dcca9e'
const NUS_RX_CHAR_UUID     = '6e400002-b5a3-f393-e0a9-e50e24dcca9e' // Write
const NUS_TX_CHAR_UUID     = '6e400003-b5a3-f393-e0a9-e50e24dcca9e' // Notify
const CFG_SERVICE_UUID     = '8e400001-b5a3-f393-e0a9-e50e24dcca9e'
const CFG_UART_CONFIG_UUID = '8e400002-b5a3-f393-e0a9-e50e24dcca9e' // Write

let characteristicRx = null  // NUS RX (write)
let characteristicTx = null  // NUS TX (Notify)
let characteristicCfg = null // UART Config (write)

// ===== Connect the device =====
async function connect() {
  const device = await navigator.bluetooth.requestDevice({
    filters: [{ name: '数熵ED-Slink' }],
    optionalServices: [NUS_SERVICE_UUID, CFG_SERVICE_UUID]
  })

  const server = await device.gatt.connect()

  // Get the NUS service (data transparent transmission)
  const nusService = await server.getPrimaryService(NUS_SERVICE_UUID)
  characteristicRx = await nusService.getCharacteristic(NUS_RX_CHAR_UUID)
  characteristicTx = await nusService.getCharacteristic(NUS_TX_CHAR_UUID)

  // Subscribe to NUS TX Notify (receive RS485 return data)
  await characteristicTx.startNotifications()
  characteristicTx.addEventListener('characteristicvaluechanged', (event) => {
    const data = new Uint8Array(event.target.value.buffer)
    const hex = Array.from(data).map(b => b.toString(16).padStart(2, '0')).join(' ')
    console.log('[RX]', hex)
  })

  // Get the Config service (serial configuration)
  const cfgService = await server.getPrimaryService(CFG_SERVICE_UUID)
  characteristicCfg = await cfgService.getCharacteristic(CFG_UART_CONFIG_UUID)

  console.log('Device connected')
}

// ===== Configure RS485 serial parameters (8-byte format) =====
function configRS485(baud = 9600, dataBits = 8, stopBits = 0, parity = 0) {
  const buffer = new ArrayBuffer(8)
  const view = new DataView(buffer)
  view.setUint32(0, baud, true)  // baud little-endian
  view.setUint8(4, dataBits)
  view.setUint8(5, stopBits)
  view.setUint8(6, parity)
  view.setUint8(7, 0x00)
  return characteristicCfg.writeValueWithoutResponse(buffer)
}

// ===== Send data to RS485 =====
function sendToRS485(bytes) {
  const buffer = new Uint8Array(bytes).buffer
  return characteristicRx.writeValueWithoutResponse(buffer)
}

// ===== Modbus CRC16 =====
function crc16(data) {
  let crc = 0xFFFF
  for (const byte of data) {
    crc ^= byte
    for (let i = 0; i < 8; i++) {
      crc = (crc & 0x0001) ? ((crc >> 1) ^ 0xA001) : (crc >> 1)
    }
  }
  return crc
}

// ===== Full example =====
async function demo() {
  await connect()
  await configRS485(9600, 8, 0, 0)

  // Modbus RTU: read holding registers, slave 01, address 0, quantity 2
  const frame = [0x01, 0x03, 0x00, 0x00, 0x00, 0x02]
  const crc = crc16(frame)
  frame.push(crc & 0xFF, (crc >> 8) & 0xFF)
  await sendToRS485(frame)
}

9. What does the appendix parameter quick reference contain?

Consolidates the BLE UUID and serial parameter quick-reference tables so you can look up values directly during development instead of re-reading the body text.

9.1 BLE UUID quick reference

PurposeService UUIDCharacteristic UUIDProperties
RS485 data write (phone → device)6E400001-...6E400002-...Write
RS485 data receive (device → phone)6E400001-...6E400003-...Notify
RS485 serial parameter configuration8E400001-...8E400002-...Write
Line state control (DTR/RTS/Break)8E400001-...8E400003-...Write
UART status notification8E400001-...8E400004-...Notify
Battery/device status9E400001-...9E400003-...Read/Notify

All full UUIDs share the suffix -B5A3-F393-E0A9-E50E24DCCA9E and differ only in prefix: 6E40 (data), 8E40 (config), 9E40 (status).

9.2 Serial parameter quick reference

Plaintext
baud:      1200 / 2400 / 4800 / 9600 / 19200 / 38400 / 57600 / 115200 / 230400 ...
data_bits: 5 / 6 / 7 / 8
stop_bits: 0 (1 bit) / 1 (1.5 bits) / 2 (2 bits)
parity:    0 (None) / 1 (Odd) / 2 (Even)

9.3 UART Config write byte quick reference

FormatByte lengthStructure
Default format8baud_le32 + data_bits + stop_bits + parity + 00
With channel identifier90x00 + baud_le32 + data_bits + stop_bits + parity + 00

9.4 Little-endian bytes for common baud rates

Baud rate4-byte little-endian
960080 25 00 00
1920000 4B 00 00
3840000 96 00 00
5760000 E1 00 00
11520000 C2 01 00

9.5 Secondary development integration key points

Connection flow

Scan for the device name 数熵ED-N2-RS485 → connect → get the NUS service → subscribe to NUS TX Notify → configure serial parameters → start sending/receiving data

Data transparent transmission

Bytes written to NUS RX are written as-is to the RS485 bus; no frame header needed

Serial configuration

Serial parameters (baud rate, etc.) must be reconfigured after each connection

MTU limit

Keep each BLE write at or below 512 bytes (best compatibility); split long data

Protocol handling

The device only forwards bytes; framing of protocols such as Modbus is handled by the host computer

FAQ

Does ED-N2 secondary development require hardware circuit knowledge?

No. The documentation abstracts the underlying hardware circuits, interface drivers, power adaptation, and Bluetooth protocol stack; developers only work with the open software interfaces and communication protocols.

What development targets are supported?

Mobile apps, WeChat mini programs, IoT host computers, embedded applications, data acquisition systems, and device management platforms. The documentation includes complete WeChat mini program samples for BLE connection and RS485 transparent transmission.

Where do I look up serial parameters and Bluetooth characteristics?

Chapters 2 and 3 define the BLE characteristics and RS485 serial parameters respectively, and the chapter 9 appendix consolidates UUID and parameter quick references for use during development.