RFID-based medicine selling cabinet medicine automatic tracing method and system

By using RFID electronic tags and the SM4 national cryptographic algorithm to generate dynamic time-sensitive codes in the pharmaceutical supply chain, and adjusting the update cycle based on temperature values, the problems of data silos and interoperability in the pharmaceutical supply chain have been solved, enabling efficient and reliable traceability of the entire life cycle of pharmaceuticals.

CN122636239APending Publication Date: 2026-08-25GUIAN NEW DISTRICT HUAXU TECH DEV CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611124182.2
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-07-28
Publication Date
2026-08-25

AI Technical Summary

Technical Problem

Existing drug supply chain traceability solutions suffer from data silos and lack dynamic encryption and verification mechanisms, making it difficult to achieve interconnection and collaborative traceability across multiple stages, which affects the safety, reliability, and tamper-proof nature of drugs throughout their entire lifecycle.

Method used

An automatic drug traceability method based on RFID is adopted for medicine vending machines. By integrating UID, production batch code and manufacturer digital signature through RFID electronic tags, combined with dynamic time-limited codes and on-chain hash values, the dynamic time-limited codes are generated using the SM4 national cryptographic algorithm, and the update cycle is adjusted based on the ambient temperature value of the drug to achieve traceability of the entire life cycle of the drug.

Benefits of technology

It improves the efficiency and accuracy of traceability throughout the entire lifecycle of the pharmaceutical supply chain, eliminates data silos, enhances the environmental adaptability and tamper resistance of anti-counterfeiting mechanisms, and ensures the reliability of drug authenticity verification and traceability information.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122636239A_ABST
    Figure CN122636239A_ABST
Patent Text Reader

Abstract

The application discloses a medicine automatic tracing method and system based on an RFID, and relates to the technical field of medicine supply chain tracing.The method comprises the following steps: step S1, obtaining a tracing code corresponding to medicine; and step S2, obtaining a comparison result and returning medicine state and medicine traceability information.The application generates a dynamic time limit code through an SM4 national encryption algorithm, generates a chain hash value based on an SM3 standard, can realize dynamic encryption and chain anchoring of the tracing code, generates a traceability information index code based on a block region number, can construct a full life cycle tracing chain of medicine from production to delivery, eliminates data islands in each link, and re-sets an update period based on a medicine ambient temperature value, an S-box lookup table replacement value, an L transformation cyclic shift parameter and a key inversion frequency, so that the update frequency of the dynamic time limit code can be matched with a medicine storage environment in real time, and the environmental adaptability of the anti-counterfeiting mechanism is improved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the technical field of pharmaceutical supply chain traceability, and in particular to an RFID-based method and system for automatic traceability of pharmaceuticals in vending machines. Background Technology

[0002] In traditional drug supply chain traceability schemes, information transmission and recording between different links often result in data silos, making it difficult to form a complete traceability system that spans the entire life cycle of drugs, and insufficient consideration is given to the integrity of the data.

[0003] Although RFID has been applied to drug supply chain traceability, in existing related solutions: (1) it is easy to be counterfeited and lacks a dynamic encryption verification mechanism; (2) it is difficult to achieve interconnection and collaborative traceability for the supply chain, which involves multiple links such as production, circulation and sales.

[0004] It is evident that addressing the problems existing in current solutions to improve the security, reliability, tamper resistance, and interoperability of the drug supply chain lifecycle traceability system is a problem that needs to be solved by those skilled in the art. Summary of the Invention

[0005] The purpose of this invention is to provide an RFID-based automatic drug traceability method and system for medicine vending machines, which can solve the problems existing in current related solutions, thereby improving the efficiency and accuracy of batch data processing. The specific solution is as follows: To solve the above-mentioned technical problems, the present invention provides the following technical solution: Firstly, an RFID-based method for automatic drug traceability in a vending machine, comprising the following steps: Step S1: Obtain the electronic data corresponding to the medicine based on the RFID antenna used to sense the RFID electronic tag at the shipping port; The RFID electronic tag integrates the drug's UID, production batch code, and manufacturer's digital signature, while the traceability code integrates a dynamic expiration code and an on-chain hash value. The dynamic validity code is generated based on the SM4 national cryptographic algorithm and updated according to a preset method; Step S2: Compare the RFID electronic tag corresponding to the traceability code with the record on the chain to obtain the comparison result. Based on the comparison result, return the authenticity value of the drug and the drug traceability information.

[0006] Optional, preset methods include: The update cycle is reset based on the S-box lookup table replacement value, the cyclic shift parameter of the L-transform, and the key inversion count under the SM4 national cryptographic algorithm, and based on the temperature value of the surrounding environment of the medicine. The update cycle is set based on the timestamp of the drug's last upload to the blockchain.

[0007] Optionally, the RFID electronic tag is located on the side of the medicine's packaging box; RFID electronic tags are applied to the side of the packaging box using a marking method. The traceability code is initially written before the medicine is placed in the vending machine, and is traceable and updated when the medicine is shipped.

[0008] Optional initial write methods include: By scanning the RFID electronic tag with a reader / writer, static data in response to the RFID electronic tag and dynamic data in response to the reader / writer are obtained. Static and dynamic data are combined and uploaded to the blockchain in a backup state.

[0009] Optional, traceability and updating include: At the moment the medicine is shipped, the RFID antenna is triggered to read the electronic tag and extract the updated dynamic time stamp and the current timestamp; The drug is traced based on the updated dynamic time-sensitive code, and the traceability code is updated based on the current timestamp.

[0010] Optionally, the initial write method also includes: Based on the SM4 national cryptographic algorithm, a key is configured for the data uploaded to the chain in combinational state, and a dynamic time-limited code is generated based on the key. The on-chain hash value of the dynamic time-limited code is automatically obtained. Based on the data backed up to the blockchain, it is stored in blocks, and based on the block number, a traceability information index code is generated.

[0011] Optional, static data includes the EPC code of the drug at the time of manufacture, the drug production date, the drug batch number, and the manufacturer code; Dynamic data includes the read timestamp of the read / write device and the device location of the read / write device.

[0012] Optionally, methods for generating on-chain hash values ​​include: Multiple fields are concatenated according to protocol rules, delimiters are added between fields, the separated fields are converted into a binary stream, the binary stream is padded according to the SM3 standard, SM3 hash operation is performed, and a fixed-length on-chain hash value is generated.

[0013] Optionally, the comparison results include whether there is a traceability information index code corresponding to the dynamic time-limited code, and whether the actual hash value is consistent with the on-chain hash value; The authenticity value of a drug includes 0 and 1. If the authenticity value is 0, it means the drug is counterfeit; if the authenticity value is 1, it means the drug is genuine. Step S2 includes the following sub-steps: Step S21: Read the RFID electronic tag data corresponding to the traceability code based on the RFID antenna; Step S22: Determine whether there is a traceability information index code corresponding to the dynamic timeliness code. If yes, proceed to step S23; otherwise, proceed to step S24. Step S23: Retrieve the on-chain hash value of the corresponding traceability information index code in the blockchain, concatenate the read RFID electronic tag data according to the same protocol rules and calculate the actual hash value, and compare the actual hash value with the on-chain hash value. If they match, the authenticity value of the drug is returned as 1, and the drug traceability information is also returned. If there is a discrepancy, the authenticity value of the medicine will be returned as 0, along with an error code and the location of the alteration. If the returned value for drug authenticity is 0, the abnormal event will be automatically transmitted to the regulatory platform. Step S24: Determine that the drug has not completed the on-chain registration, return the unregistered status code, and simultaneously push the unregistered information to the regulatory platform.

[0014] Secondly, the RFID-based automatic drug traceability system for vending machines includes a configuration module and a traceability module. The configuration module obtains the electronic data corresponding to the medicine based on the RFID antenna used to sense the RFID electronic tag at the shipping port; The RFID electronic tag integrates the drug's UID, production batch code, and manufacturer's digital signature, while the traceability code integrates a dynamic expiration code and an on-chain hash value. The dynamic validity code is generated based on the SM4 national cryptographic algorithm and updated according to a preset method; The traceability module compares the RFID electronic tag corresponding to the traceability code with the record on the chain to obtain the comparison result. Based on the comparison result, it returns the authenticity value of the drug and the drug traceability information.

