Robot Device Unique ID Implementation Guide: Coding, Assignment, and Migration

    A practical guide to implementing unique product identification for robots: how to design a four-segment coding scheme, ensure code uniqueness at the database level, handle concurrent serial number allocation, and migrate legacy devices. Includes Python and PostgreSQL code examples for the full assignment workflow.

    1. Background: Why Robots Need an “Identity Card”

    Robot applications are expanding from laboratories into factories, warehouses, healthcare, and public services. The same device model may move between multiple operators, and after retrofitting, part replacement, and software upgrades, its state may differ significantly from the factory configuration. Without a unified identifier, regulators struggle to confirm device ownership, operators struggle to trace the root cause of failures, and responsible parties are hard to locate after a safety incident.

    According to the source material, the industry regulator released the Interim Measures for the Administration of Robot Product Identification Codes (Draft for Comment) for public consultation on November 6, 2026, with the comment period closing on December 5. At the time of writing, the consultation period had not yet ended, and the final provisions are subject to official publication. The core of the draft is to assign a unique product identity code to every robot leaving the factory, supporting industry safety governance and full lifecycle management.

    The humanoid robot sector already has practical foundations. According to public information, by May 2026, a full lifecycle management service platform covered more than 100 companies, with over 28,000 humanoid robots assigned codes. The platform uses a 29-digit, four-segment code corresponding to a country code, company code, product code, and serial code. The draft regulation extends the scope to industrial robots, service robots, special-purpose robots, and the full range of categories, which means developers will face more device models, more vendors, and more complex integration scenarios.

    For developers, unique device identification is more than attaching a label to the hardware. It requires a unified data model, reliable uniqueness guarantees, complete event records, and cross-organization query capability.

    2. Three Design Goals

    Before designing the identification scheme, clarify the problems it must solve. This article summarizes three goals.

    Identifiable: The same device must be uniquely pointed to by the same code in every business system. Once assigned, a code can never be reused or arbitrarily changed.

    Traceable: From design, manufacturing, factory release, delivery, and repair through disposal, every key milestone must be recorded, and the device’s complete history must be reconstructable in chronological order.

    Governable: When a safety hazard or batch defect occurs, regulators and manufacturers must be able to quickly filter affected devices by code and notify the corresponding operators. Query permissions on the platform should be role-based: regulators, manufacturers, and operators should each see only data within their scope of responsibility.

    These three goals determine the direction of the code structure, data model, and API design. The code structure handles uniqueness, the data model handles history, and the APIs handle cross-system collaboration.

    3. Anatomy of the Code Structure

    The value of a four-segment code is that each segment carries a distinct responsibility, and their combination guarantees global uniqueness.

    Segment Meaning Primary Purpose
    Country code Identifies the country or region scope of the code Supports cross-region identification and statistics
    Company code Identifies the manufacturer Supports per-company aggregation and accountability
    Product code Identifies the product model or category Supports per-model filtering and batch handling
    Serial code Identifies an individual unit of a product Guarantees uniqueness within a model

    A few design considerations. The company code should be assigned centrally by the regulator or a registration authority to avoid duplicates across companies. The serial code should be allocated monotonically within the company and product scope, and must not depend on mutable data such as device location or personnel information. The code itself should not embed customer information, geographic location, or repair records—these belong in a controlled database, linked by the code.

    The segment lengths described here (3-digit country code, 9-digit company code, 8-digit product code, 9-digit serial code, 29 digits total) are used only to illustrate the implementation. Official segment lengths, character sets, and whether a checksum is included are subject to the relevant standards.

    4. Designing the Code Assignment Workflow

    Code assignment typically happens before the device leaves the factory. A robust workflow includes the following steps:

    1. Register company and product information, and verify that the company code and product code are valid.
    2. Obtain the next serial code from the serial number allocation service; the allocation process must be concurrency-safe.
    3. Assemble the full code according to the coding rules and validate its format.
    4. Write the code to the device’s identification carrier, such as a QR code on the nameplate, an electronic tag, or a read-only field in the firmware.
    5. Register the code and the device’s basic information with the platform, and wait for the platform’s acknowledgment.
    6. Perform a read-back verification of the written result to confirm the code matches the physical device.
    7. If any step fails, do not reclaim the assigned code. Instead, move the device to an exception queue and wait for re-writing. Never allow a state where “the platform has a record but the device has no code,” or vice versa.

    Steps 4 and 6 are the most commonly overlooked. If the code exists only in the platform and is not bound to the physical device, all downstream traceability is meaningless. The identification carrier should therefore be as durable as possible and physically attached to the device’s main structure.

    5. Code Implementation

    The code below splits the workflow into four parts: code object and parsing, database uniqueness, serial number allocation, and registration with read-back. The examples use Python and PostgreSQL (psycopg 3); field rules need to be adjusted according to the official standard.

    1. Code Object, Assembly, and Parsing

    1. import logging
    2. import re
    3. from dataclasses import dataclass
    4. import psycopg
    5. from psycopg import errors
    6. logger = logging.getLogger("robot_code")
    7. # Illustrative format: 3-digit country + 9-digit company + 8-digit product + 9-digit serial, 29 digits total
    8. CODE_PATTERN = re.compile(r"^(\d{3})(\d{9})(\d{8})(\d{9})$")
    9. FIELD_LIMITS = {
    10. "country": 999,
    11. "company": 999_999_999,
    12. "product": 99_999_999,
    13. "serial": 999_999_999,
    14. }
    15. class RobotCodeError(ValueError):
    16. """Invalid code value or format."""
    17. class DuplicateCodeError(RuntimeError):
    18. """Code or idempotency key already exists."""
    19. @dataclass(frozen=True)
    20. class RobotCode:
    21. country: int
    22. company: int
    23. product: int
    24. serial: int
    25. def __post_init__(self) -> None:
    26. for name, limit in FIELD_LIMITS.items():
    27. value = getattr(self, name)
    28. if not isinstance(value, int) or isinstance(value, bool):
    29. raise RobotCodeError(f"{name} must be an integer")
    30. if not 0 <= value <= limit:
    31. raise RobotCodeError(f"{name} out of range 0~{limit}: {value}")
    32. def __str__(self) -> str:
    33. return (
    34. f"{self.country:03d}{self.company:09d}"
    35. f"{self.product:08d}{self.serial:09d}"
    36. )
    37. def build_robot_code(country: int, company: int, product: int, serial: int) -> str:
    38. """Assemble the code per the four-segment rules. Raises RobotCodeError on out-of-range values."""
    39. return str(RobotCode(country, company, product, serial))
    40. def parse_robot_code(code: str) -> RobotCode:
    41. """Split a 29-digit code back into four segments. Raises RobotCodeError on invalid format."""
    42. if not isinstance(code, str):
    43. raise RobotCodeError("code must be a string")
    44. match = CODE_PATTERN.fullmatch(code)
    45. if match is None:
    46. raise RobotCodeError(f"invalid code format: {code!r}")
    47. country, company, product, serial = (int(g) for g in match.groups())
    48. return RobotCode(country, company, product, serial)

    build_robot_code returns a string only after validation passes. Out-of-range values or format errors raise explicit exceptions, so callers never receive None.

    2. Database-Level Uniqueness

    Application-layer validation is only the first line of defense. Uniqueness must ultimately be enforced by database constraints; otherwise, concurrent writes or scripts bypassing the application can still produce duplicates.

    1. DDL = """
    2. CREATE TABLE IF NOT EXISTS robot_device (
    3. id BIGSERIAL PRIMARY KEY,
    4. robot_code CHAR(29) NOT NULL,
    5. company_key CHAR(9) NOT NULL,
    6. product_key CHAR(8) NOT NULL,
    7. serial_no BIGINT NOT NULL,
    8. idem_key VARCHAR(64) NOT NULL,
    9. status VARCHAR(16) NOT NULL DEFAULT 'registered',
    10. created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    11. CONSTRAINT uk_robot_code UNIQUE (robot_code),
    12. CONSTRAINT uk_product_serial UNIQUE (company_key, product_key, serial_no),
    13. CONSTRAINT uk_idem_key UNIQUE (idem_key)
    14. );
    15. CREATE TABLE IF NOT EXISTS robot_serial_counter (
    16. company_key CHAR(9) NOT NULL,
    17. product_key CHAR(8) NOT NULL,
    18. next_serial BIGINT NOT NULL,
    19. PRIMARY KEY (company_key, product_key)
    20. );
    21. """

    The three unique constraints guard against three different risks. uk_robot_code prevents duplicate codes, uk_product_serial prevents duplicate serial numbers within the same product, and uk_idem_key ensures that repeated requests for the same device produce only one record.

    3. Concurrency-Safe Serial Number Allocation

    Serial number allocation is the most common source of concurrency conflicts. If two processes read the same counter value simultaneously, they will allocate identical serial codes. The implementation below uses SELECT ... FOR UPDATE to lock the counter row, keeping the read and increment in the same transaction.

    1. def allocate_serial(conn: psycopg.Connection, company: int, product: int) -> int:
    2. """Get the next serial number within the current transaction. The caller must already be in a transaction."""
    3. key = (f"{company:09d}", f"{product:08d}")
    4. with conn.cursor() as cur:
    5. cur.execute(
    6. "INSERT INTO robot_serial_counter (company_key, product_key, next_serial) "
    7. "VALUES (%s, %s, 1) ON CONFLICT DO NOTHING",
    8. key,
    9. )
    10. cur.execute(
    11. "SELECT next_serial FROM robot_serial_counter "
    12. "WHERE company_key = %s AND product_key = %s FOR UPDATE",
    13. key,
    14. )
    15. (serial,) = cur.fetchone()
    16. if serial > FIELD_LIMITS["serial"]:
    17. raise RobotCodeError("Serial codes exhausted; a new product code is required")
    18. cur.execute(
    19. "UPDATE robot_serial_counter SET next_serial = next_serial + 1 "
    20. "WHERE company_key = %s AND product_key = %s",
    21. key,
    22. )
    23. return serial

    Because the counter and the device record are committed in the same transaction, a failed insert rolls back the counter as well, so serial numbers never develop gaps.

    4. Registration, Writing, and Read-Back

    1. def register_device(
    2. conn: psycopg.Connection,
    3. country: int,
    4. company: int,
    5. product: int,
    6. idem_key: str,
    7. ) -> str:
    8. """Register one device. idem_key is usually composed of the batch ID and device SN; retries return the existing code."""
    9. with conn.transaction():
    10. with conn.cursor() as cur:
    11. cur.execute(
    12. "SELECT robot_code FROM robot_device WHERE idem_key = %s",
    13. (idem_key,),
    14. )
    15. row = cur.fetchone()
    16. if row is not None:
    17. logger.info("idempotency hit", extra={"idem_key": idem_key})
    18. return row[0]
    19. serial = allocate_serial(conn, company, product)
    20. code = build_robot_code(country, company, product, serial)
    21. with conn.cursor() as cur:
    22. try:
    23. cur.execute(
    24. "INSERT INTO robot_device "
    25. "(robot_code, company_key, product_key, serial_no, idem_key) "
    26. "VALUES (%s, %s, %s, %s, %s)",
    27. (code, f"{company:09d}", f"{product:08d}", serial, idem_key),
    28. )
    29. except errors.UniqueViolation as exc:
    30. raise DuplicateCodeError(f"code or idempotency key conflict: {code}") from exc
    31. logger.info("registration complete", extra={"robot_code": code, "step": "db_insert"})
    32. return code
    33. def mark_status(conn: psycopg.Connection, code: str, status: str) -> None:
    34. with conn.transaction():
    35. with conn.cursor() as cur:
    36. cur.execute(
    37. "UPDATE robot_device SET status = %s WHERE robot_code = %s",
    38. (status, code),
    39. )
    40. def verify_readback(code: str, read_fn) -> bool:
    41. """read_fn reads the code from the physical carrier; assignment is complete only when the read-back matches."""
    42. try:
    43. actual = read_fn()
    44. except Exception:
    45. logger.exception("read-back failed", extra={"robot_code": code, "step": "readback"})
    46. return False
    47. return actual == code
    48. def commission(conn, writer, reader, country, company, product, batch_id, sn) -> str:
    49. """Full assignment workflow: register, write, read back. Failed devices enter the exception queue with their codes unchanged."""
    50. code = register_device(conn, country, company, product, f"{batch_id}:{sn}")
    51. try:
    52. writer.write(code)
    53. ok = verify_readback(code, reader.read)
    54. except Exception:
    55. logger.exception("write failed", extra={"robot_code": code, "step": "write"})
    56. ok = False
    57. mark_status(conn, code, "bound" if ok else "exception")
    58. if not ok:
    59. raise RuntimeError(f"assignment incomplete, moved to exception queue: {code}")
    60. return code

    A registered device starts in the registered state and changes to bound only after a successful read-back. If writing or read-back fails, the device enters the exception state. Devices in the exception queue should be re-written with the original code, not reassigned a new one. Once a code is assigned it can never be reused, otherwise platform records and physical devices will diverge.

    6. Migrating Legacy Devices

    Devices already in the field often have no code, or carry an internal legacy number. Migration should first establish a mapping between legacy identifiers and new codes, then assign codes in batches.

    A mapping table is recommended, storing the legacy identifier, the new code, the source, and a status:

    1. CREATE TABLE IF NOT EXISTS legacy_device_map (
    2. legacy_id VARCHAR(64) PRIMARY KEY,
    3. robot_code CHAR(29) NOT NULL UNIQUE,
    4. source VARCHAR(32) NOT NULL,
    5. status VARCHAR(16) NOT NULL DEFAULT 'pending',
    6. note TEXT
    7. );

    The migration can proceed in the following order:

    1. Inventory and deduplication: Group by device SN and model. When the same SN maps to multiple legacy records, do not merge automatically—route them to manual review.
    2. Map new codes: Do not delete legacy codes; only add a record to the mapping table. Historical queries can still locate devices via the legacy code.
    3. Batch assignment: Use “batch ID plus SN” as the idem_key. If a batch fails midway, simply re-run it—devices already processed will return their original codes directly.
    4. Duplicate handling: When one physical device corresponds to multiple legacy codes, keep the earliest valid record, mark the rest as duplicate, and route them to manual review.
    5. Failure retries: Re-write devices in the exception state batch by batch, recording the retry count and reason each time. Devices exceeding the retry limit should be physically inspected by hand.

    After migration completes, reconcile three counts: the number of records in the source system, the number of mapping table entries, and the number of devices that have completed code binding. Only when all three match can the migration be considered closed out.