Skip to content
dukelecPublic

About

Serial / CDBUS / CDNET GUI Tool

Topics

Resources

Stars

212 stars

Watchers

6 watching

Forks

Repository files navigation

CDBUS GUI Tool

CDBUS GUI is an open-source, cross-platform serial debugging tool supporting register read/write, waveform plotting, log printing, IAP upgrades, and more.

Download:

git clone --recursive https://github.com/dukelec/cdbus_gui

Dependence:

Python version >= 3.8
pip3 install json5 websockets pyserial u-msgpack-python aiohttp IntelHex

Usage:

Run main.py, then open the following URL in your web browser: http://localhost:8910

For Windows users without Python, tools/build_win.sh (run on Linux) makes dist/cdbus_gui-<version>-win64.zip: the embeddable Python with the dependencies and this tool. Unzip it anywhere and run cdbus_gui.bat (cdbus_gui_udp.bat for main_udp.py), it opens the page in the browser by itself. Windows 10 or later, x64.

Every page carries a top bar with the tool version and a language picker (Auto follows the browser, otherwise English / Simplified Chinese / Traditional Chinese, the choice is remembered per browser). Hovering the version shows the full asset version, the same v3.0-<hash of all own front end files> that main.py prints at startup and that every own css / js url is tagged with, so an updated front end always reaches the browser: the hash changes, the urls change, and the cached files are bypassed. Bump VERSION in html/common.js for a release; the hash part follows the files on its own, and it is rechecked per request, so an edit under html/ takes effect on the next reload without a restart.

The underlying protocol for serial port is CDBUS, which uses the following frame format:
src, dst, len, [payload], crc_l, crc_h

Each frame includes a 3-byte header, a variable-length payload, and a 2-byte CRC (identical to Modbus CRC).
For more information on the CDBUS protocol, please refer to:

The payload is encoded using the CDNET protocol. For detailed information, please refer to:

Index Page

  • "Serial": The first field accepts a port name or matching string (e.g., ACM0, Bridge, 2E3C:5740), with wildcard support.
    The second field is the baud rate, supporting arbitrary values.
  • "Available": Lists all serial ports on the computer.
  • "Devices": Quickly open the debug page for each device (list expands automatically).
  • "Logs": Aggregates logs from all devices.
    (Pressing Enter inserts a blank line; Holding Alt or Ctrl + Alt allows block selection.)
  • "Record": Start records every frame on the bus, sent and received, into records/cdbus_<time>.pcapng until Stop; the line next to the buttons shows the file, the packet count and the size while it runs. Pressing Enter in the "Logs" window of any page puts a mark into the recording at the same time as the blank line goes into the log, so a moment noticed in the log can be found in the capture. The recording is done by the backend, so it covers every page and goes on while pages are reloaded. See Wireshark for reading the file.
  • "Replay": plays a recording back through the backend, as if the bus were sending it again, so a session can be looked at afterwards, several devices together. Pick a file of records/ (or Browse for one from elsewhere, e.g. off a recorder's card), Load, and Play: the "Logs" window of the index page gets the interleaved log of every device with the timestamps of the capture, and every device page that is open gets its own log, waveforms and pictures, the same way it does live. The marks come out as ---- mark: ... ---- lines. The registers are rebuilt from the traffic, every read and write seen gives the value a register held at that moment, and when playing stops the device pages show the registers as they were at that time. Play to says how far to play: to a time, to the end when left empty, and the buttons under the marks set it to a mark's time. Play on for a later moment, or Rewind and play again for an earlier one, at once or paced at 1x to 10x. Open the device pages first (the addresses in the file are listed, grey when no page is open for them) and close the serial port, live frames would mix in.
  • Auto-reconnect supported for serial ports.
  • Modified settings are saved automatically.
  • Supports ANSI color codes.

Device Page

  • Displays registers for reading and writing.
  • Hover over a register to view its description, type, and default value.
  • Titles from "seps" of the config split the list into sections (System, Bus, PID, ...).
  • Registers are grouped for atomic R/W; groups can be edited freely.
  • R reads a group, W writes it. Read All / Write All act on all groups.
  • The drop-down next to Read All / Write All picks the group set out of "sets" in the config: the first one, the default (named default in the bundled configs), or any other set (e.g. less). Each set lists the registers its "show" names, or every register but the ones its "hide" names (one of the two, every register with neither; written like the groups, ["first", "last"] for a run of registers or ["name"] for one), plus any register one of its groups covers. A listed register outside the groups of a side has a dead R or W button. The sets are offered in the order the config file has them. A set other than the default without any group that lists no register is not offered; with only the default left the drop-down is locked.
  • A set can bring registers of its own in a "list" (rows as in reg.list), e.g. the project private registers of one firmware branch, which may sit at the same addresses as another branch's. They join the register list by address only while the set is in use, so picking such a set, or leaving it, reloads the page.
  • In Button Edit, Show / Hide act on the registers picked on either side: a hidden register leaves its groups, and one that is enabled is shown. Hidden registers stay out of the list unless Show Hidden is ticked, then they are listed greyed, so one can be shown again.
  • The chosen set and the read period are remembered per device page (by its name); the periodic read switch itself always starts off.
  • Supports arrays and multiple formats, displayed in hexadecimal (H) or as byte arrays (B).
  • Small notches on the R/W buttons indicate gaps; groups are read before writing so that the data in gaps remains unchanged.
  • Update Config File writes the button groups of the set in use back into the config file, as Load Default drops only this browser's edits of it: the other sets keep theirs.
  • The small pin beside R / W keeps a register in a bar at the top of the page, which stays in view while the page is scrolled, so a register can be worked on while watching a plot. The copy up there is the very same value as the one in the list: either can be typed into, and its R / W do exactly what the ones in the list do, group and all. Every button is drawn the way the register's own row in the list draws it: registers that sit next to each other in the list stay together up there and their buttons join into one bar, and where a group carries on into a register the bar is not showing, that end of the button is left open, so a lone member of a group never reads as a group of its own. A pinned register is not taken out of the list. What is pinned is remembered per device page (by its name), the triangle on the left folds the bar away, and with nothing pinned there is no bar at all.
  • The same pin sits beside the Logs heading and in the controls of every plot, and sends that one thing up to the bar as well. Those really move rather than being copied, and come back to the same place when the pin is clicked again. They look the same up there as they did down the page, except that pinned plots share the width side by side; either can be dragged to any size by its corner, and the bar scrolls once it has taken 80% of the window. This is what the bar is for: the waveform and the registers that drive it end up next to each other and stay there while the page is scrolled.
  • Each plugin gets a row of its own in the bar, and the small arrows on the left of a row move it past the others. The order is remembered per device page as well.

Waveform Plots:

  • Supports real-time display and long data recording, including FFT visualization.
  • Supports multiple windows with adjustable sizes.
  • Mouse wheel with Shift or Ctrl scales the X or Y axis; by default, both axes scale together.
  • Touchscreen zoom and independent X/Y scaling are supported.
  • Double-click to reset the view (zoom to fit). Hold the left or middle mouse button to pan.
  • Individual channels can be toggled on or off for clarity.
  • Multiple plots can be started or stopped simultaneously via the dbg_raw_msk register.
  • Supports formula-based waveforms (e.g., u_cal below). Click Re-Calc to refresh the plot after modifying or adding formulas.
  • Channels opens a dialog to pick which registers the plot samples, the formulas derived from them, and the reg_overlay list shared by all plots. The dialog shows how many config register slots the current choice takes.
  • The choice is kept in the browser, like the register button groups. Load Default puts the three boxes of that dialog back to the config file, this plot's channels and formulas plus the shared overlay list; the other plots keep the channels they were given. If the config file is edited so that a saved choice no longer fits, it is dropped on the next page load and the file wins.
  • Update Config File in the same dialog writes the channels, formulas and overlays into the config file instead. A formula may span several lines, indent the follow up lines.

Update Config File replaces only the spans that belong to the keys you changed, so the rest of the file, its comments and its layout included, stays byte for byte the same. Comments inside a replaced span are lost. The previous version of the file is kept next to it as <name>.json.bak, overwritten on each save. After a successful write the browser copy of what was written is dropped, so the file is the one source for it again, and Load Default from then on means what the file now says. Every value written is read back before the file is replaced, so a key the file names twice, or anything else the parser reads differently, is reported instead of saved.

Picture Preview:

  • Preview images (e.g., JPEG files) sent from the device.

IAP and Data Import/Export:

  • IAP supports readback verification, device-side CRC validation, or no validation.
  • IAP supports Intel HEX files with multiple segments.
  • Register data, log outputs, and waveform data can be exported and imported together (in MessagePack format).
  • Waveform data can also be exported as CSV for AI analysis, with selectable plot, series, X range, decimation step, and significant digits to save tokens.

Wireshark

The .pcapng files of "Record" open in Wireshark, with the wireshark/cdbus.lua dissector of cdbus_tools, which also documents the recording format: copy it into the personal Lua plugins folder (listed under Help > About Wireshark > Folders: ~/.local/lib/wireshark/plugins/ on Linux, %APPDATA%\Wireshark\plugins\ on Windows, ~/.config/wireshark/plugins/ on macOS) and restart Wireshark, or for one run:

wireshark -X lua_script:cdbus.lua records/cdbus_20260101_120000.pcapng

Each frame is shown as it is on the wire, the CDBUS header and the CRC (checked), and the CDNET packet inside: level 0 or level 1, the addresses as the tool writes them (00:NN:MM, 80:NN:MM, a0:NN:MM, 90:MH:ML, b0:MH:ML), the ports, and what the packet does on the ports the tool uses: register reads and writes with the address, flash commands, the device info and debug text. The Source and Destination columns carry the CDNET addresses, the frame's direction (sent or received) is in its frame details, and the marks are packets of their own with the mark text, also readable as the packet comment without the dissector. A level 0 packet and a local link level 1 packet carry no net, so the dissector shows the one set under Edit > Preferences > Protocols > CDNET (the --local-net of the backend, 0 by default). Useful filters: cdnet.dst_port == 5, cdnet.src == "80:00:fe", cdnet.reg.addr == 0x10, cdnet.text contains "err", cdmark, cdbus.crc.bad.

The same file also decodes a capture Wireshark takes on the IPv6/UDP side of the bus, the tun0 of cdnet_tun or the cdbus0 ethernet port of the CDBUS Bridge: a UDP packet with an address under fdcd::/104 is taken as a CDNET packet, the last 3 bytes of the IPv6 addresses are shown as the CDNET addresses and the UDP ports as the CDNET ports, with the host's port_offset (0xcd00) taken off, so the cdnet.* filters work the same there. The prefix and the offset are preferences next to the local net. (main_udp.py records as well, the frames rebuilt from its UDP packets, so a recording reads the same whichever backend made it; a capture on the interface itself also gets the packets of every other program on the bus.)

External API

Lets a script (or an AI agent) drive the tool from outside: open and close the serial port, record the bus to a pcapng file and put marks into it, read and write registers, change the R / W button groups, read the log, start and stop waveforms, fetch waveform data, reload the page and run an IAP upgrade. Requests are relayed to the device page in the browser, and the page does the real work, the same way it does when you click a button, so a script and the user share one state.

The server listens on localhost:8911 by default, GET http://localhost:8911/ prints the endpoint list, and tools/cdg_api.py wraps the same thing for python.

See doc/api.md for the endpoints and how to use them.

JSON Format

  • The register list can be auto-generated by the MCU (printed when it powers up).
  • Uses JSON5 format, supporting hexadecimal values and comments.
  • The "fmt" string with "[]" is an array, which displays all data in one text box.
  • "{}" denotes struct arrays; each array element has its own text box containing multiple members of the struct.
  • A register entry may carry an optional last member, the range of what may be written to it: [[min, max, step], ...], or just [min, max, step] when there is only one range. Both ends are included, step may be left out, and null as an end means it is not limited. Several ranges are alternatives: the value is good when it fits any one of them, and step counts from the min of the range it fits. A write is refused, and the input boxes of the whole group turn red, as soon as one value is outside; the ranges also show up in the tooltip of the input box. The step is only enforced where it is exact, that is when min, step and the value are all integers; on a float it is only a hint of the granularity. The ranges apply to every value of the register, so a "[]" or "{}" register shares one set of them, and they are skipped for text ("[c]" shown as a string) and for registers shown as raw bytes ("show": 2). A bound beyond 2^53 has to be written as a string, e.g. [["0", "18446744073709551615"]], as a json number cannot hold it exactly.

E.g. cdstep-v6.json

{
    "reg": {
        // fmt: [c]: string, b: int8_t, B: uint8_t, h: int16_t, H: uint16_t, i: int32_t, I: uint32_t
        //       q: int64_t, Q: uint64_t, f: float, d: double
        // show: 0: normal, 1: hex, 2: bytes
        "list": [
            [ 0x0000, 2, "H", 1, "magic_code", "Magic code: 0xcdcd" ],
            [ 0x0002, 2, "H", 1, "conf_ver", "Config version" ],
            [ 0x0004, 1, "B", 0, "conf_from", "0: default config, 1: all from flash, 2: partly from flash" ],
            [ 0x0005, 1, "B", 0, "do_reboot", "1: reboot to bl, 2: reboot to app" ],
            [ 0x0007, 1, "b", 0, "save_conf", "Write 1 to save current config to flash" ],

            // the last member is optional: [[min, max, step], ...], or [min, max, step] for a single
            // range; both ends included, step optional, null for an end that is not limited
            [ 0x000c, 1, "B", 1, "bus_cfg_mac", "RS-485 port id, range: 0~254", [0, 254] ],
            [ 0x0010, 4, "I", 0, "bus_cfg_baud_l", "RS-485 baud rate for first byte" ],
            [ 0x0014, 4, "I", 0, "bus_cfg_baud_h", "RS-485 baud rate for follow bytes" ],
            // ...

            [ 0x00bc, 4, "i", 0, "tc_pos", "Set target position" ],
            [ 0x00c0, 4, "I", 0, "tc_speed", "Set target speed" ],
            [ 0x00c4, 4, "I", 0, "tc_accel", "Set target accel" ],
            [ 0x00c8, 4, "I", 0, "tc_accel_emg", "Set emergency accel" ],

            [ 0x00d4, 4, "f", 0, "pid_pos_kp", "" ],
            [ 0x00d8, 4, "f", 0, "pid_pos_ki", "" ],
            [ 0x00dc, 4, "f", 0, "pid_pos_kd", "" ],
            [ 0x0100, 4, "i", 0, "cal_pos", "PID input position" ],
            [ 0x0104, 4, "f", 0, "cal_speed", "PID output speed" ],

            [ 0x0108, 1, "B", 0, "state", "0: disable drive, 1: enable drive" ],

            // --------------- Follows are not writable: -------------------
            [ 0x0109, 1, "B", 0, "tc_state", "t_curve: 0: stop, 1: run" ],
            [ 0x010c, 4, "i", 0, "cur_pos", "Motor current position" ],
            [ 0x0110, 4, "f", 0, "tc_vc", "Motor current speed" ],
            [ 0x0114, 4, "f", 0, "tc_ac", "Motor current accel" ],

            [ 0x0124, 4, "I", 0, "loop_cnt", "Count for plot" ],
            [ 0x0128, 10, "[c]", 0, "string_test", "String test" ]
        ],
        
        // section titles over the list: the register a section starts with -> title
        "seps": { "magic_code": "System", "bus_cfg_mac": "Bus", "tc_pos": "Trap planner", "pid_pos_kp": "PID" },
        
        // button groups
        "sets": {
            "default": {
                "r": [["magic_code","save_conf"],["bus_cfg_mac","bus_cfg_tx_pre_len"],["dbg_en"],["qxchg_mcast"],
                      ["qxchg_set","qxchg_ret"],["dbg_raw_msk"],["dbg_raw[0]","dbg_raw[1]"],["ref_volt","lim_en"],
                      ["tc_pos","tc_accel"],["tc_accel_emg"],["pid_pos_kp","pid_pos_kd"],["cal_pos","cal_speed"],
                      ["state"],["tc_state","cur_pos"],["tc_vc","tc_ac"],["loop_cnt"],["string_test"]],
                "w": [["magic_code","conf_ver"],["do_reboot"],["save_conf"],["bus_cfg_mac"],["bus_cfg_baud_l","bus_cfg_baud_h"],
                      ["bus_cfg_filter_m"],["bus_cfg_mode"],["bus_cfg_tx_permit_len","bus_cfg_tx_pre_len"],["dbg_en"],
                      ["qxchg_mcast"],["qxchg_set","qxchg_ret"],["dbg_raw_msk"],["dbg_raw[0]","dbg_raw[1]"],
                      ["ref_volt","md_val"],["set_home"],["lim_en"],["tc_pos"],["tc_speed","tc_accel"],["tc_accel_emg"],
                      ["pid_pos_kp","pid_pos_kd"],["state"],["string_test"]]
            },
            "less": {
                "show": [["tc_pos","tc_accel"],["state","loop_cnt"]],
                "r": [["tc_pos","tc_accel"],["state","loop_cnt"]],
                "w": [["tc_pos"],["tc_speed","tc_accel"],["state"]]
            }
        },
        
        // registers the top bar starts out with
        "pin": ["tc_pos", "state"],
        
        // other languages: "list" for the register descriptions, "seps" for the section titles
        "trans": {
            "zh-CN": {
                "list": { "tc_pos": "设置目标位置", "state": "0:关闭驱动,1:使能驱动" },
                "seps": { "pid_pos_kp": "PID 参数" }
            },
            "zh-TW": {
                "list": { "tc_pos": "設置目標位置", "state": "0:關閉驅動,1:使能驅動" }
            }
        }
    },
    
    "plot": {
        "mask": "dbg_raw_msk",
        "reg_overlay": [
            // addr, ofs, len, type, name
            //[0x1234, 8, 4, "f", "name"],
            ["pid_pos_ki", 20, 4, "i", "pid target"],
            ["pid_pos_ki", 24, 4, "f", "i_term"],
            ["pid_pos_ki", 28, 4, "i", "last_in"]
        ],
        "plots": [
            {
                // "color": ["black", "red", "green"]
                "cfg_reg": "dbg_raw[0]",
                "x_fmt": "H1",
                "label": ["N", "tc_pos", "tc_state", "cal_pos", "cur_pos", "tc_vc", "tc_ac"],
                "cal": {
                    "pos_err": "_d[4].at(-1) - _d[3].at(-1)" // data4 - data3
                },
                "fft": {
                    "sample_rate": 5000,
                    "size": 4096
                }
            }, {
                "cfg_reg": "dbg_raw[1]",
                "x_fmt": "H1",
                "label": ["N", "pid target", "i_term", "last_in", "cal_speed"]
            }
        ]
    },
    
    "iap": { "reboot": 0x0005, "keep_bl": 0x0006, "batch_pkts": 3 }
}
  • "iap": "reboot" and "keep_bl" are the register addresses of do_reboot and keep_bl. With "keep_bl" set, the bootloader is searched for by writing keep_bl repeatedly until it is acked (one frame locks a bootloader that only listens briefly after power-up), then the device info is read to tell the bootloader from an app. The probe period is derived from the baud rate (20 ms at 115200), or set in ms with an optional "probe_period". Without "keep_bl", the device info is polled instead.

  • "sets" holds the register group sets, each one a set to pick on the device page, with "r" for the read groups and "w" for the write groups, and either "show" or "hide" to pick the registers it lists (every register with neither), in the same ["first", "last"] / ["name"] form as the groups, and optionally a "list" of registers of its own; the first set is the default, the one a page starts with. You can leave them empty and edit via the UI (after editing, the browser debug window will print them, and Update Config File writes them into "sets").

  • "seps" puts a title over a section of the register list, keyed by the register the section starts with, a register a set brings of its own included. A title is left out while no register of its section is listed, and "" gives a plain line.

  • "pin" is the set of registers the top bar of the device page starts out with; from then on the browser remembers what is pinned, so this is only the starting point.

  • "trans" holds the texts in other languages, by language ("zh-CN", or "zh-TW" for any traditional Chinese), each one shaped like "reg": "list" has the register descriptions by register name, the registers a set brings of its own included, and "seps" the section titles. The page shows the ones of the language it runs in, and the English ones where there is none, so only a few may be translated. tests/test_configs.py checks that every name is known to the config.

  • The "x_fmt" of "plot" data corresponds to two packet formats:

    • "x1 a1 b1 a2 b2 …" – x-axis data is shared across groups. "H" denotes a uint16_t counter, incremented each loop; a number after "H" gives the delta to recover subsequent x values.
    • "x1 a1 b1 x2 a2 b2 …" – each data set has its own x value, suitable for variable loop periods.

More Info

As a side note, CDNET Address refers to the IPv6 concept, allowing strings to represent different addresses, defined as follows.

/* CDNET Address string formats:
*
*            localhost      local link     unique local    multicast
*             10:00:00
* level0:                    00:NN:MM
* level1:                    80:NN:MM        a0:NN:MM       f0:MH:ML
*
* Notes:
*   NN: net_id, MM: mac_addr, MH/ML: multicast_id (H: high byte, L: low byte)
*/
  • Broadcast and multicast can also use the "link-local" format; the "multicast" format is generally not needed for simple cases.
  • "Unique local" is used only across network segments — for example, when multiple subnets each contain multiple devices.

Serial CDNET packets can be directly mapped to UDP packets, enabling multiple software applications to access the same serial device. Please refer to: https://github.com/dukelec/cdnet_tun

To access a serial device via UDP, run the main_udp.py program instead.

About

Serial / CDBUS / CDNET GUI Tool

Topics

Resources

Stars

212 stars

Watchers

6 watching

Forks

Releases

Packages

Contributors

Languages