[0015] The beneficial effects of this invention are as follows: By generating dynamic time-sensitive codes using the SM4 national cryptographic algorithm and generating on-chain hash values ​​based on the SM3 standard, dynamic encryption and on-chain anchoring of traceability codes can be achieved. By combining static and dynamic data for on-chain storage in both combined and backup states, and generating traceability information index codes based on block area numbers, a full lifecycle traceability chain for pharmaceuticals from production to shipment can be constructed, eliminating data silos at each stage. By resetting the update cycle based on the ambient temperature of the pharmaceutical environment, the S-box lookup table replacement value, the L-transform cyclic shift parameter, and the number of key inversions, the update frequency of the dynamic time-sensitive codes can be matched with the pharmaceutical storage environment in real time, improving the environmental adaptability of the anti-counterfeiting mechanism. Attached Figure Description

[0016] To more clearly illustrate the embodiments of the present invention, the accompanying drawings used in the embodiments will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0017] Figure 1 A schematic diagram of the basic process of an RFID-based automatic drug traceability method for a medicine vending machine, as provided in one embodiment of the present invention; Figure 2 A flowchart illustrating the reading and writing process of an RFID-based automatic drug traceability method for a medicine vending machine, provided by this invention. Figure 3 This is a schematic diagram of the device structure of the present invention; Figure 4 This is a structural diagram of the actuation mechanism of the present invention.

[0018] Attached labels: 1 vending machine; 2 touch screen; 3 RFID reader / writer; 4 pick-up area; 5 medicine drop area; 6 push mechanism; 7 shelf. Detailed Implementation

[0019] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those of ordinary skill in the art without creative effort are within the protection scope of the present invention.

[0020] Example, refer to Figures 1-4 As an embodiment of the present invention, an automatic drug traceability method based on RFID for medicine vending machines is provided, comprising the following steps: Step S1: Based on the RFID antenna used to sense the RFID electronic tag at the shipping port, obtain the electronic data corresponding to the medicine and retrieve the traceability code corresponding to the electronic data. Both RFID electronic tags and traceability codes integrate the drug's UID, production batch code, and manufacturer's digital signature, and the electronic data is configured with a dynamic expiration code and an on-chain hash value in the storage system; The dynamic validity code is generated based on the SM4 national cryptographic algorithm and updated according to a preset method; Step S2: Compare the dynamic expiration code and the on-chain hash value with the on-chain record to obtain the comparison result. Based on the comparison result, return the drug status and drug traceability information.

[0021] Specifically, the application scenario of this application is an unattended medicine vending machine. After the medicines are put into the vending machine in batches and the drug traceability code and RFID electronic tag are bound and pre-registered in batches at the back-end management terminal of the unattended medicine vending machine, the medicines are sold to users before they purchase the medicines. After each box of medicine is placed in the cabinet, the backend management terminal and the cloud platform (i.e., the medical insurance supervision platform) are linked to ensure that each box of medicine can only be reimbursed once. At the same time, the receipt printing function and the automatic traceability code acquisition function configured in this application can achieve functions that cannot be achieved in the current technology: when the user chooses to pay through a third-party platform, the traceability code can also be automatically obtained from the cloud platform to ensure effective supervision of the sale status of medicines and prevent the risk of medical insurance fund abuse such as medical insurance fraud.

[0022] This application, in conjunction with the hardware module of the unmanned medicine vending machine, enables the coordinated scheduling of the scanning head, RFID reading and writing module, 5G module, and receipt printer. It eliminates the need for manual scanning of drug traceability codes, improving the intelligence and compliance of the medicine vending machine. Compared with existing technologies, the automatic transfer device provided in this application is novel, capable of reading two storage media simultaneously: reading the traceability code from the scanning head and reading the electronic information from the electronic tag from the RFID reading and writing module. This reduces the risk of not being able to read the traceability code when the medicine is taken out of the vending machine, significantly improving the success rate of traceability code recognition and regulatory feasibility.

[0023] Furthermore, this invention generates dynamic time-sensitive codes using the SM4 national cryptographic algorithm and generates on-chain hash values ​​based on the SM3 standard. This enables dynamic encryption and on-chain anchoring of the dynamic time-sensitive codes. By combining static and dynamic data for on-chain storage in both combined and backup states, and generating traceability information index codes based on block area numbers, data silos at each stage are eliminated. By resetting the update cycle based on the ambient temperature of the drug, the S-box lookup table replacement value, the L-transform cyclic shift parameter, and the number of key inversions, the update frequency of the dynamic time-sensitive codes can be matched with the drug storage environment in real time, improving the environmental adaptability of the anti-counterfeiting mechanism.

[0024] Furthermore, this application applies to the scenario of drug delivery traceability in automated medicine vending machines based on RFID technology, with the following limitations: Application scenarios include the dispensing port of an automated medicine vending machine equipped with an RFID antenna, the RFID antenna communicating with the first controller via serial port, the first controller being connected to the RFID reading and writing module and the motor, the motor being connected to the push mechanism, the second controller communicating with the first controller via serial port, the second controller being connected to the 5G module, and the vending machine being equipped with a touch screen. In the application scenario, the medicine packaging is a medicine packaging box with integrated RFID electronic tags. The RFID electronic tag consists of a PET substrate layer, a nano silver antenna layer and a biodegradable encapsulation layer, and has a built-in miniature temperature sensor. The RFID electronic tag is located on the side of the medicine packaging box. In the application scenario, the RFID electronic tag integrates the drug UID, production batch code and manufacturer's digital signature. The electronic data corresponds to a dynamic time-limited code and an on-chain hash value. The dynamic time-limited code is generated based on the SM4 national cryptographic algorithm. Application scenarios include a distributed verification network consisting of blockchain master nodes, blockchain backup nodes, blockchain indexes, regulatory platforms, and a whitelist of pre-authorized shipments from local vending machines; In the application scenario, the traceability operation is triggered by the RFID antenna at the shipping port sensing the electronic tag, the on-chain operation is triggered by the RFID antenna sensing the medicine box, that is, after the user takes the medicine, and the dynamic time-sensitive code update is triggered when the difference between the current timestamp and the previous on-chain timestamp reaches the update cycle.

[0025] Furthermore, the RFID electronic tag also incorporates a miniature temperature sensor to monitor the temperature of the environment surrounding the medicine, providing a data basis for subsequent updates to the dynamic expiration code.

[0026] Furthermore, each time the dynamic time-sensitive code is updated, a block is generated to record the operator, the operation timestamp, and the updated hash value to ensure that the data cannot be tampered with.

[0027] Furthermore, for the RFID antenna used to sense RFID electronic tags at the shipping port, the RFID antenna communicates with the first controller via serial port, and the second controller communicates with the first controller via serial port. The first controller is connected to the RFID reader / writer module and the motor, and the motor is connected to the drive mechanism; The second controller is connected to a 5G module, and a touch screen is installed on the vending machine. The touch screen is connected to the second controller, and a dispensing port is set at the top of the RFID antenna. When a dispensing action is detected, the second controller is triggered to send an on-chain request to the blockchain network. After triggering the on-chain request, the traceability code, drug UID, production batch code, dynamic expiration code, and current temperature value are packaged into a data package to be uploaded to the chain. The SM3 standard is then used to generate an on-chain hash value, which is simultaneously written to the traceability code. After the on-chain hash value is verified by the blockchain network consensus, it is written to the distributed ledger. After the on-chain is completed, the dynamic expiration code is automatically updated, and the updated dynamic expiration code is simultaneously written to the encrypted storage area to ensure that the dynamic expiration code changes in real time with the drug storage environment, thereby enhancing the anti-counterfeiting timeliness and environmental adaptability.

[0028] Furthermore, between steps S1 and S2, the drug UID and traceability information index code are extracted based on the dynamic validity code, and it is determined whether the traceability code structure conforms to the preset protocol format. The preset protocol format includes a dynamic validity code field and an on-chain hash value field. If so, proceed to step S2; If not, a format error code will be returned, and a shipment interception signal will be triggered to prevent the motor-driven push mechanism from performing the shipment action.

[0029] Preset methods include: The update cycle is reset based on the S-box lookup table replacement value, the cyclic shift parameter of the L-transform, and the key inversion count under the SM4 national cryptographic algorithm, and based on the temperature value of the surrounding environment of the medicine. The update cycle is set based on the timestamp of the drug's last upload to the blockchain.

[0030] Furthermore, the dynamic time-limited code is generated based on the dynamic key generation mechanism of the SM4 national cryptographic algorithm; For the encryption process, for example, if the input is 128 bits of plaintext, it is divided into four 32-bit words: X0, X1, X2, and X3. The process involves 32 iterations, each generating a new character, which is then processed by the F function. The new character representation is X_{i+4}=X_i⊕F(X_{i+1},X_{i+2},X_{i+3},rk_i}); The output ciphertext is X35, X34, X33, X32: For F(B0, B1, B2, rk) = (B0⊕B1⊕B2⊕rk), perform T function calculation, which is to first apply S-box substitution and then apply linear transformation L; The initial key MK is divided into MK0, MK1, MK2, and MK3; The initial key is XORed with the FK array to obtain K0, K1, K2, K3; For i from 0 to 31, calculate K_{i+4}=K_i⊕T'(K_{i+1}⊕K_{i+2}⊕K_{i+3}⊕CK_i}); Among them, the T' function is similar to the T function, but the linear transformation is different. For example, the linear transformation L' corresponding to the T' function uses a different cyclic shift parameter than the linear transformation L corresponding to the T function.

[0031] Furthermore, SM4 has a symmetric Feistel structure, so the decryption process is the same as the encryption process, but the order of use of the round keys is reversed, that is, they are applied in the order of rk31 to rk0. To illustrate whether the final output needs to be reversed, for example, the encrypted output is X35, X34, X33, X32, while the original input is X0, X1, X2, X3. After the final round, these four characters need to be reversed and combined into ciphertext.

[0032] For the verification process, determine whether each round of processing generates X_{i+4}, and whether the encrypted output is in reverse order; If, during the encryption process, the four characters after 32 iterations are X32, X33, X34, and X35, then determine whether the ciphertext is composed of X35, X34, X33, and X32, or determine whether the arrangement of the encrypted output changes after each round. For example, the initial input is X0, X1, X2, X3; After the first round, we get X4 = X0 ⊕ F(X1, X2, X3, rk0). Then, in the next round, we process X1, X2, X3, X4 to get X5, and so on, until the 32nd round generates X35. At this point, the final four characters are X32, X33, X34, X35. Alternatively, is there a cyclic shift in each round of processing, for example, after each processing, the new character becomes the fourth position? For example, in each round, the new X_{i+4} = X_i⊕F(X_{i+1}⊕X_{i+2}⊕X_{i+3}⊕ rk_i} is the transformed result; Then, in the next round, the four characters become X_{i+1}, X_{i+2}, X_{i+3}, X_{i+4}, and so on. After 32 rounds, we get X32 to X35. Then, the final ciphertext is these four words in reverse order, namely X35, X34, X33, X32; Therefore, during encryption, the final output is the four words in reverse order.

[0033] Furthermore, during decryption, the same process is followed, but the round keys are used in reverse order. For example, during decryption, the ciphertext is divided into X35, X34, X33, and X32. Then, the round keys rk31 to rk0 are used to process the ciphertext to obtain the original X0, X1, X2, and X3. In this way, the encryption and decryption structures are symmetrical, only the order of the round keys is reversed, similar to the characteristics of the Feistel network. Therefore, the decryption process is the same as the encryption process, only the order of the round keys is reversed.

[0034] Furthermore, regarding the FK and CK parameters in the key expansion, FK is a fixed set of four 32-bit constants, for example, FK0=0xA3B1BAC6, FK1=0x56AA3350, FK2=0x677D9197, FK3=0xB27022DC; CK is an array of 32 32-bit constants, and the value of each CK_i is generated by a specific method, for example, a function based on a sequence of integers. Furthermore, the S-box lookup table replacement value is explained. The S-box of SM4 is a 256-byte lookup table, and the replacement value for each byte is different. For example, the construction of an S-box is based on a certain mathematical transformation, such as the inverse operation on GF(2^8), combined with affine transformation, similar to the S-box of AES, but with different parameters; When implementing this, attention needs to be paid to the handling of byte order, whether each word is stored in big-endian, and whether the order of each operation is correct. For example, when splitting 128-bit data into four 32-bit words, it is necessary to choose whether to arrange them in big-endian or little-endian order.

[0035] For performance optimization, for example, pre-compute the S-box, use a lookup table, or convert linear transformations L and L' into matrix multiplication or bit operations.

[0036] Furthermore, the preset methods include: Step a1: Extract the S-box lookup table replacement value from the current round function of the SM4 national cryptographic algorithm, perform a bitwise XOR operation on the S-box lookup table replacement value and the round key extension constant FK0, and perform a bitwise NOT operation on the XOR operation result to generate the first time factor; Step a2: Extract the cyclic shift parameter of the L transform from the current round function of the SM4 national cryptographic algorithm, perform a modular addition operation on the cyclic shift parameter and the first time efficiency coefficient, perform a cyclic left shift operation on the result of the modular addition operation, the shift number is equal to the current round number, and generate the second time efficiency coefficient; Step a3: Obtain the number of key inversions in the current key scheduling process of the SM4 national cryptographic algorithm, perform a subtraction operation between the number of key inversions and the total number of rounds of the SM4 algorithm, and perform a bitwise AND operation between the subtraction result and the second timeliness coefficient to generate the third timeliness coefficient; Step a4: Obtain the temperature value of the environment surrounding the drug, multiply the integer part of the temperature value with the third efficiency coefficient, divide the decimal part of the temperature value with the third efficiency coefficient, and add the result of the multiplication and the result of the division to generate the periodic adjustment amount; Step a5: Obtain the last on-chain timestamp of the drug, perform a modulo addition operation on the last on-chain timestamp and the periodic adjustment amount, use the result of the modulo addition operation as the target trigger timestamp for the next dynamic timeliness code update, and use the periodic adjustment amount as the reset update period.

[0037] Furthermore, MK is the master key, which is 128 bits long and consists of four 32-bit words concatenated in sequence; MK0, MK1, MK2, and MK3 are the four 32-bit word components of the master key, arranged in order from most significant bit to least significant bit. FK stands for Fixed Key Constants, which are four 32-bit fixed constants used in the key expansion algorithm. FK0, FK1, FK2, and FK3 are four components of the fixed key constant, and their hexadecimal values ​​are 0xA3B1BAC6, 0x56AA3350, 0x677D9197, and 0xB27022DC, respectively. CK is an array of cryptographic constants, consisting of 32 32-bit constants used in the key expansion algorithm, denoted as CK0 to CK1. 31 ; CKᵢ is the i-th element in the encryption constant array, where i is an integer from 0 to 31; K is the extended key, which is a sequence of 32 32-bit words generated during the key expansion process, denoted as K0 to K1. 35 ; K0, K1, K2, and K3 are the initial extended keys, which are obtained by performing XOR operations between MK0 to MK3 and FK0 to FK3 respectively; Kᵢ, Kᵢ+1, Kᵢ+2, Kᵢ+3, and Kᵢ+4 are the i-th, i+1, i+2, i+3, and i+4th elements in the extended key sequence; rk is the round key, a 32-bit key used in each round of the 32nd iteration of the SM4 encryption algorithm, denoted as rk0 to rk0. 31 ; rkᵢ is the round key used in the i-th round, where i is an integer from 0 to 31; S stands for S-box (Substitution Box), an 8-bit input, 8-bit output non-linear byte substitution table used in the SM4 algorithm, containing 256 substitution values; The S-box lookup table replacement value is the byte value output after the input byte has undergone nonlinear transformation by the S-box; L is a linear transformation, a 32-bit linear transformation used in the T function, consisting of circular shift and XOR operations; L' is a linear transformation, a 32-bit linear transformation used in the T' function, employing a different cyclic shift parameter than L; The cyclic shift parameter of the L-transform is the number of cyclic left shifts of a 32-bit word as specified in the L-transform. F is the round function, a non-linear function that processes the state word in each iteration of the SM4 algorithm; X is the status word, a 32-bit intermediate variable generated in each round of the SM4 algorithm encryption process; X0, X1, X2, and X3 are the initial four 32-bit status words in the encryption process, which are obtained by splitting 128-bit plaintext blocks word by word; Xᵢ, Xᵢ+1, Xᵢ+2, Xᵢ+3, and Xᵢ+4 are the state words for the i-th round and subsequent rounds, where i is an integer from 0 to 31; X 32 X 33X 34 X 35 These are the four 32-bit status words generated after the 32nd iteration; B0, B1, and B2 are the three 32-bit parameters input to the F function; opad is the external padding constant, which is the 0x5C repeating padding sequence used in the HMAC-SM3 algorithm; ipad is the padding constant, a 0x36 repeating padding sequence used in the HMAC-SM3 algorithm; Wᵢ is the message extension word, a 32-bit word generated during the message extension stage of the SM3 algorithm, where i is an integer from 0 to 67; W'ᵢ is the message secondary extension word, a 32-bit word generated during the message extension stage of the SM3 algorithm, where i is an integer from 0 to 63.

[0038] The dynamic time-sensitive code is initially written before the medicine is placed in the vending machine, and is traceable and updated when the medicine is shipped.

[0039] Initial write methods include: The RFID electronic tag is identified by a reader / writer device via radio frequency identification. Static data responding to the RFID electronic tag and dynamic data responding to the reader / writer device are obtained. A dynamic time-sensitive code is generated based on the dynamic data and stored in the storage database. Static and dynamic data are combined and uploaded to the blockchain in a backup state.

[0040] Furthermore, the initial write method includes: The RFID electronic tag is radio frequency identified by the reading and writing device, the electronic tag's response circuit is activated, the static data returned by the electronic tag is received, the system clock of the reading and writing device is read to obtain the reading timestamp, and the location of the reading and writing device is read to obtain the device location. Determine whether the static data contains all categories of EPC code, drug production date, drug batch number, and manufacturer code; If so, concatenate the static data with the read timestamp and device location fields to generate combined state data; concatenate the static data, read timestamp, and device location fields to generate backup state data; If not, return a static data missing signal and terminate the initial write process; Send a request to the blockchain master node to upload the combinational data, receive the main chain hash value returned by the blockchain master node, and complete the combinational data upload. Send a request to the blockchain backup node to upload the backup state data to the blockchain backup node, receive the backup chain hash value returned by the blockchain backup node, and complete the backup state upload to the blockchain. Determine if the main chain hash value is the same as the backup chain hash value; if so, write the main chain hash value into the traceability code field of the RFID electronic tag to complete the initial write; if not, return a consistency exception signal and trigger the re-on-chain process.

[0041] The update methods include: At the moment the medicine is shipped, the RFID antenna is triggered to read the electronic tag and extract the updated dynamic time stamp and the current timestamp; Based on the updated dynamic expiration code, the drug is traced and its status is identified. The dynamic expiration code of the drug is updated based on the current timestamp.

[0042] The initial write method also includes: Based on the SM4 national cryptographic algorithm, a key is configured for the data uploaded to the chain in combinational state, and a dynamic time-limited code is generated based on the key. The on-chain hash value of the dynamic time-limited code is automatically obtained. Based on the data backed up to the blockchain, it is stored in blocks, and based on the block number, a traceability information index code is generated.

[0043] Furthermore, the initial write method also includes: Extract the EPC code, drug production date, drug batch number and manufacturer code from the combinatorial data, and fill the extracted results into the four words MK0, MK1, MK2 and MK3 of the initial key MK of the SM4 national cryptographic algorithm in byte order to generate the initial key; Perform an XOR operation between the initial key and the FK array to obtain K0, K1, K2, and K3. Perform 32 rounds of key expansion to generate round key sequences rk0 to rk31. The timestamp and device location are combined into 128-bit plaintext, input into the SM4 encryption function, and encrypted for 32 rounds using a round key sequence. The ciphertext is then output as a dynamic time-limited code. The dynamic validity code is concatenated with the drug UID, production batch code and manufacturer digital signature in the RFID electronic tag to generate a validity verification data string. Perform SM3 hash operation on the timeliness verification data string to generate the on-chain hash value of the dynamic timeliness code; Write the dynamic expiration code and the on-chain hash value into the dynamic expiration code field and the on-chain hash value field of the traceability code, respectively; The backup data is divided into multiple data blocks according to the equal-length rule. The multiple data blocks are then distributed to multiple block areas of the blockchain backup node for storage, and the area number of the block area where each data block is located is recorded. The regional numbers are concatenated into strings according to the storage order to generate traceability information index codes. A one-to-one mapping relationship between the traceability information index codes and drug UIDs is established, and this mapping relationship is written into the blockchain index library.

[0044] Static data includes the EPC code of the drug at the time of manufacture, the drug production date, the drug batch number, and the manufacturer code; Dynamic data includes the read timestamp of the read / write device and the device location of the read / write device.

[0045] Methods for generating on-chain hash values ​​include: Multiple fields are concatenated according to protocol rules, delimiters are added between fields, the separated fields are converted into a binary stream, the binary stream is padded according to the SM3 standard, SM3 hash operation is performed, and a fixed-length on-chain hash value is generated.

[0046] Furthermore, multiple fields are concatenated according to protocol rules, for example: Input data = UID||Counter||Sensor data||Timestamp; Where || represents byte concatenation; You can add separators between fields, such as 0x00, to avoid ambiguity.

[0047] Furthermore, binary streams, such as UTF-8 or big-endian encoding; Pad the binary stream, for example, by appending 0x80, to make the length satisfy modulo 512 remainder 448.

[0048] Furthermore, perform SM3 hash operations, for example, initialize the hash context: Load SM3 initial values ​​(IV): IV=7380166F 4914B2B9 172442D7 DA8A0600 A96F30BC163138AA E38DEE4D B0FB0E4E Message chunking: Divide the padded data into 512-bit (64-byte) chunks; For each block, perform expansion and compression functions: expansion includes expanding the 512-bit block into 132 32-bit words (W0~W67, W'0~W'63); compression includes iteratively using SM3's substitution functions, including Boolean operations, shifting, and modulo addition. Generate the final hash value: After the last round of compression, the output is a 256-bit, or 32-byte, hash value.

[0049] Furthermore, a timestamp is embedded in the read / write device to ensure that the hash value is unique each time. For example, input data = UID||counter value (0x0001, 0x0002, ...)||timestamp; HMAC is generated using a pre-set key to enhance anti-forgery capabilities. For example, HMAC-SM3(key, data)=SM3((key⊕opad)||SM3((key⊕ipad)||data)); Hardware implementations can mask power consumption and timing differences, such as constant-time algorithms.

[0050] Furthermore, ⊕ is the bitwise XOR operation, which performs an XOR logical operation on each bit of two equal-length binary data; || is the field concatenation operation, which joins multiple data fields end to end in byte order into a continuous data string; mod is the modulo operation, which performs a division operation on two integers and takes the remainder; in the modulo addition context, it means modulo 2³² addition; & is the bitwise AND operation, which performs an AND logical operation on each bit of two equal-length binary data; ~ is the bitwise NOT operation, which performs a NOT logical operation on each bit of binary data; and <<< is the circular left shift operation, which shifts a 32-bit word to the left by a specified number of bits, filling the shifted-out high bits with low bits.

[0051] Furthermore, methods for generating on-chain hash values ​​include: Obtain multiple fields to be hashed, including drug UID, production batch code, manufacturer digital signature, dynamic expiration code, current timestamp, and ambient temperature value of the drug. Check if any field has an empty value; If all field values ​​are not empty, the multiple fields are sorted according to fixed protocol rules, and the sorting order is: drug UID, production batch code, manufacturer digital signature, dynamic expiration code, current timestamp, and ambient temperature value of the drug. If a field has an empty value, record the field missing event, terminate the on-chain hash value generation process, and send a shipment failure signal. Perform field concatenation on the sorted multiple fields, insert a hexadecimal separator 0x00 between two adjacent fields, and generate a concatenated data string; Determine whether the concatenated data string contains non-ASCII characters; If yes, convert the concatenated data string to a binary stream using UTF-8 encoding; otherwise, convert the concatenated data string to a binary stream using big-endian encoding. If the concatenated data string is encoded into a binary stream in big-endian order, then the bit length of the binary stream is calculated, and it is determined whether the remainder obtained by dividing the bit length by 512 is equal to 448. If so, append a 64-bit binary representation of the original concatenated data string bit length to the end of the padded binary stream to generate the message to be hashed; If not, append a hexadecimal byte 0x80 sequentially to the end of the binary stream, then append n hexadecimal bytes 0x00 sequentially, where n is the number of bytes required to make the remainder of the binary stream bit length divided by 512 equal to 448. Finally, append the bit length value of the original concatenated data string in binary representation to the end of the padded binary stream to generate the message to be hashed. Divide the message to be hashed into multiple message blocks of 512 bits each, and check if the number of message blocks is zero. If the number of message blocks is zero, record the field missing event, terminate the on-chain hash value generation process, and send a shipment failure signal; If the number of message blocks is not zero, load the SM3 initial value IV and initialize the hash context; Execute message expansion and compression functions sequentially for each message block in the order of message blocks, and determine whether the current message block is the last message block; If it is the last message block, the 256-bit output value after the last round of compression will be used as the on-chain hash value. The on-chain hash value will be written into the on-chain hash value field of the traceability code, and the mapping relationship between the on-chain hash value and the drug UID will be written into the blockchain index library. If it is not the last message block, continue processing the next message block and repeat the steps: execute the message expansion and compression functions for each message block in order, and determine whether the current message block is the last message block.

[0052] The comparison results include whether there is a traceability information index code corresponding to the dynamic time-limited code, and whether the actual hash value is consistent with the on-chain hash value; The status of a drug is either 0 or 1. If the drug has been sold, the status is 1; if the drug has not been sold, the status is 0. Step S2 includes the following sub-steps: Step S21: Based on the RFID antenna, read the electronic data corresponding to the RFID electronic tag data and obtain the dynamic validity code corresponding to the electronic data; Step S22: Determine whether there is a traceability information index code corresponding to the dynamic timeliness code. If yes, proceed to step S23; otherwise, proceed to step S24. Step S23: Retrieve the on-chain hash value of the corresponding traceability information index code in the blockchain, concatenate the read RFID electronic tag data according to the same protocol rules and calculate the actual hash value, and compare the actual hash value with the on-chain hash value. If they match, the drug status is returned as 1, and the drug traceability information is returned. If there is a discrepancy, the drug status will be returned as 0; If the drug status returns as 1, the system will automatically obtain the traceability code from the regulatory platform and print a receipt based on the traceability code. When medicines are sold in unmanned vending machines, the system automatically obtains a traceability code from the cloud platform and prints a receipt for the medicine based on the traceability code. At the same time, the system marks the medicine as sold on the cloud platform. Payment methods for unmanned medicine vending machines include medical insurance payment and third-party payment. Both medical insurance payment and third-party payment can automatically obtain the traceability code registered on the cloud platform to print a receipt for the medicine.

[0053] Furthermore, step S23 also includes reading the electronic data corresponding to the dynamic validity code, obtaining the original data fields, such as UID, and the on-chain hash value of the corresponding dynamic validity code; Data is concatenated according to the same rules and the SM3 algorithm is called to generate a temporary hash. If the temporary hash is the same as the on-chain hash, then the actual hash value is consistent with the on-chain hash value; if the temporary hash is different from the on-chain hash value, then the actual hash value is inconsistent with the on-chain hash value.

[0054] If they match, the drug status is returned as 1, and the traceability code is automatically obtained from the regulatory platform, and a receipt is printed based on the traceability code. If there is a discrepancy, the drug status will be returned as 0, and a delivery failure signal will be displayed; Furthermore, when drug traceability information is returned, the on-chain hash value is automatically updated to the actual hash value; Each time the hash value on the chain is updated, the new hash value is bound to the previous hash value, such as Hash_new=SM3(Hash_old||new data)). This binding mechanism ensures the immutability and time series integrity of the hash chain.

[0055] Furthermore, the dynamic expiration code is parsed into an index field set and a verification field set; The index field set includes drug UID, production batch code, and traceability information index code; the verification field set includes dynamic expiration code and on-chain hash value. Determine the network connection status of blockchain nodes; If the connection is normal, a query request is initiated to the distributed ledger based on the traceability information index code; If the connection is abnormal, check if the most recent on-chain hash value corresponding to the drug's UID is stored locally. If a backup exists, the backup hash value is used as a temporary on-chain hash value for comparison, and the verification mode is marked as offline verification. If there is no backup, a network error status code will be returned, triggering a shipment suspension, pending network recovery or manual instructions.

[0056] Furthermore, step S22 also includes the following sub-steps: Step S221: Based on the drug UID and production batch code, retrieve the traceability information index code in the blockchain distributed ledger; Step S222: Determine whether a unique matching traceability information index code has been retrieved; If yes, proceed to step S23; otherwise, proceed to step S223. Step S223: If the search result is empty, that is, there is no matching record, then proceed to step S24. If the search results are not unique, i.e. there are multiple conflicting records, an index conflict anomaly event will be pushed to the regulatory platform, a conflict status code will be returned, shipment will be intercepted, and the RFID electronic tag for the drug UID will be reconfigured. If the retrieval times out, i.e. the blockchain node response takes more than 10 seconds, the local backup verification node is started to retry. If the retry is successful, the process jumps to step S23; if the retry fails, a network timeout status code is returned, triggering a shipment suspension.

[0057] Furthermore, step S23 also includes the following sub-steps: Step S231: Retrieve the on-chain hash value of the corresponding traceability information index code in the blockchain; Step S232: Concatenate the currently read RFID electronic tag data fields according to the protocol rules to generate a data string to be verified; Step S233: Perform a hash operation on the data string to be verified using the SM3 algorithm to generate an actual hash value; Step S234: Determine whether the actual hash value is consistent with the hash value on the chain; If so, return the drug status to 1 and proceed to step S235; If not, proceed to step S236; Step S235: Return drug traceability information, including: manufacturer code, drug production date, distribution node record, and historical temperature curve; Determine if the current verification mode is offline verification. If so, add an offline verification watermark to the traceability information and prompt the user to re-verify online after the network is restored. If not, trigger the on-chain hash value update, generate Hash_new = SM3(Hash_old || data string to be verified || current timestamp), write Hash_new to the blockchain, and synchronously update the on-chain hash value field in the dynamic time-limited code; Step S236: Return the drug authenticity value to 0; The field difference location algorithm is activated, including: The data string to be verified is split by field, and the split results include UID field, batch code field, dynamic expiration code field, and manufacturer digital signature field. Calculate the local hash value of each field and compare the local hash value of each field with the local hash value of the corresponding field on the chain; If the UID field or the batch code field is inconsistent, error code E101 is returned. E101 indicates identity tampering, and the tampering location is marked as the identity layer. If the dynamic validity code field is inconsistent, error code E102 is returned. E102 indicates that the validity period has been tampered with, and the location of the tampering is marked as the validity period layer. If the manufacturer's digital signature fields are inconsistent, error code E103 will be returned. E103 indicates that the signature has been tampered with, and the location of the tampering is marked as the signature layer. If multiple fields are inconsistent at the same time, error code E104 is returned. E104 indicates compound tampering, and the tampering location is marked as multiple layers. Automatically transmit exception events to the management backend. The exception events include: error code, medicine box location, actual hash value, on-chain hash value, and current timestamp.

[0058] In one embodiment, the hardware environment of the automated medicine vending machine includes: An ultra-high frequency RFID antenna is installed at the shipping port. The ultra-high frequency RFID antenna operates at a frequency of 920MHz-925MHz. The antenna communicates with the first controller via an RS232 serial port. The first controller is an STM32F407 microcontroller. The first controller is connected to the RFID read / write module via an SPI interface. The core component of the RFID read / write module is an AS3993 chip. The first controller is connected to the stepper motor driver via a GPIO interface. The stepper motor is mechanically connected to the drug pushing mechanism. The second controller communicates with the first controller via a USB-to-RS232 serial cable. The second controller is a Raspberry Pi 4B and runs a Linux system. The second controller is connected to a 5G communication module (Quectel RM500Q) via a USB interface. It is connected to a 10.1-inch capacitive touchscreen via an HDMI interface. An infrared beam sensor (ITR9606) is installed inside the pickup port. The RDIF read / write module is connected to the second controller via a GPIO interface. The RFID electronic tag adopts a three-layer structure of PET substrate layer, nano silver antenna layer and biodegradable encapsulation layer. The tag has a built-in NT3H2111 chip and a miniature temperature sensor. The measurement range of the miniature temperature sensor is distributed from -40℃ to +85℃, with a resolution of 0.0625℃. The tag is attached to the side of the medicine packaging box by hot melt adhesive marking. The Hyperledger Fabric consortium blockchain is deployed, consisting of one master node (Orderer) and two backup nodes (Peers). It establishes a TLS encrypted connection with the second controller of the medicine vending machine via a 5G network. The blockchain index uses the CouchDB state database, and the regulatory platform subscribes to blockchain events in real time through the SDK interface.

[0059] The medicine to be stored is placed within the sensing area of ​​the RFID reader / writer module, which is the same model as the medicine vending machine. The reader / writer emits a radio frequency signal to activate the RFID electronic tag. The static data returned by the tag includes: EPC code: 0xE20060060000000000000001 (96-bit), drug production date: 20260101, drug batch code: LOT20261001A, manufacturer code: MFG001; The read / write device synchronously reads the system clock to obtain the read timestamp, 20260603120000 (UTC+8); it reads the device's built-in GPS positioning module to obtain the device location: N31.2304E121.4737; The first controller determines whether the static data simultaneously contains four fields: EPC code, drug production date, drug batch number, and manufacturer code. In this embodiment, all four fields exist, so the process jumps to step 3. Combined state data is generated by concatenating the fields in order. Combined state data = EPC code || 0x00 || Drug production date || 0x00 || Drug batch code || 0x00 || Manufacturer code || 0x00 || Read timestamp || 0x00 || Device location; Backup state data is generated by concatenating fields in order (the field order is the same as the combined state data). Backup state data = EPC code || 0x00 || Drug production date || 0x00 || Drug batch code || 0x00 || Manufacturer code || 0x00 || Read timestamp || 0x00 || Device location; The second controller sends the combinational state data to the blockchain master node through the 5G module. After the master node performs the SM3 hash operation, it returns the main chain hash value, which is represented as Hash_main, Hash_main=0xA1B2C3D4E5F6.... The main chain hash value is 256 bits and 32 bytes. The second controller sends the backup state data to the blockchain backup node. After the backup node performs the SM3 hash operation, it returns the backup chain hash value, which is represented as Hash_backup, Hash_backup=0xA1B2C3D4E5F6... The backup chain hash value is 256 bits and 32 bytes. The second controller determines whether Hash_main and Hash_backup are the same. In this embodiment, they are the same. Hash_main is written into the traceability code field of the RFID electronic tag as the on-chain hash value. Extract the EPC code (0xE20060060000000000000001), drug production date (20260101), drug batch code (LOT20261001A), and manufacturer code (MFG001) from the combinational state data, and fill them into the SM4 initial key MK in byte order; MK0=0xE2006006, MK1=0x00000000, MK2=0x00000001, MK3=0x20261001; Perform an XOR operation between the MK and FK arrays, including: K0=MK0⊕FK0=0xE2006006⊕0xA3B1BAC6=0x41B1DAC0; K1=MK1⊕FK1=0x00000000⊕0x56AA3350=0x56AA3350; K2=MK2⊕FK2=0x00000000⊕0x677D9197=0x677D9197; K3=MK3⊕FK3=0x20261001⊕0xB27022DC=0x925632DD; Perform 32 rounds of key expansion to generate round key sequences rk0 to rk31; The read timestamp (20260603120000) and device location (N31.2304E121.4737) are combined into 128-bit plaintext, input into the SM4 encryption function, and 32 rounds of iterative encryption are performed using the round key sequence. The output ciphertext is used as the dynamic time code, DynamicCode=0x7F8E9D0A1B2C3D4E5F60718293A4B5C6; The DynamicCode is concatenated with the drug UID (0xE200600600000000000000001), production batch code (LOT20261001A), and manufacturer's digital signature (0x1234567890ABCDEF) to generate a time-sensitive verification data string. The SM3 hash operation is then performed to generate the on-chain hash value DynamicHash of the dynamic time-sensitive code, where DynamicHash = SM3(DynamicCode||UID||Batch Code||Signature). Write DynamicCode to the dynamic expiration code field of the traceability code, and write DynamicHash to the on-chain hash value field of the traceability code; The backup data is divided into multiple data blocks according to the 512-byte equal-length rule. In this embodiment, the backup data length is 256 bytes, which is divided into 1 data block. If the data block is less than 512 bytes, it is stored according to the original length. Assign the data block to block area number 01 of the blockchain backup node and record area number 01; Concatenate the region numbers in the storage order to generate the traceability information index code IndexCode, IndexCode=01; Establish a one-to-one mapping relationship between the traceability information index code and the drug UID (0xE20060060000000000000001), and write it into the blockchain index library.

[0060] During drug storage, the RFID electronic tag contains a built-in miniature temperature sensor that collects temperature values ​​in real time. In this embodiment, the currently collected temperature value is 25.5℃; Extract from the current round function of SM4 (currently round 5, i=5): S-box lookup table replacement value: The current input byte is 0x12, and after S-box lookup table, the output is 0xC3; The cyclic shift parameter of the L-transform is 10 bits for the current round of the cyclic left shift. Key inversion count: The number of key inversions performed during the current key scheduling process is 3; Perform a bitwise XOR operation on the S-box lookup table replacement value and the round key extension constant FK0 to obtain 0xA3B1BA05. Perform a bitwise NOT operation on the XOR result to obtain 0x5C4E45FA. Perform a modular addition operation on the cyclic shift parameter of the L-transform and the first time factor to obtain 0x5C4E4604. Perform a cyclic left shift operation on the result of the modular addition operation, with the shift number equal to the current round number 5, to obtain 0x89C8C080. The key is inverted 3 times, the total number of rounds of the SM4 algorithm is 32, the subtraction operation is performed, and 29 is obtained. The result of the subtraction operation is bitwise ANDed with the second time factor, and 0x00000000 is obtained (the lower 5 bits of the valid value are retained after the bitwise AND).

[0061] In another embodiment, the user selects the medicine and completes payment via a touchscreen, and the second controller sends a delivery instruction to the first controller. The first controller drives a stepper motor to activate a push mechanism, pushing the medicine to the delivery slot. As the medicine passes the delivery slot, an RFID antenna senses the electronic tag and reads the electronic data. Retrieval via electronic data: Dynamic validity code: 0x7F8E9D0A1B2C3D4E5F60718293A4B5C6; On-chain hash value: 0xA1B2C3D4E5F6... (256 bits); The second controller extracts the drug UID (0xE200600600000000000000001) and traceability information index code (01) based on the dynamic time-sensitive code. Determine whether the traceability code structure contains both a dynamic expiration code field and an on-chain hash value field. In this embodiment, both fields exist; proceed to step 3. The second controller detects the TCP connection status with the blockchain master node through the 5G module. If the connection is normal, it initiates a query request to the distributed ledger based on the traceability information index code 01; if the connection is abnormal, it queries whether the local vending machine stores a backup of the most recent on-chain hash value corresponding to the drug UID; in this embodiment, if the network connection is normal, it jumps to step 4. The second controller retrieves the traceability information index code in the blockchain distributed ledger based on the drug UID (0xE20060060000000000000001) and production batch code (LOT20261001A); in this embodiment, a unique matching index code 01 is found, and the process jumps to step 5. The second controller retrieves the on-chain hash value 0xA1B2C3D4E5F6... corresponding to the traceability information index code 01 in the blockchain; Read the raw data fields from the RFID tag: UID, production batch code, manufacturer's digital signature, and dynamic validity code. Concatenate them according to the same protocol rules as in step one and calculate the actual hash value SM3 (UID||0x00||batch code||0x00||signature||0x00||dynamic validity code); in this embodiment, the two are consistent, so proceed to step 6. The drug status is returned as 1, and the drug traceability information is returned: Manufacturer code: MFG001; Drug production date: 20260101; Distribution node record: Factory → Warehouse → Dispenser; Temperature history curve: 25.5℃, 24.8℃, 25.2℃; The second controller determines whether the current verification mode is offline verification. In this embodiment, it is online verification, which triggers the update of the outgoing chain hash value. Generate a new on-chain hash value: Hash_new=SM3(Hash_old||data string to be verified||current timestamp 20260603150000); Hash_new is written to the blockchain distributed ledger via the 5G module, and the on-chain hash value field in the dynamic time-sensitive code is updated synchronously. The second controller packages the traceability code, drug UID, production batch code, updated dynamic time-sensitive code, current temperature value 25.5℃, shipping timestamp 20260603150000, and vending machine number VM001 into a data package to be uploaded to the blockchain. It then calls SM3 to generate a new hash value for uploading to the blockchain. After verification by the blockchain network consensus, the hash value is written into the distributed ledger, completing the shipment uploading to the blockchain.

[0062] Furthermore, this invention generates dynamic time-sensitive codes using the SM4 national cryptographic algorithm and generates on-chain hash values ​​based on the SM3 standard. This enables dynamic encryption and on-chain anchoring of traceability codes. By combining static and dynamic data for on-chain storage in both combined and backup states, and generating traceability information index codes based on block area numbers, a full lifecycle traceability chain for pharmaceuticals from production to shipment can be constructed, eliminating data silos at each stage. By resetting the update cycle based on the ambient temperature of the pharmaceutical environment, the S-box lookup table replacement value, the L-transform cyclic shift parameter, and the number of key inversions, the update frequency of the dynamic time-sensitive codes can be matched with the pharmaceutical storage environment in real time, improving the environmental adaptability of the anti-counterfeiting mechanism.

[0063] Furthermore, the motor driving the actuation mechanism is controlled by pre-written PLC code, the contents of which include: The PLC controller reads the pre-written PLC code and performs self-tests on the stepper motor driver, lead screw drive assembly, and position sensor. The self-tests include checking whether the enable signal of the stepper motor driver is normal, checking whether the origin switch of the lead screw drive assembly is in the initial position, and checking whether the feedback signal of the position sensor is within the effective range. If the self-test passes, the PLC controller sends a ready status signal to the first controller; if the self-test fails, the PLC controller sets the fault flag register, sends a fault interrupt signal to the first controller, and stops subsequent operation. The PLC controller monitors the GPIO control signals output by the first controller in real time through the I / O interface; When the built-in verification algorithm engine of the first main control chip completes the format verification and the verification pass flag register is set, the first controller outputs a high-level trigger signal to the input terminal of the PLC controller through the corresponding bit of the GPIO control register. After the PLC controller detects the rising edge of the high-level trigger signal, it analyzes the duration of the trigger signal. If the duration is within the preset valid range, the trigger is confirmed to be valid; if the duration exceeds the preset valid range, it is determined to be a false trigger, and the PLC controller ignores this signal and continues to monitor. After confirming that the trigger is valid, the PLC controller outputs a pulse sequence to the stepper motor driver. The frequency of the pulse sequence gradually increases from the starting frequency to the operating frequency according to the preset acceleration curve, so that the stepper motor can start smoothly from a stationary state and avoid loss of steps due to direct high-speed start. After receiving the pulse sequence, the stepper motor drives the lead screw transmission assembly. The lead screw converts the rotational motion into linear motion, pushing the push plate along the guide rail towards the shelf. The push plate contacts the rear end of the medicine packaging box, pushing the medicine forward from the shelf. During the movement of the pusher plate, the position sensor detects the current position of the pusher plate in real time and sends the position feedback signal back to the analog input terminal or high-speed counter terminal of the PLC controller in the form of analog quantity or pulse. The PLC controller compares the position feedback signal with a preset segmented position threshold. When the push plate is in the first segment interval, the PLC controller maintains the current operating frequency; When the push plate enters the second segment interval, the PLC controller reduces the pulse sequence frequency to the deceleration frequency, causing the push plate to decelerate. When the push plate reaches the preset push-out position, the PLC controller stops outputting the pulse sequence, the stepper motor brake locks, and the push plate stays at the push-out position, ensuring that the medicine is completely removed from the shelf and falls into the retrieval area. After the PLC controller stops outputting the pulse sequence, it delays for a preset time and then reads the feedback signal from the position sensor again to confirm whether the push plate is stably in the pushed-out position. If the deviation between the position feedback signal and the ejection position is within the preset tolerance range, the PLC controller determines that the ejection is successful, sets the ejection completion flag register, and sends an ejection completion confirmation signal to the first controller through the I / O interface. After receiving the confirmation signal that the push is complete, the first controller synchronously sends the drug landing information to the second controller, which serves as the timestamp reference for the data packet header in the communication protocol encapsulation. If the deviation between the position feedback signal and the ejection position exceeds the preset tolerance range, it is determined that the ejection is not complete. After confirming successful ejection, the PLC controller delays the return time to ensure that the medicine has completely fallen into the retrieval area. The PLC controller then outputs a reverse pulse sequence to the stepper motor driver. The frequency of the reverse pulse sequence increases according to the preset return acceleration curve and then remains constant. The drive screw transmission assembly drives the push plate to return to the initial position along the guide rail.

[0064] More preferably, when the position sensor detects that the push plate has reached the origin switch position, the PLC controller stops outputting the reverse pulse sequence, the stepper motor brake is locked, and the push plate stays in the initial position, waiting for the next trigger; If the position sensor does not detect that the push plate has reached the push position within the preset maximum operating time, it is determined that the push timeout has occurred. The PLC controller immediately stops outputting the pulse sequence, sets the timeout fault flag, and sends a timeout abnormal signal to the first controller. If the stepper motor driver feeds back an overcurrent signal, it is determined that the push plate is blocked or the rotor is stalled. The PLC controller immediately stops outputting the pulse sequence, sets the stall fault flag, and sends a stall abnormal signal to the first controller. If the position sensor feedback signal exceeds the effective range or a disconnection occurs, it is determined to be a sensor fault. The PLC controller will stop running and set the sensor fault flag.

[0065] In one embodiment, the first master control chip writes the raw data into the UART transmit register, and the transmit DMA engine moves the data block from the transmit FIFO to the UART transmit register, and sends it to the second master control chip via the TXD pin in an asynchronous serial frame format (1 start bit, 8 data bits, 1 parity bit, 1 stop bit). After the DMA transfer is completed, the transmission completion interrupt is triggered. The first main control chip synchronously sets the corresponding bit of the GPIO control register and outputs a high-level trigger signal (lasting for 15ms, within the preset effective range of 10~20ms) to the PLC controller. The PLC detects the rising edge, confirms the trigger is valid, and outputs a pulse sequence to the stepper motor driver. The frequency increases from 500Hz to 2000Hz according to the preset acceleration curve, driving the lead screw to push the push plate. The position sensor provides feedback on the push plate position: when entering the second segment interval, the PLC reduces the frequency to 800Hz to decelerate; when it reaches the push-out position (45mm from the origin), the pulse stops, the motor brake locks, and after a 200ms delay to confirm that the position deviation is within the ±0.5mm tolerance, the push-out completion flag register is set, and a push-out completion confirmation signal is sent to the first controller. After receiving the signal, the first controller simultaneously sends the drug landing information to the second controller (timestamp reference: 2026-06-08T14:32:15). Return to position: After a 1.5s delay to ensure the medicine falls, the PLC outputs a reverse pulse sequence, which increases in frequency according to the preset return acceleration curve and then moves at a constant speed to drive the push plate back to the original switch position, stops the pulse, and waits for the next trigger. The second main control chip detects the falling edge of the start bit on the RXD pin and samples at a baud rate of 115200. The receive DMA engine moves the serial frame to the receive FIFO and then writes it into the receive data buffer. The protocol stack encapsulation engine executes the second method: It reads the device ID (DISPENSER-OUT-03) from the device identifier register; reads the timestamp (2026-06-08T14:32:15.000Z); writes it to the packet header; writes the raw data as the payload to the body; calculates the payload CRC according to the CRC-16-CCITT standard: polynomial 0x1021, initial value 0xFFFF, input / output inverted, output XOR value 0x0000. The calculated CRC checksum is 0x3A7F; this is then written to the packet tail.

[0066] The total length of the verification data packet (including header, body, and trailer) is 312 bytes, which does not exceed the preset threshold of 1024 bytes; the CRC is recalculated and compared with the trailer 0x3A7F. All 16 bits are consistent, and the encapsulation status register is set to the encapsulation success flag. The data packet is transmitted to the 5G module baseband chip via the SPI bus and then uploaded to the cloud platform API gateway through the hospital's 5G private network. The second controller receives an interrupt signal from the 5G module within a 500ms period, confirming successful transmission.

[0067] Those skilled in the art will further recognize that the units and algorithm steps of the various examples described in conjunction with the embodiments disclosed herein can be implemented in electronic hardware, computer software, or a combination of both. To clearly illustrate the interchangeability of hardware and software, the components and steps of the various examples have been generally described in terms of functionality in the foregoing description. Whether these functions are implemented in hardware or software depends on the specific application and design constraints of the technical solution. Those skilled in the art can use different methods to implement the described functions for each specific application, but such implementations should not be considered beyond the scope of this invention.

[0068] The steps of the methods or algorithms described in conjunction with the embodiments disclosed herein can be implemented directly by hardware, a software module executed by a processor, or a combination of both. The software module can be located in random access memory (RAM), main memory, read-only memory (ROM), electrically programmable ROM, electrically erasable programmable ROM, registers, hard disk, removable disk, CD-ROM, or any other form of storage medium known in the art.

[0069] Finally, it should be noted that in this document, relational terms such as "first" and "second" are used only to distinguish one entity or operation from another, and do not necessarily require or imply any such actual relationship or order between these entities or operations. Furthermore, the terms "comprising," "including," or any other variations thereof are intended to cover non-exclusive inclusion, such that a process, method, article, or apparatus that comprises a list of elements includes not only those elements but also other elements not expressly listed, or elements inherent to such a process, method, article, or apparatus. Without further limitations, an element defined by the phrase "comprising one..." does not exclude the presence of other identical elements in the process, method, article, or apparatus that includes the element.

[0070] The technical solution provided by the present invention has been described in detail above. Specific examples have been used to illustrate the principle and implementation of the present invention. The description of the above embodiments is only for the purpose of helping to understand the method and core idea of ​​the present invention. At the same time, for those skilled in the art, there will be changes in the specific implementation and application scope based on the idea of ​​the present invention. Therefore, the content of this specification should not be construed as a limitation of the present invention.

Claims

1. A method for automatic drug traceability in RFID-based medicine vending machines, characterized in that, Includes the following steps: Step S1: Based on the RFID antenna used to sense the RFID electronic tag at the shipping port, obtain the electronic data corresponding to the medicine and retrieve the traceability code corresponding to the electronic data. Both RFID electronic tags and traceability codes integrate the drug's UID, production batch code, and manufacturer's digital signature, and the electronic data is configured with a dynamic expiration code and an on-chain hash value in the storage system; The dynamic validity code is generated based on the SM4 national cryptographic algorithm and updated according to a preset method; Step S2: Compare the dynamic expiration code and the on-chain hash value with the on-chain record to obtain the comparison result. Based on the comparison result, return the drug status and drug traceability information.

2. The RFID-based automatic drug traceability method for medicine vending machines as described in claim 1, characterized in that, The storage facility is pre-set to match the traceability codes of stored medicines with RFID electronic tags. Before placing the medicine into the medicine cabinet, RFID electronic tags are attached to the bottom of the medicine box using a marking method; Preset methods include: The update cycle is reset based on the S-box lookup table replacement value, the cyclic shift parameter of the L-transform, and the key inversion count under the SM4 national cryptographic algorithm, and based on the temperature value of the surrounding environment of the medicine. The update cycle is set based on the timestamp of the drug's last upload to the blockchain.

3. The RFID-based automatic drug traceability method for medicine vending machines as described in claim 1, characterized in that, The dynamic time-sensitive code is initially written before the medicine is placed in the vending machine and updated when the medicine is shipped.

4. The RFID-based automatic drug traceability method for medicine vending machines as described in claim 3, characterized in that, Initial write methods include: The RFID electronic tag is scanned by the reading and writing device to obtain static data in response to the RFID electronic tag and dynamic data in response to the reading and writing device. A dynamic time-sensitive code is generated based on the dynamic data and stored in the storage database. Static and dynamic data are combined and uploaded to the blockchain in a backup state.

5. The RFID-based automatic drug traceability method for medicine vending machines as described in claim 3, characterized in that, The update methods include: At the moment the medicine is shipped, the RFID antenna is triggered to read the electronic tag and extract the updated dynamic time stamp and the current timestamp; Based on the updated dynamic expiration code, the drug is traced and its status is identified. The dynamic expiration code of the drug is updated based on the current timestamp.

6. The RFID-based automatic drug traceability method for medicine vending machines as described in claim 4, characterized in that, The initial write method also includes: Based on the SM4 national cryptographic algorithm, a key is configured for the data uploaded to the chain in combinational state, and a dynamic time-limited code is generated based on the key. The on-chain hash value of the dynamic time-limited code is automatically obtained. Based on the data backed up to the blockchain, it is stored in blocks, and based on the block number, a traceability information index code is generated.

7. The RFID-based automatic drug traceability method for medicine vending machines as described in claim 4, characterized in that, Static data includes the EPC code of the drug at the time of manufacture, the drug production date, the drug batch number, and the manufacturer code; Dynamic data includes the read timestamp of the read / write device and the device location of the read / write device.

8. The RFID-based automatic drug traceability method for medicine vending machines as described in claim 6, characterized in that, Methods for generating on-chain hash values ​​include: Multiple fields are concatenated according to protocol rules, delimiters are added between fields, the separated fields are converted into a binary stream, the binary stream is padded according to the SM3 standard, SM3 hash operation is performed, and a fixed-length on-chain hash value is generated.

9. The RFID-based automatic drug traceability method for medicine vending machines as described in claim 1, characterized in that, The comparison results include whether there is a traceability information index code corresponding to the dynamic time-limited code, and whether the actual hash value is consistent with the on-chain hash value; The status of a drug is either 0 or 1. If the drug has been sold, the status is 1; if the drug has not been sold, the status is 0. Step S2 includes the following sub-steps: Step S21: Based on the RFID antenna, read the electronic data corresponding to the RFID electronic tag data and obtain the dynamic validity code corresponding to the electronic data; Step S22: Determine whether there is a traceability information index code corresponding to the dynamic timeliness code. If yes, proceed to step S23; otherwise, proceed to step S24. Step S23: Retrieve the on-chain hash value of the corresponding traceability information index code in the blockchain, concatenate the read RFID electronic tag data according to the same protocol rules and calculate the actual hash value, and compare the actual hash value with the on-chain hash value. If they match, the drug status is returned as 1, and the drug traceability information is returned. If there is a discrepancy, the drug status will be returned as 0; If the drug status returns as 1, the system will automatically obtain the traceability code from the regulatory platform and print a receipt based on the traceability code. When medicines installed in unmanned vending machines are sold, they automatically obtain a traceability code from the cloud platform and print a receipt for the medicine based on the traceability code. At the same time, the cloud platform marks the medicine as sold. Payment methods for unmanned medicine vending machines include medical insurance payment and third-party payment. Both medical insurance payment and third-party payment can automatically obtain the traceability code registered on the cloud platform to print a receipt for the medicine.

10. An RFID-based automatic drug traceability system for a medicine vending machine, the system being used to execute the RFID-based automatic drug traceability method for a medicine vending machine as described in claim 1, characterized in that, Includes a configuration module and a traceability module; The configuration module obtains the electronic data corresponding to the medicine based on the RFID antenna used to sense the RFID electronic tag at the shipping port; The RFID electronic tag integrates the drug's UID, production batch code, and manufacturer's digital signature, while the traceability code integrates a dynamic expiration code and an on-chain hash value. The dynamic validity code is generated based on the SM4 national cryptographic algorithm and updated according to a preset method; The traceability module compares the RFID electronic tag corresponding to the traceability code with the record on the chain to obtain the comparison result. Based on the comparison result, it returns the drug status and drug traceability information.