diff --git a/.claude/settings.local.json b/.claude/settings.local.json new file mode 100644 index 0000000..6fe2959 --- /dev/null +++ b/.claude/settings.local.json @@ -0,0 +1,9 @@ +{ + "permissions": { + "allow": [ + "Bash(source /opt/rk3506-toolchain/environment-setup)", + "Bash(java -jar fastddsgen.jar lib/System.idl -d lib/ -replace)", + "Bash(make)" + ] + } +} diff --git a/.qtcreator/CMakeLists.txt.user b/.qtcreator/CMakeLists.txt.user new file mode 100644 index 0000000..6abe076 --- /dev/null +++ b/.qtcreator/CMakeLists.txt.user @@ -0,0 +1,318 @@ + + + + + + EnvironmentId + {834c89b2-b6a0-49f4-8777-82ca3f17a41d} + + + ProjectExplorer.Project.ActiveTarget + 0 + + + ProjectExplorer.Project.EditorSettings + + true + true + true + + Cpp + + CppGlobal + + + + QmlJS + + QmlJSGlobal + + + 2 + UTF-8 + false + 4 + false + 0 + 80 + true + true + 1 + 0 + false + true + false + 2 + true + true + 0 + 8 + true + false + 1 + false + true + true + *.md, *.MD, Makefile + false + true + true + + + + ProjectExplorer.Project.PluginSettings + + + true + false + true + true + true + true + + false + + + 0 + true + + true + true + Builtin.DefaultTidyAndClazy + 10 + true + + + + true + + 0 + + + + ProjectExplorer.Project.Target.0 + + Desktop + true + Desktop Qt 6.11.1 MinGW 64-bit + Desktop Qt 6.11.1 MinGW 64-bit + qt.qt6.6111.win64_mingw_kit + 0 + 0 + 0 + + Release + 2 + false + + -DCMAKE_BUILD_TYPE:STRING=Release +-DCMAKE_COLOR_DIAGNOSTICS:BOOL=ON +-DCMAKE_CXX_COMPILER:FILEPATH=%{Compiler:Executable:Cxx} +-DCMAKE_C_COMPILER:FILEPATH=%{Compiler:Executable:C} +-DCMAKE_GENERATOR:STRING=MinGW Makefiles +-DCMAKE_PREFIX_PATH:PATH=%{Qt:QT_INSTALL_PREFIX} +-DCMAKE_PROJECT_INCLUDE_BEFORE:FILEPATH=%{BuildConfig:BuildDirectory:NativeFilePath}/.qtcreator/cmake-helper/qtcreator-project.cmake +-DQT_CREATOR_ENABLE_MAINTENANCE_TOOL_PROVIDER:BOOL=ON +-DQT_CREATOR_ENABLE_PACKAGE_MANAGER_SETUP:BOOL=ON +-DQT_ENABLE_QML_DEBUG:BOOL=%{Qt:QT_ENABLE_QML_DEBUG} +-DQT_QMAKE_EXECUTABLE:FILEPATH=%{Qt:qmakeExecutable} + .\build\%{Asciify:%{Kit:FileSystemName}-%{BuildConfig:Name}} + + + + + all + + false + + true + 构建 + CMakeProjectManager.MakeStep + + 1 + 构建 + 构建 + ProjectExplorer.BuildSteps.Build + + + + + + clean + + false + + true + 构建 + CMakeProjectManager.MakeStep + + 1 + 清除 + 清除 + ProjectExplorer.BuildSteps.Clean + + 2 + false + + false + + Release + CMakeProjectManager.CMakeBuildConfiguration + 0 + 0 + + + 0 + 部署 + 部署 + ProjectExplorer.BuildSteps.Deploy + + 1 + + false + ProjectExplorer.DefaultDeployConfiguration + + + + + + + + + false + + true + 构建 + ApplicationManagerPlugin.Deploy.CMakePackageStep + + + install-package --acknowledge + true + Install Application Manager package + ApplicationManagerPlugin.Deploy.InstallPackageStep + + + + + + + + 2 + 部署 + 部署 + ProjectExplorer.BuildSteps.Deploy + + 1 + + false + ApplicationManagerPlugin.Deploy.Configuration + + 2 + + false + + false + + + true + true + 0 + true + + + 2 + + false + -e cpu-cycles --call-graph "dwarf,4096" -F 250 + + ProjectExplorer.CustomExecutableRunConfiguration + + false + + true + true + %{RunConfig:Executable:Path} + + 1 + + 1 + + + 0 + 部署 + 部署 + ProjectExplorer.BuildSteps.Deploy + + 1 + + false + ProjectExplorer.DefaultDeployConfiguration + + + + + + + + + false + + true + 构建 + ApplicationManagerPlugin.Deploy.CMakePackageStep + + + install-package --acknowledge + true + Install Application Manager package + ApplicationManagerPlugin.Deploy.InstallPackageStep + + + + + + + + 2 + 部署 + 部署 + ProjectExplorer.BuildSteps.Deploy + + 1 + + false + ApplicationManagerPlugin.Deploy.Configuration + + 2 + + true + true + 0 + true + + + 2 + + false + -e cpu-cycles --call-graph "dwarf,4096" -F 250 + + ProjectExplorer.CustomExecutableRunConfiguration + + false + + true + true + %{RunConfig:Executable:Path} + + 1 + + + + ProjectExplorer.Project.TargetCount + 1 + + + Version + 22 + + diff --git a/CMakeLists.txt b/CMakeLists.txt index dd03ab7..72079be 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -30,7 +30,7 @@ include_directories(common) include_directories(lib) message(STATUS "Configuring System...") -add_library(System_lib lib/SystemTypeObjectSupport.cxx lib/SystemPubSubTypes.cxx) +add_library(System_lib lib/WeighingDDSTypeTypeObjectSupport.cxx lib/WeighingDDSTypePubSubTypes.cxx) target_link_libraries(System_lib fastcdr fastdds) # Demo Application. @@ -52,6 +52,8 @@ add_executable(Core core/main.cxx core/Publisher.cxx core/Subscriber.cxx + core/msg.hpp + lib/WeighingDDSType.hpp ) target_compile_definitions(Core PRIVATE PROGRAM_MODULE="${PROGRAM_MODULE}" PROGRAM_VERSION="${PROGRAM_VERSION}") target_include_directories(Core PRIVATE core) @@ -125,6 +127,7 @@ add_executable(Print print/MsgHandler.cxx common/SerialMsgHandler.cxx lib/strcode.cpp + print/MsgHandler.hpp ) target_compile_definitions(Print PRIVATE PROGRAM_MODULE="${PROGRAM_MODULE}" PROGRAM_VERSION="${PROGRAM_VERSION}") target_include_directories(Print PRIVATE print) @@ -132,6 +135,24 @@ target_link_libraries(Print fastcdr fastdds System_lib ) +# ReadCard Application. +set(PROGRAM_MODULE "ReadCard") +add_executable(ReadCard + readcard/main.cxx + readcard/Publisher.cxx + readcard/Subscriber.cxx + readcard/MsgHandler.cxx + readcard/Publisher.hpp + readcard/msg.hpp + common/SerialMsgHandler.cxx + readcard/MsgHandler.hpp + ) +target_compile_definitions(ReadCard PRIVATE PROGRAM_MODULE="${PROGRAM_MODULE}" PROGRAM_VERSION="${PROGRAM_VERSION}") +target_include_directories(ReadCard PRIVATE readcard) +target_link_libraries(ReadCard fastcdr fastdds + System_lib + ) + # Weigh Application. set(PROGRAM_MODULE "Weigh") add_executable(Weigh @@ -141,6 +162,7 @@ add_executable(Weigh weigh/MsgHandler.cxx weigh/WeightStabilityDetector.cxx common/SerialMsgHandler.cxx + common/SerialMsgHandler.hpp ) target_compile_definitions(Weigh PRIVATE PROGRAM_MODULE="${PROGRAM_MODULE}" PROGRAM_VERSION="${PROGRAM_VERSION}") target_include_directories(Weigh PRIVATE weigh) diff --git a/RC522.c b/RC522.c new file mode 100644 index 0000000..912174b --- /dev/null +++ b/RC522.c @@ -0,0 +1,666 @@ +//#include "intrins.h" +#include "main.h" +#include "RC522.h" +#include "stdio.h" +//#include "tim.h" + +extern TIM_HandleTypeDef htim6; + +#define MAXRLEN 18 + + +///////////////////////////////////////////////////////////////////// +#define RC522_RST_HIGH HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_SET); //任意未接IO +#define RC522_RST_LOW HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_RESET); //任意未接IO + +#define RC522_ENABLE HAL_GPIO_WritePin(ADDR_ALE_GPIO_Port,ADDR_ALE_Pin,GPIO_PIN_RESET); +#define RC522_DISABLE HAL_GPIO_WritePin(ADDR_ALE_GPIO_Port,ADDR_ALE_Pin,GPIO_PIN_SET); + +extern SPI_HandleTypeDef hspi1; + +#define fac_us 25 //72 //时钟频率,单位MHZ + +/*微秒级延时函数*/ +//void delay_us(uint32_t nus) +//{ +// uint32_t ticks; +// uint32_t told,tnow,tcnt=0; +// uint32_t reload=SysTick->LOAD; //LOAD的值 +// ticks=nus*fac_us; //需要的节拍数 +//// delay_osschedlock(); //阻止os调度,防止打断us延时 +//// vTaskSuspendAll(); +// told=SysTick->VAL; //刚进入时的计数器值 +// while(1) +// { +// +// tnow=SysTick->VAL; +// if(tnow!=told) +// { +// if(tnow=ticks) //时间超过/等于要延迟的时间,则退出. +// { +// break; +// } +// } +// } +//// delay_osschedunlock(); //恢复os调度 +//// xTaskResumeAll(); //恢复OS调度 +//} + +void delay_us(uint16_t nus) +{ + __HAL_TIM_SetCounter(&htim6,0); + __HAL_TIM_ENABLE(&htim6); + while(__HAL_TIM_GetCounter(&htim6)SR&SPI_FLAG_TXE)==0)//等待发送区空 + { + retry++; + if(retry>20000)return -1; + } + SPIx->DR=*p_TxData++;//发送一个byte + retry=0; + while((SPIx->SR&SPI_FLAG_RXNE)==0)//等待接收完一个byte + { + SPIx->SR = SPIx->SR; + retry++; + if(retry>20000)return -1; + } + SPIx->DR; + } + return 0; +} +//------------------------------------------------------------------------------------ +int32_t SPI_ReadNBytes(SPI_TypeDef* SPIx, uint8_t *p_RxData,uint32_t readDataNum) +{ + uint16_t retry=0; + while(readDataNum--) + { + SPIx->DR = 0xFF; + while(!(SPIx->SR&SPI_FLAG_TXE)) + { + retry++; + if(retry>20000)return -1; + } + retry = 0; + while(!(SPIx->SR&SPI_FLAG_RXNE)) + { + retry++; + if(retry>20000)return -1; + } + *p_RxData++ = SPIx->DR; + } + return 0; +} +//------------------------------------------------------------------------------------ +void RC522_Init(void) +{ + RC522_ENABLE; + HAL_SPI_Transmit(&hspi1, (uint8_t *)0xaa, sizeof((uint8_t *)0xaa), 0xFF);//启动传输 + RC522_DISABLE; + + HAL_Delay(50); + PcdReset();//复位RC522读卡器 + HAL_Delay(10); + PcdReset();//复位RC522读卡器 + HAL_Delay(10); + + PcdAntennaOff();//关闭天线发射 + HAL_Delay(10); + PcdAntennaOn();//开启天线发射 + + printf("RFID-MFRC522 初始化完成\r\n"); //测试引脚初始化完成 +// printf("RFID-MFRC522 Initialization Finished!\r\n"); //测试引脚初始化完成 + printf("FindCard Starting ...\r\n"); //测试引脚初始化完成 +} +//------------------------------------------------------------------------------- +//功 能:寻卡 +//参数说明: req_code[IN]:寻卡方式 +// 0x52 = 寻感应区内所有符合14443A标准的卡 +// 0x26 = 寻未进入休眠状态的卡 +// pTagType[OUT]:卡片类型代码 +// 0x4400 = Mifare_UltraLight +// 0x0400 = Mifare_One(S50) +// 0x0200 = Mifare_One(S70) +// 0x0800 = Mifare_Pro(X) +// 0x4403 = Mifare_DESFire +//返 回: 成功返回MI_OK +char PcdRequest(unsigned char req_code, unsigned char *pTagType) +{ + char status; + unsigned int unLen; + unsigned char ucComMF522Buf[MAXRLEN]; + + ClearBitMask(Status2Reg, 0x08); //清RC522寄存位 + WriteRawRC(BitFramingReg, 0x07); //写RC623寄存器 + SetBitMask(TxControlReg, 0x03); //置RC522寄存位 + + ucComMF522Buf[0] = req_code; + + status = PcdComMF522(PCD_TRANSCEIVE, ucComMF522Buf, 1, ucComMF522Buf, &unLen); + if ((status == MI_OK) && (unLen == 0x10)) + { + *pTagType = ucComMF522Buf[0]; + *(pTagType + 1) = ucComMF522Buf[1]; + } + else + { + status = MI_ERR; + } + return status; +} +//------------------------------------------------------------------------------- +//功 能:防冲撞 +//参数说明: pSnr[OUT]:卡片序列号,4字节 +//返 回: 成功返回MI_OK +char PcdAnticoll(unsigned char *pSnr) +{ + char status; + unsigned char i, snr_check = 0; + unsigned int unLen; + unsigned char ucComMF522Buf[MAXRLEN]; + ClearBitMask(Status2Reg, 0x08); + WriteRawRC(BitFramingReg, 0x00); + ClearBitMask(CollReg, 0x80); + ucComMF522Buf[0] = PICC_ANTICOLL1; + ucComMF522Buf[1] = 0x20; + + status = PcdComMF522(PCD_TRANSCEIVE, ucComMF522Buf, 2, ucComMF522Buf, &unLen); + if (status == MI_OK) + { + for (i = 0; i < 4; i++) + { + *(pSnr + i) = ucComMF522Buf[i]; + snr_check ^= ucComMF522Buf[i]; + } + if (snr_check != ucComMF522Buf[i]) + { + status = MI_ERR; + } + } + SetBitMask(CollReg, 0x80); + return status; +} +//--------------------------------------------------------------------------- +//功 能:选定卡片 +//参数说明: pSnr[IN]:卡片序列号,4字节 +//返 回: 成功返回MI_OK +char PcdSelect(unsigned char *pSnr) +{ + char status; + unsigned char i; + unsigned int unLen; + unsigned char ucComMF522Buf[MAXRLEN]; + ucComMF522Buf[0] = PICC_ANTICOLL1; + ucComMF522Buf[1] = 0x70; + ucComMF522Buf[6] = 0; + for (i = 0; i < 4; i++) + { + ucComMF522Buf[i + 2] = *(pSnr + i); + ucComMF522Buf[6] ^= *(pSnr + i); + } + CalulateCRC(ucComMF522Buf, 7, &ucComMF522Buf[7]); + ClearBitMask(Status2Reg, 0x08); + status = PcdComMF522(PCD_TRANSCEIVE, ucComMF522Buf, 9, ucComMF522Buf, &unLen); + if ((status == MI_OK) && (unLen == 0x18)) + { + status = MI_OK; + } + else + { + status = MI_ERR; + } + return status; +} +//---------------------------------------------------------------------------------- +//功 能:验证卡片密码 +//参数说明: auth_mode[IN]: 密码验证模式 +// 0x60 = 验证A密钥 +// 0x61 = 验证B密钥 +// addr[IN]:块地址 +// pKey[IN]:密码 +// pSnr[IN]:卡片序列号,4字节 +//返 回: 成功返回MI_OK +char PcdAuthState(unsigned char auth_mode, unsigned char addr, unsigned char *pKey, unsigned char *pSnr) +{ + char status; + unsigned int unLen; + unsigned char i, ucComMF522Buf[MAXRLEN]; + ucComMF522Buf[0] = auth_mode; + ucComMF522Buf[1] = addr; + for (i = 0; i < 6; i++) + { + ucComMF522Buf[i + 2] = *(pKey + i); + } + for (i = 0; i < 6; i++) + { + ucComMF522Buf[i + 8] = *(pSnr + i); + } + status = PcdComMF522(PCD_AUTHENT, ucComMF522Buf, 12, ucComMF522Buf, &unLen); + if ((status != MI_OK) || (!(ReadRawRC(Status2Reg) & 0x08))) + { + status = MI_ERR; + } + return status; +} +//-------------------------------------------------------------------------------------- +//功 能:读取M1卡一块数据 +//参数说明: addr[IN]:块地址 +// p [OUT]:读出的数据,16字节 +//返 回: 成功返回MI_OK +char PcdRead(unsigned char addr, unsigned char *pData) +{ + char status; + unsigned int unLen; + unsigned char i, ucComMF522Buf[MAXRLEN]; + ucComMF522Buf[0] = PICC_READ; + ucComMF522Buf[1] = addr; + CalulateCRC(ucComMF522Buf, 2, &ucComMF522Buf[2]); + + status = PcdComMF522(PCD_TRANSCEIVE, ucComMF522Buf, 4, ucComMF522Buf, &unLen); + if ((status == MI_OK) && (unLen == 0x90)) + { + for (i = 0; i < 16; i++) + { + *(pData + i) = ucComMF522Buf[i]; + } + } + else + { + status = MI_ERR; + } + return status; +} +//----------------------------------------------------------------------------------- +//功 能:写数据到M1卡一块 +//参数说明: addr[IN]:块地址 +// p [IN]:写入的数据,16字节 +//返 回: 成功返回MI_OK +char PcdWrite(unsigned char addr, unsigned char *pData) +{ + char status; + unsigned int unLen; + unsigned char i, ucComMF522Buf[MAXRLEN]; + ucComMF522Buf[0] = PICC_WRITE; + ucComMF522Buf[1] = addr; + CalulateCRC(ucComMF522Buf, 2, &ucComMF522Buf[2]); + status = PcdComMF522(PCD_TRANSCEIVE, ucComMF522Buf, 4, ucComMF522Buf, &unLen); + if ((status != MI_OK) || (unLen != 4) || ((ucComMF522Buf[0] & 0x0F) != 0x0A)) + { + status = MI_ERR; + } + if (status == MI_OK) + { + for (i = 0; i < 16; i++) + { + ucComMF522Buf[i] = *(pData + i); + } + CalulateCRC(ucComMF522Buf, 16, &ucComMF522Buf[16]); + + status = PcdComMF522(PCD_TRANSCEIVE, ucComMF522Buf, 18, ucComMF522Buf, &unLen); + if ((status != MI_OK) || (unLen != 4) || ((ucComMF522Buf[0] & 0x0F) != 0x0A)) + { + status = MI_ERR; + } + } + return status; +} +//---------------------------------------------------------------------------------- +//功 能:扣款和充值 +//参数说明: dd_mode[IN]:命令字 +// 0xC0 = 扣款 +// 0xC1 = 充值 +// addr[IN]:钱包地址 +// pValue[IN]:4字节增(减)值,低位在前 +//返 回: 成功返回MI_OK +char PcdValue(unsigned char dd_mode, unsigned char addr, unsigned char *pValue) +{ + char status; + unsigned int unLen; + unsigned char i, ucComMF522Buf[MAXRLEN]; + ucComMF522Buf[0] = dd_mode; + ucComMF522Buf[1] = addr; + CalulateCRC(ucComMF522Buf, 2, &ucComMF522Buf[2]); + status = PcdComMF522(PCD_TRANSCEIVE, ucComMF522Buf, 4, ucComMF522Buf, &unLen); + + if ((status != MI_OK) || (unLen != 4) || ((ucComMF522Buf[0] & 0x0F) != 0x0A)) + { + status = MI_ERR; + } + if (status == MI_OK) + { + for (i = 0; i < 16; i++) + { + ucComMF522Buf[i] = *(pValue + i); + } + CalulateCRC(ucComMF522Buf, 4, &ucComMF522Buf[4]); + unLen = 0; + status = PcdComMF522(PCD_TRANSCEIVE, ucComMF522Buf, 6, ucComMF522Buf, &unLen); + if (status != MI_ERR) + { + status = MI_OK; + } + } + if (status == MI_OK) + { + ucComMF522Buf[0] = PICC_TRANSFER; + ucComMF522Buf[1] = addr; + CalulateCRC(ucComMF522Buf, 2, &ucComMF522Buf[2]); + + status = PcdComMF522(PCD_TRANSCEIVE, ucComMF522Buf, 4, ucComMF522Buf, &unLen); + + if ((status != MI_OK) || (unLen != 4) || ((ucComMF522Buf[0] & 0x0F) != 0x0A)) + { + status = MI_ERR; + } + } + return status; +} +//------------------------------------------------------------------------------------ +//功 能:备份钱包 +//参数说明: sourceaddr[IN]:源地址 +// goaladdr[IN]:目标地址 +//返 回: 成功返回MI_OK +char PcdBakValue(unsigned char sourceaddr, unsigned char goaladdr) +{ + char status; + unsigned int unLen; + unsigned char ucComMF522Buf[MAXRLEN]; + ucComMF522Buf[0] = PICC_RESTORE; + ucComMF522Buf[1] = sourceaddr; + CalulateCRC(ucComMF522Buf, 2, &ucComMF522Buf[2]); + status = PcdComMF522(PCD_TRANSCEIVE, ucComMF522Buf, 4, ucComMF522Buf, &unLen); + if ((status != MI_OK) || (unLen != 4) || ((ucComMF522Buf[0] & 0x0F) != 0x0A)) + { + status = MI_ERR; + } + if (status == MI_OK) + { + ucComMF522Buf[0] = 0; + ucComMF522Buf[1] = 0; + ucComMF522Buf[2] = 0; + ucComMF522Buf[3] = 0; + CalulateCRC(ucComMF522Buf, 4, &ucComMF522Buf[4]); + status = PcdComMF522(PCD_TRANSCEIVE, ucComMF522Buf, 6, ucComMF522Buf, &unLen); + if (status != MI_ERR) + { + status = MI_OK; + } + } + if (status != MI_OK) + { + return MI_ERR; + } + ucComMF522Buf[0] = PICC_TRANSFER; + ucComMF522Buf[1] = goaladdr; + CalulateCRC(ucComMF522Buf, 2, &ucComMF522Buf[2]); + status = PcdComMF522(PCD_TRANSCEIVE, ucComMF522Buf, 4, ucComMF522Buf, &unLen); + if ((status != MI_OK) || (unLen != 4) || ((ucComMF522Buf[0] & 0x0F) != 0x0A)) + { + status = MI_ERR; + } + return status; +} +//------------------------------------------------------------------------------------ +//功 能:命令卡片进入休眠状态 +//返 回: 成功返回MI_OK +char PcdHalt(void) +{ + // char status; + unsigned int unLen; + unsigned char ucComMF522Buf[MAXRLEN]; + + ucComMF522Buf[0] = PICC_HALT; + ucComMF522Buf[1] = 0; + CalulateCRC(ucComMF522Buf, 2, &ucComMF522Buf[2]); + + PcdComMF522(PCD_TRANSCEIVE, ucComMF522Buf, 4, ucComMF522Buf, &unLen); + + return MI_OK; +} +//-------------------------------------------------------------------------------------- +//用MF522计算CRC16函数 +void CalulateCRC(unsigned char *pIndata, unsigned char len, unsigned char *pOutData) +{ + unsigned char i, n; + ClearBitMask(DivIrqReg, 0x04); + WriteRawRC(CommandReg, PCD_IDLE); + SetBitMask(FIFOLevelReg, 0x80); + for (i = 0; i < len; i++) + { + WriteRawRC(FIFODataReg, *(pIndata + i)); + } + WriteRawRC(CommandReg, PCD_CALCCRC); + i = 0xFF; + do + { + n = ReadRawRC(DivIrqReg); + i--; + } while ((i != 0) && !(n & 0x04)); + pOutData[0] = ReadRawRC(CRCResultRegL); + pOutData[1] = ReadRawRC(CRCResultRegM); +} +//----------------------------------------------------------------------------------------- +//功 能:复位RC522 +//返 回: 成功返回MI_OK +char PcdReset(void) +{ +// RC522_RST_HIGH; +// delay_us(10); +// RC522_RST_LOW; +// HAL_Delay(60); +// RC522_RST_HIGH; +// HAL_GPIO_WritePin(LED_RUN_GPIO_Port,LED_RUN_Pin,GPIO_PIN_RESET); + delay_us(4000); + + + WriteRawRC(CommandReg, PCD_RESETPHASE); + HAL_Delay(20); + + WriteRawRC(ModeReg, 0x3D); + WriteRawRC(TReloadRegL, 30); + WriteRawRC(TReloadRegH, 0); + WriteRawRC(TModeReg, 0x8D); + WriteRawRC(TPrescalerReg, 0x3E); + WriteRawRC(TxAutoReg, 0x40); + + ClearBitMask(TestPinEnReg, 0x80); + WriteRawRC(TxAutoReg, 0x40); + + return MI_OK; +} +//------------------------------------------------------------------------------------- +//功 能:读RC632寄存器 +//参数说明:Address[IN]:寄存器地址 +//返 回:读出的值 +unsigned char ReadRawRC(unsigned char Address) +{ + unsigned char ucAddr; + unsigned char ucResult = 0; + ucAddr = ((Address << 1) & 0x7E) | 0x80; + HAL_Delay(10); + RC522_ENABLE; + SPI_WriteNBytes(SPI1, &ucAddr, 1); //向总线写多个数据 + SPI_ReadNBytes(SPI1, &ucResult, 1); //向总线读多个数据 +// HAL_SPI_Transmit(&hspi1,&ucAddr,1,0xff); +// HAL_SPI_Receive(&hspi1,&ucResult,1,0xff); +// while(HAL_SPI_Transmit(&hspi1,&ucAddr,1,0xff) == HAL_OK); +// while(HAL_SPI_Receive(&hspi1,&ucResult,1,0xff) == HAL_OK); + RC522_DISABLE; + return ucResult; +} +//--------------------------------------------------------------------------------------------- +//功 能:写RC632寄存器 +//参数说明:Address[IN]:寄存器地址 +// value[IN]:写入的值 +void WriteRawRC(unsigned char Address, unsigned char value) +{ + unsigned char ucAddr; + uint8_t write_buffer[2] = {0}; + ucAddr = ((Address << 1) & 0x7E); + write_buffer[0] = ucAddr; + write_buffer[1] = value; + HAL_Delay(10); + RC522_ENABLE; + SPI_WriteNBytes(SPI1, write_buffer, 2); +// HAL_SPI_Transmit(&hspi1,write_buffer,2,0xff); +// while(HAL_SPI_Transmit(&hspi1,write_buffer,2,0xff) == HAL_OK); + RC522_DISABLE; +} +//--------------------------------------------------------------------------------------------- +//功 能:置RC522寄存器位 +//参数说明:reg[IN]:寄存器地址 +// mask[IN]:置位值 +void SetBitMask(unsigned char reg, unsigned char mask) +{ + char tmp = 0x0; + tmp = ReadRawRC(reg); //读RC632寄存器 + WriteRawRC(reg, tmp | mask); // set bit mask +} +//----------------------------------------------------------------------------------------------- +//功 能:清RC522寄存器位 +//参数说明:reg[IN]:寄存器地址 +// mask[IN]:清位值 +void ClearBitMask(unsigned char reg, unsigned char mask) +{ + char tmp = 0x0; + tmp = ReadRawRC(reg); + WriteRawRC(reg, tmp & ~mask); // clear bit mask +} +//------------------------------------------------------------------------------------------ +//功 能:通过RC522和ISO14443卡通讯 +//参数说明:Command[IN]:RC522命令字 +// pIn [IN]:通过RC522发送到卡片的数据 +// InLenByte[IN]:发送数据的字节长度 +// pOut [OUT]:接收到的卡片返回数据 +// *pOutLenBit[OUT]:返回数据的位长度 +char PcdComMF522(unsigned char Command, + unsigned char *pInData, + unsigned char InLenByte, + unsigned char *pOutData, + unsigned int *pOutLenBit) +{ + char status = MI_ERR; + unsigned char irqEn = 0x00; + unsigned char waitFor = 0x00; + unsigned char lastBits; + unsigned char n; + unsigned int i; + switch (Command) + { + case PCD_AUTHENT: + irqEn = 0x12; + waitFor = 0x10; + break; + case PCD_TRANSCEIVE: + irqEn = 0x77; + waitFor = 0x30; + break; + default: + break; + } + WriteRawRC(ComIEnReg, irqEn | 0x80); + ClearBitMask(ComIrqReg, 0x80); + WriteRawRC(CommandReg, PCD_IDLE); + SetBitMask(FIFOLevelReg, 0x80); + for (i = 0; i < InLenByte; i++) + { + WriteRawRC(FIFODataReg, pInData[i]); + } + WriteRawRC(CommandReg, Command); + if (Command == PCD_TRANSCEIVE) + { + SetBitMask(BitFramingReg, 0x80); + } + i = 800; //根据时钟频率调整,操作M1卡最大等待时间25ms + do + { + n = ReadRawRC(ComIrqReg); + i--; + } while ((i != 0) && !(n & 0x01) && !(n & waitFor)); + ClearBitMask(BitFramingReg, 0x80); + if (i != 0) + { + if (!(ReadRawRC(ErrorReg) & 0x1B)) + { + status = MI_OK; + if (n & irqEn & 0x01) + { + status = MI_NOTAGERR; + } + if (Command == PCD_TRANSCEIVE) + { + n = ReadRawRC(FIFOLevelReg); + lastBits = ReadRawRC(ControlReg) & 0x07; + if (lastBits) + { + *pOutLenBit = (n - 1) * 8 + lastBits; + } + else + { + *pOutLenBit = n * 8; + } + if (n == 0) + { + n = 1; + } + if (n > MAXRLEN) + { + n = MAXRLEN; + } + for (i = 0; i < n; i++) + { + pOutData[i] = ReadRawRC(FIFODataReg); + } + } + } + else + { + status = MI_ERR; + } + } + SetBitMask(ControlReg, 0x80); // stop timer now + WriteRawRC(CommandReg, PCD_IDLE); + return status; +} +//-------------------------------------------------------------------------------------- +//开启天线 +//每次启动或关闭天险发射之间应至少有1ms的间隔 +void PcdAntennaOn(void) +{ + unsigned char i; + i = ReadRawRC(TxControlReg); + if (!(i & 0x03)) + { + SetBitMask(TxControlReg, 0x03); + } +} +//---------------------------------------------------------------------------------------- +//关闭天线 +void PcdAntennaOff(void) +{ + ClearBitMask(TxControlReg, 0x03); +} +//------------------------------------------------ +void RC522_Config(unsigned char Card_Type) +{ + ClearBitMask(Status2Reg, 0x08); + WriteRawRC(ModeReg, 0x3D); + WriteRawRC(RxSelReg, 0x86); + WriteRawRC(RFCfgReg, 0x7F); + WriteRawRC(TReloadRegL, 30); + WriteRawRC(TReloadRegH, 0); + WriteRawRC(TModeReg, 0x8D); + WriteRawRC(TPrescalerReg, 0x3E); + HAL_Delay(5); + PcdAntennaOn(); +} diff --git a/RFID_S50.c b/RFID_S50.c new file mode 100644 index 0000000..988f5da --- /dev/null +++ b/RFID_S50.c @@ -0,0 +1,532 @@ +/******************************************************************************* + * ļ User\src\RFID_S50.c + * ־ + * ̼汾 V3.5.0 + * 汾 V1.0 + * ޸ 2016218 + * Ȩ а޹˾ + ****************************************************************************** + * ã + * DZ + * + * + * + * + * + ******************************************************************************/ +#ifdef RFIDS50_DEV + +#include "stm32f10x.h" +#include "RFID_S50.h" +#include +#include +#include "FiveSuart.h" +#include "CANManager.h" + + +#define RFID_S50_CMD_Parameter 20 //0x14 ڲ +#define RFID_S50_CMD_Control 21 //0x15 豸 򿪻ر +#define RFID_S50_CMD_Beep 22 //0x16 +#define RFID_S50_CMD_Password 23 //0x17 +#define RFID_S50_CMD_FindCard 24 //0x18 ԶѰ +#define RFID_S50_CMD_ReadCard 25 //0x19 +#define RFID_S50_CMD_WriteCard 26 //0x1A д +#define RFID_S50_CMD_Stop 27 //0x1B ֹ +#define RFID_S50_CMD_Reset 29 //0x1D λ + +RFID_S50_Parameter RFID_S50_Para; + +//֤д modified by Hy 2019-10-20 +uint8_t RFID_S50_CheckedData[16]={0}; + +//֤д modified by Hy 2019-10-20 +uint8_t RFID_S50_CheckedBlockID=0; + +//Ƿдɹ modified by Hy 2019-10-20 +bool isWrite=false; + +// modified by Hy 2019-10-20 +void ReadCard(uint8_t blockID) +{ + uint16_t crcResult=0; + uint8_t crcL=0; + uint8_t crcH=0; + uint8_t m_buf[6]={0}; + + m_buf[0] = 0x05; // + m_buf[1] = 0x01; //ַ + m_buf[2] = 0x04; // + m_buf[3] = blockID; // + crcResult = CRC16(m_buf, 4); + crcL = (uint8_t)(crcResult & 0xFF); + crcH = (uint8_t)(crcResult >> 8); + m_buf[4] = crcH; + m_buf[5] = crcL; + Usart_SendData(RFID_S50_Para.CommPara.USARTID,m_buf,6); +} + +/******************************************************************************* +* Function Name : RFID_S50_OnCommand +* Description : +* Input : data +* Output : None +* Return : None +* Attention : +*******************************************************************************/ +void RFID_S50_OnCommand(uint8_t * pData ,uint16_t m_len ) +{ + //յȫ + if (pData[1] == 1) + { + //ַ1 + uint16_t crcResult = 0; //У + uint8_t crcL = 0; //Уλ + uint8_t crcH = 0; //Уλ + crcResult = CRC16(pData,m_len - 2); + crcL = (uint8_t)(crcResult & 0xFF); + crcH = (uint8_t)(crcResult >> 8); + + //if ((crcL == pData[m_len - 1]) || (crcH == pData[m_len])) + if ((crcH == pData[m_len - 2]) && (crcL == pData[m_len-1])) + { + + //ͨУ + uint8_t m_Command = pData[2]; // + if (pData[3]==0) + { + // + CanTxMsg TxMsg; + TxMsg.RTR = CAN_RTR_DATA; // Ϊ֡ + TxMsg.IDE = CAN_ID_EXT; // ʹչ֡ + switch (m_Command) + { + case 1: // + { + uint32_t m_id=GetCANID(DeviceID,RFID_S50_CMD_Beep,0x01); + //سɹϢ + CAN_SendResult(m_id,0x00); + } + break; + case 2: //Ѱ + { + TxMsg.ExtId=GetCANID(DeviceID,RFID_S50_CMD_FindCard,0x01); + TxMsg.DLC=5; + TxMsg.Data[0]=0x00; + TxMsg.Data[1]=pData[4]; + TxMsg.Data[2]=pData[5]; + TxMsg.Data[3]=pData[6]; + TxMsg.Data[4]=pData[7]; + CAN_SendData(&TxMsg); + } + break; + case 3: // + { + uint32_t m_id=GetCANID(DeviceID,RFID_S50_CMD_Password,0x01); + //سɹϢ + CAN_SendResult(m_id,0x00); + } + break; + case 4: //ݿ鷵 + { + int flag = 0; + int i = 0; + //֤ modified by Hy 2019-10-20 + if(isWrite) + { + isWrite=false; + if(RFID_S50_CheckedBlockID==pData[4]) + { + for (i = 0; i < 16; i++) + { + if (RFID_S50_CheckedData[i] != pData[i+5]) + { + flag = 1; + break; + } + } + if (flag == 1) + { + uint32_t m_id=GetCANID(DeviceID,RFID_S50_CMD_WriteCard,0x01); + //ʧϢ + CAN_SendResult(m_id,0x01); + } + else + { + uint32_t m_id=GetCANID(DeviceID,RFID_S50_CMD_WriteCard,0x01); + //سɹϢ + CAN_SendResult(m_id,0x00); + } + } + } + else + { + //ȷ1ֽڵĿź16ֽ + TxMsg.ExtId=GetCANID(DeviceID,RFID_S50_CMD_ReadCard,0x01); + TxMsg.DLC=2; + TxMsg.Data[0]=0x00; + TxMsg.Data[1]=pData[4]; + CAN_SendData(&TxMsg); + + TxMsg.ExtId=GetCANID(DeviceID,RFID_S50_CMD_ReadCard,0x02); + TxMsg.DLC=8; + TxMsg.Data[0]=pData[5]; + TxMsg.Data[1]=pData[6]; + TxMsg.Data[2]=pData[7]; + TxMsg.Data[3]=pData[8]; + TxMsg.Data[4]=pData[9]; + TxMsg.Data[5]=pData[10]; + TxMsg.Data[6]=pData[11]; + TxMsg.Data[7]=pData[12]; + CAN_SendData(&TxMsg); + + TxMsg.ExtId=GetCANID(DeviceID,RFID_S50_CMD_ReadCard,0x03); + TxMsg.DLC=8; + TxMsg.Data[0]=pData[13]; + TxMsg.Data[1]=pData[14]; + TxMsg.Data[2]=pData[15]; + TxMsg.Data[3]=pData[16]; + TxMsg.Data[4]=pData[17]; + TxMsg.Data[5]=pData[18]; + TxMsg.Data[6]=pData[19]; + TxMsg.Data[7]=pData[20]; + CAN_SendData(&TxMsg); + } + } + + break; + case 5: //д + { + //дɹ modified by Hy 2019-10-20 + isWrite=true; + ReadCard(RFID_S50_CheckedBlockID); + } + break; + + case 8: //ֹIC + { + uint32_t m_id=GetCANID(DeviceID,RFID_S50_CMD_Stop,0x01); + //سɹϢ + CAN_SendResult(m_id,0x00); + } + break; + } + } + else + { + //ʧ + CanTxMsg TxMsg; + TxMsg.RTR = CAN_RTR_DATA; // Ϊ֡ + TxMsg.IDE = CAN_ID_EXT; // ʹչ֡ + switch (m_Command) + { + case 4: //ݿ鷵 + { + //ȡCANID + TxMsg.ExtId=GetCANID(DeviceID,RFID_S50_CMD_ReadCard,0x01); + TxMsg.DLC=3; + TxMsg.Data[0]=0x01; + TxMsg.Data[1]=pData[3]; + TxMsg.Data[2]=pData[4]; + CAN_SendData(&TxMsg); + } + + } + + } + }//У + } + else + { + //ַ׼ȷ践 + RFID_S50_Reset(); + } + +} + +//յ +void RFID_S50_OnData(uint8_t * m_buf,int m_len) +{ + int m_idx=0; + uint8_t temp; + for (m_idx=0;m_idxCommandID) + { + case RFID_S50_CMD_Parameter: //0x14 ôڲ + { + RFID_S50_Reset(); + RFID_S50_Para.Times=1; //óʱʱ + RFID_S50_Para.CommPara.USARTID =RxMsg->Value[0]; //ں + RFID_S50_Para.CommPara.BaudRate =RxMsg->Value[1]; // + RFID_S50_Para.CommPara.WordLength =RxMsg->Value[2]; //λ + RFID_S50_Para.CommPara.StopBits =RxMsg->Value[3]; //ֹͣλ + RFID_S50_Para.CommPara.Parity =RxMsg->Value[4]; //Уλ + RFID_S50_Para.Type =RxMsg->Value[5]; // + iTemp=GetCANID(DeviceID,0x14,0x01); + CAN_SendResult(iTemp,00); + bResult=true; + } + break; + + case RFID_S50_CMD_Control: //0x15 豸 + { + if (RxMsg->Value[0]==1) + { + //豸 + //1򿪴 + //2ǰ豸պҽӵ + uint32_t tmp_BaudRate=GetBaudRate(RFID_S50_Para.CommPara.BaudRate); + uint16_t tmp_Parity =GetParity(RFID_S50_Para.CommPara.Parity); + + Usart_Open(RFID_S50_Para.CommPara.USARTID,tmp_BaudRate,RFID_S50_Para.CommPara.WordLength,RFID_S50_Para.CommPara.StopBits,tmp_Parity); + SetDeviceOnData(RFID_S50_Para.CommPara.USARTID,RFID_S50_OnData); + SetDeviceProcess(RFID_S50_Para.CommPara.USARTID,RFID_S50_Process); + + //TIM2_Configuration(Weight_Times*2000); //ʱ2 + + //TIM_Cmd(TIM2, ENABLE); //򿪳ʱʱ + + iTemp=GetCANID(DeviceID,RFID_S50_CMD_Control,0x01); + CAN_SendResult(iTemp,00); + + + RFID_S50_Para.Open=true; + + } + else if (RxMsg->Value[0]==0) + { + //ر豸 + } + bResult=true; + } + break; + + case RFID_S50_CMD_Beep: // + { + uint16_t crcResult=0; + uint8_t crcL=0; + uint8_t crcH=0; + uint8_t m_buf[6]={0}; + + if (!RFID_S50_Para.Open) + return false; + + + m_buf[0] = 0x05; // + m_buf[1] = 0x01; //ַ + m_buf[2] = 0x01; // + m_buf[3] = 0x0F; //ʱ + crcResult = CRC16(m_buf, 4); + crcL = (uint8_t)(crcResult & 0xFF); + crcH = (uint8_t)(crcResult >> 8); + m_buf[4] = crcH; //0xBC + m_buf[5] = crcL; //0x10 + Usart_SendData(RFID_S50_Para.CommPara.USARTID,m_buf,6); + bResult=true; + } + break; + + case RFID_S50_CMD_Password : // 22 0x16 + { + uint16_t crcResult=0; + uint8_t crcL=0; + uint8_t crcH=0; + uint8_t m_buf[13]={0}; + m_buf[0] = 0x0C; // + m_buf[1] = 0x01; //ַ + m_buf[2] = 0x03; // + memcpy(m_buf+3,RxMsg->Value,8); //CAN8ֽ + + crcResult = CRC16(m_buf,11); + crcL = (uint8_t)(crcResult & 0xFF); + crcH = (uint8_t)(crcResult >> 8); + m_buf[11] = crcH; + m_buf[12] = crcL; + Usart_SendData(RFID_S50_Para.CommPara.USARTID,m_buf,13); + bResult=true; + } + break; + case RFID_S50_CMD_FindCard : // 23 ԶѰ 0x18 + { + uint16_t crcResult=0; + uint8_t crcL=0; + uint8_t crcH=0; + uint8_t m_buf[5]={0}; + + if (!RFID_S50_Para.Open) + return false; + + m_buf[0] = 0x04; // + m_buf[1] = 0x01; //ַ + m_buf[2] = 0x02; // Ѱ + crcResult = CRC16(m_buf, 3); + + crcL = (uint8_t)(crcResult & 0xFF); + crcH = (uint8_t)(crcResult >> 8); + m_buf[3] = crcH; + m_buf[4] = crcL; + Usart_SendData(RFID_S50_Para.CommPara.USARTID,m_buf,5); + bResult=true; + } + break; + case RFID_S50_CMD_ReadCard : // 24 0x19 + { + uint16_t crcResult=0; + uint8_t crcL=0; + uint8_t crcH=0; + uint8_t m_buf[6]={0}; + + if (!RFID_S50_Para.Open) + return false; + + m_buf[0] = 0x05; // + m_buf[1] = 0x01; //ַ + m_buf[2] = 0x04; // + m_buf[3] = RxMsg->Value[0]; // + crcResult = CRC16(m_buf, 4); + crcL = (uint8_t)(crcResult & 0xFF); + crcH = (uint8_t)(crcResult >> 8); + m_buf[4] = crcH; + m_buf[5] = crcL; + Usart_SendData(RFID_S50_Para.CommPara.USARTID,m_buf,6); + bResult=true; + } + break; + case RFID_S50_CMD_WriteCard : // 25 д 0x19 + { + if (RxMsg->BlockID==1) + { + //һ + RFID_S50_ProcessData[0]=RxMsg->Value[0]; + RFID_S50_CheckedBlockID=RxMsg->Value[0]; + } + else if (RxMsg->BlockID==2) + { + //ڶ + memcpy(RFID_S50_ProcessData+1,RxMsg->Value,8); + + } + else if (RxMsg->BlockID==3) + { + // + uint16_t crcResult=0; + uint8_t crcL=0; + uint8_t crcH=0; + uint8_t m_buf[22]={0}; + + if (!RFID_S50_Para.Open) + return false; + + memcpy(RFID_S50_ProcessData+9,RxMsg->Value,8); + + m_buf[0] = 0x15; // + m_buf[1] = 0x01; //ַ + m_buf[2] = 0x05; // + + memcpy(m_buf+3,RFID_S50_ProcessData,17); //CAN17ֽ + crcResult = CRC16(m_buf,20); + crcL = (uint8_t)(crcResult & 0xFF); + crcH = (uint8_t)(crcResult >> 8); + m_buf[20] = crcH; + m_buf[21] = crcL; + Usart_SendData(RFID_S50_Para.CommPara.USARTID,m_buf,22); + //дʱ modified by Hy 2019-10-20 + memcpy(RFID_S50_CheckedData,RFID_S50_ProcessData+1,16); + } + bResult=true; + } + break; + + case RFID_S50_CMD_Stop: //ֹ + { + uint16_t crcResult=0; + uint8_t crcL=0; + uint8_t crcH=0; + uint8_t m_buf[5]={0}; + + if (!RFID_S50_Para.Open) + return false; + + m_buf[0] = 0x04; // + m_buf[1] = 0x01; //ַ + m_buf[2] = 0x08; // + crcResult = CRC16(m_buf, 3); + + crcL = (uint8_t)(crcResult & 0xFF); + crcH = (uint8_t)(crcResult >> 8); + m_buf[3] = crcH; + m_buf[4] = crcL; + Usart_SendData(RFID_S50_Para.CommPara.USARTID,m_buf,5); + bResult=true; + } + break; + case RFID_S50_CMD_Reset: + { + uint32_t m_id=GetCANID(DeviceID,RFID_S50_CMD_Reset,0x01); + //سɹϢ + CAN_SendResult(m_id,0x00); + RFID_S50_Reset(); + bResult=true; + } + break; + } + return bResult; +} + +// void TIM3_IRQHandler(void) +// { +// if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET) +// { +// TIM_ClearITPendingBit(TIM3, TIM_IT_Update ); + +// } +// } + +//λ +void RFID_S50_Reset() +{ + RFID_S50_Para.IndexFlag=0; +} + + +#endif + diff --git a/common/CanMsgHandler.cxx b/common/CanMsgHandler.cxx index 0b434b9..d995b6b 100644 --- a/common/CanMsgHandler.cxx +++ b/common/CanMsgHandler.cxx @@ -83,6 +83,8 @@ bool CanMsgHandler::OpenPort(const std::string& port, const std::string& baudrat // return false; // } + + return true; } diff --git a/common/SerialMsgHandler.cxx b/common/SerialMsgHandler.cxx index 0c698cd..1178584 100644 --- a/common/SerialMsgHandler.cxx +++ b/common/SerialMsgHandler.cxx @@ -23,6 +23,8 @@ bool SerialMsgHandler::OpenPort(const std::string &port, const std::string &baud ClosePort(); + + fd = open(tty.c_str(), O_RDWR | O_NOCTTY | O_NDELAY); if (fd == -1) { @@ -51,16 +53,31 @@ bool SerialMsgHandler::OpenPort(const std::string &port, const std::string &baud if (baudrate == "115200") { baund = B115200; + } else if (baudrate == "9600") { baund = B9600; + + } + else if (baudrate == "19200") + { + baund = B19200; + } + else if (baudrate == "57600") + { + baund = B57600; } else { baund = B9600; + } + // ========== 新增:保存波特率 ========== + baudrate_ = baund; + + return setPortAttributes(baund); } @@ -69,6 +86,10 @@ bool SerialMsgHandler::setPortAttributes(int baudrate) { struct termios options; + // ========== 新增:调试打印配置前的状态 ========== + std::cout << "[DEBUG] setPortAttributes: configuring port with baudrate=" << baudrate << std::endl; + + // 获取当前串口设置 if (tcgetattr(fd, &options) != 0) { @@ -116,3 +137,17 @@ bool SerialMsgHandler::setPortAttributes(int baudrate) return true; } + +// ========== 新增:刷新串口配置 ========== +bool SerialMsgHandler::refreshPort() +{ + if (fd == -1) { + std::cout << "[DEBUG] refreshPort: fd is -1, skip" << std::endl; + return false; + } + + // ========== 调试打印 ========== + std::cout << "[DEBUG] refreshPort: reconfiguring port, baudrate=" << baudrate_ << std::endl; + + return setPortAttributes(baudrate_); +} \ No newline at end of file diff --git a/common/SerialMsgHandler.hpp b/common/SerialMsgHandler.hpp index 9e485c4..8079f2a 100644 --- a/common/SerialMsgHandler.hpp +++ b/common/SerialMsgHandler.hpp @@ -3,6 +3,8 @@ #include #include +#include +#include #include "MsgHandler.hpp" @@ -19,6 +21,8 @@ public: bool setPortAttributes(int baudrate); private: + + speed_t baudrate_; // 新增:保存波特率(speed_t 类型) }; #endif // _SERIALMSGHANDLER_HPP_ diff --git a/config.json b/config.json new file mode 100644 index 0000000..b611464 --- /dev/null +++ b/config.json @@ -0,0 +1,100 @@ +{ + "dds": + { + "domain": 0 + }, + "mqtt": + { + "server_url": "mqtt://192.168.1.2:1883", + "client_id": "ddsmqtt_sub_pub_0", + "username": "admin", + "password": "admin", + "sub_topic": ["command"], + "sub_qos": [0], + "pub_topic": ["response"], + "pub_qos": [0] + }, + "httpserver": + { + "port": 8080 + }, + "ioctrl": + { + "bus": "can", + "port": "can0", + "baudrate": "500000", + "device": "5serial", + "device_id": 1, + "iomap": + { + "out": + { + "frontbarrup": [1, 1], + "frontbarrdown": [2, 1], + "backbarrup": [3, 1], + "backbarrdown": [4, 1], + "frontled": [5, 1], + "backled": [6, 1] + }, + "in": + { + "frontdetect": [5, 1], + "backdetect": [6, 1] + } + } + }, + "led": + { + "ip": "192.168.0.199", + "port": 80, + "path": "/home/bo/project/app/dds/led/build/" + }, + "print": + { + "bus": "serial", + "port": "ttyS2", + "baudrate": "9600", + "device": "NP80A" + }, + "readcard": + { + "bus": "serial", + "port": "ttyS1", + "baudrate": "9600", + "device": "RC522", + "password": + [ + { + "sector": 1, + "data": [1, 2, 3, 4, 5, 6] + }, + { + "sector": 2, + "data": [7, 8, 9, 10, 11, 12] + }, + { + "sector": 3, + "data": [13, 14, 15, 16, 17, 18] + }, + { + "sector": 4, + "data": [19, 20, 21, 22, 23, 24] + }, + { + "sector": 5, + "data": [25, 26, 27, 28, 29, 30] + }, + { + "sector": 10, + "data": [177, 10, 35, 209, 143, 32] + } + ] + }, + "weigh": + { + "bus": "serial", + "port": "ttyS5", + "baudrate": "9600", + "device": "Keli" + } +} \ No newline at end of file diff --git a/core/Publisher.cxx b/core/Publisher.cxx index 8254960..0686779 100644 --- a/core/Publisher.cxx +++ b/core/Publisher.cxx @@ -24,7 +24,10 @@ #include #include #include +#include +#include #include +#include // 新增:用于 std::fabs #include #include @@ -33,10 +36,30 @@ #include #include -#include "SystemPubSubTypes.hpp" +#include "WeighingDDSTypePubSubTypes.hpp" #include "msg.hpp" #include "DEBUG.hpp" + +// // 【新增】红外对射状态打印函数 +// #include +// void print_infrared_status() +// { +// while (!DdsMsgData::stop_flag_) +// { +// { +// std::lock_guard lock(DdsMsgData::infrared_mtx_); +// std::cout << "[红外对射状态] Front: " +// << DdsMsgData::latest_infrared_.FrontResistanceSignal() +// << " Back: " +// << DdsMsgData::latest_infrared_.BackResistanceSignal() +// << std::endl; +// } +// std::this_thread::sleep_for(std::chrono::seconds(2)); +// } +// } + + using namespace eprosima::fastdds::dds; PublisherApp::PublisherApp( @@ -55,7 +78,7 @@ PublisherApp::PublisherApp( , summary_type_(new WeighingSystem::SummaryUpdatePubSubType()) , print_topic_(nullptr) , print_writer_(nullptr) - , print_type_(new InternalSystem::PrintReqPubSubType()) + , print_type_(new WeighingSystem::PrintReqPubSubType()) , matched_(0) , samples_sent_(0) , stop_(false) @@ -319,7 +342,7 @@ bool PublisherApp::light_ctrl(const std::map& ctrl) bool PublisherApp::print_receipt(const std::map& msg) { - InternalSystem::PrintReq req; + WeighingSystem::PrintReq req; req.msg() = msg; @@ -336,22 +359,40 @@ bool PublisherApp::print_receipt(const std::map& msg) #define WEIGH_IDLE 0 #define WEIGH_LIC 1 #define WEIGH_STABLE1 2 -#define WEIGH_STABLE2 3 -#define WEIGH_SEND 4 -#define WEIGH_PRINT 5 -#define WEIGH_ERROR 6 -#define WEIGH_LEAVE 7 +//#define WEIGH_STABLE2 3 +//#define WEIGH_SEND 4 +//#define WEIGH_PRINT 5 +//#define WEIGH_ERROR 6 +#define WEIGH_LEAVE 3 +#define WEIGH_STABLE_WAIT 4 void PublisherApp::run() { std::string license_no; float stable_weight = 0; float stable_weight1 = 0; - float stable_weight2 = 0; + //float stable_weight2 = 0; int weigh_state = WEIGH_IDLE; + std::chrono::steady_clock::time_point stable_start_time; + bool stable_timer_running = false; // 稳定计时是否在跑 + float stable_weight_at_wait = 0; // 记录进入WEIGH_STABLE_WAIT时的稳定重量 + + // 【新增】启动红外对射状态打印线程 + //std::thread infrared_thread(print_infrared_status); while (!is_stopped()) { + // 【调试】每 20 帧打印一次状态机关键变量 + static int dbg_cnt = 0; + if (++dbg_cnt % 20 == 0) + { + DEBUG("[HEARTBEAT] state=" << weigh_state + << " lic=[" << license_no << "]" + << " sw=" << stable_weight + << " sw1=" << stable_weight1 + << " tr=" << stable_timer_running); + } + std::unique_lock dds_lock(DdsMsgData::queue_cv_mtx_, std::try_to_lock); if (dds_lock.owns_lock()) { @@ -364,10 +405,15 @@ void PublisherApp::run() DEBUG("车牌: " << info.License()); DEBUG("类型: " << info.NewTag()); - if (license_no.empty() == true) + //if (license_no.empty() == true) + if (true) // 收到车牌识别就触发,不做条件判断 { license_no = info.License(); weigh_state = WEIGH_LIC; + // 识别到车牌,抬起前拦车器 + std::map ctrl; + ctrl["FrontBar"] = "up"; + bar_ctrl(ctrl); } } else if (!DdsMsgData::ScaleInfo_queue_.empty()) @@ -386,23 +432,32 @@ void PublisherApp::run() { stable_weight = info.StableValue(); } - else - { - stable_weight = 0; - } + // else + // { + // stable_weight = 0; + // } + + // if (info.HasVehicle() == 0) + // { + // license_no.clear(); + // if (weigh_state == WEIGH_LEAVE) + // { + // std::this_thread::sleep_for(std::chrono::seconds(5)); + // std::map ctrl; + // ctrl["FrontBar"] = "down"; + // bar_ctrl(ctrl); + // weigh_state = WEIGH_IDLE; + // } + // } if (info.HasVehicle() == 0) { - license_no.clear(); - if (weigh_state == WEIGH_LEAVE) - { - std::this_thread::sleep_for(std::chrono::seconds(5)); - std::map ctrl; - ctrl["FrontBar"] = "down"; - bar_ctrl(ctrl); - weigh_state = WEIGH_IDLE; - } + // else if (license_no.empty() != true) + // { + // license_no.clear(); + // } } + } else if (!DdsMsgData::BarUpdate_queue_.empty()) { @@ -440,15 +495,44 @@ void PublisherApp::run() auto formatFloat = [](float value) -> std::string { std::ostringstream oss; - oss << std::fixed << std::setprecision(0) << value; + oss << std::fixed << std::setprecision(2) << value; return oss.str(); }; + DEBUG("==== WeightInfoOk 接收 ===="); + DEBUG(" IsPrintTicker = " << info.IsPrintTicker()); + DEBUG(" GrossDeviceID = " << info.GrossDeviceID()); + DEBUG(" GrossDeviceName = " << info.GrossDeviceName()); + DEBUG(" TareDeviceID = " << info.TareDeviceID()); + DEBUG(" TareDeviceName = " << info.TareDeviceName()); + DEBUG(" EnterpriseName = " << info.EnterpriseName()); + DEBUG(" BillNumber = " << info.BillNumber()); + DEBUG(" CarNumber = " << info.CarNumber()); + DEBUG(" Supplier = " << info.Supplier()); + DEBUG(" GoodsType = " << info.GoodsType()); + DEBUG(" GrossWeight = " << info.GrossWeight()); + DEBUG(" GrossTime = " << info.GrossTime()); + DEBUG(" GrossOperater = " << info.GrossOperater()); + DEBUG(" Tare = " << info.Tare()); + DEBUG(" TareTime = " << info.TareTime()); + DEBUG(" TareOperater = " << info.TareOperater()); + DEBUG(" Suttle = " << info.Suttle()); + DEBUG(" duduction1 = " << info.duduction1()); + DEBUG(" duduction2 = " << info.duduction2()); + DEBUG(" duduction3 = " << info.duduction3()); + DEBUG(" INCoalYard = " << info.INCoalYard()); + DEBUG(" OutCoalYard = " << info.OutCoalYard()); + DEBUG(" BatchNumber = " << info.BatchNumber()); + DEBUG(" Warning = " << info.Warning()); + DEBUG(" Tips = " << info.Tips()); + DEBUG(" TicketType = " << info.TicketType()); + DEBUG("============================"); + if (info.IsPrintTicker() == true) { std::map print_msg; - print_msg["Title"] = "五彩湾"; + print_msg["Title"] = "贵州渝黔锰业有限公司提货单"; print_msg["GrossDeviceID"] = std::to_string(info.GrossDeviceID()); print_msg["GrossDeviceName"] = info.GrossDeviceName(); print_msg["TareDeviceID"] = std::to_string(info.TareDeviceID()); @@ -475,6 +559,12 @@ void PublisherApp::run() print_msg["Tips"] = info.Tips(); print_msg["TicketType"] = info.TicketType(); + print_msg["OrderNumber"] = info.OrderNumber(); + print_msg["TrainNumber"] = info.VehicleAndVesselNumber(); + print_msg["Customer"] = info.ReceiveCompany(); + print_msg["Transporter"] = info.TransportCompany(); + + print_receipt(print_msg); std::this_thread::sleep_for(std::chrono::seconds(1)); } @@ -483,14 +573,14 @@ void PublisherApp::run() ctrl["FrontBar"] = "up"; bar_ctrl(ctrl); } - else if (!DdsMsgData::WeightInfoError_queue_.empty()) - { - WeighingSystem::WeightInfoError info = std::move(DdsMsgData::WeightInfoError_queue_.front()); - DdsMsgData::WeightInfoError_queue_.pop(); - dds_lock.unlock(); - - weigh_state = WEIGH_ERROR; - } + // else if (!DdsMsgData::WeightInfoError_queue_.empty()) + // { + // WeighingSystem::WeightInfoError info = std::move(DdsMsgData::WeightInfoError_queue_.front()); + // DdsMsgData::WeightInfoError_queue_.pop(); + // dds_lock.unlock(); + + // weigh_state = WEIGH_ERROR; + // } else { dds_lock.unlock(); @@ -498,67 +588,146 @@ void PublisherApp::run() } // logic + // switch (weigh_state) + // { + // case WEIGH_IDLE: + // break; + // case WEIGH_LIC: + // if ((stable_weight != 0) && (license_no.empty() != true)) + // { + // DEBUG("stable_weight1 " << stable_weight); + // DEBUG("license_no " << license_no); + // stable_weight1 = stable_weight; + // weigh_state = WEIGH_STABLE1; + // } + // break; + // case WEIGH_STABLE1: + // if (stable_weight == 0) + // { + // DEBUG("weigh1 clear"); + // weigh_state = WEIGH_STABLE2; + // } + // break; + // case WEIGH_STABLE2: + // if ((stable_weight != 0) && (license_no.empty() != true)) + // { + // DEBUG("license_no " << license_no); + // DEBUG("stable_weight2 " << stable_weight); + // stable_weight2 = stable_weight; + // if ((stable_weight1 - stable_weight2) > 45) + // { + // weigh_state = WEIGH_SEND; + // } + // else + // { + // DEBUG("stable_weight2 error"); + // stable_weight1 = stable_weight; + // weigh_state = WEIGH_STABLE1; + // } + // } + // break; + // case WEIGH_SEND: + // DEBUG("send summary"); + // { + // WeighingSystem::SummaryUpdate info; + // info.License() = license_no; + // info.StableValue() = stable_weight2; + // summary_writer_->write(&info); + // } + // weigh_state = WEIGH_PRINT; + // break; + // case WEIGH_PRINT: + // break; + // case WEIGH_ERROR: + // std::this_thread::sleep_for(std::chrono::seconds(3)); + // weigh_state = WEIGH_STABLE2; + // break; + // case WEIGH_LEAVE: + // break; + // default: + // weigh_state = WEIGH_IDLE; + // break; + // } switch (weigh_state) { - case WEIGH_IDLE: - break; - case WEIGH_LIC: - if ((stable_weight != 0) && (license_no.empty() != true)) + case WEIGH_IDLE: + break; + case WEIGH_LIC: + DEBUG("[STATE] WEIGH_LIC sw=" << stable_weight << " lic=[" << license_no << "]"); + if ((stable_weight != 0) && (license_no.empty() != true)) + { + DEBUG("stable_weight1 " << stable_weight); + DEBUG("license_no " << license_no); + stable_weight1 = stable_weight; + weigh_state = WEIGH_STABLE1; + } + break; + case WEIGH_STABLE1: + if (stable_weight == 0) + { + DEBUG("weigh1 clear, wait for card..."); + // 重量归零,重置计时器 + stable_timer_running = false; + } + else + { + // 读取前红外对射状态 + long front_ir = 0; { - DEBUG("stable_weight1 " << stable_weight); - DEBUG("license_no " << license_no); - stable_weight1 = stable_weight; - weigh_state = WEIGH_STABLE1; + std::lock_guard lock(DdsMsgData::infrared_mtx_); + front_ir = DdsMsgData::latest_infrared_.FrontResistanceSignal(); } - break; - case WEIGH_STABLE1: - if (stable_weight == 0) + + if (front_ir != 0) // 红外被遮挡(==1),关闭计时器 { - DEBUG("weigh1 clear"); - weigh_state = WEIGH_STABLE2; + stable_timer_running = false; + DEBUG("Front infrared blocked (sig=" << front_ir + << "), timer closed."); } - break; - case WEIGH_STABLE2: - if ((stable_weight != 0) && (license_no.empty() != true)) + else // 红外无遮挡(==0),启动/继续计时 { - DEBUG("license_no " << license_no); - DEBUG("stable_weight2 " << stable_weight); - stable_weight2 = stable_weight; - if ((stable_weight1 - stable_weight2) > 45) + if (!stable_timer_running) { - weigh_state = WEIGH_SEND; - } - else - { - DEBUG("stable_weight2 error"); - stable_weight1 = stable_weight; - weigh_state = WEIGH_STABLE1; + stable_start_time = std::chrono::steady_clock::now(); + stable_timer_running = true; + DEBUG("Infrared clear, starting 10s timer..."); } + auto now = std::chrono::steady_clock::now(); + auto elapsed = std::chrono::duration_cast(now - stable_start_time).count(); } - break; - case WEIGH_SEND: - DEBUG("send summary"); + } + break; + case WEIGH_STABLE_WAIT: + // 第一次进入时记录当前重量为基准 + if (stable_weight_at_wait == 0) + { + stable_weight_at_wait = stable_weight; + } + // 等待司机下车刷卡,通过重量变化 > 30KG 检测司机下车 + if (stable_weight > 0 && stable_weight_at_wait > 0) + { + float weight_diff = std::abs(stable_weight - stable_weight_at_wait); + if (weight_diff > 30) { - WeighingSystem::SummaryUpdate info; - info.License() = license_no; - info.StableValue() = stable_weight2; - summary_writer_->write(&info); + DEBUG("Weight changed by " << weight_diff << " kg, driver may have left, waiting for card..."); + stable_weight_at_wait = stable_weight; // 更新基准重量 } - weigh_state = WEIGH_PRINT; - break; - case WEIGH_PRINT: - break; - case WEIGH_ERROR: - std::this_thread::sleep_for(std::chrono::seconds(3)); - weigh_state = WEIGH_STABLE2; - break; - case WEIGH_LEAVE: - break; - default: - weigh_state = WEIGH_IDLE; - break; + } + else if (stable_weight == 0) + { + DEBUG("Scale is empty, waiting for card..."); + stable_weight_at_wait = 0; + } + break; + case WEIGH_LEAVE: + break; + default: + weigh_state = WEIGH_IDLE; + break; } - + + + // Wait for period or stop event std::unique_lock period_lock(mutex_); cv_.wait_for(period_lock, std::chrono::milliseconds(period_ms_), [this]() @@ -566,6 +735,11 @@ void PublisherApp::run() return is_stopped(); }); } + + // // 【新增】停止红外打印线程 + // DdsMsgData::stop_flag_ = true; + // infrared_thread.join(); + } @@ -598,4 +772,4 @@ void PublisherApp::stop() { stop_.store(true); cv_.notify_one(); -} \ No newline at end of file +} diff --git a/core/Subscriber.cxx b/core/Subscriber.cxx index 9cf04eb..4f5b8e8 100644 --- a/core/Subscriber.cxx +++ b/core/Subscriber.cxx @@ -32,13 +32,19 @@ #include #include -#include "SystemPubSubTypes.hpp" +#include "WeighingDDSTypePubSubTypes.hpp" #include "msg.hpp" #include "DEBUG.hpp" using namespace eprosima::fastdds::dds; +// 【新增】静态成员变量定义 +// std::mutex DdsMsgData::infrared_mtx_; +// WeighingSystem::InfraredUpdate DdsMsgData::latest_infrared_; +// std::atomic DdsMsgData::stop_flag_{false}; + + SubscriberApp::SubscriberApp( const int& domain_id) : factory_(nullptr) @@ -383,6 +389,7 @@ void SubscriberApp::on_data_available( DdsMsgData::LightsUpdate_queue_.push(std::move(sample_)); lock.unlock(); } + } } } @@ -398,6 +405,11 @@ void SubscriberApp::on_data_available( DdsMsgData::InfraredUpdate_queue_.push(std::move(sample_)); lock.unlock(); } + // 【新增】保存最新红外对射状态 + { + std::lock_guard lock(DdsMsgData::infrared_mtx_); + DdsMsgData::latest_infrared_ = sample_; + } } } } @@ -498,4 +510,4 @@ void SubscriberApp::stop() { stop_.store(true); terminate_cv_.notify_all(); -} \ No newline at end of file +} diff --git a/core/Subscriber.hpp b/core/Subscriber.hpp index 669b2cf..c8e3a98 100644 --- a/core/Subscriber.hpp +++ b/core/Subscriber.hpp @@ -29,7 +29,7 @@ #include #include -#include "System.hpp" +#include "WeighingDDSType.hpp" class SubscriberApp : public eprosima::fastdds::dds::DataReaderListener { @@ -94,4 +94,4 @@ private: std::condition_variable terminate_cv_; }; -#endif // FAST_DDS_GENERATED__SUBSCRIBERAPP_HPP \ No newline at end of file +#endif // FAST_DDS_GENERATED__SUBSCRIBERAPP_HPP diff --git a/core/main.cxx b/core/main.cxx index dd5fc46..a307663 100644 --- a/core/main.cxx +++ b/core/main.cxx @@ -72,6 +72,8 @@ std::queue DdsMsgData::ScaleInfo_queue_; std::queue DdsMsgData::WeightInfoOk_queue_; std::queue DdsMsgData::WeightInfoError_queue_; std::mutex DdsMsgData::queue_cv_mtx_; +std::mutex DdsMsgData::infrared_mtx_; +WeighingSystem::InfraredUpdate DdsMsgData::latest_infrared_; int main(int argc, char** argv) { diff --git a/core/msg.hpp b/core/msg.hpp index f93a94f..6ae1997 100644 --- a/core/msg.hpp +++ b/core/msg.hpp @@ -3,10 +3,17 @@ #include #include -#include "System.hpp" +#include "WeighingDDSType.hpp" +#include class DdsMsgData { public: + + // 【修改】红外对射最新状态存储(放在最前面,保持正确缩进) + static std::mutex infrared_mtx_; + static WeighingSystem::InfraredUpdate latest_infrared_; + // static std::atomic stop_flag_; + static std::queue BarUpdate_queue_; static std::queue LightsUpdate_queue_; static std::queue InfraredUpdate_queue_; @@ -16,6 +23,8 @@ public: static std::queue WeightInfoOk_queue_; static std::queue WeightInfoError_queue_; static std::mutex queue_cv_mtx_; + + }; -#endif \ No newline at end of file +#endif diff --git a/demo/Publisher.cxx b/demo/Publisher.cxx index 7045623..72f9b46 100644 --- a/demo/Publisher.cxx +++ b/demo/Publisher.cxx @@ -33,7 +33,7 @@ #include #include -#include "SystemPubSubTypes.hpp" +#include "WeighingDDSTypePubSubTypes.hpp" using namespace eprosima::fastdds::dds; @@ -44,7 +44,7 @@ PublisherApp::PublisherApp( , publisher_(nullptr) , topic_(nullptr) , writer_(nullptr) - , type_(new WeighRspPubSubType()) + , type_(new WeighingSystem::ScaleInfoPubSubType()) , matched_(0) , samples_sent_(0) , stop_(false) @@ -169,7 +169,7 @@ bool PublisherApp::publish() if (!is_stopped()) { /* Initialize your structure here */ - WeighRsp sample_; + WeighingSystem::ScaleInfo sample_; ret = (RETCODE_OK == writer_->write(&sample_)); } return ret; @@ -184,4 +184,4 @@ void PublisherApp::stop() { stop_.store(true); cv_.notify_one(); -} \ No newline at end of file +} diff --git a/demo/Subscriber.cxx b/demo/Subscriber.cxx index bc10fe1..7d7bf4e 100644 --- a/demo/Subscriber.cxx +++ b/demo/Subscriber.cxx @@ -32,7 +32,7 @@ #include #include -#include "SystemPubSubTypes.hpp" +#include "WeighingDDSTypePubSubTypes.hpp" using namespace eprosima::fastdds::dds; @@ -43,7 +43,7 @@ SubscriberApp::SubscriberApp( , subscriber_(nullptr) , topic_(nullptr) , reader_(nullptr) - , type_(new WeighReqPubSubType()) + , type_(new WeighingSystem::ScaleInfoPubSubType()) , samples_received_(0) , stop_(false) { @@ -127,7 +127,7 @@ void SubscriberApp::on_subscription_matched( void SubscriberApp::on_data_available( DataReader* reader) { - WeighRsp sample_; + WeighingSystem::ScaleInfo sample_; SampleInfo info; while ((!is_stopped()) && (RETCODE_OK == reader->take_next_sample(&sample_, &info))) { @@ -156,4 +156,4 @@ void SubscriberApp::stop() { stop_.store(true); terminate_cv_.notify_all(); -} \ No newline at end of file +} diff --git a/demo/Subscriber.hpp b/demo/Subscriber.hpp index 81132dc..f6d8448 100644 --- a/demo/Subscriber.hpp +++ b/demo/Subscriber.hpp @@ -29,7 +29,7 @@ #include #include -#include "System.hpp" +#include "WeighingDDSType.hpp" class SubscriberApp : public eprosima::fastdds::dds::DataReaderListener { @@ -72,4 +72,4 @@ private: std::condition_variable terminate_cv_; }; -#endif // FAST_DDS_GENERATED__SUBSCRIBERAPP_HPP \ No newline at end of file +#endif // FAST_DDS_GENERATED__SUBSCRIBERAPP_HPP diff --git a/fastddsgen.jar b/fastddsgen.jar new file mode 100644 index 0000000..16ef944 Binary files /dev/null and b/fastddsgen.jar differ diff --git a/gatectrl/MsgHandler.cxx b/gatectrl/MsgHandler.cxx index bf5786f..25a5576 100644 --- a/gatectrl/MsgHandler.cxx +++ b/gatectrl/MsgHandler.cxx @@ -238,11 +238,11 @@ int MsgHandler::ParseDeviceMsg(std::vector& data) { if (p.second.second == 0) { - this->new_bar_state.FrontResistanceSignal = 0; + this->new_bar_state.FrontResistanceSignal = 1; } else { - this->new_bar_state.FrontResistanceSignal = 1; + this->new_bar_state.FrontResistanceSignal = 0; } } else if (p.first == "BackResistance") diff --git a/gatectrl/Subscriber.cxx b/gatectrl/Subscriber.cxx index 6eb439b..8f9904e 100644 --- a/gatectrl/Subscriber.cxx +++ b/gatectrl/Subscriber.cxx @@ -212,9 +212,22 @@ void SubscriberApp::run(std::shared_ptr handler) { if(!MsgData::BarCommandUpdate_queue_.empty()) { + WeighingSystem::BarCommandUpdate cmd = std::move(MsgData::BarCommandUpdate_queue_.front()); MsgData::BarCommandUpdate_queue_.pop(); lock.unlock(); + + // std::cout << "[DEBUG] DDS Received: " + // << "FrontBarSignalUp=" << cmd.FrontBarSignalUp() << ", " + // << "FrontBarSignalDown=" << cmd.FrontBarSignalDown() << ", " + // << "FrontBarEnable=" << cmd.FrontBarEnable() << ", " + // << "BackBarSignalUp=" << cmd.BackBarSignalUp() << ", " + // << "BackBarSignalDown=" << cmd.BackBarSignalDown() << ", " + // << "BackBarEnable=" << cmd.BackBarEnable() + // << std::endl; + + + std::vector port; if (!std::filesystem::exists(getExeDir() / "frontbar.lock")) { diff --git a/httpserver/Publisher.cxx b/httpserver/Publisher.cxx index 0b47d14..7ad7061 100644 --- a/httpserver/Publisher.cxx +++ b/httpserver/Publisher.cxx @@ -26,6 +26,7 @@ #include #include + #include #include #include @@ -154,6 +155,10 @@ void PublisherApp::run(std::shared_ptr handler) if (handler->PostMsg.empty() != true) { + + std::cout << "[HTTPServer] 原始数据: " << handler->PostMsg << std::endl; + + json j = json::parse(handler->PostMsg); DEBUG("车牌: " << j["AlarmInfoPlate"]["result"]["PlateResult"]["license"]); diff --git a/led/Subscriber.cxx b/led/Subscriber.cxx index 39a341a..d859624 100644 --- a/led/Subscriber.cxx +++ b/led/Subscriber.cxx @@ -32,7 +32,7 @@ #include #include -#include "SystemPubSubTypes.hpp" +#include "WeighingDDSTypePubSubTypes.hpp" #include "msg.hpp" #include "DEBUG.hpp" @@ -312,4 +312,4 @@ void SubscriberApp::stop() { stop_.store(true); terminate_cv_.notify_all(); -} \ No newline at end of file +} diff --git a/led/Subscriber.hpp b/led/Subscriber.hpp index 248e4a0..5e2c08e 100644 --- a/led/Subscriber.hpp +++ b/led/Subscriber.hpp @@ -29,7 +29,7 @@ #include #include -#include "System.hpp" +#include "WeighingDDSType.hpp" class SubscriberApp : public eprosima::fastdds::dds::DataReaderListener { @@ -81,4 +81,4 @@ private: std::condition_variable terminate_cv_; }; -#endif // FAST_DDS_GENERATED__SUBSCRIBERAPP_HPP \ No newline at end of file +#endif // FAST_DDS_GENERATED__SUBSCRIBERAPP_HPP diff --git a/led/main.cxx b/led/main.cxx index afe94a6..277aa03 100644 --- a/led/main.cxx +++ b/led/main.cxx @@ -133,7 +133,7 @@ void send_text(std::string ip_addr, int port, std::string text) int dynamic_type = 1; int display_effects = 0; int display_speed = 16; - int stay_time = 10; + int stay_time = 15; int gif_flag = 0; char *bg_color = "0xff000000"; char *color = "0xffffffff"; @@ -165,7 +165,7 @@ void send_text(std::string ip_addr, int port, std::string text) DEBUG("add_dynamic:" << err); delete_dynamic(dynamic_area); - err = add_program_in_playlist(play_list, program, 0, 10, ali, ali, ali, ali, 127); + err = add_program_in_playlist(play_list, program, 0, 15, ali, ali, ali, ali, 127); DEBUG("add_program_in_playlist:" << err); err = update_dynamic_small(ip.data(), port, user_name, user_pwd, play_list, "", 1, 0); if (err != 0) @@ -269,8 +269,6 @@ int main(int argc, char** argv) int type = 0; std::string addr = "192.168.1.100"; uint8_t clear_led = 1; - uint8_t weight_stable = 0; - std::string license = ""; for (int i = 1; i < argc; i++) { @@ -371,18 +369,8 @@ int main(int argc, char** argv) { send_text(addr, port, default_text); clear_led = 1; - license.clear(); } } - - if (info.WeightOK() == true) - { - weight_stable = 1; - } - else - { - weight_stable = 0; - } } else if (!DdsMsgData::LicenseSnapUpdate_queue_.empty()) { @@ -390,8 +378,8 @@ int main(int argc, char** argv) DdsMsgData::LicenseSnapUpdate_queue_.pop(); lock.unlock(); - license = info.License(); - weight_stable = 0; + send_text(addr, port, info.License()); + clear_led = 0; } else { @@ -399,17 +387,7 @@ int main(int argc, char** argv) } } - if (type == 1) - { - if ((weight_stable == 1) && (!license.empty())) - { - std::string text = license + std::string(",司机请下车等候,切勿停留在车上!"); - send_text(addr, port, text); - clear_led = 0; - weight_stable = 0; - license.clear(); - } - } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); } diff --git a/led/msg.hpp b/led/msg.hpp index 7a2fd30..2a6873e 100644 --- a/led/msg.hpp +++ b/led/msg.hpp @@ -3,7 +3,7 @@ #include #include -#include "System.hpp" +#include "WeighingDDSType.hpp" class DdsMsgData { public: @@ -14,4 +14,4 @@ public: static std::mutex queue_cv_mtx_; }; -#endif \ No newline at end of file +#endif diff --git a/lib/System.hpp b/lib/WeighingDDSType.hpp similarity index 91% rename from lib/System.hpp rename to lib/WeighingDDSType.hpp index 5a62873..e87d981 100644 --- a/lib/System.hpp +++ b/lib/WeighingDDSType.hpp @@ -13,19 +13,21 @@ // limitations under the License. /*! - * @file System.hpp + * @file WeighingDDSType.hpp * This header file contains the declaration of the described types in the IDL file. * * This file was generated by the tool fastddsgen. */ -#ifndef FAST_DDS_GENERATED__INTERNALSYSTEM_SYSTEM_HPP -#define FAST_DDS_GENERATED__INTERNALSYSTEM_SYSTEM_HPP +#ifndef FAST_DDS_GENERATED__WEIGHINGSYSTEM_WEIGHINGDDSTYPE_HPP +#define FAST_DDS_GENERATED__WEIGHINGSYSTEM_WEIGHINGDDSTYPE_HPP #include #include #include #include +#include + #include #if defined(_WIN32) @@ -40,23 +42,23 @@ #if defined(_WIN32) #if defined(EPROSIMA_USER_DLL_EXPORT) -#if defined(SYSTEM_SOURCE) -#define SYSTEM_DllAPI __declspec( dllexport ) +#if defined(WEIGHINGDDSTYPE_SOURCE) +#define WEIGHINGDDSTYPE_DllAPI __declspec( dllexport ) #else -#define SYSTEM_DllAPI __declspec( dllimport ) -#endif // SYSTEM_SOURCE +#define WEIGHINGDDSTYPE_DllAPI __declspec( dllimport ) +#endif // WEIGHINGDDSTYPE_SOURCE #else -#define SYSTEM_DllAPI +#define WEIGHINGDDSTYPE_DllAPI #endif // EPROSIMA_USER_DLL_EXPORT #else -#define SYSTEM_DllAPI +#define WEIGHINGDDSTYPE_DllAPI #endif // _WIN32 namespace WeighingSystem { /*! * @brief This class represents the structure ScaleInfo defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class ScaleInfo { @@ -327,7 +329,7 @@ private: }; /*! * @brief This class represents the structure ScaleCommand defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class ScaleCommand { @@ -487,7 +489,7 @@ private: }; /*! * @brief This class represents the structure WeightInfoOk defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class WeightInfoOk { @@ -570,6 +572,14 @@ public: m_IsPrintTicker = x.m_IsPrintTicker; + m_OrderNumber = x.m_OrderNumber; + + m_VehicleAndVesselNumber = x.m_VehicleAndVesselNumber; + + m_ReceiveCompany = x.m_ReceiveCompany; + + m_TransportCompany = x.m_TransportCompany; + } /*! @@ -607,6 +617,10 @@ public: m_Tips = std::move(x.m_Tips); m_TicketType = std::move(x.m_TicketType); m_IsPrintTicker = x.m_IsPrintTicker; + m_OrderNumber = std::move(x.m_OrderNumber); + m_VehicleAndVesselNumber = std::move(x.m_VehicleAndVesselNumber); + m_ReceiveCompany = std::move(x.m_ReceiveCompany); + m_TransportCompany = std::move(x.m_TransportCompany); } /*! @@ -673,6 +687,14 @@ public: m_IsPrintTicker = x.m_IsPrintTicker; + m_OrderNumber = x.m_OrderNumber; + + m_VehicleAndVesselNumber = x.m_VehicleAndVesselNumber; + + m_ReceiveCompany = x.m_ReceiveCompany; + + m_TransportCompany = x.m_TransportCompany; + return *this; } @@ -712,6 +734,10 @@ public: m_Tips = std::move(x.m_Tips); m_TicketType = std::move(x.m_TicketType); m_IsPrintTicker = x.m_IsPrintTicker; + m_OrderNumber = std::move(x.m_OrderNumber); + m_VehicleAndVesselNumber = std::move(x.m_VehicleAndVesselNumber); + m_ReceiveCompany = std::move(x.m_ReceiveCompany); + m_TransportCompany = std::move(x.m_TransportCompany); return *this; } @@ -749,7 +775,11 @@ public: m_Warning == x.m_Warning && m_Tips == x.m_Tips && m_TicketType == x.m_TicketType && - m_IsPrintTicker == x.m_IsPrintTicker); + m_IsPrintTicker == x.m_IsPrintTicker && + m_OrderNumber == x.m_OrderNumber && + m_VehicleAndVesselNumber == x.m_VehicleAndVesselNumber && + m_ReceiveCompany == x.m_ReceiveCompany && + m_TransportCompany == x.m_TransportCompany); } /*! @@ -1764,6 +1794,162 @@ public: } + /*! + * @brief This function copies the value in member OrderNumber + * @param _OrderNumber New value to be copied in member OrderNumber + */ + eProsima_user_DllExport void OrderNumber( + const std::string& _OrderNumber) + { + m_OrderNumber = _OrderNumber; + } + + /*! + * @brief This function moves the value in member OrderNumber + * @param _OrderNumber New value to be moved in member OrderNumber + */ + eProsima_user_DllExport void OrderNumber( + std::string&& _OrderNumber) + { + m_OrderNumber = std::move(_OrderNumber); + } + + /*! + * @brief This function returns a constant reference to member OrderNumber + * @return Constant reference to member OrderNumber + */ + eProsima_user_DllExport const std::string& OrderNumber() const + { + return m_OrderNumber; + } + + /*! + * @brief This function returns a reference to member OrderNumber + * @return Reference to member OrderNumber + */ + eProsima_user_DllExport std::string& OrderNumber() + { + return m_OrderNumber; + } + + + /*! + * @brief This function copies the value in member VehicleAndVesselNumber + * @param _VehicleAndVesselNumber New value to be copied in member VehicleAndVesselNumber + */ + eProsima_user_DllExport void VehicleAndVesselNumber( + const std::string& _VehicleAndVesselNumber) + { + m_VehicleAndVesselNumber = _VehicleAndVesselNumber; + } + + /*! + * @brief This function moves the value in member VehicleAndVesselNumber + * @param _VehicleAndVesselNumber New value to be moved in member VehicleAndVesselNumber + */ + eProsima_user_DllExport void VehicleAndVesselNumber( + std::string&& _VehicleAndVesselNumber) + { + m_VehicleAndVesselNumber = std::move(_VehicleAndVesselNumber); + } + + /*! + * @brief This function returns a constant reference to member VehicleAndVesselNumber + * @return Constant reference to member VehicleAndVesselNumber + */ + eProsima_user_DllExport const std::string& VehicleAndVesselNumber() const + { + return m_VehicleAndVesselNumber; + } + + /*! + * @brief This function returns a reference to member VehicleAndVesselNumber + * @return Reference to member VehicleAndVesselNumber + */ + eProsima_user_DllExport std::string& VehicleAndVesselNumber() + { + return m_VehicleAndVesselNumber; + } + + + /*! + * @brief This function copies the value in member ReceiveCompany + * @param _ReceiveCompany New value to be copied in member ReceiveCompany + */ + eProsima_user_DllExport void ReceiveCompany( + const std::string& _ReceiveCompany) + { + m_ReceiveCompany = _ReceiveCompany; + } + + /*! + * @brief This function moves the value in member ReceiveCompany + * @param _ReceiveCompany New value to be moved in member ReceiveCompany + */ + eProsima_user_DllExport void ReceiveCompany( + std::string&& _ReceiveCompany) + { + m_ReceiveCompany = std::move(_ReceiveCompany); + } + + /*! + * @brief This function returns a constant reference to member ReceiveCompany + * @return Constant reference to member ReceiveCompany + */ + eProsima_user_DllExport const std::string& ReceiveCompany() const + { + return m_ReceiveCompany; + } + + /*! + * @brief This function returns a reference to member ReceiveCompany + * @return Reference to member ReceiveCompany + */ + eProsima_user_DllExport std::string& ReceiveCompany() + { + return m_ReceiveCompany; + } + + + /*! + * @brief This function copies the value in member TransportCompany + * @param _TransportCompany New value to be copied in member TransportCompany + */ + eProsima_user_DllExport void TransportCompany( + const std::string& _TransportCompany) + { + m_TransportCompany = _TransportCompany; + } + + /*! + * @brief This function moves the value in member TransportCompany + * @param _TransportCompany New value to be moved in member TransportCompany + */ + eProsima_user_DllExport void TransportCompany( + std::string&& _TransportCompany) + { + m_TransportCompany = std::move(_TransportCompany); + } + + /*! + * @brief This function returns a constant reference to member TransportCompany + * @return Constant reference to member TransportCompany + */ + eProsima_user_DllExport const std::string& TransportCompany() const + { + return m_TransportCompany; + } + + /*! + * @brief This function returns a reference to member TransportCompany + * @return Reference to member TransportCompany + */ + eProsima_user_DllExport std::string& TransportCompany() + { + return m_TransportCompany; + } + + private: @@ -1795,11 +1981,15 @@ private: std::string m_Tips; std::string m_TicketType; bool m_IsPrintTicker{false}; + std::string m_OrderNumber; + std::string m_VehicleAndVesselNumber; + std::string m_ReceiveCompany; + std::string m_TransportCompany; }; /*! * @brief This class represents the structure WeightInfoError defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class WeightInfoError { @@ -1979,7 +2169,7 @@ private: }; /*! * @brief This class represents the structure BarCommandUpdate defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class BarCommandUpdate { @@ -2287,7 +2477,7 @@ private: }; /*! * @brief This class represents the structure LightsCommandUpdate defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class LightsCommandUpdate { @@ -2521,7 +2711,7 @@ private: }; /*! * @brief This class represents the structure InfraredCommandUpdate defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class InfraredCommandUpdate { @@ -2755,7 +2945,7 @@ private: }; /*! * @brief This class represents the structure BarUpdate defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class BarUpdate { @@ -2915,7 +3105,7 @@ private: }; /*! * @brief This class represents the structure LightsUpdate defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class LightsUpdate { @@ -3075,7 +3265,7 @@ private: }; /*! * @brief This class represents the structure InfraredUpdate defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class InfraredUpdate { @@ -3235,7 +3425,7 @@ private: }; /*! * @brief This class represents the structure LicenseSnapUpdate defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class LicenseSnapUpdate { @@ -3405,7 +3595,7 @@ private: }; /*! * @brief This class represents the structure Voice defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class Voice { @@ -3575,7 +3765,7 @@ private: }; /*! * @brief This class represents the structure SummaryUpdate defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class SummaryUpdate { @@ -3743,38 +3933,34 @@ private: float m_StableValue{0.0}; }; - -} // namespace WeighingSystem -namespace InternalSystem { - /*! - * @brief This class represents the structure PrintReq defined by the user in the IDL file. - * @ingroup System + * @brief This class represents the structure ReadCardReq defined by the user in the IDL file. + * @ingroup WeighingDDSType */ -class PrintReq +class ReadCardReq { public: /*! * @brief Default constructor. */ - eProsima_user_DllExport PrintReq() + eProsima_user_DllExport ReadCardReq() { } /*! * @brief Default destructor. */ - eProsima_user_DllExport ~PrintReq() + eProsima_user_DllExport ~ReadCardReq() { } /*! * @brief Copy constructor. - * @param x Reference to the object PrintReq that will be copied. + * @param x Reference to the object ReadCardReq that will be copied. */ - eProsima_user_DllExport PrintReq( - const PrintReq& x) + eProsima_user_DllExport ReadCardReq( + const ReadCardReq& x) { m_index = x.m_index; @@ -3784,10 +3970,10 @@ public: /*! * @brief Move constructor. - * @param x Reference to the object PrintReq that will be copied. + * @param x Reference to the object ReadCardReq that will be copied. */ - eProsima_user_DllExport PrintReq( - PrintReq&& x) noexcept + eProsima_user_DllExport ReadCardReq( + ReadCardReq&& x) noexcept { m_index = x.m_index; m_msg = std::move(x.m_msg); @@ -3795,10 +3981,10 @@ public: /*! * @brief Copy assignment. - * @param x Reference to the object PrintReq that will be copied. + * @param x Reference to the object ReadCardReq that will be copied. */ - eProsima_user_DllExport PrintReq& operator =( - const PrintReq& x) + eProsima_user_DllExport ReadCardReq& operator =( + const ReadCardReq& x) { m_index = x.m_index; @@ -3810,10 +3996,10 @@ public: /*! * @brief Move assignment. - * @param x Reference to the object PrintReq that will be copied. + * @param x Reference to the object ReadCardReq that will be copied. */ - eProsima_user_DllExport PrintReq& operator =( - PrintReq&& x) noexcept + eProsima_user_DllExport ReadCardReq& operator =( + ReadCardReq&& x) noexcept { m_index = x.m_index; @@ -3823,10 +4009,10 @@ public: /*! * @brief Comparison operator. - * @param x PrintReq object to compare. + * @param x ReadCardReq object to compare. */ eProsima_user_DllExport bool operator ==( - const PrintReq& x) const + const ReadCardReq& x) const { return (m_index == x.m_index && m_msg == x.m_msg); @@ -3834,10 +4020,10 @@ public: /*! * @brief Comparison operator. - * @param x PrintReq object to compare. + * @param x ReadCardReq object to compare. */ eProsima_user_DllExport bool operator !=( - const PrintReq& x) const + const ReadCardReq& x) const { return !(*this == x); } @@ -3876,7 +4062,7 @@ public: * @param _msg New value to be copied in member msg */ eProsima_user_DllExport void msg( - const std::map& _msg) + const std::map>& _msg) { m_msg = _msg; } @@ -3886,7 +4072,7 @@ public: * @param _msg New value to be moved in member msg */ eProsima_user_DllExport void msg( - std::map&& _msg) + std::map>&& _msg) { m_msg = std::move(_msg); } @@ -3895,7 +4081,7 @@ public: * @brief This function returns a constant reference to member msg * @return Constant reference to member msg */ - eProsima_user_DllExport const std::map& msg() const + eProsima_user_DllExport const std::map>& msg() const { return m_msg; } @@ -3904,7 +4090,7 @@ public: * @brief This function returns a reference to member msg * @return Reference to member msg */ - eProsima_user_DllExport std::map& msg() + eProsima_user_DllExport std::map>& msg() { return m_msg; } @@ -3914,37 +4100,37 @@ public: private: uint32_t m_index{0}; - std::map m_msg; + std::map> m_msg; }; /*! - * @brief This class represents the structure PrintRsp defined by the user in the IDL file. - * @ingroup System + * @brief This class represents the structure ReadCardRsp defined by the user in the IDL file. + * @ingroup WeighingDDSType */ -class PrintRsp +class ReadCardRsp { public: /*! * @brief Default constructor. */ - eProsima_user_DllExport PrintRsp() + eProsima_user_DllExport ReadCardRsp() { } /*! * @brief Default destructor. */ - eProsima_user_DllExport ~PrintRsp() + eProsima_user_DllExport ~ReadCardRsp() { } /*! * @brief Copy constructor. - * @param x Reference to the object PrintRsp that will be copied. + * @param x Reference to the object ReadCardRsp that will be copied. */ - eProsima_user_DllExport PrintRsp( - const PrintRsp& x) + eProsima_user_DllExport ReadCardRsp( + const ReadCardRsp& x) { m_index = x.m_index; @@ -3954,10 +4140,10 @@ public: /*! * @brief Move constructor. - * @param x Reference to the object PrintRsp that will be copied. + * @param x Reference to the object ReadCardRsp that will be copied. */ - eProsima_user_DllExport PrintRsp( - PrintRsp&& x) noexcept + eProsima_user_DllExport ReadCardRsp( + ReadCardRsp&& x) noexcept { m_index = x.m_index; m_msg = std::move(x.m_msg); @@ -3965,10 +4151,10 @@ public: /*! * @brief Copy assignment. - * @param x Reference to the object PrintRsp that will be copied. + * @param x Reference to the object ReadCardRsp that will be copied. */ - eProsima_user_DllExport PrintRsp& operator =( - const PrintRsp& x) + eProsima_user_DllExport ReadCardRsp& operator =( + const ReadCardRsp& x) { m_index = x.m_index; @@ -3980,10 +4166,10 @@ public: /*! * @brief Move assignment. - * @param x Reference to the object PrintRsp that will be copied. + * @param x Reference to the object ReadCardRsp that will be copied. */ - eProsima_user_DllExport PrintRsp& operator =( - PrintRsp&& x) noexcept + eProsima_user_DllExport ReadCardRsp& operator =( + ReadCardRsp&& x) noexcept { m_index = x.m_index; @@ -3993,10 +4179,10 @@ public: /*! * @brief Comparison operator. - * @param x PrintRsp object to compare. + * @param x ReadCardRsp object to compare. */ eProsima_user_DllExport bool operator ==( - const PrintRsp& x) const + const ReadCardRsp& x) const { return (m_index == x.m_index && m_msg == x.m_msg); @@ -4004,10 +4190,10 @@ public: /*! * @brief Comparison operator. - * @param x PrintRsp object to compare. + * @param x ReadCardRsp object to compare. */ eProsima_user_DllExport bool operator !=( - const PrintRsp& x) const + const ReadCardRsp& x) const { return !(*this == x); } @@ -4046,7 +4232,7 @@ public: * @param _msg New value to be copied in member msg */ eProsima_user_DllExport void msg( - const std::string& _msg) + const std::map>& _msg) { m_msg = _msg; } @@ -4056,7 +4242,7 @@ public: * @param _msg New value to be moved in member msg */ eProsima_user_DllExport void msg( - std::string&& _msg) + std::map>&& _msg) { m_msg = std::move(_msg); } @@ -4065,7 +4251,7 @@ public: * @brief This function returns a constant reference to member msg * @return Constant reference to member msg */ - eProsima_user_DllExport const std::string& msg() const + eProsima_user_DllExport const std::map>& msg() const { return m_msg; } @@ -4074,7 +4260,7 @@ public: * @brief This function returns a reference to member msg * @return Reference to member msg */ - eProsima_user_DllExport std::string& msg() + eProsima_user_DllExport std::map>& msg() { return m_msg; } @@ -4084,37 +4270,37 @@ public: private: uint32_t m_index{0}; - std::string m_msg; + std::map> m_msg; }; /*! - * @brief This class represents the structure IoCtrlReq defined by the user in the IDL file. - * @ingroup System + * @brief This class represents the structure PrintReq defined by the user in the IDL file. + * @ingroup WeighingDDSType */ -class IoCtrlReq +class PrintReq { public: /*! * @brief Default constructor. */ - eProsima_user_DllExport IoCtrlReq() + eProsima_user_DllExport PrintReq() { } /*! * @brief Default destructor. */ - eProsima_user_DllExport ~IoCtrlReq() + eProsima_user_DllExport ~PrintReq() { } /*! * @brief Copy constructor. - * @param x Reference to the object IoCtrlReq that will be copied. + * @param x Reference to the object PrintReq that will be copied. */ - eProsima_user_DllExport IoCtrlReq( - const IoCtrlReq& x) + eProsima_user_DllExport PrintReq( + const PrintReq& x) { m_index = x.m_index; @@ -4124,10 +4310,10 @@ public: /*! * @brief Move constructor. - * @param x Reference to the object IoCtrlReq that will be copied. + * @param x Reference to the object PrintReq that will be copied. */ - eProsima_user_DllExport IoCtrlReq( - IoCtrlReq&& x) noexcept + eProsima_user_DllExport PrintReq( + PrintReq&& x) noexcept { m_index = x.m_index; m_msg = std::move(x.m_msg); @@ -4135,10 +4321,10 @@ public: /*! * @brief Copy assignment. - * @param x Reference to the object IoCtrlReq that will be copied. + * @param x Reference to the object PrintReq that will be copied. */ - eProsima_user_DllExport IoCtrlReq& operator =( - const IoCtrlReq& x) + eProsima_user_DllExport PrintReq& operator =( + const PrintReq& x) { m_index = x.m_index; @@ -4150,10 +4336,10 @@ public: /*! * @brief Move assignment. - * @param x Reference to the object IoCtrlReq that will be copied. + * @param x Reference to the object PrintReq that will be copied. */ - eProsima_user_DllExport IoCtrlReq& operator =( - IoCtrlReq&& x) noexcept + eProsima_user_DllExport PrintReq& operator =( + PrintReq&& x) noexcept { m_index = x.m_index; @@ -4163,10 +4349,10 @@ public: /*! * @brief Comparison operator. - * @param x IoCtrlReq object to compare. + * @param x PrintReq object to compare. */ eProsima_user_DllExport bool operator ==( - const IoCtrlReq& x) const + const PrintReq& x) const { return (m_index == x.m_index && m_msg == x.m_msg); @@ -4174,10 +4360,10 @@ public: /*! * @brief Comparison operator. - * @param x IoCtrlReq object to compare. + * @param x PrintReq object to compare. */ eProsima_user_DllExport bool operator !=( - const IoCtrlReq& x) const + const PrintReq& x) const { return !(*this == x); } @@ -4258,33 +4444,33 @@ private: }; /*! - * @brief This class represents the structure IoCtrlRsp defined by the user in the IDL file. - * @ingroup System + * @brief This class represents the structure PrintRsp defined by the user in the IDL file. + * @ingroup WeighingDDSType */ -class IoCtrlRsp +class PrintRsp { public: /*! * @brief Default constructor. */ - eProsima_user_DllExport IoCtrlRsp() + eProsima_user_DllExport PrintRsp() { } /*! * @brief Default destructor. */ - eProsima_user_DllExport ~IoCtrlRsp() + eProsima_user_DllExport ~PrintRsp() { } /*! * @brief Copy constructor. - * @param x Reference to the object IoCtrlRsp that will be copied. + * @param x Reference to the object PrintRsp that will be copied. */ - eProsima_user_DllExport IoCtrlRsp( - const IoCtrlRsp& x) + eProsima_user_DllExport PrintRsp( + const PrintRsp& x) { m_index = x.m_index; @@ -4294,10 +4480,10 @@ public: /*! * @brief Move constructor. - * @param x Reference to the object IoCtrlRsp that will be copied. + * @param x Reference to the object PrintRsp that will be copied. */ - eProsima_user_DllExport IoCtrlRsp( - IoCtrlRsp&& x) noexcept + eProsima_user_DllExport PrintRsp( + PrintRsp&& x) noexcept { m_index = x.m_index; m_msg = std::move(x.m_msg); @@ -4305,10 +4491,10 @@ public: /*! * @brief Copy assignment. - * @param x Reference to the object IoCtrlRsp that will be copied. + * @param x Reference to the object PrintRsp that will be copied. */ - eProsima_user_DllExport IoCtrlRsp& operator =( - const IoCtrlRsp& x) + eProsima_user_DllExport PrintRsp& operator =( + const PrintRsp& x) { m_index = x.m_index; @@ -4320,10 +4506,10 @@ public: /*! * @brief Move assignment. - * @param x Reference to the object IoCtrlRsp that will be copied. + * @param x Reference to the object PrintRsp that will be copied. */ - eProsima_user_DllExport IoCtrlRsp& operator =( - IoCtrlRsp&& x) noexcept + eProsima_user_DllExport PrintRsp& operator =( + PrintRsp&& x) noexcept { m_index = x.m_index; @@ -4333,10 +4519,10 @@ public: /*! * @brief Comparison operator. - * @param x IoCtrlRsp object to compare. + * @param x PrintRsp object to compare. */ eProsima_user_DllExport bool operator ==( - const IoCtrlRsp& x) const + const PrintRsp& x) const { return (m_index == x.m_index && m_msg == x.m_msg); @@ -4344,10 +4530,10 @@ public: /*! * @brief Comparison operator. - * @param x IoCtrlRsp object to compare. + * @param x PrintRsp object to compare. */ eProsima_user_DllExport bool operator !=( - const IoCtrlRsp& x) const + const PrintRsp& x) const { return !(*this == x); } @@ -4386,7 +4572,7 @@ public: * @param _msg New value to be copied in member msg */ eProsima_user_DllExport void msg( - const std::map& _msg) + const std::string& _msg) { m_msg = _msg; } @@ -4396,7 +4582,7 @@ public: * @param _msg New value to be moved in member msg */ eProsima_user_DllExport void msg( - std::map&& _msg) + std::string&& _msg) { m_msg = std::move(_msg); } @@ -4405,7 +4591,7 @@ public: * @brief This function returns a constant reference to member msg * @return Constant reference to member msg */ - eProsima_user_DllExport const std::map& msg() const + eProsima_user_DllExport const std::string& msg() const { return m_msg; } @@ -4414,7 +4600,7 @@ public: * @brief This function returns a reference to member msg * @return Reference to member msg */ - eProsima_user_DllExport std::map& msg() + eProsima_user_DllExport std::string& msg() { return m_msg; } @@ -4424,12 +4610,12 @@ public: private: uint32_t m_index{0}; - std::map m_msg; + std::string m_msg; }; -} // namespace InternalSystem +} // namespace WeighingSystem -#endif // _FAST_DDS_GENERATED_INTERNALSYSTEM_SYSTEM_HPP_ +#endif // _FAST_DDS_GENERATED_WEIGHINGSYSTEM_WEIGHINGDDSTYPE_HPP_ diff --git a/lib/System.idl b/lib/WeighingDDSType.idl similarity index 81% rename from lib/System.idl rename to lib/WeighingDDSType.idl index 590d581..d50a322 100644 --- a/lib/System.idl +++ b/lib/WeighingDDSType.idl @@ -73,6 +73,12 @@ module WeighingSystem { // 打印磅单相关 string TicketType; // 磅单类型 1:一次称重 2:二次称重 boolean IsPrintTicker; // 是否打印磅单 + + // 绥阳铁合金称重成功扩展属性 + string OrderNumber; // 订单号 + string VehicleAndVesselNumber; // 车船号 + string ReceiveCompany; // 收货单位 + string TransportCompany; // 运输单位 }; // ============================================ @@ -193,34 +199,61 @@ module WeighingSystem { // 称重类 // ============================================ struct SummaryUpdate { - string License; // 车牌号 - float StableValue; // 稳定重量 + string License; // 五彩湾为车牌号;绥阳铁合金为刷卡卡号 + float StableValue; // 稳定重量;绥阳铁合金按吨传输 }; -}; -module InternalSystem -{ - struct PrintReq + // ============================================ + // Topic: ReadCardReq <-- 订阅 Topic (设备驱动侧) + // 类型: ReadCardReq + // 发布者: Core + // 订阅者: ReadCard + // 载荷: map> + // 协议键: "find" / "stop" / "read" / "write" / "beep" / "reset" + // ============================================ + struct ReadCardReq { unsigned long index; - map msg; + map > msg; }; - struct PrintRsp + // ============================================ + // Topic: ReadCardRsp <-- 发布 Topic (设备驱动侧) + // 类型: ReadCardRsp + // 发布者: ReadCard + // 订阅者: Core / MqttDds + // 载荷: map> + // 协议键: "find" / "read" / "write" / "stop" / "beep" + // ============================================ + struct ReadCardRsp { unsigned long index; - string msg; + map > msg; }; - struct IoCtrlReq + // ============================================ + // Topic: PrintReq <-- 发布 Topic (Core → Print) + // 类型: PrintReq + // 发布者: Core + // 订阅者: Print + // 载荷: map + // ============================================ + struct PrintReq { unsigned long index; map msg; }; - struct IoCtrlRsp + // ============================================ + // Topic: PrintRsp <-- 发布 Topic (Print → Core) + // 类型: PrintRsp + // 发布者: Print + // 订阅者: Core + // 载荷: string + // ============================================ + struct PrintRsp { unsigned long index; - map msg; + string msg; }; -}; \ No newline at end of file +}; diff --git a/lib/SystemCdrAux.hpp b/lib/WeighingDDSTypeCdrAux.hpp similarity index 82% rename from lib/SystemCdrAux.hpp rename to lib/WeighingDDSTypeCdrAux.hpp index 0aed01e..aa52fb5 100644 --- a/lib/SystemCdrAux.hpp +++ b/lib/WeighingDDSTypeCdrAux.hpp @@ -13,16 +13,19 @@ // limitations under the License. /*! - * @file SystemCdrAux.hpp + * @file WeighingDDSTypeCdrAux.hpp * This source file contains some definitions of CDR related functions. * * This file was generated by the tool fastddsgen. */ -#ifndef FAST_DDS_GENERATED__INTERNALSYSTEM_SYSTEMCDRAUX_HPP -#define FAST_DDS_GENERATED__INTERNALSYSTEM_SYSTEMCDRAUX_HPP +#ifndef FAST_DDS_GENERATED__WEIGHINGSYSTEM_WEIGHINGDDSTYPECDRAUX_HPP +#define FAST_DDS_GENERATED__WEIGHINGSYSTEM_WEIGHINGDDSTYPECDRAUX_HPP -#include "System.hpp" +#include "WeighingDDSType.hpp" + +constexpr uint32_t WeighingSystem_PrintRsp_max_cdr_typesize {268UL}; +constexpr uint32_t WeighingSystem_PrintRsp_max_key_cdr_typesize {0UL}; constexpr uint32_t WeighingSystem_SummaryUpdate_max_cdr_typesize {268UL}; constexpr uint32_t WeighingSystem_SummaryUpdate_max_key_cdr_typesize {0UL}; @@ -33,33 +36,33 @@ constexpr uint32_t WeighingSystem_LightsUpdate_max_key_cdr_typesize {0UL}; constexpr uint32_t WeighingSystem_InfraredUpdate_max_cdr_typesize {12UL}; constexpr uint32_t WeighingSystem_InfraredUpdate_max_key_cdr_typesize {0UL}; -constexpr uint32_t InternalSystem_PrintReq_max_cdr_typesize {16UL}; -constexpr uint32_t InternalSystem_PrintReq_max_key_cdr_typesize {0UL}; +constexpr uint32_t WeighingSystem_ReadCardRsp_max_cdr_typesize {16UL}; +constexpr uint32_t WeighingSystem_ReadCardRsp_max_key_cdr_typesize {0UL}; constexpr uint32_t WeighingSystem_WeightInfoError_max_cdr_typesize {524UL}; constexpr uint32_t WeighingSystem_WeightInfoError_max_key_cdr_typesize {0UL}; -constexpr uint32_t WeighingSystem_WeightInfoOk_max_cdr_typesize {4977UL}; +constexpr uint32_t WeighingSystem_WeightInfoOk_max_cdr_typesize {6020UL}; constexpr uint32_t WeighingSystem_WeightInfoOk_max_key_cdr_typesize {0UL}; -constexpr uint32_t InternalSystem_IoCtrlRsp_max_cdr_typesize {16UL}; -constexpr uint32_t InternalSystem_IoCtrlRsp_max_key_cdr_typesize {0UL}; - constexpr uint32_t WeighingSystem_InfraredCommandUpdate_max_cdr_typesize {17UL}; constexpr uint32_t WeighingSystem_InfraredCommandUpdate_max_key_cdr_typesize {0UL}; constexpr uint32_t WeighingSystem_LightsCommandUpdate_max_cdr_typesize {20UL}; constexpr uint32_t WeighingSystem_LightsCommandUpdate_max_key_cdr_typesize {0UL}; +constexpr uint32_t WeighingSystem_ReadCardReq_max_cdr_typesize {16UL}; +constexpr uint32_t WeighingSystem_ReadCardReq_max_key_cdr_typesize {0UL}; + +constexpr uint32_t WeighingSystem_PrintReq_max_cdr_typesize {16UL}; +constexpr uint32_t WeighingSystem_PrintReq_max_key_cdr_typesize {0UL}; + constexpr uint32_t WeighingSystem_LicenseSnapUpdate_max_cdr_typesize {268UL}; constexpr uint32_t WeighingSystem_LicenseSnapUpdate_max_key_cdr_typesize {0UL}; constexpr uint32_t WeighingSystem_ScaleInfo_max_cdr_typesize {16UL}; constexpr uint32_t WeighingSystem_ScaleInfo_max_key_cdr_typesize {0UL}; -constexpr uint32_t InternalSystem_PrintRsp_max_cdr_typesize {268UL}; -constexpr uint32_t InternalSystem_PrintRsp_max_key_cdr_typesize {0UL}; - constexpr uint32_t WeighingSystem_Voice_max_cdr_typesize {268UL}; constexpr uint32_t WeighingSystem_Voice_max_key_cdr_typesize {0UL}; @@ -72,9 +75,6 @@ constexpr uint32_t WeighingSystem_ScaleCommand_max_key_cdr_typesize {0UL}; constexpr uint32_t WeighingSystem_BarUpdate_max_cdr_typesize {12UL}; constexpr uint32_t WeighingSystem_BarUpdate_max_key_cdr_typesize {0UL}; -constexpr uint32_t InternalSystem_IoCtrlReq_max_cdr_typesize {16UL}; -constexpr uint32_t InternalSystem_IoCtrlReq_max_key_cdr_typesize {0UL}; - namespace eprosima { namespace fastcdr { @@ -136,23 +136,23 @@ eProsima_user_DllExport void serialize_key( eProsima_user_DllExport void serialize_key( eprosima::fastcdr::Cdr& scdr, - const InternalSystem::PrintReq& data); + const WeighingSystem::ReadCardReq& data); eProsima_user_DllExport void serialize_key( eprosima::fastcdr::Cdr& scdr, - const InternalSystem::PrintRsp& data); + const WeighingSystem::ReadCardRsp& data); eProsima_user_DllExport void serialize_key( eprosima::fastcdr::Cdr& scdr, - const InternalSystem::IoCtrlReq& data); + const WeighingSystem::PrintReq& data); eProsima_user_DllExport void serialize_key( eprosima::fastcdr::Cdr& scdr, - const InternalSystem::IoCtrlRsp& data); + const WeighingSystem::PrintRsp& data); } // namespace fastcdr } // namespace eprosima -#endif // FAST_DDS_GENERATED__INTERNALSYSTEM_SYSTEMCDRAUX_HPP +#endif // FAST_DDS_GENERATED__WEIGHINGSYSTEM_WEIGHINGDDSTYPECDRAUX_HPP diff --git a/lib/SystemCdrAux.ipp b/lib/WeighingDDSTypeCdrAux.ipp similarity index 95% rename from lib/SystemCdrAux.ipp rename to lib/WeighingDDSTypeCdrAux.ipp index 3318cf5..c0501f9 100644 --- a/lib/SystemCdrAux.ipp +++ b/lib/WeighingDDSTypeCdrAux.ipp @@ -13,16 +13,16 @@ // limitations under the License. /*! - * @file SystemCdrAux.ipp + * @file WeighingDDSTypeCdrAux.ipp * This source file contains some declarations of CDR related functions. * * This file was generated by the tool fastddsgen. */ -#ifndef FAST_DDS_GENERATED__INTERNALSYSTEM_SYSTEMCDRAUX_IPP -#define FAST_DDS_GENERATED__INTERNALSYSTEM_SYSTEMCDRAUX_IPP +#ifndef FAST_DDS_GENERATED__WEIGHINGSYSTEM_WEIGHINGDDSTYPECDRAUX_IPP +#define FAST_DDS_GENERATED__WEIGHINGSYSTEM_WEIGHINGDDSTYPECDRAUX_IPP -#include "SystemCdrAux.hpp" +#include "WeighingDDSTypeCdrAux.hpp" #include #include @@ -358,6 +358,18 @@ eProsima_user_DllExport size_t calculate_serialized_size( calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(27), data.IsPrintTicker(), current_alignment); + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(28), + data.OrderNumber(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(29), + data.VehicleAndVesselNumber(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(30), + data.ReceiveCompany(), current_alignment); + + calculated_size += calculator.calculate_member_serialized_size(eprosima::fastcdr::MemberId(31), + data.TransportCompany(), current_alignment); + calculated_size += calculator.end_calculate_type_serialized_size(previous_encoding, current_alignment); @@ -406,6 +418,10 @@ eProsima_user_DllExport void serialize( << eprosima::fastcdr::MemberId(25) << data.Tips() << eprosima::fastcdr::MemberId(26) << data.TicketType() << eprosima::fastcdr::MemberId(27) << data.IsPrintTicker() + << eprosima::fastcdr::MemberId(28) << data.OrderNumber() + << eprosima::fastcdr::MemberId(29) << data.VehicleAndVesselNumber() + << eprosima::fastcdr::MemberId(30) << data.ReceiveCompany() + << eprosima::fastcdr::MemberId(31) << data.TransportCompany() ; scdr.end_serialize_type(current_state); } @@ -537,6 +553,22 @@ eProsima_user_DllExport void deserialize( dcdr >> data.IsPrintTicker(); break; + case 28: + dcdr >> data.OrderNumber(); + break; + + case 29: + dcdr >> data.VehicleAndVesselNumber(); + break; + + case 30: + dcdr >> data.ReceiveCompany(); + break; + + case 31: + dcdr >> data.TransportCompany(); + break; + default: ret_value = false; break; @@ -609,6 +641,14 @@ void serialize_key( scdr << data.IsPrintTicker(); + scdr << data.OrderNumber(); + + scdr << data.VehicleAndVesselNumber(); + + scdr << data.ReceiveCompany(); + + scdr << data.TransportCompany(); + } @@ -1655,10 +1695,10 @@ void serialize_key( template<> eProsima_user_DllExport size_t calculate_serialized_size( eprosima::fastcdr::CdrSizeCalculator& calculator, - const InternalSystem::PrintReq& data, + const WeighingSystem::ReadCardReq& data, size_t& current_alignment) { - using namespace InternalSystem; + using namespace WeighingSystem; static_cast(data); @@ -1685,9 +1725,9 @@ eProsima_user_DllExport size_t calculate_serialized_size( template<> eProsima_user_DllExport void serialize( eprosima::fastcdr::Cdr& scdr, - const InternalSystem::PrintReq& data) + const WeighingSystem::ReadCardReq& data) { - using namespace InternalSystem; + using namespace WeighingSystem; eprosima::fastcdr::Cdr::state current_state(scdr); scdr.begin_serialize_type(current_state, @@ -1705,9 +1745,9 @@ eProsima_user_DllExport void serialize( template<> eProsima_user_DllExport void deserialize( eprosima::fastcdr::Cdr& cdr, - InternalSystem::PrintReq& data) + WeighingSystem::ReadCardReq& data) { - using namespace InternalSystem; + using namespace WeighingSystem; cdr.deserialize_type(eprosima::fastcdr::CdrVersion::XCDRv2 == cdr.get_cdr_version() ? eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : @@ -1735,9 +1775,9 @@ eProsima_user_DllExport void deserialize( void serialize_key( eprosima::fastcdr::Cdr& scdr, - const InternalSystem::PrintReq& data) + const WeighingSystem::ReadCardReq& data) { - using namespace InternalSystem; + using namespace WeighingSystem; static_cast(scdr); static_cast(data); @@ -1751,10 +1791,10 @@ void serialize_key( template<> eProsima_user_DllExport size_t calculate_serialized_size( eprosima::fastcdr::CdrSizeCalculator& calculator, - const InternalSystem::PrintRsp& data, + const WeighingSystem::ReadCardRsp& data, size_t& current_alignment) { - using namespace InternalSystem; + using namespace WeighingSystem; static_cast(data); @@ -1781,9 +1821,9 @@ eProsima_user_DllExport size_t calculate_serialized_size( template<> eProsima_user_DllExport void serialize( eprosima::fastcdr::Cdr& scdr, - const InternalSystem::PrintRsp& data) + const WeighingSystem::ReadCardRsp& data) { - using namespace InternalSystem; + using namespace WeighingSystem; eprosima::fastcdr::Cdr::state current_state(scdr); scdr.begin_serialize_type(current_state, @@ -1801,9 +1841,9 @@ eProsima_user_DllExport void serialize( template<> eProsima_user_DllExport void deserialize( eprosima::fastcdr::Cdr& cdr, - InternalSystem::PrintRsp& data) + WeighingSystem::ReadCardRsp& data) { - using namespace InternalSystem; + using namespace WeighingSystem; cdr.deserialize_type(eprosima::fastcdr::CdrVersion::XCDRv2 == cdr.get_cdr_version() ? eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : @@ -1831,9 +1871,9 @@ eProsima_user_DllExport void deserialize( void serialize_key( eprosima::fastcdr::Cdr& scdr, - const InternalSystem::PrintRsp& data) + const WeighingSystem::ReadCardRsp& data) { - using namespace InternalSystem; + using namespace WeighingSystem; static_cast(scdr); static_cast(data); @@ -1847,10 +1887,10 @@ void serialize_key( template<> eProsima_user_DllExport size_t calculate_serialized_size( eprosima::fastcdr::CdrSizeCalculator& calculator, - const InternalSystem::IoCtrlReq& data, + const WeighingSystem::PrintReq& data, size_t& current_alignment) { - using namespace InternalSystem; + using namespace WeighingSystem; static_cast(data); @@ -1877,9 +1917,9 @@ eProsima_user_DllExport size_t calculate_serialized_size( template<> eProsima_user_DllExport void serialize( eprosima::fastcdr::Cdr& scdr, - const InternalSystem::IoCtrlReq& data) + const WeighingSystem::PrintReq& data) { - using namespace InternalSystem; + using namespace WeighingSystem; eprosima::fastcdr::Cdr::state current_state(scdr); scdr.begin_serialize_type(current_state, @@ -1897,9 +1937,9 @@ eProsima_user_DllExport void serialize( template<> eProsima_user_DllExport void deserialize( eprosima::fastcdr::Cdr& cdr, - InternalSystem::IoCtrlReq& data) + WeighingSystem::PrintReq& data) { - using namespace InternalSystem; + using namespace WeighingSystem; cdr.deserialize_type(eprosima::fastcdr::CdrVersion::XCDRv2 == cdr.get_cdr_version() ? eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : @@ -1927,9 +1967,9 @@ eProsima_user_DllExport void deserialize( void serialize_key( eprosima::fastcdr::Cdr& scdr, - const InternalSystem::IoCtrlReq& data) + const WeighingSystem::PrintReq& data) { - using namespace InternalSystem; + using namespace WeighingSystem; static_cast(scdr); static_cast(data); @@ -1943,10 +1983,10 @@ void serialize_key( template<> eProsima_user_DllExport size_t calculate_serialized_size( eprosima::fastcdr::CdrSizeCalculator& calculator, - const InternalSystem::IoCtrlRsp& data, + const WeighingSystem::PrintRsp& data, size_t& current_alignment) { - using namespace InternalSystem; + using namespace WeighingSystem; static_cast(data); @@ -1973,9 +2013,9 @@ eProsima_user_DllExport size_t calculate_serialized_size( template<> eProsima_user_DllExport void serialize( eprosima::fastcdr::Cdr& scdr, - const InternalSystem::IoCtrlRsp& data) + const WeighingSystem::PrintRsp& data) { - using namespace InternalSystem; + using namespace WeighingSystem; eprosima::fastcdr::Cdr::state current_state(scdr); scdr.begin_serialize_type(current_state, @@ -1993,9 +2033,9 @@ eProsima_user_DllExport void serialize( template<> eProsima_user_DllExport void deserialize( eprosima::fastcdr::Cdr& cdr, - InternalSystem::IoCtrlRsp& data) + WeighingSystem::PrintRsp& data) { - using namespace InternalSystem; + using namespace WeighingSystem; cdr.deserialize_type(eprosima::fastcdr::CdrVersion::XCDRv2 == cdr.get_cdr_version() ? eprosima::fastcdr::EncodingAlgorithmFlag::DELIMIT_CDR2 : @@ -2023,9 +2063,9 @@ eProsima_user_DllExport void deserialize( void serialize_key( eprosima::fastcdr::Cdr& scdr, - const InternalSystem::IoCtrlRsp& data) + const WeighingSystem::PrintRsp& data) { - using namespace InternalSystem; + using namespace WeighingSystem; static_cast(scdr); static_cast(data); @@ -2040,5 +2080,5 @@ void serialize_key( } // namespace fastcdr } // namespace eprosima -#endif // FAST_DDS_GENERATED__INTERNALSYSTEM_SYSTEMCDRAUX_IPP +#endif // FAST_DDS_GENERATED__WEIGHINGSYSTEM_WEIGHINGDDSTYPECDRAUX_IPP diff --git a/lib/SystemPubSubTypes.cxx b/lib/WeighingDDSTypePubSubTypes.cxx similarity index 96% rename from lib/SystemPubSubTypes.cxx rename to lib/WeighingDDSTypePubSubTypes.cxx index e74e590..daa30ad 100644 --- a/lib/SystemPubSubTypes.cxx +++ b/lib/WeighingDDSTypePubSubTypes.cxx @@ -13,19 +13,19 @@ // limitations under the License. /*! - * @file SystemPubSubTypes.cpp + * @file WeighingDDSTypePubSubTypes.cpp * This header file contains the implementation of the serialization functions. * * This file was generated by the tool fastddsgen. */ -#include "SystemPubSubTypes.hpp" +#include "WeighingDDSTypePubSubTypes.hpp" #include #include -#include "SystemCdrAux.hpp" -#include "SystemTypeObjectSupport.hpp" +#include "WeighingDDSTypeCdrAux.hpp" +#include "WeighingDDSTypeTypeObjectSupport.hpp" using SerializedPayload_t = eprosima::fastdds::rtps::SerializedPayload_t; using InstanceHandle_t = eprosima::fastdds::rtps::InstanceHandle_t; @@ -2398,22 +2398,19 @@ namespace WeighingSystem { register_SummaryUpdate_type_identifier(type_identifiers_); } -} // namespace WeighingSystem - -namespace InternalSystem { - PrintReqPubSubType::PrintReqPubSubType() + ReadCardReqPubSubType::ReadCardReqPubSubType() { - set_name("InternalSystem::PrintReq"); - uint32_t type_size = InternalSystem_PrintReq_max_cdr_typesize; + set_name("WeighingSystem::ReadCardReq"); + uint32_t type_size = WeighingSystem_ReadCardReq_max_cdr_typesize; type_size += static_cast(eprosima::fastcdr::Cdr::alignment(type_size, 4)); /* possible submessage alignment */ max_serialized_type_size = type_size + 4; /*encapsulation*/ is_compute_key_provided = false; - uint32_t key_length = InternalSystem_PrintReq_max_key_cdr_typesize > 16 ? InternalSystem_PrintReq_max_key_cdr_typesize : 16; + uint32_t key_length = WeighingSystem_ReadCardReq_max_key_cdr_typesize > 16 ? WeighingSystem_ReadCardReq_max_key_cdr_typesize : 16; key_buffer_ = reinterpret_cast(malloc(key_length)); memset(key_buffer_, 0, key_length); } - PrintReqPubSubType::~PrintReqPubSubType() + ReadCardReqPubSubType::~ReadCardReqPubSubType() { if (key_buffer_ != nullptr) { @@ -2421,12 +2418,12 @@ namespace InternalSystem { } } - bool PrintReqPubSubType::serialize( + bool ReadCardReqPubSubType::serialize( const void* const data, SerializedPayload_t& payload, DataRepresentationId_t data_representation) { - const PrintReq* p_type = static_cast(data); + const ReadCardReq* p_type = static_cast(data); // Object that manages the raw buffer. eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(payload.data), payload.max_size); @@ -2458,14 +2455,14 @@ namespace InternalSystem { return true; } - bool PrintReqPubSubType::deserialize( + bool ReadCardReqPubSubType::deserialize( SerializedPayload_t& payload, void* data) { try { // Convert DATA to pointer of your type - PrintReq* p_type = static_cast(data); + ReadCardReq* p_type = static_cast(data); // Object that manages the raw buffer. eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(payload.data), payload.length); @@ -2488,7 +2485,7 @@ namespace InternalSystem { return true; } - uint32_t PrintReqPubSubType::calculate_serialized_size( + uint32_t ReadCardReqPubSubType::calculate_serialized_size( const void* const data, DataRepresentationId_t data_representation) { @@ -2499,7 +2496,7 @@ namespace InternalSystem { eprosima::fastcdr::CdrVersion::XCDRv1 :eprosima::fastcdr::CdrVersion::XCDRv2); size_t current_alignment {0}; return static_cast(calculator.calculate_serialized_size( - *static_cast(data), current_alignment)) + + *static_cast(data), current_alignment)) + 4u /*encapsulation*/; } catch (eprosima::fastcdr::exception::Exception& /*exception*/) @@ -2508,18 +2505,18 @@ namespace InternalSystem { } } - void* PrintReqPubSubType::create_data() + void* ReadCardReqPubSubType::create_data() { - return reinterpret_cast(new PrintReq()); + return reinterpret_cast(new ReadCardReq()); } - void PrintReqPubSubType::delete_data( + void ReadCardReqPubSubType::delete_data( void* data) { - delete(reinterpret_cast(data)); + delete(reinterpret_cast(data)); } - bool PrintReqPubSubType::compute_key( + bool ReadCardReqPubSubType::compute_key( SerializedPayload_t& payload, InstanceHandle_t& handle, bool force_md5) @@ -2529,7 +2526,7 @@ namespace InternalSystem { return false; } - PrintReq data; + ReadCardReq data; if (deserialize(payload, static_cast(&data))) { return compute_key(static_cast(&data), handle, force_md5); @@ -2538,7 +2535,7 @@ namespace InternalSystem { return false; } - bool PrintReqPubSubType::compute_key( + bool ReadCardReqPubSubType::compute_key( const void* const data, InstanceHandle_t& handle, bool force_md5) @@ -2548,17 +2545,17 @@ namespace InternalSystem { return false; } - const PrintReq* p_type = static_cast(data); + const ReadCardReq* p_type = static_cast(data); // Object that manages the raw buffer. eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(key_buffer_), - InternalSystem_PrintReq_max_key_cdr_typesize); + WeighingSystem_ReadCardReq_max_key_cdr_typesize); // Object that serializes the data. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS, eprosima::fastcdr::CdrVersion::XCDRv2); ser.set_encoding_flag(eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR2); eprosima::fastcdr::serialize_key(ser, *p_type); - if (force_md5 || InternalSystem_PrintReq_max_key_cdr_typesize > 16) + if (force_md5 || WeighingSystem_ReadCardReq_max_key_cdr_typesize > 16) { md5_.init(); md5_.update(key_buffer_, static_cast(ser.get_serialized_data_length())); @@ -2578,24 +2575,24 @@ namespace InternalSystem { return true; } - void PrintReqPubSubType::register_type_object_representation() + void ReadCardReqPubSubType::register_type_object_representation() { - register_PrintReq_type_identifier(type_identifiers_); + register_ReadCardReq_type_identifier(type_identifiers_); } - PrintRspPubSubType::PrintRspPubSubType() + ReadCardRspPubSubType::ReadCardRspPubSubType() { - set_name("InternalSystem::PrintRsp"); - uint32_t type_size = InternalSystem_PrintRsp_max_cdr_typesize; + set_name("WeighingSystem::ReadCardRsp"); + uint32_t type_size = WeighingSystem_ReadCardRsp_max_cdr_typesize; type_size += static_cast(eprosima::fastcdr::Cdr::alignment(type_size, 4)); /* possible submessage alignment */ max_serialized_type_size = type_size + 4; /*encapsulation*/ is_compute_key_provided = false; - uint32_t key_length = InternalSystem_PrintRsp_max_key_cdr_typesize > 16 ? InternalSystem_PrintRsp_max_key_cdr_typesize : 16; + uint32_t key_length = WeighingSystem_ReadCardRsp_max_key_cdr_typesize > 16 ? WeighingSystem_ReadCardRsp_max_key_cdr_typesize : 16; key_buffer_ = reinterpret_cast(malloc(key_length)); memset(key_buffer_, 0, key_length); } - PrintRspPubSubType::~PrintRspPubSubType() + ReadCardRspPubSubType::~ReadCardRspPubSubType() { if (key_buffer_ != nullptr) { @@ -2603,12 +2600,12 @@ namespace InternalSystem { } } - bool PrintRspPubSubType::serialize( + bool ReadCardRspPubSubType::serialize( const void* const data, SerializedPayload_t& payload, DataRepresentationId_t data_representation) { - const PrintRsp* p_type = static_cast(data); + const ReadCardRsp* p_type = static_cast(data); // Object that manages the raw buffer. eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(payload.data), payload.max_size); @@ -2640,14 +2637,14 @@ namespace InternalSystem { return true; } - bool PrintRspPubSubType::deserialize( + bool ReadCardRspPubSubType::deserialize( SerializedPayload_t& payload, void* data) { try { // Convert DATA to pointer of your type - PrintRsp* p_type = static_cast(data); + ReadCardRsp* p_type = static_cast(data); // Object that manages the raw buffer. eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(payload.data), payload.length); @@ -2670,7 +2667,7 @@ namespace InternalSystem { return true; } - uint32_t PrintRspPubSubType::calculate_serialized_size( + uint32_t ReadCardRspPubSubType::calculate_serialized_size( const void* const data, DataRepresentationId_t data_representation) { @@ -2681,7 +2678,7 @@ namespace InternalSystem { eprosima::fastcdr::CdrVersion::XCDRv1 :eprosima::fastcdr::CdrVersion::XCDRv2); size_t current_alignment {0}; return static_cast(calculator.calculate_serialized_size( - *static_cast(data), current_alignment)) + + *static_cast(data), current_alignment)) + 4u /*encapsulation*/; } catch (eprosima::fastcdr::exception::Exception& /*exception*/) @@ -2690,18 +2687,18 @@ namespace InternalSystem { } } - void* PrintRspPubSubType::create_data() + void* ReadCardRspPubSubType::create_data() { - return reinterpret_cast(new PrintRsp()); + return reinterpret_cast(new ReadCardRsp()); } - void PrintRspPubSubType::delete_data( + void ReadCardRspPubSubType::delete_data( void* data) { - delete(reinterpret_cast(data)); + delete(reinterpret_cast(data)); } - bool PrintRspPubSubType::compute_key( + bool ReadCardRspPubSubType::compute_key( SerializedPayload_t& payload, InstanceHandle_t& handle, bool force_md5) @@ -2711,7 +2708,7 @@ namespace InternalSystem { return false; } - PrintRsp data; + ReadCardRsp data; if (deserialize(payload, static_cast(&data))) { return compute_key(static_cast(&data), handle, force_md5); @@ -2720,7 +2717,7 @@ namespace InternalSystem { return false; } - bool PrintRspPubSubType::compute_key( + bool ReadCardRspPubSubType::compute_key( const void* const data, InstanceHandle_t& handle, bool force_md5) @@ -2730,17 +2727,17 @@ namespace InternalSystem { return false; } - const PrintRsp* p_type = static_cast(data); + const ReadCardRsp* p_type = static_cast(data); // Object that manages the raw buffer. eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(key_buffer_), - InternalSystem_PrintRsp_max_key_cdr_typesize); + WeighingSystem_ReadCardRsp_max_key_cdr_typesize); // Object that serializes the data. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS, eprosima::fastcdr::CdrVersion::XCDRv2); ser.set_encoding_flag(eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR2); eprosima::fastcdr::serialize_key(ser, *p_type); - if (force_md5 || InternalSystem_PrintRsp_max_key_cdr_typesize > 16) + if (force_md5 || WeighingSystem_ReadCardRsp_max_key_cdr_typesize > 16) { md5_.init(); md5_.update(key_buffer_, static_cast(ser.get_serialized_data_length())); @@ -2760,24 +2757,24 @@ namespace InternalSystem { return true; } - void PrintRspPubSubType::register_type_object_representation() + void ReadCardRspPubSubType::register_type_object_representation() { - register_PrintRsp_type_identifier(type_identifiers_); + register_ReadCardRsp_type_identifier(type_identifiers_); } - IoCtrlReqPubSubType::IoCtrlReqPubSubType() + PrintReqPubSubType::PrintReqPubSubType() { - set_name("InternalSystem::IoCtrlReq"); - uint32_t type_size = InternalSystem_IoCtrlReq_max_cdr_typesize; + set_name("WeighingSystem::PrintReq"); + uint32_t type_size = WeighingSystem_PrintReq_max_cdr_typesize; type_size += static_cast(eprosima::fastcdr::Cdr::alignment(type_size, 4)); /* possible submessage alignment */ max_serialized_type_size = type_size + 4; /*encapsulation*/ is_compute_key_provided = false; - uint32_t key_length = InternalSystem_IoCtrlReq_max_key_cdr_typesize > 16 ? InternalSystem_IoCtrlReq_max_key_cdr_typesize : 16; + uint32_t key_length = WeighingSystem_PrintReq_max_key_cdr_typesize > 16 ? WeighingSystem_PrintReq_max_key_cdr_typesize : 16; key_buffer_ = reinterpret_cast(malloc(key_length)); memset(key_buffer_, 0, key_length); } - IoCtrlReqPubSubType::~IoCtrlReqPubSubType() + PrintReqPubSubType::~PrintReqPubSubType() { if (key_buffer_ != nullptr) { @@ -2785,12 +2782,12 @@ namespace InternalSystem { } } - bool IoCtrlReqPubSubType::serialize( + bool PrintReqPubSubType::serialize( const void* const data, SerializedPayload_t& payload, DataRepresentationId_t data_representation) { - const IoCtrlReq* p_type = static_cast(data); + const PrintReq* p_type = static_cast(data); // Object that manages the raw buffer. eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(payload.data), payload.max_size); @@ -2822,14 +2819,14 @@ namespace InternalSystem { return true; } - bool IoCtrlReqPubSubType::deserialize( + bool PrintReqPubSubType::deserialize( SerializedPayload_t& payload, void* data) { try { // Convert DATA to pointer of your type - IoCtrlReq* p_type = static_cast(data); + PrintReq* p_type = static_cast(data); // Object that manages the raw buffer. eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(payload.data), payload.length); @@ -2852,7 +2849,7 @@ namespace InternalSystem { return true; } - uint32_t IoCtrlReqPubSubType::calculate_serialized_size( + uint32_t PrintReqPubSubType::calculate_serialized_size( const void* const data, DataRepresentationId_t data_representation) { @@ -2863,7 +2860,7 @@ namespace InternalSystem { eprosima::fastcdr::CdrVersion::XCDRv1 :eprosima::fastcdr::CdrVersion::XCDRv2); size_t current_alignment {0}; return static_cast(calculator.calculate_serialized_size( - *static_cast(data), current_alignment)) + + *static_cast(data), current_alignment)) + 4u /*encapsulation*/; } catch (eprosima::fastcdr::exception::Exception& /*exception*/) @@ -2872,18 +2869,18 @@ namespace InternalSystem { } } - void* IoCtrlReqPubSubType::create_data() + void* PrintReqPubSubType::create_data() { - return reinterpret_cast(new IoCtrlReq()); + return reinterpret_cast(new PrintReq()); } - void IoCtrlReqPubSubType::delete_data( + void PrintReqPubSubType::delete_data( void* data) { - delete(reinterpret_cast(data)); + delete(reinterpret_cast(data)); } - bool IoCtrlReqPubSubType::compute_key( + bool PrintReqPubSubType::compute_key( SerializedPayload_t& payload, InstanceHandle_t& handle, bool force_md5) @@ -2893,7 +2890,7 @@ namespace InternalSystem { return false; } - IoCtrlReq data; + PrintReq data; if (deserialize(payload, static_cast(&data))) { return compute_key(static_cast(&data), handle, force_md5); @@ -2902,7 +2899,7 @@ namespace InternalSystem { return false; } - bool IoCtrlReqPubSubType::compute_key( + bool PrintReqPubSubType::compute_key( const void* const data, InstanceHandle_t& handle, bool force_md5) @@ -2912,17 +2909,17 @@ namespace InternalSystem { return false; } - const IoCtrlReq* p_type = static_cast(data); + const PrintReq* p_type = static_cast(data); // Object that manages the raw buffer. eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(key_buffer_), - InternalSystem_IoCtrlReq_max_key_cdr_typesize); + WeighingSystem_PrintReq_max_key_cdr_typesize); // Object that serializes the data. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS, eprosima::fastcdr::CdrVersion::XCDRv2); ser.set_encoding_flag(eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR2); eprosima::fastcdr::serialize_key(ser, *p_type); - if (force_md5 || InternalSystem_IoCtrlReq_max_key_cdr_typesize > 16) + if (force_md5 || WeighingSystem_PrintReq_max_key_cdr_typesize > 16) { md5_.init(); md5_.update(key_buffer_, static_cast(ser.get_serialized_data_length())); @@ -2942,24 +2939,24 @@ namespace InternalSystem { return true; } - void IoCtrlReqPubSubType::register_type_object_representation() + void PrintReqPubSubType::register_type_object_representation() { - register_IoCtrlReq_type_identifier(type_identifiers_); + register_PrintReq_type_identifier(type_identifiers_); } - IoCtrlRspPubSubType::IoCtrlRspPubSubType() + PrintRspPubSubType::PrintRspPubSubType() { - set_name("InternalSystem::IoCtrlRsp"); - uint32_t type_size = InternalSystem_IoCtrlRsp_max_cdr_typesize; + set_name("WeighingSystem::PrintRsp"); + uint32_t type_size = WeighingSystem_PrintRsp_max_cdr_typesize; type_size += static_cast(eprosima::fastcdr::Cdr::alignment(type_size, 4)); /* possible submessage alignment */ max_serialized_type_size = type_size + 4; /*encapsulation*/ is_compute_key_provided = false; - uint32_t key_length = InternalSystem_IoCtrlRsp_max_key_cdr_typesize > 16 ? InternalSystem_IoCtrlRsp_max_key_cdr_typesize : 16; + uint32_t key_length = WeighingSystem_PrintRsp_max_key_cdr_typesize > 16 ? WeighingSystem_PrintRsp_max_key_cdr_typesize : 16; key_buffer_ = reinterpret_cast(malloc(key_length)); memset(key_buffer_, 0, key_length); } - IoCtrlRspPubSubType::~IoCtrlRspPubSubType() + PrintRspPubSubType::~PrintRspPubSubType() { if (key_buffer_ != nullptr) { @@ -2967,12 +2964,12 @@ namespace InternalSystem { } } - bool IoCtrlRspPubSubType::serialize( + bool PrintRspPubSubType::serialize( const void* const data, SerializedPayload_t& payload, DataRepresentationId_t data_representation) { - const IoCtrlRsp* p_type = static_cast(data); + const PrintRsp* p_type = static_cast(data); // Object that manages the raw buffer. eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(payload.data), payload.max_size); @@ -3004,14 +3001,14 @@ namespace InternalSystem { return true; } - bool IoCtrlRspPubSubType::deserialize( + bool PrintRspPubSubType::deserialize( SerializedPayload_t& payload, void* data) { try { // Convert DATA to pointer of your type - IoCtrlRsp* p_type = static_cast(data); + PrintRsp* p_type = static_cast(data); // Object that manages the raw buffer. eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(payload.data), payload.length); @@ -3034,7 +3031,7 @@ namespace InternalSystem { return true; } - uint32_t IoCtrlRspPubSubType::calculate_serialized_size( + uint32_t PrintRspPubSubType::calculate_serialized_size( const void* const data, DataRepresentationId_t data_representation) { @@ -3045,7 +3042,7 @@ namespace InternalSystem { eprosima::fastcdr::CdrVersion::XCDRv1 :eprosima::fastcdr::CdrVersion::XCDRv2); size_t current_alignment {0}; return static_cast(calculator.calculate_serialized_size( - *static_cast(data), current_alignment)) + + *static_cast(data), current_alignment)) + 4u /*encapsulation*/; } catch (eprosima::fastcdr::exception::Exception& /*exception*/) @@ -3054,18 +3051,18 @@ namespace InternalSystem { } } - void* IoCtrlRspPubSubType::create_data() + void* PrintRspPubSubType::create_data() { - return reinterpret_cast(new IoCtrlRsp()); + return reinterpret_cast(new PrintRsp()); } - void IoCtrlRspPubSubType::delete_data( + void PrintRspPubSubType::delete_data( void* data) { - delete(reinterpret_cast(data)); + delete(reinterpret_cast(data)); } - bool IoCtrlRspPubSubType::compute_key( + bool PrintRspPubSubType::compute_key( SerializedPayload_t& payload, InstanceHandle_t& handle, bool force_md5) @@ -3075,7 +3072,7 @@ namespace InternalSystem { return false; } - IoCtrlRsp data; + PrintRsp data; if (deserialize(payload, static_cast(&data))) { return compute_key(static_cast(&data), handle, force_md5); @@ -3084,7 +3081,7 @@ namespace InternalSystem { return false; } - bool IoCtrlRspPubSubType::compute_key( + bool PrintRspPubSubType::compute_key( const void* const data, InstanceHandle_t& handle, bool force_md5) @@ -3094,17 +3091,17 @@ namespace InternalSystem { return false; } - const IoCtrlRsp* p_type = static_cast(data); + const PrintRsp* p_type = static_cast(data); // Object that manages the raw buffer. eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(key_buffer_), - InternalSystem_IoCtrlRsp_max_key_cdr_typesize); + WeighingSystem_PrintRsp_max_key_cdr_typesize); // Object that serializes the data. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS, eprosima::fastcdr::CdrVersion::XCDRv2); ser.set_encoding_flag(eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR2); eprosima::fastcdr::serialize_key(ser, *p_type); - if (force_md5 || InternalSystem_IoCtrlRsp_max_key_cdr_typesize > 16) + if (force_md5 || WeighingSystem_PrintRsp_max_key_cdr_typesize > 16) { md5_.init(); md5_.update(key_buffer_, static_cast(ser.get_serialized_data_length())); @@ -3124,13 +3121,13 @@ namespace InternalSystem { return true; } - void IoCtrlRspPubSubType::register_type_object_representation() + void PrintRspPubSubType::register_type_object_representation() { - register_IoCtrlRsp_type_identifier(type_identifiers_); + register_PrintRsp_type_identifier(type_identifiers_); } -} // namespace InternalSystem +} // namespace WeighingSystem // Include auxiliary functions like for serializing/deserializing. -#include "SystemCdrAux.ipp" +#include "WeighingDDSTypeCdrAux.ipp" diff --git a/lib/SystemPubSubTypes.hpp b/lib/WeighingDDSTypePubSubTypes.hpp similarity index 96% rename from lib/SystemPubSubTypes.hpp rename to lib/WeighingDDSTypePubSubTypes.hpp index b0e4835..13a399d 100644 --- a/lib/SystemPubSubTypes.hpp +++ b/lib/WeighingDDSTypePubSubTypes.hpp @@ -13,15 +13,15 @@ // limitations under the License. /*! - * @file SystemPubSubTypes.hpp + * @file WeighingDDSTypePubSubTypes.hpp * This header file contains the declaration of the serialization functions. * * This file was generated by the tool fastddsgen. */ -#ifndef FAST_DDS_GENERATED__INTERNALSYSTEM_SYSTEM_PUBSUBTYPES_HPP -#define FAST_DDS_GENERATED__INTERNALSYSTEM_SYSTEM_PUBSUBTYPES_HPP +#ifndef FAST_DDS_GENERATED__WEIGHINGSYSTEM_WEIGHINGDDSTYPE_PUBSUBTYPES_HPP +#define FAST_DDS_GENERATED__WEIGHINGSYSTEM_WEIGHINGDDSTYPE_PUBSUBTYPES_HPP #include #include @@ -29,12 +29,12 @@ #include #include -#include "System.hpp" +#include "WeighingDDSType.hpp" #if !defined(FASTDDS_GEN_API_VER) || (FASTDDS_GEN_API_VER != 3) #error \ - Generated System is not compatible with current installed Fast DDS. Please, regenerate it with fastddsgen. + Generated WeighingDDSType is not compatible with current installed Fast DDS. Please, regenerate it with fastddsgen. #endif // FASTDDS_GEN_API_VER namespace WeighingSystem @@ -42,7 +42,7 @@ namespace WeighingSystem /*! * @brief This class represents the TopicDataType of the type ScaleInfo defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class ScaleInfoPubSubType : public eprosima::fastdds::dds::TopicDataType { @@ -123,7 +123,7 @@ namespace WeighingSystem /*! * @brief This class represents the TopicDataType of the type ScaleCommand defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class ScaleCommandPubSubType : public eprosima::fastdds::dds::TopicDataType { @@ -204,7 +204,7 @@ namespace WeighingSystem /*! * @brief This class represents the TopicDataType of the type WeightInfoOk defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class WeightInfoOkPubSubType : public eprosima::fastdds::dds::TopicDataType { @@ -285,7 +285,7 @@ namespace WeighingSystem /*! * @brief This class represents the TopicDataType of the type WeightInfoError defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class WeightInfoErrorPubSubType : public eprosima::fastdds::dds::TopicDataType { @@ -366,7 +366,7 @@ namespace WeighingSystem /*! * @brief This class represents the TopicDataType of the type BarCommandUpdate defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class BarCommandUpdatePubSubType : public eprosima::fastdds::dds::TopicDataType { @@ -447,7 +447,7 @@ namespace WeighingSystem /*! * @brief This class represents the TopicDataType of the type LightsCommandUpdate defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class LightsCommandUpdatePubSubType : public eprosima::fastdds::dds::TopicDataType { @@ -528,7 +528,7 @@ namespace WeighingSystem /*! * @brief This class represents the TopicDataType of the type InfraredCommandUpdate defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class InfraredCommandUpdatePubSubType : public eprosima::fastdds::dds::TopicDataType { @@ -609,7 +609,7 @@ namespace WeighingSystem /*! * @brief This class represents the TopicDataType of the type BarUpdate defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class BarUpdatePubSubType : public eprosima::fastdds::dds::TopicDataType { @@ -690,7 +690,7 @@ namespace WeighingSystem /*! * @brief This class represents the TopicDataType of the type LightsUpdate defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class LightsUpdatePubSubType : public eprosima::fastdds::dds::TopicDataType { @@ -771,7 +771,7 @@ namespace WeighingSystem /*! * @brief This class represents the TopicDataType of the type InfraredUpdate defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class InfraredUpdatePubSubType : public eprosima::fastdds::dds::TopicDataType { @@ -852,7 +852,7 @@ namespace WeighingSystem /*! * @brief This class represents the TopicDataType of the type LicenseSnapUpdate defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class LicenseSnapUpdatePubSubType : public eprosima::fastdds::dds::TopicDataType { @@ -933,7 +933,7 @@ namespace WeighingSystem /*! * @brief This class represents the TopicDataType of the type Voice defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class VoicePubSubType : public eprosima::fastdds::dds::TopicDataType { @@ -1014,7 +1014,7 @@ namespace WeighingSystem /*! * @brief This class represents the TopicDataType of the type SummaryUpdate defined by the user in the IDL file. - * @ingroup System + * @ingroup WeighingDDSType */ class SummaryUpdatePubSubType : public eprosima::fastdds::dds::TopicDataType { @@ -1092,23 +1092,20 @@ namespace WeighingSystem unsigned char* key_buffer_; }; -} // namespace WeighingSystem -namespace InternalSystem -{ /*! - * @brief This class represents the TopicDataType of the type PrintReq defined by the user in the IDL file. - * @ingroup System + * @brief This class represents the TopicDataType of the type ReadCardReq defined by the user in the IDL file. + * @ingroup WeighingDDSType */ - class PrintReqPubSubType : public eprosima::fastdds::dds::TopicDataType + class ReadCardReqPubSubType : public eprosima::fastdds::dds::TopicDataType { public: - typedef PrintReq type; + typedef ReadCardReq type; - eProsima_user_DllExport PrintReqPubSubType(); + eProsima_user_DllExport ReadCardReqPubSubType(); - eProsima_user_DllExport ~PrintReqPubSubType() override; + eProsima_user_DllExport ~ReadCardReqPubSubType() override; eProsima_user_DllExport bool serialize( const void* const data, @@ -1178,18 +1175,18 @@ namespace InternalSystem }; /*! - * @brief This class represents the TopicDataType of the type PrintRsp defined by the user in the IDL file. - * @ingroup System + * @brief This class represents the TopicDataType of the type ReadCardRsp defined by the user in the IDL file. + * @ingroup WeighingDDSType */ - class PrintRspPubSubType : public eprosima::fastdds::dds::TopicDataType + class ReadCardRspPubSubType : public eprosima::fastdds::dds::TopicDataType { public: - typedef PrintRsp type; + typedef ReadCardRsp type; - eProsima_user_DllExport PrintRspPubSubType(); + eProsima_user_DllExport ReadCardRspPubSubType(); - eProsima_user_DllExport ~PrintRspPubSubType() override; + eProsima_user_DllExport ~ReadCardRspPubSubType() override; eProsima_user_DllExport bool serialize( const void* const data, @@ -1259,18 +1256,18 @@ namespace InternalSystem }; /*! - * @brief This class represents the TopicDataType of the type IoCtrlReq defined by the user in the IDL file. - * @ingroup System + * @brief This class represents the TopicDataType of the type PrintReq defined by the user in the IDL file. + * @ingroup WeighingDDSType */ - class IoCtrlReqPubSubType : public eprosima::fastdds::dds::TopicDataType + class PrintReqPubSubType : public eprosima::fastdds::dds::TopicDataType { public: - typedef IoCtrlReq type; + typedef PrintReq type; - eProsima_user_DllExport IoCtrlReqPubSubType(); + eProsima_user_DllExport PrintReqPubSubType(); - eProsima_user_DllExport ~IoCtrlReqPubSubType() override; + eProsima_user_DllExport ~PrintReqPubSubType() override; eProsima_user_DllExport bool serialize( const void* const data, @@ -1340,18 +1337,18 @@ namespace InternalSystem }; /*! - * @brief This class represents the TopicDataType of the type IoCtrlRsp defined by the user in the IDL file. - * @ingroup System + * @brief This class represents the TopicDataType of the type PrintRsp defined by the user in the IDL file. + * @ingroup WeighingDDSType */ - class IoCtrlRspPubSubType : public eprosima::fastdds::dds::TopicDataType + class PrintRspPubSubType : public eprosima::fastdds::dds::TopicDataType { public: - typedef IoCtrlRsp type; + typedef PrintRsp type; - eProsima_user_DllExport IoCtrlRspPubSubType(); + eProsima_user_DllExport PrintRspPubSubType(); - eProsima_user_DllExport ~IoCtrlRspPubSubType() override; + eProsima_user_DllExport ~PrintRspPubSubType() override; eProsima_user_DllExport bool serialize( const void* const data, @@ -1419,7 +1416,7 @@ namespace InternalSystem unsigned char* key_buffer_; }; -} // namespace InternalSystem +} // namespace WeighingSystem -#endif // FAST_DDS_GENERATED__INTERNALSYSTEM_SYSTEM_PUBSUBTYPES_HPP +#endif // FAST_DDS_GENERATED__WEIGHINGSYSTEM_WEIGHINGDDSTYPE_PUBSUBTYPES_HPP diff --git a/lib/SystemTypeObjectSupport.cxx b/lib/WeighingDDSTypeTypeObjectSupport.cxx similarity index 88% rename from lib/SystemTypeObjectSupport.cxx rename to lib/WeighingDDSTypeTypeObjectSupport.cxx index 0d8984d..56ee6c9 100644 --- a/lib/SystemTypeObjectSupport.cxx +++ b/lib/WeighingDDSTypeTypeObjectSupport.cxx @@ -13,13 +13,13 @@ // limitations under the License. /*! - * @file SystemTypeObjectSupport.cxx + * @file WeighingDDSTypeTypeObjectSupport.cxx * Source file containing the implementation to register the TypeObject representation of the described types in the IDL file * * This file was generated by the tool fastddsgen. */ -#include "SystemTypeObjectSupport.hpp" +#include "WeighingDDSTypeTypeObjectSupport.hpp" #include #include @@ -33,7 +33,7 @@ #include #include -#include "System.hpp" +#include "WeighingDDSType.hpp" using namespace eprosima::fastdds::dds::xtypes; @@ -1319,6 +1319,158 @@ void register_WeightInfoOk_type_identifier( CompleteStructMember member_IsPrintTicker = TypeObjectUtils::build_complete_struct_member(common_IsPrintTicker, detail_IsPrintTicker); TypeObjectUtils::add_complete_struct_member(member_seq_WeightInfoOk, member_IsPrintTicker); } + { + TypeIdentifierPair type_ids_OrderNumber; + ReturnCode_t return_code_OrderNumber {eprosima::fastdds::dds::RETCODE_OK}; + return_code_OrderNumber = + eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->type_object_registry().get_type_identifiers( + "anonymous_string_unbounded", type_ids_OrderNumber); + + if (eprosima::fastdds::dds::RETCODE_OK != return_code_OrderNumber) + { + { + SBound bound = 0; + StringSTypeDefn string_sdefn = TypeObjectUtils::build_string_s_type_defn(bound); + if (eprosima::fastdds::dds::RETCODE_BAD_PARAMETER == + TypeObjectUtils::build_and_register_s_string_type_identifier(string_sdefn, + "anonymous_string_unbounded", type_ids_OrderNumber)) + { + EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, + "anonymous_string_unbounded already registered in TypeObjectRegistry for a different type."); + } + } + } + StructMemberFlag member_flags_OrderNumber = TypeObjectUtils::build_struct_member_flag(eprosima::fastdds::dds::xtypes::TryConstructFailAction::DISCARD, + false, false, false, false); + MemberId member_id_OrderNumber = 0x0000001c; + bool common_OrderNumber_ec {false}; + CommonStructMember common_OrderNumber {TypeObjectUtils::build_common_struct_member(member_id_OrderNumber, member_flags_OrderNumber, TypeObjectUtils::retrieve_complete_type_identifier(type_ids_OrderNumber, common_OrderNumber_ec))}; + if (!common_OrderNumber_ec) + { + EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, "Structure OrderNumber member TypeIdentifier inconsistent."); + return; + } + MemberName name_OrderNumber = "OrderNumber"; + eprosima::fastcdr::optional member_ann_builtin_OrderNumber; + ann_custom_WeightInfoOk.reset(); + CompleteMemberDetail detail_OrderNumber = TypeObjectUtils::build_complete_member_detail(name_OrderNumber, member_ann_builtin_OrderNumber, ann_custom_WeightInfoOk); + CompleteStructMember member_OrderNumber = TypeObjectUtils::build_complete_struct_member(common_OrderNumber, detail_OrderNumber); + TypeObjectUtils::add_complete_struct_member(member_seq_WeightInfoOk, member_OrderNumber); + } + { + TypeIdentifierPair type_ids_VehicleAndVesselNumber; + ReturnCode_t return_code_VehicleAndVesselNumber {eprosima::fastdds::dds::RETCODE_OK}; + return_code_VehicleAndVesselNumber = + eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->type_object_registry().get_type_identifiers( + "anonymous_string_unbounded", type_ids_VehicleAndVesselNumber); + + if (eprosima::fastdds::dds::RETCODE_OK != return_code_VehicleAndVesselNumber) + { + { + SBound bound = 0; + StringSTypeDefn string_sdefn = TypeObjectUtils::build_string_s_type_defn(bound); + if (eprosima::fastdds::dds::RETCODE_BAD_PARAMETER == + TypeObjectUtils::build_and_register_s_string_type_identifier(string_sdefn, + "anonymous_string_unbounded", type_ids_VehicleAndVesselNumber)) + { + EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, + "anonymous_string_unbounded already registered in TypeObjectRegistry for a different type."); + } + } + } + StructMemberFlag member_flags_VehicleAndVesselNumber = TypeObjectUtils::build_struct_member_flag(eprosima::fastdds::dds::xtypes::TryConstructFailAction::DISCARD, + false, false, false, false); + MemberId member_id_VehicleAndVesselNumber = 0x0000001d; + bool common_VehicleAndVesselNumber_ec {false}; + CommonStructMember common_VehicleAndVesselNumber {TypeObjectUtils::build_common_struct_member(member_id_VehicleAndVesselNumber, member_flags_VehicleAndVesselNumber, TypeObjectUtils::retrieve_complete_type_identifier(type_ids_VehicleAndVesselNumber, common_VehicleAndVesselNumber_ec))}; + if (!common_VehicleAndVesselNumber_ec) + { + EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, "Structure VehicleAndVesselNumber member TypeIdentifier inconsistent."); + return; + } + MemberName name_VehicleAndVesselNumber = "VehicleAndVesselNumber"; + eprosima::fastcdr::optional member_ann_builtin_VehicleAndVesselNumber; + ann_custom_WeightInfoOk.reset(); + CompleteMemberDetail detail_VehicleAndVesselNumber = TypeObjectUtils::build_complete_member_detail(name_VehicleAndVesselNumber, member_ann_builtin_VehicleAndVesselNumber, ann_custom_WeightInfoOk); + CompleteStructMember member_VehicleAndVesselNumber = TypeObjectUtils::build_complete_struct_member(common_VehicleAndVesselNumber, detail_VehicleAndVesselNumber); + TypeObjectUtils::add_complete_struct_member(member_seq_WeightInfoOk, member_VehicleAndVesselNumber); + } + { + TypeIdentifierPair type_ids_ReceiveCompany; + ReturnCode_t return_code_ReceiveCompany {eprosima::fastdds::dds::RETCODE_OK}; + return_code_ReceiveCompany = + eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->type_object_registry().get_type_identifiers( + "anonymous_string_unbounded", type_ids_ReceiveCompany); + + if (eprosima::fastdds::dds::RETCODE_OK != return_code_ReceiveCompany) + { + { + SBound bound = 0; + StringSTypeDefn string_sdefn = TypeObjectUtils::build_string_s_type_defn(bound); + if (eprosima::fastdds::dds::RETCODE_BAD_PARAMETER == + TypeObjectUtils::build_and_register_s_string_type_identifier(string_sdefn, + "anonymous_string_unbounded", type_ids_ReceiveCompany)) + { + EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, + "anonymous_string_unbounded already registered in TypeObjectRegistry for a different type."); + } + } + } + StructMemberFlag member_flags_ReceiveCompany = TypeObjectUtils::build_struct_member_flag(eprosima::fastdds::dds::xtypes::TryConstructFailAction::DISCARD, + false, false, false, false); + MemberId member_id_ReceiveCompany = 0x0000001e; + bool common_ReceiveCompany_ec {false}; + CommonStructMember common_ReceiveCompany {TypeObjectUtils::build_common_struct_member(member_id_ReceiveCompany, member_flags_ReceiveCompany, TypeObjectUtils::retrieve_complete_type_identifier(type_ids_ReceiveCompany, common_ReceiveCompany_ec))}; + if (!common_ReceiveCompany_ec) + { + EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, "Structure ReceiveCompany member TypeIdentifier inconsistent."); + return; + } + MemberName name_ReceiveCompany = "ReceiveCompany"; + eprosima::fastcdr::optional member_ann_builtin_ReceiveCompany; + ann_custom_WeightInfoOk.reset(); + CompleteMemberDetail detail_ReceiveCompany = TypeObjectUtils::build_complete_member_detail(name_ReceiveCompany, member_ann_builtin_ReceiveCompany, ann_custom_WeightInfoOk); + CompleteStructMember member_ReceiveCompany = TypeObjectUtils::build_complete_struct_member(common_ReceiveCompany, detail_ReceiveCompany); + TypeObjectUtils::add_complete_struct_member(member_seq_WeightInfoOk, member_ReceiveCompany); + } + { + TypeIdentifierPair type_ids_TransportCompany; + ReturnCode_t return_code_TransportCompany {eprosima::fastdds::dds::RETCODE_OK}; + return_code_TransportCompany = + eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->type_object_registry().get_type_identifiers( + "anonymous_string_unbounded", type_ids_TransportCompany); + + if (eprosima::fastdds::dds::RETCODE_OK != return_code_TransportCompany) + { + { + SBound bound = 0; + StringSTypeDefn string_sdefn = TypeObjectUtils::build_string_s_type_defn(bound); + if (eprosima::fastdds::dds::RETCODE_BAD_PARAMETER == + TypeObjectUtils::build_and_register_s_string_type_identifier(string_sdefn, + "anonymous_string_unbounded", type_ids_TransportCompany)) + { + EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, + "anonymous_string_unbounded already registered in TypeObjectRegistry for a different type."); + } + } + } + StructMemberFlag member_flags_TransportCompany = TypeObjectUtils::build_struct_member_flag(eprosima::fastdds::dds::xtypes::TryConstructFailAction::DISCARD, + false, false, false, false); + MemberId member_id_TransportCompany = 0x0000001f; + bool common_TransportCompany_ec {false}; + CommonStructMember common_TransportCompany {TypeObjectUtils::build_common_struct_member(member_id_TransportCompany, member_flags_TransportCompany, TypeObjectUtils::retrieve_complete_type_identifier(type_ids_TransportCompany, common_TransportCompany_ec))}; + if (!common_TransportCompany_ec) + { + EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, "Structure TransportCompany member TypeIdentifier inconsistent."); + return; + } + MemberName name_TransportCompany = "TransportCompany"; + eprosima::fastcdr::optional member_ann_builtin_TransportCompany; + ann_custom_WeightInfoOk.reset(); + CompleteMemberDetail detail_TransportCompany = TypeObjectUtils::build_complete_member_detail(name_TransportCompany, member_ann_builtin_TransportCompany, ann_custom_WeightInfoOk); + CompleteStructMember member_TransportCompany = TypeObjectUtils::build_complete_struct_member(common_TransportCompany, detail_TransportCompany); + TypeObjectUtils::add_complete_struct_member(member_seq_WeightInfoOk, member_TransportCompany); + } CompleteStructType struct_type_WeightInfoOk = TypeObjectUtils::build_complete_struct_type(struct_flags_WeightInfoOk, header_WeightInfoOk, member_seq_WeightInfoOk); if (eprosima::fastdds::dds::RETCODE_BAD_PARAMETER == TypeObjectUtils::build_and_register_struct_type_object(struct_type_WeightInfoOk, type_name_WeightInfoOk.to_string(), type_ids_WeightInfoOk)) @@ -2498,29 +2650,26 @@ void register_SummaryUpdate_type_identifier( } } } - -} // namespace WeighingSystem -namespace InternalSystem { // TypeIdentifier is returned by reference: dependent structures/unions are registered in this same method -void register_PrintReq_type_identifier( - TypeIdentifierPair& type_ids_PrintReq) +void register_ReadCardReq_type_identifier( + TypeIdentifierPair& type_ids_ReadCardReq) { - ReturnCode_t return_code_PrintReq {eprosima::fastdds::dds::RETCODE_OK}; - return_code_PrintReq = + ReturnCode_t return_code_ReadCardReq {eprosima::fastdds::dds::RETCODE_OK}; + return_code_ReadCardReq = eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->type_object_registry().get_type_identifiers( - "InternalSystem::PrintReq", type_ids_PrintReq); - if (eprosima::fastdds::dds::RETCODE_OK != return_code_PrintReq) + "WeighingSystem::ReadCardReq", type_ids_ReadCardReq); + if (eprosima::fastdds::dds::RETCODE_OK != return_code_ReadCardReq) { - StructTypeFlag struct_flags_PrintReq = TypeObjectUtils::build_struct_type_flag(eprosima::fastdds::dds::xtypes::ExtensibilityKind::APPENDABLE, + StructTypeFlag struct_flags_ReadCardReq = TypeObjectUtils::build_struct_type_flag(eprosima::fastdds::dds::xtypes::ExtensibilityKind::APPENDABLE, false, false); - QualifiedTypeName type_name_PrintReq = "InternalSystem::PrintReq"; - eprosima::fastcdr::optional type_ann_builtin_PrintReq; - eprosima::fastcdr::optional ann_custom_PrintReq; - CompleteTypeDetail detail_PrintReq = TypeObjectUtils::build_complete_type_detail(type_ann_builtin_PrintReq, ann_custom_PrintReq, type_name_PrintReq.to_string()); - CompleteStructHeader header_PrintReq; - header_PrintReq = TypeObjectUtils::build_complete_struct_header(TypeIdentifier(), detail_PrintReq); - CompleteStructMemberSeq member_seq_PrintReq; + QualifiedTypeName type_name_ReadCardReq = "WeighingSystem::ReadCardReq"; + eprosima::fastcdr::optional type_ann_builtin_ReadCardReq; + eprosima::fastcdr::optional ann_custom_ReadCardReq; + CompleteTypeDetail detail_ReadCardReq = TypeObjectUtils::build_complete_type_detail(type_ann_builtin_ReadCardReq, ann_custom_ReadCardReq, type_name_ReadCardReq.to_string()); + CompleteStructHeader header_ReadCardReq; + header_ReadCardReq = TypeObjectUtils::build_complete_struct_header(TypeIdentifier(), detail_ReadCardReq); + CompleteStructMemberSeq member_seq_ReadCardReq; { TypeIdentifierPair type_ids_index; ReturnCode_t return_code_index {eprosima::fastdds::dds::RETCODE_OK}; @@ -2546,44 +2695,68 @@ void register_PrintReq_type_identifier( } MemberName name_index = "index"; eprosima::fastcdr::optional member_ann_builtin_index; - ann_custom_PrintReq.reset(); - CompleteMemberDetail detail_index = TypeObjectUtils::build_complete_member_detail(name_index, member_ann_builtin_index, ann_custom_PrintReq); + ann_custom_ReadCardReq.reset(); + CompleteMemberDetail detail_index = TypeObjectUtils::build_complete_member_detail(name_index, member_ann_builtin_index, ann_custom_ReadCardReq); CompleteStructMember member_index = TypeObjectUtils::build_complete_struct_member(common_index, detail_index); - TypeObjectUtils::add_complete_struct_member(member_seq_PrintReq, member_index); + TypeObjectUtils::add_complete_struct_member(member_seq_ReadCardReq, member_index); } { TypeIdentifierPair type_ids_msg; ReturnCode_t return_code_msg {eprosima::fastdds::dds::RETCODE_OK}; return_code_msg = eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->type_object_registry().get_type_identifiers( - "anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded", type_ids_msg); + "anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded", type_ids_msg); if (eprosima::fastdds::dds::RETCODE_OK != return_code_msg) { return_code_msg = eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->type_object_registry().get_type_identifiers( - "anonymous_string_unbounded", type_ids_msg); + "anonymous_sequence_byte_unbounded", type_ids_msg); if (eprosima::fastdds::dds::RETCODE_OK != return_code_msg) { + return_code_msg = + eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->type_object_registry().get_type_identifiers( + "_byte", type_ids_msg); + + if (eprosima::fastdds::dds::RETCODE_OK != return_code_msg) + { + EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, + "Sequence element TypeIdentifier unknown to TypeObjectRegistry."); + return; + } + bool element_identifier_anonymous_sequence_byte_unbounded_ec {false}; + TypeIdentifier* element_identifier_anonymous_sequence_byte_unbounded {new TypeIdentifier(TypeObjectUtils::retrieve_complete_type_identifier(type_ids_msg, element_identifier_anonymous_sequence_byte_unbounded_ec))}; + if (!element_identifier_anonymous_sequence_byte_unbounded_ec) + { + EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, "Sequence element TypeIdentifier inconsistent."); + return; + } + EquivalenceKind equiv_kind_anonymous_sequence_byte_unbounded = EK_COMPLETE; + if (TK_NONE == type_ids_msg.type_identifier2()._d()) + { + equiv_kind_anonymous_sequence_byte_unbounded = EK_BOTH; + } + CollectionElementFlag element_flags_anonymous_sequence_byte_unbounded = 0; + PlainCollectionHeader header_anonymous_sequence_byte_unbounded = TypeObjectUtils::build_plain_collection_header(equiv_kind_anonymous_sequence_byte_unbounded, element_flags_anonymous_sequence_byte_unbounded); { SBound bound = 0; - StringSTypeDefn string_sdefn = TypeObjectUtils::build_string_s_type_defn(bound); + PlainSequenceSElemDefn seq_sdefn = TypeObjectUtils::build_plain_sequence_s_elem_defn(header_anonymous_sequence_byte_unbounded, bound, + eprosima::fastcdr::external(element_identifier_anonymous_sequence_byte_unbounded)); if (eprosima::fastdds::dds::RETCODE_BAD_PARAMETER == - TypeObjectUtils::build_and_register_s_string_type_identifier(string_sdefn, - "anonymous_string_unbounded", type_ids_msg)) + TypeObjectUtils::build_and_register_s_sequence_type_identifier(seq_sdefn, "anonymous_sequence_byte_unbounded", type_ids_msg)) { EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, - "anonymous_string_unbounded already registered in TypeObjectRegistry for a different type."); + "anonymous_sequence_byte_unbounded already registered in TypeObjectRegistry for a different type."); } } } - bool element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded_ec {false}; - TypeIdentifier* element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded {new TypeIdentifier(TypeObjectUtils::retrieve_complete_type_identifier(type_ids_msg, element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded_ec))}; - if (!element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded_ec) + bool element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded_ec {false}; + TypeIdentifier* element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded {new TypeIdentifier(TypeObjectUtils::retrieve_complete_type_identifier(type_ids_msg, element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded_ec))}; + if (!element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded_ec) { EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, - "anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded inconsistent element TypeIdentifier."); + "anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded inconsistent element TypeIdentifier."); return; } return_code_msg = @@ -2604,38 +2777,38 @@ void register_PrintReq_type_identifier( } } } - bool key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded_ec {false}; - TypeIdentifier* key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded {new TypeIdentifier(TypeObjectUtils::retrieve_complete_type_identifier(type_ids_msg, key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded_ec))}; - if (!key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded_ec) + bool key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded_ec {false}; + TypeIdentifier* key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded {new TypeIdentifier(TypeObjectUtils::retrieve_complete_type_identifier(type_ids_msg, key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded_ec))}; + if (!key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded_ec) { EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, - "anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded inconsistent key TypeIdentifier."); + "anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded inconsistent key TypeIdentifier."); return; } - EquivalenceKind equiv_kind_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded = EK_BOTH; - if ((EK_COMPLETE == key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->_d() || EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->_d()) || - (TI_PLAIN_SEQUENCE_SMALL == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->_d() && EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->seq_sdefn().header().equiv_kind()) || - (TI_PLAIN_SEQUENCE_LARGE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->_d() && EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->seq_ldefn().header().equiv_kind()) || - (TI_PLAIN_ARRAY_SMALL == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->_d() && EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->array_sdefn().header().equiv_kind()) || - (TI_PLAIN_ARRAY_LARGE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->_d() && EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->array_ldefn().header().equiv_kind()) || - (TI_PLAIN_MAP_SMALL == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->_d() && (EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->map_sdefn().key_identifier()->_d() || EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->map_sdefn().header().equiv_kind())) || - (TI_PLAIN_MAP_LARGE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->_d() && (EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->map_ldefn().key_identifier()->_d() || EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->map_ldefn().header().equiv_kind()))) + EquivalenceKind equiv_kind_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded = EK_BOTH; + if ((EK_COMPLETE == key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->_d() || EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->_d()) || + (TI_PLAIN_SEQUENCE_SMALL == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->_d() && EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->seq_sdefn().header().equiv_kind()) || + (TI_PLAIN_SEQUENCE_LARGE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->_d() && EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->seq_ldefn().header().equiv_kind()) || + (TI_PLAIN_ARRAY_SMALL == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->_d() && EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->array_sdefn().header().equiv_kind()) || + (TI_PLAIN_ARRAY_LARGE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->_d() && EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->array_ldefn().header().equiv_kind()) || + (TI_PLAIN_MAP_SMALL == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->_d() && (EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->map_sdefn().key_identifier()->_d() || EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->map_sdefn().header().equiv_kind())) || + (TI_PLAIN_MAP_LARGE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->_d() && (EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->map_ldefn().key_identifier()->_d() || EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->map_ldefn().header().equiv_kind()))) { - equiv_kind_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded = EK_COMPLETE; + equiv_kind_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded = EK_COMPLETE; } - CollectionElementFlag element_flags_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded = 0; - CollectionElementFlag key_flags_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded = 0; - PlainCollectionHeader header_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded = TypeObjectUtils::build_plain_collection_header(equiv_kind_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded, element_flags_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded); + CollectionElementFlag element_flags_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded = 0; + CollectionElementFlag key_flags_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded = 0; + PlainCollectionHeader header_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded = TypeObjectUtils::build_plain_collection_header(equiv_kind_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded, element_flags_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded); { SBound bound = 0; - PlainMapSTypeDefn map_sdefn = TypeObjectUtils::build_plain_map_s_type_defn(header_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded, bound, - eprosima::fastcdr::external(element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded), key_flags_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded, - eprosima::fastcdr::external(key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded)); + PlainMapSTypeDefn map_sdefn = TypeObjectUtils::build_plain_map_s_type_defn(header_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded, bound, + eprosima::fastcdr::external(element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded), key_flags_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded, + eprosima::fastcdr::external(key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded)); if (eprosima::fastdds::dds::RETCODE_BAD_PARAMETER == - TypeObjectUtils::build_and_register_s_map_type_identifier(map_sdefn, "anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded", type_ids_msg)) + TypeObjectUtils::build_and_register_s_map_type_identifier(map_sdefn, "anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded", type_ids_msg)) { EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, - "anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded already registered in TypeObjectRegistry for a different type."); + "anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded already registered in TypeObjectRegistry for a different type."); } } } @@ -2651,40 +2824,40 @@ void register_PrintReq_type_identifier( } MemberName name_msg = "msg"; eprosima::fastcdr::optional member_ann_builtin_msg; - ann_custom_PrintReq.reset(); - CompleteMemberDetail detail_msg = TypeObjectUtils::build_complete_member_detail(name_msg, member_ann_builtin_msg, ann_custom_PrintReq); + ann_custom_ReadCardReq.reset(); + CompleteMemberDetail detail_msg = TypeObjectUtils::build_complete_member_detail(name_msg, member_ann_builtin_msg, ann_custom_ReadCardReq); CompleteStructMember member_msg = TypeObjectUtils::build_complete_struct_member(common_msg, detail_msg); - TypeObjectUtils::add_complete_struct_member(member_seq_PrintReq, member_msg); + TypeObjectUtils::add_complete_struct_member(member_seq_ReadCardReq, member_msg); } - CompleteStructType struct_type_PrintReq = TypeObjectUtils::build_complete_struct_type(struct_flags_PrintReq, header_PrintReq, member_seq_PrintReq); + CompleteStructType struct_type_ReadCardReq = TypeObjectUtils::build_complete_struct_type(struct_flags_ReadCardReq, header_ReadCardReq, member_seq_ReadCardReq); if (eprosima::fastdds::dds::RETCODE_BAD_PARAMETER == - TypeObjectUtils::build_and_register_struct_type_object(struct_type_PrintReq, type_name_PrintReq.to_string(), type_ids_PrintReq)) + TypeObjectUtils::build_and_register_struct_type_object(struct_type_ReadCardReq, type_name_ReadCardReq.to_string(), type_ids_ReadCardReq)) { EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, - "InternalSystem::PrintReq already registered in TypeObjectRegistry for a different type."); + "WeighingSystem::ReadCardReq already registered in TypeObjectRegistry for a different type."); } } } // TypeIdentifier is returned by reference: dependent structures/unions are registered in this same method -void register_PrintRsp_type_identifier( - TypeIdentifierPair& type_ids_PrintRsp) +void register_ReadCardRsp_type_identifier( + TypeIdentifierPair& type_ids_ReadCardRsp) { - ReturnCode_t return_code_PrintRsp {eprosima::fastdds::dds::RETCODE_OK}; - return_code_PrintRsp = + ReturnCode_t return_code_ReadCardRsp {eprosima::fastdds::dds::RETCODE_OK}; + return_code_ReadCardRsp = eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->type_object_registry().get_type_identifiers( - "InternalSystem::PrintRsp", type_ids_PrintRsp); - if (eprosima::fastdds::dds::RETCODE_OK != return_code_PrintRsp) + "WeighingSystem::ReadCardRsp", type_ids_ReadCardRsp); + if (eprosima::fastdds::dds::RETCODE_OK != return_code_ReadCardRsp) { - StructTypeFlag struct_flags_PrintRsp = TypeObjectUtils::build_struct_type_flag(eprosima::fastdds::dds::xtypes::ExtensibilityKind::APPENDABLE, + StructTypeFlag struct_flags_ReadCardRsp = TypeObjectUtils::build_struct_type_flag(eprosima::fastdds::dds::xtypes::ExtensibilityKind::APPENDABLE, false, false); - QualifiedTypeName type_name_PrintRsp = "InternalSystem::PrintRsp"; - eprosima::fastcdr::optional type_ann_builtin_PrintRsp; - eprosima::fastcdr::optional ann_custom_PrintRsp; - CompleteTypeDetail detail_PrintRsp = TypeObjectUtils::build_complete_type_detail(type_ann_builtin_PrintRsp, ann_custom_PrintRsp, type_name_PrintRsp.to_string()); - CompleteStructHeader header_PrintRsp; - header_PrintRsp = TypeObjectUtils::build_complete_struct_header(TypeIdentifier(), detail_PrintRsp); - CompleteStructMemberSeq member_seq_PrintRsp; + QualifiedTypeName type_name_ReadCardRsp = "WeighingSystem::ReadCardRsp"; + eprosima::fastcdr::optional type_ann_builtin_ReadCardRsp; + eprosima::fastcdr::optional ann_custom_ReadCardRsp; + CompleteTypeDetail detail_ReadCardRsp = TypeObjectUtils::build_complete_type_detail(type_ann_builtin_ReadCardRsp, ann_custom_ReadCardRsp, type_name_ReadCardRsp.to_string()); + CompleteStructHeader header_ReadCardRsp; + header_ReadCardRsp = TypeObjectUtils::build_complete_struct_header(TypeIdentifier(), detail_ReadCardRsp); + CompleteStructMemberSeq member_seq_ReadCardRsp; { TypeIdentifierPair type_ids_index; ReturnCode_t return_code_index {eprosima::fastdds::dds::RETCODE_OK}; @@ -2710,29 +2883,120 @@ void register_PrintRsp_type_identifier( } MemberName name_index = "index"; eprosima::fastcdr::optional member_ann_builtin_index; - ann_custom_PrintRsp.reset(); - CompleteMemberDetail detail_index = TypeObjectUtils::build_complete_member_detail(name_index, member_ann_builtin_index, ann_custom_PrintRsp); + ann_custom_ReadCardRsp.reset(); + CompleteMemberDetail detail_index = TypeObjectUtils::build_complete_member_detail(name_index, member_ann_builtin_index, ann_custom_ReadCardRsp); CompleteStructMember member_index = TypeObjectUtils::build_complete_struct_member(common_index, detail_index); - TypeObjectUtils::add_complete_struct_member(member_seq_PrintRsp, member_index); + TypeObjectUtils::add_complete_struct_member(member_seq_ReadCardRsp, member_index); } { TypeIdentifierPair type_ids_msg; ReturnCode_t return_code_msg {eprosima::fastdds::dds::RETCODE_OK}; return_code_msg = eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->type_object_registry().get_type_identifiers( - "anonymous_string_unbounded", type_ids_msg); + "anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded", type_ids_msg); if (eprosima::fastdds::dds::RETCODE_OK != return_code_msg) { + return_code_msg = + eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->type_object_registry().get_type_identifiers( + "anonymous_sequence_byte_unbounded", type_ids_msg); + + if (eprosima::fastdds::dds::RETCODE_OK != return_code_msg) + { + return_code_msg = + eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->type_object_registry().get_type_identifiers( + "_byte", type_ids_msg); + + if (eprosima::fastdds::dds::RETCODE_OK != return_code_msg) + { + EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, + "Sequence element TypeIdentifier unknown to TypeObjectRegistry."); + return; + } + bool element_identifier_anonymous_sequence_byte_unbounded_ec {false}; + TypeIdentifier* element_identifier_anonymous_sequence_byte_unbounded {new TypeIdentifier(TypeObjectUtils::retrieve_complete_type_identifier(type_ids_msg, element_identifier_anonymous_sequence_byte_unbounded_ec))}; + if (!element_identifier_anonymous_sequence_byte_unbounded_ec) + { + EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, "Sequence element TypeIdentifier inconsistent."); + return; + } + EquivalenceKind equiv_kind_anonymous_sequence_byte_unbounded = EK_COMPLETE; + if (TK_NONE == type_ids_msg.type_identifier2()._d()) + { + equiv_kind_anonymous_sequence_byte_unbounded = EK_BOTH; + } + CollectionElementFlag element_flags_anonymous_sequence_byte_unbounded = 0; + PlainCollectionHeader header_anonymous_sequence_byte_unbounded = TypeObjectUtils::build_plain_collection_header(equiv_kind_anonymous_sequence_byte_unbounded, element_flags_anonymous_sequence_byte_unbounded); + { + SBound bound = 0; + PlainSequenceSElemDefn seq_sdefn = TypeObjectUtils::build_plain_sequence_s_elem_defn(header_anonymous_sequence_byte_unbounded, bound, + eprosima::fastcdr::external(element_identifier_anonymous_sequence_byte_unbounded)); + if (eprosima::fastdds::dds::RETCODE_BAD_PARAMETER == + TypeObjectUtils::build_and_register_s_sequence_type_identifier(seq_sdefn, "anonymous_sequence_byte_unbounded", type_ids_msg)) + { + EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, + "anonymous_sequence_byte_unbounded already registered in TypeObjectRegistry for a different type."); + } + } + } + bool element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded_ec {false}; + TypeIdentifier* element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded {new TypeIdentifier(TypeObjectUtils::retrieve_complete_type_identifier(type_ids_msg, element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded_ec))}; + if (!element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded_ec) + { + EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, + "anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded inconsistent element TypeIdentifier."); + return; + } + return_code_msg = + eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->type_object_registry().get_type_identifiers( + "anonymous_string_unbounded", type_ids_msg); + + if (eprosima::fastdds::dds::RETCODE_OK != return_code_msg) + { + { + SBound bound = 0; + StringSTypeDefn string_sdefn = TypeObjectUtils::build_string_s_type_defn(bound); + if (eprosima::fastdds::dds::RETCODE_BAD_PARAMETER == + TypeObjectUtils::build_and_register_s_string_type_identifier(string_sdefn, + "anonymous_string_unbounded", type_ids_msg)) + { + EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, + "anonymous_string_unbounded already registered in TypeObjectRegistry for a different type."); + } + } + } + bool key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded_ec {false}; + TypeIdentifier* key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded {new TypeIdentifier(TypeObjectUtils::retrieve_complete_type_identifier(type_ids_msg, key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded_ec))}; + if (!key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded_ec) + { + EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, + "anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded inconsistent key TypeIdentifier."); + return; + } + EquivalenceKind equiv_kind_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded = EK_BOTH; + if ((EK_COMPLETE == key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->_d() || EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->_d()) || + (TI_PLAIN_SEQUENCE_SMALL == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->_d() && EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->seq_sdefn().header().equiv_kind()) || + (TI_PLAIN_SEQUENCE_LARGE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->_d() && EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->seq_ldefn().header().equiv_kind()) || + (TI_PLAIN_ARRAY_SMALL == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->_d() && EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->array_sdefn().header().equiv_kind()) || + (TI_PLAIN_ARRAY_LARGE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->_d() && EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->array_ldefn().header().equiv_kind()) || + (TI_PLAIN_MAP_SMALL == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->_d() && (EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->map_sdefn().key_identifier()->_d() || EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->map_sdefn().header().equiv_kind())) || + (TI_PLAIN_MAP_LARGE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->_d() && (EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->map_ldefn().key_identifier()->_d() || EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded->map_ldefn().header().equiv_kind()))) + { + equiv_kind_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded = EK_COMPLETE; + } + CollectionElementFlag element_flags_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded = 0; + CollectionElementFlag key_flags_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded = 0; + PlainCollectionHeader header_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded = TypeObjectUtils::build_plain_collection_header(equiv_kind_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded, element_flags_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded); { SBound bound = 0; - StringSTypeDefn string_sdefn = TypeObjectUtils::build_string_s_type_defn(bound); + PlainMapSTypeDefn map_sdefn = TypeObjectUtils::build_plain_map_s_type_defn(header_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded, bound, + eprosima::fastcdr::external(element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded), key_flags_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded, + eprosima::fastcdr::external(key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded)); if (eprosima::fastdds::dds::RETCODE_BAD_PARAMETER == - TypeObjectUtils::build_and_register_s_string_type_identifier(string_sdefn, - "anonymous_string_unbounded", type_ids_msg)) + TypeObjectUtils::build_and_register_s_map_type_identifier(map_sdefn, "anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded", type_ids_msg)) { EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, - "anonymous_string_unbounded already registered in TypeObjectRegistry for a different type."); + "anonymous_map_anonymous_string_unbounded_anonymous_sequence_byte_unbounded_unbounded already registered in TypeObjectRegistry for a different type."); } } } @@ -2748,40 +3012,40 @@ void register_PrintRsp_type_identifier( } MemberName name_msg = "msg"; eprosima::fastcdr::optional member_ann_builtin_msg; - ann_custom_PrintRsp.reset(); - CompleteMemberDetail detail_msg = TypeObjectUtils::build_complete_member_detail(name_msg, member_ann_builtin_msg, ann_custom_PrintRsp); + ann_custom_ReadCardRsp.reset(); + CompleteMemberDetail detail_msg = TypeObjectUtils::build_complete_member_detail(name_msg, member_ann_builtin_msg, ann_custom_ReadCardRsp); CompleteStructMember member_msg = TypeObjectUtils::build_complete_struct_member(common_msg, detail_msg); - TypeObjectUtils::add_complete_struct_member(member_seq_PrintRsp, member_msg); + TypeObjectUtils::add_complete_struct_member(member_seq_ReadCardRsp, member_msg); } - CompleteStructType struct_type_PrintRsp = TypeObjectUtils::build_complete_struct_type(struct_flags_PrintRsp, header_PrintRsp, member_seq_PrintRsp); + CompleteStructType struct_type_ReadCardRsp = TypeObjectUtils::build_complete_struct_type(struct_flags_ReadCardRsp, header_ReadCardRsp, member_seq_ReadCardRsp); if (eprosima::fastdds::dds::RETCODE_BAD_PARAMETER == - TypeObjectUtils::build_and_register_struct_type_object(struct_type_PrintRsp, type_name_PrintRsp.to_string(), type_ids_PrintRsp)) + TypeObjectUtils::build_and_register_struct_type_object(struct_type_ReadCardRsp, type_name_ReadCardRsp.to_string(), type_ids_ReadCardRsp)) { EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, - "InternalSystem::PrintRsp already registered in TypeObjectRegistry for a different type."); + "WeighingSystem::ReadCardRsp already registered in TypeObjectRegistry for a different type."); } } } // TypeIdentifier is returned by reference: dependent structures/unions are registered in this same method -void register_IoCtrlReq_type_identifier( - TypeIdentifierPair& type_ids_IoCtrlReq) +void register_PrintReq_type_identifier( + TypeIdentifierPair& type_ids_PrintReq) { - ReturnCode_t return_code_IoCtrlReq {eprosima::fastdds::dds::RETCODE_OK}; - return_code_IoCtrlReq = + ReturnCode_t return_code_PrintReq {eprosima::fastdds::dds::RETCODE_OK}; + return_code_PrintReq = eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->type_object_registry().get_type_identifiers( - "InternalSystem::IoCtrlReq", type_ids_IoCtrlReq); - if (eprosima::fastdds::dds::RETCODE_OK != return_code_IoCtrlReq) + "WeighingSystem::PrintReq", type_ids_PrintReq); + if (eprosima::fastdds::dds::RETCODE_OK != return_code_PrintReq) { - StructTypeFlag struct_flags_IoCtrlReq = TypeObjectUtils::build_struct_type_flag(eprosima::fastdds::dds::xtypes::ExtensibilityKind::APPENDABLE, + StructTypeFlag struct_flags_PrintReq = TypeObjectUtils::build_struct_type_flag(eprosima::fastdds::dds::xtypes::ExtensibilityKind::APPENDABLE, false, false); - QualifiedTypeName type_name_IoCtrlReq = "InternalSystem::IoCtrlReq"; - eprosima::fastcdr::optional type_ann_builtin_IoCtrlReq; - eprosima::fastcdr::optional ann_custom_IoCtrlReq; - CompleteTypeDetail detail_IoCtrlReq = TypeObjectUtils::build_complete_type_detail(type_ann_builtin_IoCtrlReq, ann_custom_IoCtrlReq, type_name_IoCtrlReq.to_string()); - CompleteStructHeader header_IoCtrlReq; - header_IoCtrlReq = TypeObjectUtils::build_complete_struct_header(TypeIdentifier(), detail_IoCtrlReq); - CompleteStructMemberSeq member_seq_IoCtrlReq; + QualifiedTypeName type_name_PrintReq = "WeighingSystem::PrintReq"; + eprosima::fastcdr::optional type_ann_builtin_PrintReq; + eprosima::fastcdr::optional ann_custom_PrintReq; + CompleteTypeDetail detail_PrintReq = TypeObjectUtils::build_complete_type_detail(type_ann_builtin_PrintReq, ann_custom_PrintReq, type_name_PrintReq.to_string()); + CompleteStructHeader header_PrintReq; + header_PrintReq = TypeObjectUtils::build_complete_struct_header(TypeIdentifier(), detail_PrintReq); + CompleteStructMemberSeq member_seq_PrintReq; { TypeIdentifierPair type_ids_index; ReturnCode_t return_code_index {eprosima::fastdds::dds::RETCODE_OK}; @@ -2807,10 +3071,10 @@ void register_IoCtrlReq_type_identifier( } MemberName name_index = "index"; eprosima::fastcdr::optional member_ann_builtin_index; - ann_custom_IoCtrlReq.reset(); - CompleteMemberDetail detail_index = TypeObjectUtils::build_complete_member_detail(name_index, member_ann_builtin_index, ann_custom_IoCtrlReq); + ann_custom_PrintReq.reset(); + CompleteMemberDetail detail_index = TypeObjectUtils::build_complete_member_detail(name_index, member_ann_builtin_index, ann_custom_PrintReq); CompleteStructMember member_index = TypeObjectUtils::build_complete_struct_member(common_index, detail_index); - TypeObjectUtils::add_complete_struct_member(member_seq_IoCtrlReq, member_index); + TypeObjectUtils::add_complete_struct_member(member_seq_PrintReq, member_index); } { TypeIdentifierPair type_ids_msg; @@ -2912,40 +3176,40 @@ void register_IoCtrlReq_type_identifier( } MemberName name_msg = "msg"; eprosima::fastcdr::optional member_ann_builtin_msg; - ann_custom_IoCtrlReq.reset(); - CompleteMemberDetail detail_msg = TypeObjectUtils::build_complete_member_detail(name_msg, member_ann_builtin_msg, ann_custom_IoCtrlReq); + ann_custom_PrintReq.reset(); + CompleteMemberDetail detail_msg = TypeObjectUtils::build_complete_member_detail(name_msg, member_ann_builtin_msg, ann_custom_PrintReq); CompleteStructMember member_msg = TypeObjectUtils::build_complete_struct_member(common_msg, detail_msg); - TypeObjectUtils::add_complete_struct_member(member_seq_IoCtrlReq, member_msg); + TypeObjectUtils::add_complete_struct_member(member_seq_PrintReq, member_msg); } - CompleteStructType struct_type_IoCtrlReq = TypeObjectUtils::build_complete_struct_type(struct_flags_IoCtrlReq, header_IoCtrlReq, member_seq_IoCtrlReq); + CompleteStructType struct_type_PrintReq = TypeObjectUtils::build_complete_struct_type(struct_flags_PrintReq, header_PrintReq, member_seq_PrintReq); if (eprosima::fastdds::dds::RETCODE_BAD_PARAMETER == - TypeObjectUtils::build_and_register_struct_type_object(struct_type_IoCtrlReq, type_name_IoCtrlReq.to_string(), type_ids_IoCtrlReq)) + TypeObjectUtils::build_and_register_struct_type_object(struct_type_PrintReq, type_name_PrintReq.to_string(), type_ids_PrintReq)) { EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, - "InternalSystem::IoCtrlReq already registered in TypeObjectRegistry for a different type."); + "WeighingSystem::PrintReq already registered in TypeObjectRegistry for a different type."); } } } // TypeIdentifier is returned by reference: dependent structures/unions are registered in this same method -void register_IoCtrlRsp_type_identifier( - TypeIdentifierPair& type_ids_IoCtrlRsp) +void register_PrintRsp_type_identifier( + TypeIdentifierPair& type_ids_PrintRsp) { - ReturnCode_t return_code_IoCtrlRsp {eprosima::fastdds::dds::RETCODE_OK}; - return_code_IoCtrlRsp = + ReturnCode_t return_code_PrintRsp {eprosima::fastdds::dds::RETCODE_OK}; + return_code_PrintRsp = eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->type_object_registry().get_type_identifiers( - "InternalSystem::IoCtrlRsp", type_ids_IoCtrlRsp); - if (eprosima::fastdds::dds::RETCODE_OK != return_code_IoCtrlRsp) + "WeighingSystem::PrintRsp", type_ids_PrintRsp); + if (eprosima::fastdds::dds::RETCODE_OK != return_code_PrintRsp) { - StructTypeFlag struct_flags_IoCtrlRsp = TypeObjectUtils::build_struct_type_flag(eprosima::fastdds::dds::xtypes::ExtensibilityKind::APPENDABLE, + StructTypeFlag struct_flags_PrintRsp = TypeObjectUtils::build_struct_type_flag(eprosima::fastdds::dds::xtypes::ExtensibilityKind::APPENDABLE, false, false); - QualifiedTypeName type_name_IoCtrlRsp = "InternalSystem::IoCtrlRsp"; - eprosima::fastcdr::optional type_ann_builtin_IoCtrlRsp; - eprosima::fastcdr::optional ann_custom_IoCtrlRsp; - CompleteTypeDetail detail_IoCtrlRsp = TypeObjectUtils::build_complete_type_detail(type_ann_builtin_IoCtrlRsp, ann_custom_IoCtrlRsp, type_name_IoCtrlRsp.to_string()); - CompleteStructHeader header_IoCtrlRsp; - header_IoCtrlRsp = TypeObjectUtils::build_complete_struct_header(TypeIdentifier(), detail_IoCtrlRsp); - CompleteStructMemberSeq member_seq_IoCtrlRsp; + QualifiedTypeName type_name_PrintRsp = "WeighingSystem::PrintRsp"; + eprosima::fastcdr::optional type_ann_builtin_PrintRsp; + eprosima::fastcdr::optional ann_custom_PrintRsp; + CompleteTypeDetail detail_PrintRsp = TypeObjectUtils::build_complete_type_detail(type_ann_builtin_PrintRsp, ann_custom_PrintRsp, type_name_PrintRsp.to_string()); + CompleteStructHeader header_PrintRsp; + header_PrintRsp = TypeObjectUtils::build_complete_struct_header(TypeIdentifier(), detail_PrintRsp); + CompleteStructMemberSeq member_seq_PrintRsp; { TypeIdentifierPair type_ids_index; ReturnCode_t return_code_index {eprosima::fastdds::dds::RETCODE_OK}; @@ -2971,96 +3235,29 @@ void register_IoCtrlRsp_type_identifier( } MemberName name_index = "index"; eprosima::fastcdr::optional member_ann_builtin_index; - ann_custom_IoCtrlRsp.reset(); - CompleteMemberDetail detail_index = TypeObjectUtils::build_complete_member_detail(name_index, member_ann_builtin_index, ann_custom_IoCtrlRsp); + ann_custom_PrintRsp.reset(); + CompleteMemberDetail detail_index = TypeObjectUtils::build_complete_member_detail(name_index, member_ann_builtin_index, ann_custom_PrintRsp); CompleteStructMember member_index = TypeObjectUtils::build_complete_struct_member(common_index, detail_index); - TypeObjectUtils::add_complete_struct_member(member_seq_IoCtrlRsp, member_index); + TypeObjectUtils::add_complete_struct_member(member_seq_PrintRsp, member_index); } { TypeIdentifierPair type_ids_msg; ReturnCode_t return_code_msg {eprosima::fastdds::dds::RETCODE_OK}; return_code_msg = eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->type_object_registry().get_type_identifiers( - "anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded", type_ids_msg); + "anonymous_string_unbounded", type_ids_msg); if (eprosima::fastdds::dds::RETCODE_OK != return_code_msg) { - return_code_msg = - eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->type_object_registry().get_type_identifiers( - "anonymous_string_unbounded", type_ids_msg); - - if (eprosima::fastdds::dds::RETCODE_OK != return_code_msg) - { - { - SBound bound = 0; - StringSTypeDefn string_sdefn = TypeObjectUtils::build_string_s_type_defn(bound); - if (eprosima::fastdds::dds::RETCODE_BAD_PARAMETER == - TypeObjectUtils::build_and_register_s_string_type_identifier(string_sdefn, - "anonymous_string_unbounded", type_ids_msg)) - { - EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, - "anonymous_string_unbounded already registered in TypeObjectRegistry for a different type."); - } - } - } - bool element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded_ec {false}; - TypeIdentifier* element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded {new TypeIdentifier(TypeObjectUtils::retrieve_complete_type_identifier(type_ids_msg, element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded_ec))}; - if (!element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded_ec) - { - EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, - "anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded inconsistent element TypeIdentifier."); - return; - } - return_code_msg = - eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->type_object_registry().get_type_identifiers( - "anonymous_string_unbounded", type_ids_msg); - - if (eprosima::fastdds::dds::RETCODE_OK != return_code_msg) - { - { - SBound bound = 0; - StringSTypeDefn string_sdefn = TypeObjectUtils::build_string_s_type_defn(bound); - if (eprosima::fastdds::dds::RETCODE_BAD_PARAMETER == - TypeObjectUtils::build_and_register_s_string_type_identifier(string_sdefn, - "anonymous_string_unbounded", type_ids_msg)) - { - EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, - "anonymous_string_unbounded already registered in TypeObjectRegistry for a different type."); - } - } - } - bool key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded_ec {false}; - TypeIdentifier* key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded {new TypeIdentifier(TypeObjectUtils::retrieve_complete_type_identifier(type_ids_msg, key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded_ec))}; - if (!key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded_ec) - { - EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, - "anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded inconsistent key TypeIdentifier."); - return; - } - EquivalenceKind equiv_kind_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded = EK_BOTH; - if ((EK_COMPLETE == key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->_d() || EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->_d()) || - (TI_PLAIN_SEQUENCE_SMALL == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->_d() && EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->seq_sdefn().header().equiv_kind()) || - (TI_PLAIN_SEQUENCE_LARGE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->_d() && EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->seq_ldefn().header().equiv_kind()) || - (TI_PLAIN_ARRAY_SMALL == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->_d() && EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->array_sdefn().header().equiv_kind()) || - (TI_PLAIN_ARRAY_LARGE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->_d() && EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->array_ldefn().header().equiv_kind()) || - (TI_PLAIN_MAP_SMALL == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->_d() && (EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->map_sdefn().key_identifier()->_d() || EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->map_sdefn().header().equiv_kind())) || - (TI_PLAIN_MAP_LARGE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->_d() && (EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->map_ldefn().key_identifier()->_d() || EK_COMPLETE == element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded->map_ldefn().header().equiv_kind()))) - { - equiv_kind_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded = EK_COMPLETE; - } - CollectionElementFlag element_flags_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded = 0; - CollectionElementFlag key_flags_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded = 0; - PlainCollectionHeader header_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded = TypeObjectUtils::build_plain_collection_header(equiv_kind_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded, element_flags_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded); { SBound bound = 0; - PlainMapSTypeDefn map_sdefn = TypeObjectUtils::build_plain_map_s_type_defn(header_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded, bound, - eprosima::fastcdr::external(element_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded), key_flags_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded, - eprosima::fastcdr::external(key_identifier_anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded)); + StringSTypeDefn string_sdefn = TypeObjectUtils::build_string_s_type_defn(bound); if (eprosima::fastdds::dds::RETCODE_BAD_PARAMETER == - TypeObjectUtils::build_and_register_s_map_type_identifier(map_sdefn, "anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded", type_ids_msg)) + TypeObjectUtils::build_and_register_s_string_type_identifier(string_sdefn, + "anonymous_string_unbounded", type_ids_msg)) { EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, - "anonymous_map_anonymous_string_unbounded_anonymous_string_unbounded_unbounded already registered in TypeObjectRegistry for a different type."); + "anonymous_string_unbounded already registered in TypeObjectRegistry for a different type."); } } } @@ -3076,20 +3273,20 @@ void register_IoCtrlRsp_type_identifier( } MemberName name_msg = "msg"; eprosima::fastcdr::optional member_ann_builtin_msg; - ann_custom_IoCtrlRsp.reset(); - CompleteMemberDetail detail_msg = TypeObjectUtils::build_complete_member_detail(name_msg, member_ann_builtin_msg, ann_custom_IoCtrlRsp); + ann_custom_PrintRsp.reset(); + CompleteMemberDetail detail_msg = TypeObjectUtils::build_complete_member_detail(name_msg, member_ann_builtin_msg, ann_custom_PrintRsp); CompleteStructMember member_msg = TypeObjectUtils::build_complete_struct_member(common_msg, detail_msg); - TypeObjectUtils::add_complete_struct_member(member_seq_IoCtrlRsp, member_msg); + TypeObjectUtils::add_complete_struct_member(member_seq_PrintRsp, member_msg); } - CompleteStructType struct_type_IoCtrlRsp = TypeObjectUtils::build_complete_struct_type(struct_flags_IoCtrlRsp, header_IoCtrlRsp, member_seq_IoCtrlRsp); + CompleteStructType struct_type_PrintRsp = TypeObjectUtils::build_complete_struct_type(struct_flags_PrintRsp, header_PrintRsp, member_seq_PrintRsp); if (eprosima::fastdds::dds::RETCODE_BAD_PARAMETER == - TypeObjectUtils::build_and_register_struct_type_object(struct_type_IoCtrlRsp, type_name_IoCtrlRsp.to_string(), type_ids_IoCtrlRsp)) + TypeObjectUtils::build_and_register_struct_type_object(struct_type_PrintRsp, type_name_PrintRsp.to_string(), type_ids_PrintRsp)) { EPROSIMA_LOG_ERROR(XTYPES_TYPE_REPRESENTATION, - "InternalSystem::IoCtrlRsp already registered in TypeObjectRegistry for a different type."); + "WeighingSystem::PrintRsp already registered in TypeObjectRegistry for a different type."); } } } -} // namespace InternalSystem +} // namespace WeighingSystem diff --git a/lib/SystemTypeObjectSupport.hpp b/lib/WeighingDDSTypeTypeObjectSupport.hpp similarity index 95% rename from lib/SystemTypeObjectSupport.hpp rename to lib/WeighingDDSTypeTypeObjectSupport.hpp index 3c5b431..7ccebb6 100644 --- a/lib/SystemTypeObjectSupport.hpp +++ b/lib/WeighingDDSTypeTypeObjectSupport.hpp @@ -13,14 +13,14 @@ // limitations under the License. /*! - * @file SystemTypeObjectSupport.hpp + * @file WeighingDDSTypeTypeObjectSupport.hpp * Header file containing the API required to register the TypeObject representation of the described types in the IDL file * * This file was generated by the tool fastddsgen. */ -#ifndef FAST_DDS_GENERATED__INTERNALSYSTEM_SYSTEM_TYPE_OBJECT_SUPPORT_HPP -#define FAST_DDS_GENERATED__INTERNALSYSTEM_SYSTEM_TYPE_OBJECT_SUPPORT_HPP +#ifndef FAST_DDS_GENERATED__WEIGHINGSYSTEM_WEIGHINGDDSTYPE_TYPE_OBJECT_SUPPORT_HPP +#define FAST_DDS_GENERATED__WEIGHINGSYSTEM_WEIGHINGDDSTYPE_TYPE_OBJECT_SUPPORT_HPP #include @@ -207,10 +207,8 @@ eProsima_user_DllExport void register_Voice_type_identifier( eProsima_user_DllExport void register_SummaryUpdate_type_identifier( eprosima::fastdds::dds::xtypes::TypeIdentifierPair& type_ids); -} // namespace WeighingSystem -namespace InternalSystem { /** - * @brief Register PrintReq related TypeIdentifier. + * @brief Register ReadCardReq related TypeIdentifier. * Fully-descriptive TypeIdentifiers are directly registered. * Hash TypeIdentifiers require to fill the TypeObject information and hash it, consequently, the TypeObject is * indirectly registered as well. @@ -219,11 +217,11 @@ namespace InternalSystem { * The returned TypeIdentifier corresponds to the complete TypeIdentifier in case of hashed TypeIdentifiers. * Invalid TypeIdentifier is returned in case of error. */ -eProsima_user_DllExport void register_PrintReq_type_identifier( +eProsima_user_DllExport void register_ReadCardReq_type_identifier( eprosima::fastdds::dds::xtypes::TypeIdentifierPair& type_ids); /** - * @brief Register PrintRsp related TypeIdentifier. + * @brief Register ReadCardRsp related TypeIdentifier. * Fully-descriptive TypeIdentifiers are directly registered. * Hash TypeIdentifiers require to fill the TypeObject information and hash it, consequently, the TypeObject is * indirectly registered as well. @@ -232,11 +230,11 @@ eProsima_user_DllExport void register_PrintReq_type_identifier( * The returned TypeIdentifier corresponds to the complete TypeIdentifier in case of hashed TypeIdentifiers. * Invalid TypeIdentifier is returned in case of error. */ -eProsima_user_DllExport void register_PrintRsp_type_identifier( +eProsima_user_DllExport void register_ReadCardRsp_type_identifier( eprosima::fastdds::dds::xtypes::TypeIdentifierPair& type_ids); /** - * @brief Register IoCtrlReq related TypeIdentifier. + * @brief Register PrintReq related TypeIdentifier. * Fully-descriptive TypeIdentifiers are directly registered. * Hash TypeIdentifiers require to fill the TypeObject information and hash it, consequently, the TypeObject is * indirectly registered as well. @@ -245,11 +243,11 @@ eProsima_user_DllExport void register_PrintRsp_type_identifier( * The returned TypeIdentifier corresponds to the complete TypeIdentifier in case of hashed TypeIdentifiers. * Invalid TypeIdentifier is returned in case of error. */ -eProsima_user_DllExport void register_IoCtrlReq_type_identifier( +eProsima_user_DllExport void register_PrintReq_type_identifier( eprosima::fastdds::dds::xtypes::TypeIdentifierPair& type_ids); /** - * @brief Register IoCtrlRsp related TypeIdentifier. + * @brief Register PrintRsp related TypeIdentifier. * Fully-descriptive TypeIdentifiers are directly registered. * Hash TypeIdentifiers require to fill the TypeObject information and hash it, consequently, the TypeObject is * indirectly registered as well. @@ -258,12 +256,12 @@ eProsima_user_DllExport void register_IoCtrlReq_type_identifier( * The returned TypeIdentifier corresponds to the complete TypeIdentifier in case of hashed TypeIdentifiers. * Invalid TypeIdentifier is returned in case of error. */ -eProsima_user_DllExport void register_IoCtrlRsp_type_identifier( +eProsima_user_DllExport void register_PrintRsp_type_identifier( eprosima::fastdds::dds::xtypes::TypeIdentifierPair& type_ids); -} // namespace InternalSystem +} // namespace WeighingSystem #endif // DOXYGEN_SHOULD_SKIP_THIS_PUBLIC -#endif // FAST_DDS_GENERATED__INTERNALSYSTEM_SYSTEM_TYPE_OBJECT_SUPPORT_HPP +#endif // FAST_DDS_GENERATED__WEIGHINGSYSTEM_WEIGHINGDDSTYPE_TYPE_OBJECT_SUPPORT_HPP diff --git a/mqttdds/Publisher.cxx b/mqttdds/Publisher.cxx index 7c4c055..bd071f9 100644 --- a/mqttdds/Publisher.cxx +++ b/mqttdds/Publisher.cxx @@ -449,7 +449,7 @@ void PublisherApp::run(std::shared_ptr dev) { print_msg.clear(); - print_msg["Title"] = "五彩湾"; + print_msg["Title"] = "贵州渝黔锰业有限公司提货单"; print_msg["GrossDeviceID"] = std::to_string(info.GrossDeviceID()); print_msg["GrossDeviceName"] = info.GrossDeviceName(); print_msg["TareDeviceID"] = std::to_string(info.TareDeviceID()); diff --git a/patch/patch_2_time_weigh b/patch/patch_2_time_weigh new file mode 100644 index 0000000..6a61cdd --- /dev/null +++ b/patch/patch_2_time_weigh @@ -0,0 +1,144 @@ +diff --git a/core/Publisher.cxx b/core/Publisher.cxx +index 6aba885..73e627f 100644 +--- a/core/Publisher.cxx ++++ b/core/Publisher.cxx +@@ -333,12 +333,21 @@ bool PublisherApp::print_receipt(const std::map& msg) + return true; + } + ++#define WEIGH_IDLE 0 ++#define WEIGH_LIC 1 ++#define WEIGH_STABLE1 2 ++#define WEIGH_STABLE2 3 ++#define WEIGH_PRINT 4 ++#define WEIGH_ERROR 5 ++#define WEIGH_LEAVE 6 ++ + void PublisherApp::run() + { +- uint8_t send_sum = 0; +- uint8_t is_print = 0; + std::string license_no = ""; + float stable_weight = 0; ++ float stable_weight1 = 0; ++ float stable_weight2 = 0; ++ int weigh_state = WEIGH_IDLE; + + while (!is_stopped()) + { +@@ -357,6 +366,7 @@ void PublisherApp::run() + if (license_no == "") + { + license_no = info.License(); ++ weigh_state = WEIGH_LIC; + } + } + else if (!DdsMsgData::ScaleInfo_queue_.empty()) +@@ -378,19 +388,18 @@ void PublisherApp::run() + else + { + stable_weight = 0; +- send_sum = 0; + } + + if (info.HasVehicle() == 0) + { + license_no = ""; +- if (is_print == 1) ++ if (weigh_state == WEIGH_LEAVE) + { + std::this_thread::sleep_for(std::chrono::seconds(5)); + std::map ctrl; + ctrl["FrontBar"] = "down"; + bar_ctrl(ctrl); +- is_print = 0; ++ weigh_state = WEIGH_IDLE; + } + } + } +@@ -464,7 +473,7 @@ void PublisherApp::run() + + print_receipt(print_msg); + +- is_print = 1; ++ weigh_state = WEIGH_LEAVE; + std::map ctrl; + ctrl["FrontBar"] = "up"; + bar_ctrl(ctrl); +@@ -477,7 +486,7 @@ void PublisherApp::run() + dds_lock.unlock(); + + std::this_thread::sleep_for(std::chrono::seconds(3)); +- send_sum = 0; ++ weigh_state = WEIGH_ERROR; + } + else + { +@@ -486,17 +495,57 @@ void PublisherApp::run() + } + + // logic +- if (send_sum == 0) ++ switch (weigh_state) + { +- if ((stable_weight != 0) && (license_no != "")) +- { +- DEBUG("send summary"); +- WeighingSystem::SummaryUpdate info; +- info.License() = license_no; +- info.StableValue() = stable_weight; +- summary_writer_->write(&info); +- send_sum = 1; +- } ++ case WEIGH_IDLE: ++ break; ++ case WEIGH_LIC: ++ if ((stable_weight != 0) && (license_no != "")) ++ { ++ DEBUG("stable_weight1 " << stable_weight); ++ DEBUG("license_no " << license_no); ++ stable_weight1 = stable_weight; ++ weigh_state = WEIGH_STABLE1; ++ } ++ break; ++ case WEIGH_STABLE1: ++ if (stable_weight == 0) ++ { ++ DEBUG("weigh1 clear"); ++ weigh_state = WEIGH_STABLE2; ++ } ++ break; ++ case WEIGH_STABLE2: ++ if ((stable_weight != 0) && (license_no != "")) ++ { ++ DEBUG("license_no " << license_no); ++ DEBUG("stable_weight2 " << stable_weight); ++ if (stable_weight < stable_weight1) ++ { ++ DEBUG("send sunnmary"); ++ WeighingSystem::SummaryUpdate info; ++ info.License() = license_no; ++ info.StableValue() = stable_weight; ++ summary_writer_->write(&info); ++ weigh_state = WEIGH_PRINT; ++ } ++ else ++ { ++ weigh_state = WEIGH_IDLE; ++ } ++ } ++ break; ++ case WEIGH_PRINT: ++ break; ++ case WEIGH_ERROR: ++ std::this_thread::sleep_for(std::chrono::seconds(3)); ++ weigh_state = WEIGH_STABLE2; ++ break; ++ case WEIGH_LEAVE: ++ break; ++ default: ++ weigh_state = WEIGH_IDLE; ++ break; + } + + // Wait for period or stop event diff --git a/patch/patch_wait_60s_weigh b/patch/patch_wait_60s_weigh new file mode 100644 index 0000000..c866cef --- /dev/null +++ b/patch/patch_wait_60s_weigh @@ -0,0 +1,128 @@ +diff --git a/core/Publisher.cxx b/core/Publisher.cxx +index 6aba885..acf2b7c 100644 +--- a/core/Publisher.cxx ++++ b/core/Publisher.cxx +@@ -333,12 +333,19 @@ bool PublisherApp::print_receipt(const std::map& msg) + return true; + } + ++#define WEIGH_IDLE 0 ++#define WEIGH_LIC 1 ++#define WEIGH_STABLE 2 ++#define WEIGH_PRINT 3 ++#define WEIGH_ERROR 4 ++#define WEIGH_LEAVE 5 ++ + void PublisherApp::run() + { +- uint8_t send_sum = 0; +- uint8_t is_print = 0; + std::string license_no = ""; + float stable_weight = 0; ++ int weigh_state = WEIGH_IDLE; ++ uint16_t weigh_timer = 0; + + while (!is_stopped()) + { +@@ -357,6 +364,7 @@ void PublisherApp::run() + if (license_no == "") + { + license_no = info.License(); ++ weigh_state = WEIGH_LIC; + } + } + else if (!DdsMsgData::ScaleInfo_queue_.empty()) +@@ -378,19 +386,18 @@ void PublisherApp::run() + else + { + stable_weight = 0; +- send_sum = 0; + } + + if (info.HasVehicle() == 0) + { + license_no = ""; +- if (is_print == 1) ++ if (weigh_state == WEIGH_LEAVE) + { + std::this_thread::sleep_for(std::chrono::seconds(5)); + std::map ctrl; + ctrl["FrontBar"] = "down"; + bar_ctrl(ctrl); +- is_print = 0; ++ weigh_state = WEIGH_IDLE; + } + } + } +@@ -464,7 +471,7 @@ void PublisherApp::run() + + print_receipt(print_msg); + +- is_print = 1; ++ weigh_state = WEIGH_LEAVE; + std::map ctrl; + ctrl["FrontBar"] = "up"; + bar_ctrl(ctrl); +@@ -477,7 +484,7 @@ void PublisherApp::run() + dds_lock.unlock(); + + std::this_thread::sleep_for(std::chrono::seconds(3)); +- send_sum = 0; ++ weigh_state = WEIGH_ERROR; + } + else + { +@@ -486,17 +493,43 @@ void PublisherApp::run() + } + + // logic +- if (send_sum == 0) ++ switch (weigh_state) + { +- if ((stable_weight != 0) && (license_no != "")) +- { +- DEBUG("send summary"); +- WeighingSystem::SummaryUpdate info; +- info.License() = license_no; +- info.StableValue() = stable_weight; +- summary_writer_->write(&info); +- send_sum = 1; +- } ++ case WEIGH_IDLE: ++ weigh_timer = 0; ++ break; ++ case WEIGH_LIC: ++ if (weigh_timer++ > 600) ++ { ++ DEBUG("timer reach"); ++ DEBUG("license_no " << license_no); ++ DEBUG("stable_weight " << stable_weight); ++ weigh_state = WEIGH_STABLE; ++ weigh_timer = 0; ++ } ++ break; ++ case WEIGH_STABLE: ++ if ((stable_weight != 0) && (license_no != "")) ++ { ++ DEBUG("send summary"); ++ WeighingSystem::SummaryUpdate info; ++ info.License() = license_no; ++ info.StableValue() = stable_weight; ++ summary_writer_->write(&info); ++ weigh_state = WEIGH_PRINT; ++ } ++ break; ++ case WEIGH_PRINT: ++ break; ++ case WEIGH_ERROR: ++ std::this_thread::sleep_for(std::chrono::seconds(3)); ++ weigh_state = WEIGH_STABLE; ++ break; ++ case WEIGH_LEAVE: ++ break; ++ default: ++ weigh_state = WEIGH_IDLE; ++ break; + } + + // Wait for period or stop event diff --git a/print/MsgHandler.cxx b/print/MsgHandler.cxx index 18013b4..a5a2c70 100644 --- a/print/MsgHandler.cxx +++ b/print/MsgHandler.cxx @@ -2,6 +2,7 @@ #include #include #include +#include #include "MsgHandler.hpp" #include "base.h" @@ -70,13 +71,48 @@ int MsgHandler::SendMsg(const std::vector& data) return -1; } - int bytesWritten = write(fd, data.data(), data.size()); - if (bytesWritten < 0) + // int bytesWritten = write(fd, data.data(), data.size()); + // if (bytesWritten < 0) + // { + // perror("发送数据失败"); + // } + + // return bytesWritten; + + // 大块数据分块发送,防止 57600 波特下打印机 UART FIFO 溢出 + // 阈值选 512:单行/单字段都 < 512 字节,走单次 write; + // 超过阈值(就是 12800 字节的章图栅格)按 256 字节切,段间等 3ms。 + constexpr size_t CHUNK_THRESHOLD = 512; + constexpr size_t CHUNK_SIZE = 256; + constexpr unsigned int INTER_US = 50000; + if (data.size() < CHUNK_THRESHOLD) { - perror("发送数据失败"); + int bytesWritten = write(fd, data.data(), data.size()); + if (bytesWritten < 0) perror("发送数据失败"); + return bytesWritten; } + size_t totalWritten = 0; + size_t pos = 0; + while (pos < data.size()) + { + size_t end = std::min(pos + CHUNK_SIZE, data.size()); + ssize_t n = write(fd, data.data() + pos, end - pos); + if (n < 0) + { + perror("发送数据失败"); + return -1; + } + totalWritten += static_cast(n); + pos = end; + if (pos < data.size()) usleep(INTER_US); - return bytesWritten; + + + } + return static_cast(totalWritten); + + + } int MsgHandler::RecvMsg(std::vector& data, int timeoutMs) @@ -127,10 +163,52 @@ int MsgHandler::RecvMsg(std::vector& data, int timeoutMs) return bytesRead; } +// 辅助函数:把 std::vector 的子区间提取出来 +static std::vector make_range(const std::vector& src, + size_t begin, size_t end) +{ + return std::vector(src.begin() + begin, src.begin() + end); +} + +// 分段发送栅格数据,防止 57600 波特下 UART FIFO 溢出 +// chunkSize:每段字节数,建议 256~512(57600 下 256 字节传输耗时≈4.5ms,留 3ms 给打印机消化) +// interChunkUs:段间等待微秒数,建议 3000~5000(3~5ms) +void MsgHandler::SendDeviceMsgChunked(const std::vector& data, + size_t chunkSize, + unsigned int interChunkUs) +{ + size_t pos = 0; + while (pos < data.size()) + { + size_t end = std::min(pos + chunkSize, data.size()); + std::vector chunk = make_range(data, pos, end); + SendDeviceMsg(chunk); + if (end < data.size()) + { // 不是最后一段,才需要等 + usleep(interChunkUs); + } + pos = end; + } +} + + void MsgHandler::HandleDdsMsg(const std::map& msg) { + + // 添加调试代码 + std::cout << "[Print] ====== HandleDdsMsg 收到的 map 内容 ======" << std::endl; + for (const auto& pair : msg) + { + std::cout << "[Print] key=[" << pair.first << "] value=[" << pair.second << "]" << std::endl; + } + std::cout << "[Print] ==========================================" << std::endl; + EncodeMsg(msg); SendDeviceMsg(m_PrintData); + sleep(2); + //SendDeviceMsg(m_PrintData); // 第 2 次 + sleep(4); + //SendDeviceMsg(m_PrintData); // 第 3 次 } void MsgHandler::EncodeMsg(const std::map& msg) @@ -138,11 +216,15 @@ void MsgHandler::EncodeMsg(const std::map& msg) if(device == "NP80A") { auto it = msg.find("Title"); + std::cout << "[Print] Title in msg: [" << (it != msg.end() ? it->second : "NOT FOUND") << "]" << std::endl; if(it != msg.end()) { - if(it->second == "五彩湾") + std::cout << "[Print] comparing: [" << it->second << "] == [贵州渝黔锰业有限公司提货单] ?" << std::endl; + if(it->second == "贵州渝黔锰业有限公司提货单") { + std::cout << "[Print] ==== 命中贵州渝黔锰业有限公司提货单条件,调用Print1_1 ====" << std::endl; Print1_1(msg); + std::cout << "[Print] DEBUG: Print1_1 done, m_PrintData.size() = " << m_PrintData.size() << std::endl; } } } @@ -208,6 +290,21 @@ std::vector MsgHandler::BuildStringLine_HSK33(std::map& return m_ba; } + +// 行内容生成器(不做任何编码转换,直接按字节写入) +// 适用于标签是已编码好的 GB2312 字节串场景(Print1_1 打印标题/字段用) +std::vector MsgHandler::BuildStringLine_RawBytes(const std::map& PointList) +{ + std::vector m_ba; + for (const auto &p : PointList) + { + m_ba.insert(m_ba.end(), p.second.begin(), p.second.end()); + } + return m_ba; +} + + + //打印机 //清空 并设置纸大小 void MsgHandler::Page_ClearAndSet(std::vector& Data, char * h1h2h3h4) @@ -636,551 +733,297 @@ bool MsgHandler::check_odd(const std::string date) return false; } -//NP80A打印通用称重 -void MsgHandler::Print1_1(const std::map& msg) -{ - //这里组装打印输出内容 - std::string szTemp; - std::map::const_iterator it; - std::vector blTemp; - std::map m_newObj; - m_PrintData.clear(); - //初始化打印机 - m_PrintData.insert(m_PrintData.end(), {0x1B, 0x40}); - //设置中文模式 - m_PrintData.insert(m_PrintData.end(), {0x1C, 0x21, 0x00}); - //设置0号字 - m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x00}); - //设置左对齐 - m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x00}); - //设置页模式 - m_PrintData.insert(m_PrintData.end(), {0x11, 0x21}); //进入页模式 - m_PrintData.insert(m_PrintData.end(), {0x11, 0x25, 00});//设置页模式打印方向 - // m_PrintData.insert(m_PrintData.end(), {0x11, 0x23, 0x02, 0x30, 0x03, 0x60});//设置页模式宽度和高度,70mm*108mm - m_PrintData.insert(m_PrintData.end(), {0x11, 0x24, 0x00, 0x00, 0x00, 0x00});//设置打印坐标起点 - - //=============================开票时间===================================== - - //加顶框 - m_newObj[1] = ("┌"); - m_newObj[23] = ("┐"); - blTemp = BuildLine(24,m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - //====抬头===================== - m_newObj.clear(); - m_newObj[0] = ("│"); - m_newObj[26] = (" 中电投新疆能源化工集团"); - m_newObj[528] = ("│"); - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - m_newObj.clear(); - m_newObj[0] = ("│"); - m_newObj[26] = (" 五彩湾发电有限责任公司"); - m_newObj[528] = ("│"); - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - m_newObj.clear(); - m_newObj[0] = ("│"); - m_newObj[26] = (" 计量单"); - m_newObj[528] = ("│"); - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - m_newObj.clear(); - m_newObj[1] = ("├"); - m_newObj[8] = ("┬"); - m_newObj[23] = ("┤"); - blTemp = BuildLine(24, m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - //====票据号===================== - - m_newObj.clear(); - m_newObj[0] = ("│"); - m_newObj[26] = (" 票据号"); - m_newObj[168] = ("│"); - it = msg.find("CoalNumber"); - if(it != msg.end()) - { - m_newObj[190] = it->second; - } - m_newObj[528] = ("│"); - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - - m_newObj.clear(); - m_newObj[1] = ("├"); - m_newObj[8] = ("┼"); - m_newObj[23] = ("┤"); - blTemp = BuildLine(24,m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - //====车牌号===================== - - m_newObj.clear(); - m_newObj[0] = ("│"); - m_newObj[26] = (" 车牌号"); - m_newObj[168] = ("│"); - it = msg.find("CarNumber"); - if(it != msg.end()) - { - m_newObj[190] = it->second; +// ===== 新增:章图读取(与 PrintTest/main.c::load_stamp_image 一致) ===== +// 把 hex ASCII 文本文件(如 "FF00A5...")转成二进制位图字节流 +// 失败返回 false,out 被清空 +bool MsgHandler::LoadStampHexImage(const std::string& path, std::vector& out) +{ + out.clear(); + std::ifstream fp(path); + if (!fp.is_open()) { + std::cerr << "[Print] 无法打开章图文件: " << path << std::endl; + return false; } - m_newObj[528] = ("│"); - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - m_newObj.clear(); - m_newObj[1] = ("├"); - m_newObj[8] = ("┼"); - m_newObj[23] = ("┤"); - blTemp = BuildLine(24,m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - //====供应商===================== - - const size_t MAX_DISPLAY_WIDTH = 28; // 每行最多28个显示位置 - - m_newObj.clear(); - m_newObj[0] = ("│"); - m_newObj[26] = (" 往来单位"); - m_newObj[168] = ("│"); - it = msg.find("Supplier"); - if (it != msg.end()) - { - // 检查显示宽度是否超过限制 - size_t display_width = get_utf8_display_width(it->second); - if (display_width > MAX_DISPLAY_WIDTH) - { - // 需要分割成多行显示 - - // 第一行:显示前32个宽度的内容 - std::vector lines = split_utf8_by_width(it->second, MAX_DISPLAY_WIDTH); - - // 输出第一行(包含前缀) - m_newObj[190] = lines[0]; - m_newObj[528] = ("│"); - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - // 输出剩余行(不包含前缀,但有边框) - for (size_t i = 1; i < lines.size(); i++) - { - m_newObj.clear(); - m_newObj[0] = ("│"); - m_newObj[168] = ("│"); - m_newObj[190] = lines[i]; - m_newObj[528] = ("│"); - - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - } + // 读取整个文件为字符串 + std::string hex_str((std::istreambuf_iterator(fp)), + std::istreambuf_iterator()); + fp.close(); + + // 转换 hex → binary(跳过空白字符) + out.reserve(hex_str.size() / 2); + size_t i = 0; + while (i < hex_str.size()) { + char c = hex_str[i]; + if (c == ' ' || c == '\n' || c == '\r' || c == '\t') { + i++; + continue; } - else - { - // 宽度不超过限制,正常显示 - m_newObj[190] = it->second; - m_newObj[528] = ("│"); - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); + if (i + 1 >= hex_str.size()) break; + char hi = hex_str[i]; + char lo = hex_str[i + 1]; + + auto hex_val = [](char ch) -> int { + if (ch >= '0' && ch <= '9') return ch - '0'; + if (ch >= 'a' && ch <= 'f') return 10 + (ch - 'a'); + if (ch >= 'A' && ch <= 'F') return 10 + (ch - 'A'); + return -1; + }; + + int h = hex_val(hi); + int l = hex_val(lo); + if (h < 0 || l < 0) { + i++; + continue; } + out.push_back(static_cast((h << 4) | l)); + i += 2; } - else - { - // 没有找到,显示空内容 - m_newObj[190] = ""; - m_newObj[528] = ("│"); - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); + + if (out.empty()) { + std::cerr << "[Print] 章图文件为空或解析失败: " << path << std::endl; + return false; } + return true; +} - m_newObj.clear(); - m_newObj[1] = ("├"); - m_newObj[7] = ("┄");//防伪 - m_newObj[8] = ("┼"); - m_newObj[23] = ("┤"); - blTemp = BuildLine(24,m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - //====品种===================== - - m_newObj.clear(); - m_newObj[0] = ("│"); - m_newObj[26] = (" 品种"); - m_newObj[168] = ("│"); - it = msg.find("GoodsType"); - if(it != msg.end()) - { - m_newObj[190] = it->second; +// ===== 新增:章图最近邻放大(与 PrintTest/main.c::print_stamp_image 中 scale>1 部分一致) ===== +bool MsgHandler::EnlargeStampNearest(const std::vector& src,int src_w, int src_h, int scale,std::vector& dst) +{ + if (scale <= 1) { + dst = src; + return true; + } + int dst_w = src_w * scale; + int dst_h = src_h * scale; + int dst_bytes_per_line = (dst_w + 7) / 8; + int src_bytes_per_line = (src_w + 7) / 8; + + dst.assign(dst_bytes_per_line * dst_h, 0); + + for (int y = 0; y < src_h; y++) { + for (int x = 0; x < src_w; x++) { + int orig_byte = y * src_bytes_per_line + x / 8; + int orig_bit = 7 - (x % 8); + uint8_t pixel = (src[orig_byte] >> orig_bit) & 1; + if (!pixel) continue; + + for (int dy = 0; dy < scale; dy++) { + for (int dx = 0; dx < scale; dx++) { + int nx = x * scale + dx; + int ny = y * scale + dy; + int new_byte = ny * dst_bytes_per_line + nx / 8; + int new_bit = 7 - (nx % 8); + dst[new_byte] |= (1 << new_bit); + } + } + } } - m_newObj[528] = ("│"); - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); + return true; +} - m_newObj.clear(); - m_newObj[1] = ("├"); - m_newObj[8] = ("┼"); - m_newObj[23] = ("┤"); - blTemp = BuildLine(24,m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); +//NP80A打印绥阳铁合金厂过磅单(完全按 PrintTest/main.c 的字节流生成) +// 关键点: +// 1) 标签用原始 GB2312 字节直接 push,绝不经过 BuildStringLine +// 2) 值用 UTF8ToGB2312 转码后直接 push +// 3) 章图改用 GS v 0(光栅位图),不再是 NV 位图 FS p +// 4) 走纸量改为 0x11(17行),让切纸位置与 PrintTest 一致 +void MsgHandler::Print1_1(const std::map& msg) +{ + std::map::const_iterator it; + m_PrintData.clear(); - //====批次号===================== + // 1. 初始化打印机 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x40}); // ESC @ 复位 + usleep(200 * 1000); - m_newObj.clear(); - m_newObj[0] = ("│"); - m_newObj[26] = (" 批次号"); - m_newObj[168] = ("│"); - it = msg.find("BatchNumber"); - if(it != msg.end()) - { - m_newObj[190] = it->second; - } - m_newObj[528] = ("│"); - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - m_newObj.clear(); - m_newObj[1] = ("├"); - m_newObj[8] = ("┴"); - m_newObj[23] = ("┤"); - blTemp = BuildLine(24, m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - std::string GrossTime; - std::string TareTime; - std::string FirstTime; - std::string SecondTime; - std::string FirstDeviceID; - std::string SecondDeviceID; - - it = msg.find("GrossTime"); - if (it != msg.end()) - { - GrossTime = it->second; + // 2. 设置中文模式 + m_PrintData.insert(m_PrintData.end(), {0x1C, 0x21, 0x00}); // FS ! 0 + usleep(100 * 1000); + + // 3. 换行 4 次(PrintTest 实际是 4 次,不是 6 次) + for (int i = 0; i < 4; i++) { + m_PrintData.insert(m_PrintData.end(), {0x0A}); } - it = msg.find("TareTime"); - if (it != msg.end()) + usleep(50 * 1000); + + // 4. 标题居中 + 倍高倍宽 + 加粗 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x01}); // ESC a 1 居中 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x11}); // GS ! 0x11 倍高倍宽 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x45, 0x01}); // ESC E 1 加粗开 + + // 绥阳铁合金厂(原始 GB2312 字节,6 个汉字) + const uint8_t title_factory[] = { + 0xCB, 0xE7, // 绥 + 0xD1, 0xF4, // 阳 + 0xCC, 0xFA, // 铁 + 0xBA, 0xCF, // 合 + 0xBD, 0xF0, // 金 + 0xB3, 0xA7, // 厂 + }; + m_PrintData.insert(m_PrintData.end(), std::begin(title_factory), std::end(title_factory)); + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); + + // 过磅单(原始 GB2312 字节,3 个汉字) + const uint8_t title_bill[] = { + 0xB9, 0xFD, // 过 + 0xB0, 0xF5, // 磅 + 0xB5, 0xA5, // 单 + }; + m_PrintData.insert(m_PrintData.end(), std::begin(title_bill), std::end(title_bill)); + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); + + // 5. 恢复正常状态 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x45, 0x00}); // 加粗关 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x00}); // 正常大小 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x00}); // 左对齐 + //m_PrintData.insert(m_PrintData.end(), {0x1B, 0x20, 0x00}); // ← 新增:字符右侧间距 16 点(≈2mm) + usleep(100 * 1000); + + // 6. 打印各项字段 —— 直接 push 字节,避免任何二次转码 + //标签是 GB2312 字节串,值是 UTF8 → 转 GB2312 后 push + // 每行结尾追加0x0A 0x0A(两次换行,和 PrintTest 一致) + auto print_line = [&](const uint8_t* label_gb, size_t label_len, const std::string& key) { - TareTime = it->second; - } + // it = msg.find(key); + // if (it == msg.end()) return; - if (GrossTime < TareTime) - { - FirstTime = GrossTime; - SecondTime = TareTime; - it = msg.find("GrossDeviceID"); - if (it != msg.end()) - { - FirstDeviceID = it->second; - } - it = msg.find("TareDeviceID"); - if (it != msg.end()) + auto it = msg.find(key); + + //每次打印前设置左缩进(ESC $ 32 点 = ≈2mm) + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x24, 0x20, 0x00}); + + // 标签 + m_PrintData.insert(m_PrintData.end(), label_gb, label_gb + label_len); + // 值 + bool has_value = (it != msg.end()) && !(it->second.empty()); + + if (has_value) { - SecondDeviceID = it->second; + std::string val_gb = ot::UTF8ToGB2312(it->second.c_str()); + m_PrintData.insert(m_PrintData.end(), val_gb.begin(), val_gb.end()); } - } - else - { - FirstTime = TareTime; - SecondTime = GrossTime; - it = msg.find("TareDeviceID"); - if (it != msg.end()) + else if (key == "RockWeight") { - FirstDeviceID = it->second; + // 扣重默认值 0.00 + std::string val_gb = ot::UTF8ToGB2312("0.00"); + m_PrintData.insert(m_PrintData.end(), val_gb.begin(), val_gb.end()); } - it = msg.find("GrossDeviceID"); - if (it != msg.end()) + else if (key == "TrainNumber") { - SecondDeviceID = it->second; + // 车船号默认值 0 + std::string val_gb = ot::UTF8ToGB2312("0"); + m_PrintData.insert(m_PrintData.end(), val_gb.begin(), val_gb.end()); } - } - //====称重类型===================== - m_newObj.clear(); - m_newObj[0] = ("│"); - m_newObj[26] = " 一次称重"; - m_newObj[528] = ("│"); - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - m_newObj.clear(); - m_newObj[1] = ("├"); - m_newObj[8] = ("┬"); - m_newObj[23] = ("┤"); - blTemp = BuildLine(24, m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - //====磅称编号===================== - - m_newObj.clear(); - m_newObj[0] = ("│"); - m_newObj[26] = (" 汽车衡编号"); - m_newObj[168] = ("│"); - m_newObj[190] = FirstDeviceID; - m_newObj[528] = ("│"); - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - m_newObj.clear(); - m_newObj[1] = ("├"); - m_newObj[8] = ("┼"); - m_newObj[23] = ("┤"); - blTemp = BuildLine(24, m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - //=========一次称重时间====================== - - m_newObj.clear(); - m_newObj[0] = ("│"); - m_newObj[26] = ("一次称重时间"); - m_newObj[168] = ("│"); - - // 防伪 - if (check_odd(FirstTime) == true) - { - m_newObj[196] = FirstTime; - } - else - { - m_newObj[190] = FirstTime; - } - m_newObj[528] = ("│"); - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - m_newObj.clear(); - m_newObj[1] = ("├"); - m_newObj[8] = ("┴"); - m_newObj[23] = ("┤"); - blTemp = BuildLine(24, m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - //====称重类型===================== - m_newObj.clear(); - m_newObj[0] = ("│"); - m_newObj[26] = " 二次称重"; - m_newObj[528] = ("│"); - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - m_newObj.clear(); - m_newObj[1] = ("├"); - m_newObj[8] = ("┬"); - m_newObj[23] = ("┤"); - blTemp = BuildLine(24, m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - //====磅称编号===================== - - m_newObj.clear(); - m_newObj[0] = ("│"); - m_newObj[26] = (" 汽车衡编号"); - m_newObj[168] = ("│"); - m_newObj[190] = SecondDeviceID; - m_newObj[528] = ("│"); - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - m_newObj.clear(); - m_newObj[1] = ("├"); - m_newObj[8] = ("┼"); - m_newObj[23] = ("┤"); - blTemp = BuildLine(24, m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - //=========二次称重时间====================== - - m_newObj.clear(); - m_newObj[0] = ("│"); - m_newObj[26] = ("二次称重时间"); - m_newObj[168] = ("│"); - - // 防伪 - if (check_odd(SecondTime) == true) - { - m_newObj[196] = SecondTime; - } - else - { - m_newObj[190] = SecondTime; - } + // 两次换行 + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); + }; - m_newObj[528] = ("│"); - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - m_newObj.clear(); - m_newObj[1] = ("├"); - m_newObj[8] = ("┼"); - m_newObj[17] = ("┬"); - m_newObj[23] = ("┤"); - blTemp = BuildLine(24, m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - //=========毛重====================== - - m_newObj.clear(); - m_newObj[0] = ("│"); - m_newObj[26] = (" 毛重"); - m_newObj[168] = ("│"); - it = msg.find("GrossWeight"); - if (it != msg.end()) - { - m_newObj[190] = it->second; - } + // 票据号: + { const uint8_t l[] = {0xC6,0xB1,0xBE,0xDD,0xBA,0xC5,0xA3,0xBA}; + print_line(l, sizeof(l), "CoalNumber"); } - m_newObj[384] = ("│"); - m_newObj[404] = ("kg"); - m_newObj[528] = ("│"); - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - m_newObj.clear(); - m_newObj[1] = ("├"); - m_newObj[8] = ("┼"); - m_newObj[17] = ("┼"); - m_newObj[23] = ("┤"); - blTemp = BuildLine(24, m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - //=========皮重====================== - - m_newObj.clear(); - m_newObj[0] = ("│"); - m_newObj[26] = (" 皮重"); - m_newObj[168] = ("│"); - - it = msg.find("TareWeight"); - if (it != msg.end()) - { - m_newObj[190] = it->second; - } + // 品种: + { const uint8_t l[] = {0xC6,0xB7,0xD6,0xD6,0xA3,0xBA}; + print_line(l, sizeof(l), "GoodsType"); } - m_newObj[384] = ("│"); - m_newObj[404] = ("kg"); - m_newObj[528] = ("┆");//防伪 - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - m_newObj.clear(); - m_newObj[1] = ("├"); - m_newObj[8] = ("┼"); - m_newObj[17] = ("┼"); - m_newObj[23] = ("┤"); - blTemp = BuildLine(24, m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - //=========净重====================== - - m_newObj.clear(); - m_newObj[0] = ("│"); - m_newObj[26] = (" 净重"); - m_newObj[168] = ("│"); - - it = msg.find("SuttleWeight"); - if (it != msg.end()) - { - m_newObj[190] = it->second; - } + // 订单号: + { const uint8_t l[] = {0xB6,0xA9,0xB5,0xA5,0xBA,0xC5,0xA3,0xBA}; + print_line(l, sizeof(l), "OrderNumber"); } + + // 车船号: + { const uint8_t l[] = {0xB3,0xB5,0xB4,0xAC,0xBA,0xC5,0xA3,0xBA}; + print_line(l, sizeof(l), "TrainNumber"); } + + // 车牌号: + { const uint8_t l[] = {0xB3,0xB5,0xC5,0xC6,0xBA,0xC5,0xA3,0xBA}; + print_line(l, sizeof(l), "CarNumber"); } + + // 供货单位: + { const uint8_t l[] = {0xB9,0xA9,0xBB,0xF5,0xB5,0xA5,0xCE,0xBB,0xA3,0xBA}; + print_line(l, sizeof(l), "Supplier"); } + + // 收货单位: + { const uint8_t l[] = {0xCA,0xD5,0xBB,0xF5,0xB5,0xA5,0xCE,0xBB,0xA3,0xBA}; + print_line(l, sizeof(l), "Customer"); } - m_newObj[384] = ("│"); - m_newObj[404] = ("kg"); - - m_newObj[528] = ("│"); - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - m_newObj.clear(); - m_newObj[1] = ("├"); - m_newObj[8] = ("┼"); - m_newObj[17] = ("┴"); - m_newObj[23] = ("┤"); - blTemp = BuildLine(24, m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - //=========备注===================== - - m_newObj.clear(); - m_newObj[0] = ("│"); - m_newObj[26] = (" 备注"); - m_newObj[168] = ("│"); - it = msg.find("Tips"); - if (it != msg.end()) + // 运输单位: + { const uint8_t l[] = {0xD4,0xCB,0xCA,0xE4,0xB5,0xA5,0xCE,0xBB,0xA3,0xBA}; + print_line(l, sizeof(l), "Transporter"); } + + // 毛重(t): + { const uint8_t l[] = {0xC3,0xAB,0xD6,0xD8,0xA3,0xA8,0x74,0xA3,0xA9,0xA3,0xBA}; + print_line(l, sizeof(l), "GrossWeight"); } + + // 毛重时间: + { const uint8_t l[] = {0xC3,0xAB,0xD6,0xD8,0xCA,0xB1,0xBC,0xE4,0xA3,0xBA}; + print_line(l, sizeof(l), "GrossTime"); } + + // 皮重(t): + { const uint8_t l[] = {0xC6,0xA4,0xD6,0xD8,0xA3,0xA8,0x74,0xA3,0xA9,0xA3,0xBA}; + print_line(l, sizeof(l), "TareWeight"); } + + // 皮重时间: + { const uint8_t l[] = {0xC6,0xA4,0xD6,0xD8,0xCA,0xB1,0xBC,0xE4,0xA3,0xBA}; + print_line(l, sizeof(l), "TareTime"); } + + // 净重(t): + { const uint8_t l[] = {0xBE,0xBB,0xD6,0xD8,0xA3,0xA8,0x74,0xA3,0xA9,0xA3,0xBA}; + print_line(l, sizeof(l), "SuttleWeight"); } + + // 扣重(t): + { const uint8_t l[] = {0xBF,0xDB,0xD6,0xD8,0xA3,0xA8,0x74,0xA3,0xA9,0xA3,0xBA}; + print_line(l, sizeof(l), "RockWeight"); } + + usleep(100 * 1000); + + // 7. 扣重打印完成后,反向走纸 10 单位(为打印章做准备) + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x6A, 0x0A}); // ESC j 10 + usleep(100 * 1000); + + // 8. 设置右对齐,准备打印章 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x02}); // ESC a 2 右对齐 + usleep(50 * 1000); + + // 9. 打印章图片(GS v 0 光栅位图,160x160 → 放大 2 倍 → 320x320) { - m_newObj[190] = it->second; + std::vector stamp_raw; + if (LoadStampHexImage("/userdata/auseft/yuqian.bin", stamp_raw)) { + std::vector stamp_scaled; + if (EnlargeStampNearest(stamp_raw, 160, 160, 2, stamp_scaled)) { + const int bytes_per_line = (320 + 7) / 8; // = 40 + const int total_lines = 320; + const uint8_t hdr[8] = { + 0x1D, 0x76, 0x30, 0x00, // GS v 0 m=0 + static_cast(bytes_per_line & 0xFF), + static_cast((bytes_per_line >> 8) & 0xFF), + static_cast(total_lines & 0xFF), + static_cast((total_lines >> 8) & 0xFF), + }; + m_PrintData.insert(m_PrintData.end(), hdr, hdr + 8); + m_PrintData.insert(m_PrintData.end(), stamp_scaled.begin(), stamp_scaled.end()); + // 不再把栅格塞进 m_PrintData,直接分块写串口,每 256 字节间隔 3ms + // SendDeviceMsg(std::vector(hdr, hdr + 8)); // 先单独发 GS v 0 头 + // usleep(50 * 1000); // 等打印机解析完头 + // SendDeviceMsgChunked(stamp_scaled, 256, 3000); // 栅格分 256 字节/段,段间等 3ms + } else { + std::cerr << "[Print] 章图放大失败" << std::endl; + } + } else { + std::cerr << "[Print] 章图加载失败,将跳过章图打印" << std::endl; + } } + usleep(100 * 1000); + + // 10. 正向走纸 7 行 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x64, 0x7}); // ESC d 17 + usleep(100 * 1000); - m_newObj[528] = ("│"); - blTemp = BuildStringLine(m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - m_newObj.clear(); - m_newObj[1] = ("└"); - m_newObj[8] = ("┴"); - m_newObj[9] = ("┄");//防伪 - m_newObj[23] = ("┘"); - blTemp = BuildLine(24, m_newObj); - m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); - m_PrintData.insert(m_PrintData.end(), {0x0A}); - - //=========打印===================== - //打印页 - m_PrintData.insert(m_PrintData.end(), {0x11, 0x0C}); - //退出页模式 - m_PrintData.insert(m_PrintData.end(), {0x11, 0x22}); - - //盖章 - m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x02});//设置右对齐 - m_PrintData.insert(m_PrintData.end(), {0x1B, 0x4B, 0x60});//向上调整位置 - m_PrintData.insert(m_PrintData.end(), {0x1B, 0x4B, 0x60});//向上调整位置 - m_PrintData.insert(m_PrintData.end(), {0x1B, 0x4B, 0x60});//向上调整位置 - m_PrintData.insert(m_PrintData.end(), {0x1B, 0x4B, 0x60});//向上调整位置 - m_PrintData.insert(m_PrintData.end(), {0x1B, 0x4B, 0x40});//向上调整位置 - m_PrintData.insert(m_PrintData.end(), {0x1C, 0x70, 0x01, 0x00});//打印下载NV位图 - - m_PrintData.insert(m_PrintData.end(), {0x1B, 0x64, 0x06});//空行并打印 - m_PrintData.insert(m_PrintData.end(), {0x1B, 0x69});//切纸 -} \ No newline at end of file + // 11. 全切 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x69}); +} diff --git a/print/MsgHandler.hpp b/print/MsgHandler.hpp index 1d9e15e..3232f76 100644 --- a/print/MsgHandler.hpp +++ b/print/MsgHandler.hpp @@ -29,10 +29,16 @@ public: } void ClosePort(); + void SendDeviceMsgChunked(const std::vector& data, + size_t chunkSize = 256, + unsigned int interChunkUs = 3000); + private: std::vector BuildLine(int m_max, const std::map& PointList, int no_line_min = 0, int no_line_max = 0); //行线条生成器 std::vector BuildStringLine(std::map& PointList); //行线条生成器 std::vector BuildStringLine_HSK33(std::map& PointList); //行线条生成器 + std::vector BuildStringLine_RawBytes(const std::map& PointList); + void Page_ClearAndSet(std::vector& Data, char * h1h2h3h4); void Page_ESCL (std::vector& Data, const char *n1n2, const char *x1x2x3x4, const char *y1y2y3y4, @@ -51,6 +57,12 @@ private: bool check_odd(const std::string date); void Print1_1(const std::map& msg); + + // ----- 新增:章图读取与放大(与 PrintTest/main.c 一致) ----- + bool LoadStampHexImage(const std::string& path, std::vector& out); + bool EnlargeStampNearest(const std::vector& src, + int src_w, int src_h, int scale, + std::vector& dst); }; -#endif \ No newline at end of file +#endif diff --git a/print/MsgHandler2.cxx b/print/MsgHandler2.cxx new file mode 100644 index 0000000..b6074cb --- /dev/null +++ b/print/MsgHandler2.cxx @@ -0,0 +1,4429 @@ +#include +#include +#include +#include + +#include "MsgHandler.hpp" +#include "base.h" +#include "strcode.h" + +MsgHandler::MsgHandler() : fd(-1) {} + +bool MsgHandler::OpenPort(const std::string& port, const std::string& baudrate) +{ + return true; +} + +void MsgHandler::ClosePort() +{ + if (fd != -1) + { + close(fd); + fd = -1; + } +} + +bool MsgHandler::SetDevice(const std::string& device) +{ + this->device = device; + + return true; +} + +int MsgHandler::SendDeviceMsg(const std::vector& data) +{ + std::cout << "write to " << this->device << std::endl; + for (int num : data) { + std::cout << std::hex << std::setw(2) << std::setfill('0') + << num << " "; + } + std::cout << std::endl; + + int bytesWritten = SendMsg(data); + + return bytesWritten; +} + +int MsgHandler::RecvDeviceMsg(std::vector& data, int timeoutMs) +{ + int bytesRead = RecvMsg(data, timeoutMs); + + if (bytesRead > 0) + { + std::cout << "read from " << this->device << std::endl; + for (int num : data) + { + std::cout << std::hex << std::setw(2) << std::setfill('0') + << num << " "; + } + std::cout << std::endl; + } + + return bytesRead; +} + +int MsgHandler::SendMsg(const std::vector& data) +{ + if (fd == -1) + { + perror("设备未打开"); + return -1; + } + + int bytesWritten = write(fd, data.data(), data.size()); + if (bytesWritten < 0) + { + perror("发送数据失败"); + } + + return bytesWritten; +} + +int MsgHandler::RecvMsg(std::vector& data, int timeoutMs) +{ + if (fd == -1) + { + perror("设备未打开\n"); + return -1; + } + + // 使用select实现超时 + fd_set readfds; + struct timeval tv; + + FD_ZERO(&readfds); + FD_SET(fd, &readfds); + + tv.tv_sec = timeoutMs / 1000; + tv.tv_usec = (timeoutMs % 1000) * 1000; + + int ret = select(fd + 1, &readfds, NULL, NULL, &tv); + if (ret == -1) + { + perror("select错误"); + return -1; + } + else if (ret == 0) + { + //无数据可读 + return 0; + } + + // 有数据可读 + uint8_t bytes; + if (ioctl(fd, FIONREAD, &bytes) < 0) + { + perror("ioctl FIONREAD失败"); + return -1; + } + data.resize(bytes); + int bytesRead = read(fd, data.data(), bytes); + if (bytesRead < 0) + { + perror("读取数据失败"); + return -1; + } + + return bytesRead; +} + +void MsgHandler::HandleDdsMsg(const std::map& msg) +{ + EncodeMsg(msg); + SendDeviceMsg(m_PrintData); +} + +void MsgHandler::EncodeMsg(const std::map& msg) +{ + if(device == "T080") + { + auto it = msg.find("Title"); + if(it != msg.end()) + { + if(it->second == "入厂排队票") + { + Print1_2(msg); + } + else if(it->second == "燃料轻磅票") + { + Print2_2(msg); + } + else if(it->second == "过衡单") + { + Print3_2(msg); + } + else if(it->second == "转煤单") + { + Print4_2(msg); + } + else if(it->second == "灰磅票") + { + Print5_2(msg); + } + else if(it->second == "提货单") + { + Print6_2(msg); + } + else if(it->second == "发货单") + { + Print6_2(msg); + } + } + } + else if(device == "Star") + { + auto it = msg.find("Title"); + if(it != msg.end()) + { + if(it->second == "入厂排队票") + { + Print1_1(msg); + } + } + } + else if(device == "NP80A") + { + auto it = msg.find("Title"); + if(it != msg.end()) + { + if(it->second == "排队票") + { + Print1_3(msg); + } + else if(it->second == "燃料轻磅票") + { + Print2_3(msg); + } + else if(it->second == "转煤单") + { + Print4_3(msg); + } + else if(it->second == "配煤票") + { + Print5_3(msg); + } + else if(it->second == "灰磅票") + { + Print6_3(msg); + } + else if(it->second == "过磅票") + { + Print8_3(msg); + } + } + } +} + +//行线条生成器 +std::vector MsgHandler::BuildLine(int m_max, const std::map& PointList, int no_line_min, int no_line_max) +{ + std::vector m_ba; + for (int i=1;isecond.c_str()); + } + else + { + if(i <= no_line_min || i >= no_line_max){ + szTemp = ot::UTF8ToGB2312("─"); + } + else { + szTemp = ot::UTF8ToGB2312(" "); + } + } + m_ba.insert(m_ba.end(), szTemp.begin(), szTemp.end()); + } + return m_ba; +} + +//行线条生成器 +std::vector MsgHandler::BuildStringLine(std::map& PointList) +{ + std::vector m_ba; + + for (auto &p : PointList) + { + char s[4]={0}; + memcpy(s,&(p.first),2); + std::string szTemp; + szTemp=ot::UTF8ToGB2312(p.second.c_str()); + //设置横向绝对位置 + m_ba.insert(m_ba.end(), {0x1B, 0x24}); + m_ba.insert(m_ba.end(), s, s+2); + m_ba.insert(m_ba.end(), szTemp.begin(), szTemp.end()); + } + return m_ba; +} + +//行线条生成器 +std::vector MsgHandler::BuildStringLine_HSK33(std::map& PointList) +{ + std::vector m_ba; + + for (auto &p : PointList) + { + std::string szTemp; + szTemp=ot::UTF8ToGB2312(p.second.c_str()); + m_ba.insert(m_ba.end(), szTemp.begin(), szTemp.end()); + } + + return m_ba; +} + +//打印机 +//清空 并设置纸大小 +void MsgHandler::Page_ClearAndSet(std::vector& Data, char * h1h2h3h4) +{ + char sbuf[8] = {0x1B, 'D', h1h2h3h4[0], h1h2h3h4[1], h1h2h3h4[2], h1h2h3h4[3], 0x0A, 0x00}; + //清空 + Data.insert(Data.end(), {0x1B, 'C', 0x0A, 0x00}); + //设置纸大小 + Data.insert(Data.end(), std::begin(sbuf), std::end(sbuf)); +} + +//根据起点和结束点的坐标值定义指定宽度的直线/边框 +/// 根据起点和结束点的坐标值定义指定宽度的直线/边框,并将此 +/// 予编号。即定义线条的格式。 +/// 本命令不可以定义斜线。 +/// 有效的定义命令同时将在打印映像缓冲区中实现线条数据。映像 +/// 命令将无法清除本命令定义的格式。 +/// 清除本命令定义的格式应使用页面格式清除指令(ESC C)或线条 +/// 令(ESC E)。 +/// n1n2: 线条编号 +/// x1x2x3x4: 起始点的X方向坐标,单位 0.1mm毫米 +/// y1y2y3y4: 起始点的Y方向坐标,单位 0.1mm毫米 +/// x5x6x7x8: 结束点的X方向坐标,单位 0.1mm毫米 +/// y5y6y7y8: 结束点的Y方向坐标,单位 0.1mm毫米 +/// d: 线条方向(根据打印机型号不同可定义值不同 +/// 规范 A +/// d=48 (“0”) 水平线 +/// d=49 (“1”) 垂直线 +/// 规范 B +/// d=48 (“0”) 水平线 +/// d=49 (“1”) 垂直线 +/// d=50 (“2”) 边框 +/// w: 以点为单位的线条宽度(1点 = 0.125mm毫米) +/// 水平线(d=”0”)应使用y方向的常数设置(即y1y2y3y4 = y5y +/// 垂直线(d=”1”)应使用x方向的常数设置(即x1x2x3x4 = x5x +/// 例如:当打印区域为水平方向104毫米,垂直方向300毫米时 +/// X方向 Y方向 +/// x1x2x3x4,x5x6x7x8 y1y2y3y4,y5y6y7y8 +/// 水平线设置范围:“0000”到“1040” “0000”到“2999” +/// 垂直线设置范围:“0000”到“1039” “0000”到“3000” +/// 方框可设置范围:“0000”到“1040” “0000”到“3000” +void MsgHandler::Page_ESCL (std::vector& Data, const char *n1n2, const char *x1x2x3x4, const char *y1y2y3y4, + const char *x5x6x7x8, const char *y5y6y7y8, char d, char w) +{ + //打印命令 + char cbuf[30]; + cbuf[0] = 0x1B; + cbuf[1] = 'L'; + memcpy(&cbuf[2],n1n2,2); + cbuf[4] = ';'; + memcpy(&cbuf[5],x1x2x3x4,4); + cbuf[9] = ','; + memcpy(&cbuf[10],y1y2y3y4,4); + cbuf[14] = ','; + memcpy(&cbuf[15],x5x6x7x8,4); + cbuf[19] = ','; + memcpy(&cbuf[20],y5y6y7y8,4); + cbuf[24] = ','; + cbuf[25] = d; + cbuf[26] = ','; + cbuf[27] = w; + cbuf[28] = 0x0A; + cbuf[29] = 0x00; + + Data.insert(Data.end(), std::begin(cbuf), std::end(cbuf)); +} + +//指定字符串的位置、字体、高度、宽度、字符间距以及字符和字符串 +/// +/// 清除本命令定义的格式应使用页面格式清除指令(ESC C)。 +/// 指定字符串的位置、字体、高度、宽度、字符间距以及字符和字符串 +/// 的旋转方向,并将此定义赋予编号。即定义字符串的格式 +/// n1n2: 字符串编号 +/// x1x2x3x4: 字符串起始点的X方向坐标,单位 0.1mm毫米 +/// y1y2y3y4: 字符串起始点的Y方向坐标,单位 0.1mm毫米 +/// w: 每个字符的宽度倍数(可设置为1,2,3,4,5,6倍) +/// h: 每个字符的高度倍数(可设置为1,2,3,4,5,6倍) +/// c: 字符的字体定义(不同字体有不同的点尺寸) +/// 1: 小字体(8x16点)/2: 标准字体(16x24点) +/// 3: 汉字(12x24汉字模式字母和数字/24x24汉字 +/// 4: 粗体(24x32点) +/// r1: 字符的旋转方向(0: 0°, 1: 90°, 2: 180°, 3: 270°) +/// r2: 字符串的旋转方向(0: 0°, 1: 90°, 2: 180°, 3: 270 +/// d1d2: 字符间距(单位: 点/0.125mm毫米) +/// 本参数以及参数前的“,”可以忽略 +/// 忽略本参数时使用“ESC Y”命令定义的间距值 +/// s1s2: 字符修饰(最终修饰由s1和s2的值叠加) +/// s1=48(“0”)无修饰 s1=49(“1”)字符加粗 +/// s2=48(“0”)无修饰 s2=49(“1”)下划线 s2=50(“2”)反白 +/// a: 打印颜色(仅在打印机设置为双色打印时有效) +/// a=48(“0”) 黑色 +/// a=49(“1”) 红色 +/// 参数“,d1d2,s1s2,a”可忽略(如果忽略则设置为黑色,无字符修饰.使用 ESC Y +/// 设置字符间距) +/// 旋转是以顺时针方向围绕参照点为中心进行。 +/// 字符放大(宽度和高度倍数放大)时字符间距不进行放大 +/// 指定字体为汉字或光学识别字符(OCR)时国际字符集定义无效 +/// 指定字体为粗体或光学识别字符(OCR)时日文假名无效(日文版本 +/// 指定字体为汉字时根据打印机型号会有不同的处理方式(语言版本 +void MsgHandler::Page_ESCPC(std::vector& Data, const char *n1n2, const char *x1x2x3x4, const char *y1y2y3y4, + char w, char h, char c, const char * r1r2, const char * s1s2) +{ + //命令 + char cbuf[34]; + cbuf[0] = 0x1B; + cbuf[1] = 'P'; + cbuf[2] = 'C'; + memcpy(&cbuf[3],n1n2,2); + cbuf[5] = ';'; + memcpy(&cbuf[6],x1x2x3x4,4); + cbuf[10] = ','; + memcpy(&cbuf[11],y1y2y3y4,4); + cbuf[15] = ','; + cbuf[16] = w; + cbuf[17] = ','; + cbuf[18] = h; + cbuf[19] = ','; + cbuf[20] = c; + cbuf[21] = ','; + cbuf[22] = r1r2[0]; + cbuf[23] = r1r2[1]; + cbuf[24] = ','; + cbuf[25] = '0'; + cbuf[26] = '2'; + cbuf[27] = ','; + cbuf[28] = s1s2[0]; + cbuf[29] = s1s2[1]; + cbuf[30] = ','; + cbuf[31] = '0'; + cbuf[32] = 0x0A; + cbuf[33] = 0x00; + + Data.insert(Data.end(), std::begin(cbuf), std::end(cbuf)); +} + +//为使用字符串格式设置命令定义的字符串赋以内容。 +/// +/// 为使用字符串格式设置命令定义的字符串赋以内容。 +/// 新定义将覆盖以前输出映像缓冲区中的内容。 +/// 因此可不重新定义格式仅重新定义字符串内容。旧的即以前定义的字 +/// 符串内容将被删除,然后生成新字符串的内容映像。 +/// 页面格式清除指令(ESC C)清除本命令定义的内容。 +/// 清除输出映像缓冲区指令(ESC X)清除本命令定义的内容。 +/// n1n2: 字符串编号 +/// a1a2……an: 打印字符串内容(最多100个字符/50个汉字) +/// +/// 字符串编号 +/// 打印字符串内容(最多100个字符/50个汉字) +void MsgHandler::Page_ESCRC(std::vector& Data, const char *n1n2, const char *str) +{ + //命令 + char cbuf[6] = {0x1B, 'R', 'C', n1n2[0], n1n2[1], ';'}; + Data.insert(Data.end(), std::begin(cbuf), std::end(cbuf)); + + int len = strlen(str); + if (len >100) + len = 100; + + int ct = 0; + for(int i=0;i8) + ct = 8; + Data.insert(Data.end(), str+i, str+i+ct); + i+=ct; + } + + Data.insert(Data.end(), {0x0A, 0x00}); +} + +/// 将位图文件(BMP文件)作为图像数据写入输出映像缓冲区。 +/// 可选择覆盖(:冒号)/叠加(;分号)方式。 +/// 页面格式清除指令(ESC C)清除本命令定义的内容。 +/// 清除输出映像缓冲区指令(ESC X)清除本命令定义的内容。 +/// x1x2x3x4: 位图打印起始点的X方向坐标,单位 0.1mm毫米 +/// y1y2y3y4: 位图打印起始点的Y方向坐标,单位 0.1mm毫米 +/// n: 位图写入的模式。 +/// :(冒号)覆盖方式 +/// ;(分号)叠加方式 +/// BMP文件数据: BMP文件的所有内容。 +/// 要求是黑白格式的非压缩BMP文件。因此并非所有的 +/// BMP文件可以直接以此方式作为图像发送到打印机。 +/// 图像最大为 64k +void MsgHandler::Page_ESCH(std::vector& Data, char n, char *x1x2x3x4, char *y1y2y3y4, char *bmp, int bmpsize) +{ + //命令 + char cbuf[13]; + cbuf[0] = 0x1B; + cbuf[1] = 'H'; + cbuf[2] = n; + memcpy(&cbuf[3],x1x2x3x4,4); + cbuf[7] = ','; + memcpy(&cbuf[8],y1y2y3y4,4); + cbuf[12] = ','; + + Data.insert(Data.end(), std::begin(cbuf), std::end(cbuf)); + + int ct = 0; + for(int i=0;i8) + ct = 8; + + Data.insert(Data.end(), bmp+i, bmp+i+ct); + i+=ct; + } + + Data.insert(Data.end(), {',' ,0x0A, 0x00}); +} + +//切纸 +void MsgHandler::Page_Cut(std::vector& Data) +{ + //打印并出纸 + Data.insert(Data.end(), {0x1B, 'B' ,0x0A, 0x00}); +} + +//结束 +void MsgHandler::Page_End(std::vector& Data) +{ + //打印并出纸 + Data.insert(Data.end(), {0x1B, 'I' ,0x0A, 0x00}); +} + +//获取长度字符串 +void MsgHandler::GtstrLength(int iVal, char *p) +{ + std::string szTemp = std::to_string(iVal); + szTemp = szTemp.substr(szTemp.length() - 4); + memcpy(p, szTemp.c_str(), 4); +} + +//Star打印机打印排队票 +void MsgHandler::Print1_1(const std::map& msg) +{ + + //这里组装打印输出内容 + std::string szTemp; + std::map::const_iterator it; + std::vector blTemp; + std::map m_newObj; + char sTemp[5]={0}; + m_PrintData.clear(); + + //画线 + bool m_PrintGrossAndTare=false; + bool m_PrintSuttle=false; + int m_AllLines=8; + int m_iTemp=0; + int m_top=10120; + + if ((msg.find("GrossWeight") != msg.end()) || (msg.find("TareWeight") != msg.end())) + { + //需要打印发运毛重和发运皮重 + m_PrintGrossAndTare=true; + m_AllLines++; + } + + if (msg.find("SuttleWeight") != msg.end()) + { + //需要打印发运净重 + m_PrintSuttle=true; + m_AllLines++; + } + + it = msg.find("MCFB"); + int m_lines = 0; + int m_oneline=40; + if(it != msg.end()) + { + m_lines=it->second.length()/m_oneline; + if ((it->second.length()%m_oneline)>0) + { + m_lines+=1; + } + m_AllLines+=m_lines; + } + + m_iTemp=74*m_AllLines+m_top+100; + GtstrLength(m_iTemp,sTemp); + + + //单位为0.1毫米 + Page_ClearAndSet(m_PrintData, sTemp); //设置纸长 104 毫米 + + m_iTemp=74*m_AllLines+m_top; + GtstrLength(m_iTemp,sTemp); + + Page_ESCL(m_PrintData, (char *)"00", (char *)"0030", (char *)"0120", (char *)"0688", sTemp, '2','1'); //框 + + m_iTemp=m_top+74; + GtstrLength(m_iTemp,sTemp); + Page_ESCL(m_PrintData, (char *)"01", (char *)"0030", sTemp, (char *)"0688", sTemp,'0','1'); //横线1 + + m_iTemp+=74; + GtstrLength(m_iTemp,sTemp); + Page_ESCL(m_PrintData, (char *)"02", (char *)"0030", sTemp, (char *)"0688", sTemp,'0','1'); //横线2 + m_iTemp+=74; + + GtstrLength(m_iTemp,sTemp); + Page_ESCL(m_PrintData, (char *)"03", (char *)"0030", sTemp, (char *)"0688", sTemp,'0','1'); //横线3 + + m_iTemp+=74; + GtstrLength(m_iTemp,sTemp); + Page_ESCL(m_PrintData, (char *)"04", (char *)"0030", sTemp, (char *)"0688", sTemp,'0','1'); //横线4 + + //毛皮重 + if (m_PrintGrossAndTare) + { + m_iTemp+=74; + GtstrLength(m_iTemp,sTemp); + Page_ESCL(m_PrintData, (char *)"05", (char *)"0030", sTemp, (char *)"0688", sTemp,'0','1'); //横线5 + } + + //净重 + if (m_PrintSuttle) + { + m_iTemp+=74; + GtstrLength(m_iTemp,sTemp); + Page_ESCL(m_PrintData, (char *)"06", (char *)"0030", sTemp, (char *)"0688", sTemp,'0','1'); //横线6 + } + + + m_iTemp+=74; + GtstrLength(m_iTemp,sTemp); + Page_ESCL(m_PrintData, (char *)"07", (char *)"0030", sTemp, (char *)"0688", sTemp,'0','1'); //横线7 + Page_ESCL(m_PrintData, (char *)"20", (char *)"0180", (char *)"0194", (char *)"0180", sTemp,'1','1'); //竖线1 + Page_ESCL(m_PrintData, (char *)"21", (char *)"0360", (char *)"0268", (char *)"0360", sTemp,'1','1'); //竖线2 + Page_ESCL(m_PrintData, (char *)"22", (char *)"0520", (char *)"0268", (char *)"0520", sTemp,'1','1'); //竖线3 + + + //煤场要若干行 + m_iTemp+=74*m_lines; + GtstrLength(m_iTemp,sTemp); + Page_ESCL(m_PrintData, (char *)"08", (char *)"0030", sTemp, (char *)"0688", sTemp,'0','1'); //横线8 + + + char sTemp1[5]={0}; + m_iTemp+=74; + GtstrLength(m_iTemp,sTemp1); + Page_ESCL(m_PrintData, (char *)"09", (char *)"0030", sTemp1, (char *)"0688", sTemp1,'0','1'); //横线9 + + Page_ESCL(m_PrintData, (char *)"23", (char *)"0180", sTemp1, (char *)"0180", sTemp,'1','1'); //竖线1 + Page_ESCL(m_PrintData, (char *)"24", (char *)"0360", sTemp1, (char *)"0360", sTemp,'1','1'); //竖线2 + Page_ESCL(m_PrintData, (char *)"25", (char *)"0510", sTemp1, (char *)"0510", sTemp,'1','1'); //竖线3 + + + m_iTemp+=74; + GtstrLength(m_iTemp,sTemp); + Page_ESCL(m_PrintData, (char *)"10", (char *)"0030", sTemp, (char *)"0688", sTemp,'0','1'); //横线10 + + //打印采样单 + it = msg.find("TitleCorp"); + if(it != msg.end()) + { + szTemp = ot::UTF8ToGB2312(it->second.c_str()) + ot::UTF8ToGB2312("入厂排队票"); //入厂排队票 + } + Page_ESCPC(m_PrintData, (char *)"00",(char *)"0030",(char *)"0000",'2','2','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"00",ot::UTF8ToGB2312(szTemp.c_str()).c_str()); + //开票时间 + Page_ESCPC(m_PrintData, (char *)"01",(char *)"0040",(char *)"0140",'1','1','3',(char *)"00",(char *)"00"); + it = msg.find("DateTime"); + if(it != msg.end()) + { + Page_ESCRC(m_PrintData, (char *)"01",ot::UTF8ToGB2312(it->second.c_str()).c_str()); + } + //供应商 + Page_ESCPC(m_PrintData, (char *)"02",(char *)"0040",(char *)"0214",'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"02",ot::UTF8ToGB2312("供应商").c_str()); + + Page_ESCPC(m_PrintData, (char *)"03",(char *)"0200",(char *)"0214",'1','1','3',(char *)"00",(char *)"00"); + it = msg.find("Supplier"); + if(it != msg.end()) + { + Page_ESCRC(m_PrintData, (char *)"03",ot::UTF8ToGB2312(it->second.c_str()).c_str()); + } + + //排队号 + Page_ESCPC(m_PrintData, (char *)"04",(char *)"0040",(char *)"0288",'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"04",ot::UTF8ToGB2312("排队号").c_str()); + + Page_ESCPC(m_PrintData, (char *)"05",(char *)"0200",(char *)"0288",'1','1','3',(char *)"00",(char *)"00"); + it = msg.find("QueueID"); + if(it != msg.end()) + { + Page_ESCRC(m_PrintData, (char *)"05",ot::UTF8ToGB2312(it->second.c_str()).c_str()); + } + + //品 种 + Page_ESCPC(m_PrintData, (char *)"06",(char *)"0380",(char *)"0288",'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"06",ot::UTF8ToGB2312("品 种").c_str()); + + Page_ESCPC(m_PrintData, (char *)"07",(char *)"0540",(char *)"0288",'1','1','3',(char *)"00",(char *)"00"); + it = msg.find("GoodsType"); + if(it != msg.end()) + { + Page_ESCRC(m_PrintData, (char *)"07",ot::UTF8ToGB2312(it->second.c_str()).c_str()); + } + + //车牌号 + Page_ESCPC(m_PrintData, (char *)"08",(char *)"0040",(char *)"0362",'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"08",ot::UTF8ToGB2312("车牌号").c_str()); + + Page_ESCPC(m_PrintData, (char *)"09",(char *)"0200",(char *)"0362",'1','1','3',(char *)"00",(char *)"00"); + it = msg.find("CarNumber"); + if(it != msg.end()) + { + Page_ESCRC(m_PrintData, (char *)"09",ot::UTF8ToGB2312(it->second.c_str()).c_str()); + } + + //自编号 + Page_ESCPC(m_PrintData, (char *)"10",(char *)"0380",(char *)"0362",'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"10",ot::UTF8ToGB2312("自编号").c_str()); + + Page_ESCPC(m_PrintData, (char *)"11",(char *)"0540",(char *)"0362",'1','1','3',(char *)"00",(char *)"00"); + it = msg.find("CarID"); + if(it != msg.end()) + { + Page_ESCRC(m_PrintData, (char *)"11",ot::UTF8ToGB2312(it->second.c_str()).c_str()); + } + + + m_iTemp=10362+74; + GtstrLength(m_iTemp,sTemp); + //毛皮重 + if (m_PrintGrossAndTare) + { + + //发运毛重 + it = msg.find("GrossWeight"); + if(it != msg.end()) + { + szTemp = ot::UTF8ToGB2312(it->second.c_str()); + } + else + szTemp=""; + + Page_ESCPC(m_PrintData, (char *)"12",(char *)"0040",sTemp,'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"12",ot::UTF8ToGB2312("发运毛重").c_str()); + + Page_ESCPC(m_PrintData, (char *)"13",(char *)"0200",sTemp,'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"13",szTemp.c_str()); + + //发运皮重 + it = msg.find("TareWeight"); + if(it != msg.end()) + { + szTemp = ot::UTF8ToGB2312(it->second.c_str()); + } + else + szTemp=""; + Page_ESCPC(m_PrintData, (char *)"14",(char *)"0380",sTemp,'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"14",ot::UTF8ToGB2312("发运皮重").c_str()); + + Page_ESCPC(m_PrintData, (char *)"15",(char *)"0540",sTemp,'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"15",szTemp.c_str()); + + m_iTemp+=74; + GtstrLength(m_iTemp,sTemp); + } + + //发运净重 + if (m_PrintSuttle) + { + it = msg.find("SuttleWeight"); + if(it != msg.end()) + { + szTemp = ot::UTF8ToGB2312(it->second.c_str()); + } + else + szTemp=""; + + Page_ESCPC(m_PrintData, (char *)"16",(char *)"0040",sTemp,'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"16",ot::UTF8ToGB2312("发运净重").c_str()); + + Page_ESCPC(m_PrintData, (char *)"17",(char *)"0200",sTemp,'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"17",szTemp.c_str()); + + m_iTemp+=74; + GtstrLength(m_iTemp,sTemp); + } + + + //采样机 + Page_ESCPC(m_PrintData, (char *)"18",(char *)"0040",sTemp,'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"18",ot::UTF8ToGB2312("采样机").c_str()); + + Page_ESCPC(m_PrintData, (char *)"19",(char *)"0200",sTemp,'1','1','3',(char *)"00",(char *)"00"); + it = msg.find("SampleID"); + if(it != msg.end()) + { + Page_ESCRC(m_PrintData, (char *)"19",ot::UTF8ToGB2312(it->second.c_str()).c_str()); + } + + //接样员 + Page_ESCPC(m_PrintData, (char *)"20",(char *)"0380",sTemp,'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"20",ot::UTF8ToGB2312("接样员").c_str()); + + + //处理煤场 + it = msg.find("MCFB"); + if (m_lines>0) + { + m_iTemp+=74; + GtstrLength(m_iTemp,sTemp); + szTemp=it->second.substr(0,m_oneline); + Page_ESCPC(m_PrintData, (char *)"21",(char *)"0040",sTemp,'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"21",ot::UTF8ToGB2312(szTemp.c_str()).c_str()); + } + + if (m_lines>1) + { + m_iTemp+=74; + GtstrLength(m_iTemp,sTemp); + szTemp=it->second.substr(1*m_oneline,m_oneline); + Page_ESCPC(m_PrintData, (char *)"22",(char *)"0040",sTemp,'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"22",ot::UTF8ToGB2312(szTemp.c_str()).c_str()); + } + + if (m_lines>2) + { + m_iTemp+=74; + GtstrLength(m_iTemp,sTemp); + szTemp=it->second.substr(2*m_oneline,m_oneline); + Page_ESCPC(m_PrintData, (char *)"23",(char *)"0040",sTemp,'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"23",ot::UTF8ToGB2312(szTemp.c_str()).c_str()); + } + + if (m_lines>3) + { + m_iTemp+=74; + GtstrLength(m_iTemp,sTemp); + szTemp=it->second.substr(3*m_oneline,m_oneline); + Page_ESCPC(m_PrintData, (char *)"24",(char *)"0040",sTemp,'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"24",ot::UTF8ToGB2312(szTemp.c_str()).c_str()); + } + + if (m_lines>4) + { + m_iTemp+=74; + GtstrLength(m_iTemp,sTemp); + szTemp=it->second.substr(4*m_oneline,m_oneline); + Page_ESCPC(m_PrintData, (char *)"25",(char *)"0040",sTemp,'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"25",ot::UTF8ToGB2312(szTemp.c_str()).c_str()); + } + + if (m_lines>5) + { + m_iTemp+=74; + GtstrLength(m_iTemp,sTemp); + szTemp=it->second.substr(5*m_oneline,m_oneline); + Page_ESCPC(m_PrintData, (char *)"26",(char *)"0040",sTemp,'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"26",ot::UTF8ToGB2312(szTemp.c_str()).c_str()); + } + + if (m_lines>6) + { + m_iTemp+=74; + GtstrLength(m_iTemp,sTemp); + szTemp=it->second.substr(6*m_oneline,m_oneline); + Page_ESCPC(m_PrintData, (char *)"27",(char *)"0040",sTemp,'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"27",ot::UTF8ToGB2312(szTemp.c_str()).c_str()); + } + + m_iTemp+=74; + GtstrLength(m_iTemp,sTemp); + + //煤场验收 + Page_ESCPC(m_PrintData, (char *)"31",(char *)"0040",sTemp,'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"31",ot::UTF8ToGB2312("煤场验收").c_str()); + + //煤 场 + Page_ESCPC(m_PrintData, (char *)"32",(char *)"0380",sTemp,'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"32",ot::UTF8ToGB2312("煤 场").c_str()); + + m_iTemp+=74; + GtstrLength(m_iTemp,sTemp); + Page_ESCPC(m_PrintData, (char *)"33",(char *)"0040",sTemp,'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"33",ot::UTF8ToGB2312("采样调换至 号,签字:").c_str()); + + m_iTemp+=74; + GtstrLength(m_iTemp,sTemp); + + + Page_ESCPC(m_PrintData, (char *)"34",(char *)"0040",sTemp,'1','1','3',(char *)"00",(char *)"00"); + Page_ESCRC(m_PrintData, (char *)"34",ot::UTF8ToGB2312("煤场调换至 号,签字:").c_str()); + + Page_Cut(m_PrintData); + Page_End(m_PrintData); +} + +//北洋打印机打印排队票 +void MsgHandler::Print1_2(const std::map& msg) +{ + std::string szTemp; + std::map::const_iterator it; + std::vector blTemp; + std::map m_newObj; + int x = 40; + int y = 0; + int dx = 590; + int dy = 950; + char s[12]; + + m_PrintData.clear(); + //初始化打印机 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x40}); + //设置中文模式 + m_PrintData.insert(m_PrintData.end(), {0x1C, 0x21, 0x00}); + + //设置打印区域 + memcpy(s, &x, 2); + memcpy(s + 2, &y, 2); + memcpy(s + 4, &dx, 2); + memcpy(s + 6, &dy, 2); + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x57}); + m_PrintData.insert(m_PrintData.end(), s, s+8); + + //设置居中 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x01}); + + //设置1号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x11}); + it = msg.find("TitleCorp"); + if(it != msg.end()) + { + szTemp = ot::UTF8ToGB2312(it->second.c_str()) + ot::UTF8ToGB2312("入厂排队票"); //入厂排队票 + } + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //设置0号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x00}); + szTemp = ot::UTF8ToGB2312(" "); + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //设置左对齐 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x00}); + + //设置页模式 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x4C}); + + //=============================开票时间===================================== + + //加顶框 + m_newObj[1] = ("┌"); + m_newObj[23] = ("┐"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //票据时间 + m_newObj.clear(); + m_newObj[1] = ("│"); + it = msg.find("DateTime"); + if(it != msg.end()) + { + m_newObj[25] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //加框 + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┬"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //供应商 + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("供应商"); + m_newObj[120] = ("│"); + it = msg.find("Supplier"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //加框 + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[12] = ("┬"); + m_newObj[17] = ("┬"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("排队号"); + m_newObj[120] = ("│"); + it = msg.find("QueueID"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[263] = ("│"); + m_newObj[288] = ("品 种"); + m_newObj[383] = ("│"); + it = msg.find("GoodsType"); + if(it != msg.end()) + { + m_newObj[408] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //加框 + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[12] = ("┬"); + m_newObj[17] = ("┬"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("车牌号"); + m_newObj[120] = ("│"); + it = msg.find("CarNumber"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[263] = ("│"); + m_newObj[288] = ("自编号"); + m_newObj[383] = ("│"); + it = msg.find("CarID"); + if(it != msg.end()) + { + m_newObj[408] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //加框 + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[12] = ("┬"); + m_newObj[17] = ("┬"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //需要打印发运毛重和发运皮重 + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("发运毛重"); + m_newObj[120] = ("│"); + it = msg.find("GrossWeight"); + if (it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[263] = ("│"); + m_newObj[288] = ("发运皮重"); + m_newObj[383] = ("│"); + it = msg.find("TareWeight"); + if (it != msg.end()) + { + m_newObj[408] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[12] = ("┼"); + m_newObj[17] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24, m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + // 需要打印发运净重 + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("发运净重"); + m_newObj[120] = ("│"); + it = msg.find("SuttleWeight"); + if (it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[263] = ("│"); + m_newObj[383] = ("│"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[12] = ("┼"); + m_newObj[17] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24, m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("采样机"); + m_newObj[120] = ("│"); + it = msg.find("SampleID"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[263] = ("│"); + m_newObj[288] = ("接样员"); + m_newObj[383] = ("│"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┴"); + m_newObj[12] = ("┴"); + m_newObj[17] = ("┴"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //这里要加入煤场信息 + it = msg.find("MCFB"); + if(it != msg.end()) + { + int m_oneline=40; + int m_lines=it->second.length()/m_oneline; + if ((it->second.length()%m_oneline)>0) + { + m_lines+=1; + } + for (int i=0;isecond.substr(i*m_oneline,m_oneline); + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = (szTemp); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + } + } + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("采样调换至 号,签字:"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("煤场调换至 号,签字:"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┬"); + m_newObj[12] = ("┬"); + m_newObj[17] = ("┬"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("煤场验收"); + m_newObj[120] = ("│"); + m_newObj[263] = ("│"); + m_newObj[288] = ("煤 场"); + m_newObj[383] = ("│"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[12] = ("┼"); + m_newObj[17] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("计 扣 量"); + m_newObj[120] = ("│"); + m_newObj[263] = ("│"); + m_newObj[288] = ("签 字"); + m_newObj[383] = ("│"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("└"); + m_newObj[6] = ("┴"); + m_newObj[12] = ("┴"); + m_newObj[17] = ("┴"); + m_newObj[23] = ("┘"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //打印、切纸 + m_PrintData.insert(m_PrintData.end(), {0x0C, 0x1D, 0x56, 0x01}); +} + +//北洋打印机打印轻磅票 +void MsgHandler::Print2_2(const std::map& msg) +{ + //这里组装打印输出内容 + std::string szTemp; + std::map::const_iterator it; + std::vector blTemp; + std::map m_newObj; + int x=40; + int y=0; + int dx=590; //570 + int dy=1400; + char s[12]; + + m_PrintData.clear(); + //初始化打印机 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x40}); + //设置中文模式 + m_PrintData.insert(m_PrintData.end(), {0x1C, 0x21, 0x00}); + + //设置打印区域 + memcpy(s, &x, 2); + memcpy(s + 2, &y, 2); + memcpy(s + 4, &dx, 2); + memcpy(s + 6, &dy, 2); + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x57}); + m_PrintData.insert(m_PrintData.end(), s, s+8); + + //设置居中 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x01}); + //设置打印方向 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x54, 0x03}); + //设置1号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x11}); + //设置左对齐 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x00}); + //设置页模式 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x4C}); + + + //打印磅单 + szTemp = (" "); + m_newObj.clear(); + m_newObj[100] = szTemp; + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //打印磅单 + m_newObj.clear(); + it = msg.find("TitleCorp"); + if(it != msg.end()) + { + m_newObj[340] = it->second + "收煤凭证"; //收煤凭证 + } + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + szTemp=(" "); + m_newObj.clear(); + m_newObj[100] = szTemp; + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //车牌号和票据号 + m_newObj.clear(); + m_newObj[10] = ("车牌号:"); + it = msg.find("CarNumber"); + if(it != msg.end()) + { + m_newObj[190] = it->second; + } + m_newObj[600] = ("NO:"); + it = msg.find("CoalNumber"); + if(it != msg.end()) + { + m_newObj[700] = it->second; + } + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[100] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //供应商 + m_newObj.clear(); + m_newObj[10] = ("供应商:"); + it = msg.find("Supplier"); + if(it != msg.end()) + { + m_newObj[190] = it->second; + } + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + m_newObj.clear(); + m_newObj[100] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //时间和品种 + m_newObj.clear(); + m_newObj[10] = ("品 种:"); + it = msg.find("GoodsType"); + if(it != msg.end()) + { + m_newObj[190] = it->second; + } + m_newObj[600] = ("时间:"); + it = msg.find("DateTime"); + if(it != msg.end()) + { + m_newObj[740] = it->second; + } + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[100] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[10] = ("毛重"); + it = msg.find("GrossWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[450] = ("皮重"); + it = msg.find("TareWeight"); + if(it != msg.end()) + { + m_newObj[558] = it->second; + } + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[100] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[10] = ("扣矸"); + it = msg.find("RockWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[450] = ("净重"); + it = msg.find("SuttleWeight"); + if(it != msg.end()) + { + m_newObj[558] = it->second; + } + + if(msg.find("AffixSeal") != msg.end()) + { + m_newObj[800] = ("盖章"); + } + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[100] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[10] = ("扣水"); + it = msg.find("WaterWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[450] = ("扣杂"); + it = msg.find("OtherWeight"); + if(it != msg.end()) + { + m_newObj[558] = it->second; + } + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[100] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + // m_newObj.clear(); + // int count = 0; + // auto m_dsz = msg.find("dsz"); + // auto m_dsd = msg.find("dsd"); + // auto m_dsf = msg.find("dsf"); + // auto m_zsd = msg.find("zsd"); + // auto m_zsf = msg.find("zsf"); + // auto m_ksd = msg.find("ksd"); + // auto m_ksf = msg.find("ksf"); + // auto m_ddsf = msg.find("ddsf"); + // if((m_dsz != msg.end()) && (m_dsd != msg.end()) && (m_dsf != msg.end())) + // { + // if(m_dsz != msg.end()) + // { + // m_newObj[10] = ("大生中"); + // m_newObj[190] = m_dsz->second; + + // count++; + // } + // if(m_dsd != msg.end()) + // { + // if(count == 0) + // { + // m_newObj[10] = ("大生丁"); + // m_newObj[190] = m_dsd->second; + // } + // else if(count == 1) + // { + // m_newObj[500] = ("大生丁"); + // m_newObj[680] = m_dsd->second; + // } + // count++; + // } + // if(m_dsf != msg.end()) + // { + // if(count == 0) + // { + // m_newObj[10] = ("大生粉"); + // m_newObj[190] = m_dsf->second; + // } + // else if(count == 1) + // { + // m_newObj[500] = ("大生粉"); + // m_newObj[680] = m_dsf->second; + // } + // else if(count == 2) + // { + // m_newObj[900] = ("大生粉"); + // m_newObj[1080] = m_dsf->second; + // } + // count++; + // } + // } + // else if((m_zsd != msg.end()) || (m_zsf != msg.end())) + // { + // if(m_zsd != msg.end()) + // { + // m_newObj[10] = ("中生丁"); + // m_newObj[190] = m_zsd->second; + + // count++; + // } + // if(m_zsf != msg.end()) + // { + // if(count == 0) + // { + // m_newObj[10] = ("中生粉"); + // m_newObj[190] = m_zsf->second; + // } + // else if(count == 1) + // { + // m_newObj[500] = ("中生粉"); + // m_newObj[680] = m_zsf->second; + // } + // count++; + // } + // } + // else if((m_ksd != msg.end()) || (m_ksf != msg.end())) + // { + // if(m_ksd != msg.end()) + // { + // m_newObj[10] = ("块生丁"); + // m_newObj[190] = m_ksd->second; + + // count++; + // } + // if(m_ksf != msg.end()) + // { + // if(count == 0) + // { + // m_newObj[10] = ("块生粉"); + // m_newObj[190] = m_ksf->second; + // } + // else if(count == 1) + // { + // m_newObj[500] = ("块生粉"); + // m_newObj[680] = m_ksf->second; + // } + // count++; + // } + // } + // else if(m_ddsf != msg.end()) + // { + // m_newObj[10] = ("丁生粉"); + // m_newObj[190] = m_ddsf->second; + // } + // blTemp = BuildStringLine(m_newObj); + // m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + // m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[100] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + //设置0号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x00}); + m_newObj.clear(); + m_newObj[10] = ("备注:单位:吨"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + if(msg.find("ElectChapter") != msg.end()) + { + //打印电子章设置横向绝对位置 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x24, 0xB6, 0x03}); + //打印电子章设置纵向绝对位置 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x24, 0x26, 0x02}); + //打印下载NV位图 + m_PrintData.insert(m_PrintData.end(), {0x1C, 0x70, 0x01, 0x00}); + //打印条码设置横向绝对位置 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x24, 0xE4, 0x02}); + //打印条码设置纵向绝对位置 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x24, 0x0D, 0x02}); + //设置条码打印字符和条码宽度,高度 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x6F, 0x00, 0x08, 0x00, 0x02}); + //打印条码命令 + //票据号 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x6B, 0x0B, 0x51, 0x41, 0x2C}); + it = msg.find("CoalNumber"); + if(it != msg.end()) + { + szTemp = ot::UTF8ToGB2312(it->second.c_str()); + } + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x00}); + } + //打印 + m_PrintData.insert(m_PrintData.end(), {0x0C}); + + //切纸 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x56, 0x01}); +} + +//北洋打印机打印通用称重票 +void MsgHandler::Print3_2(const std::map& msg) +{ + //这里组装打印输出内容 + std::string szTemp; + std::map::const_iterator it; + std::vector blTemp; + std::map m_newObj; + int x = 40; + int y = 0; + int dx = 590; + int dy = 850; + char s[12]; + + m_PrintData.clear(); + //初始化打印机 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x40}); + //设置中文模式 + m_PrintData.insert(m_PrintData.end(), {0x1C, 0x21, 0x00}); + + //设置打印区域 + memcpy(s, &x, 2); + memcpy(s + 2, &y, 2); + memcpy(s + 4, &dx, 2); + memcpy(s + 6, &dy, 2); + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x57}); + m_PrintData.insert(m_PrintData.end(), s, s+8); + + //设置居中 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x01}); + + //设置1号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x11}); + //打印物料过衡单 + it = msg.find("TitleCorp"); + if(it != msg.end()) + { + szTemp = ot::UTF8ToGB2312(it->second.c_str()) + ot::UTF8ToGB2312("过衡单"); //过衡单 + } + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //设置0号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x00}); + szTemp = ot::UTF8ToGB2312(" "); + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //设置左对齐 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x00}); + + //设置页模式 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x4C}); + + + //=============================开票时间===================================== + + //加顶框 + //加顶框 + m_newObj[1] = ("┌"); + m_newObj[23] = ("┐"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====票据号===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("票据号"); + m_newObj[120] = ("│"); + it = msg.find("CoalNumber"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====车牌号===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("车牌号"); + m_newObj[120] = ("│"); + it = msg.find("CarNumber"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //=======供应商===================== + m_newObj.clear(); + m_newObj[1] = ("│"); + it = msg.find("SupplierTitle"); + if(it != msg.end()) + { + m_newObj[26] = it->second; + } + m_newObj[120] = ("│"); + it = msg.find("Supplier"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //=========品种===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("品种"); + m_newObj[120] = ("│"); + it = msg.find("GoodsType"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //=========皮重时间===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("皮重时间"); + m_newObj[120] = ("│"); + it = msg.find("TareWeightTime"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //=========毛重时间===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("毛重时间"); + m_newObj[120] = ("│"); + it = msg.find("GrossWeightTime"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[17] = ("┬"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //=========毛重====================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("毛重"); + m_newObj[120] = ("│"); + it = msg.find("GrossWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[384] = ("│"); + m_newObj[404] = ("吨"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[17] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //=========皮重====================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("皮重"); + m_newObj[120] = ("│"); + it = msg.find("TareWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[384] = ("│"); + m_newObj[404] = ("吨"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[17] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //=========净重====================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("净重"); + m_newObj[120] = ("│"); + + it = msg.find("SuttleWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[384] = ("│"); + m_newObj[404] = ("吨"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[17] = ("┴"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //=========操作员===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("操作员"); + m_newObj[120] = ("│"); + it = msg.find("Operator"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //=========备注===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("备注"); + m_newObj[120] = ("│"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("└"); + m_newObj[6] = ("┴"); + m_newObj[23] = ("┘"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //打印、切纸 + m_PrintData.insert(m_PrintData.end(), {0x0C, 0x1D, 0x56, 0x01}); +} + +//北洋打印机打印转煤票 +void MsgHandler::Print4_2(const std::map& msg) +{ + //这里组装打印输出内容 + std::string szTemp; + std::map::const_iterator it; + std::vector blTemp; + std::map m_newObj; + int x = 40; + int y = 0; + int dx = 590; + int dy = 850; + char s[12]; + + m_PrintData.clear(); + //初始化打印机 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x40}); + //设置中文模式 + m_PrintData.insert(m_PrintData.end(), {0x1C, 0x21, 0x00}); + + //设置打印区域 + memcpy(s, &x, 2); + memcpy(s + 2, &y, 2); + memcpy(s + 4, &dx, 2); + memcpy(s + 6, &dy, 2); + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x57}); + m_PrintData.insert(m_PrintData.end(), s, s+8); + + //设置居中 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x01}); + //设置1号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x11}); + it = msg.find("TitleCorp"); + if(it != msg.end()) + { + szTemp = ot::UTF8ToGB2312(it->second.c_str()) + ot::UTF8ToGB2312("转煤单"); //转煤单 + } + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //设置0号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x00}); + szTemp = ot::UTF8ToGB2312(" "); + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //设置左对齐 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x00}); + + //设置页模式 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x4C}); + + //=============================开票时间===================================== + + //加顶框 + m_newObj[1] = ("┌"); + m_newObj[23] = ("┐"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====票据号===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("称重编号"); + m_newObj[120] = ("│"); + it = msg.find("CoalNumber"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //=========时间===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("时间"); + m_newObj[120] = ("│"); + it = msg.find("DateTime"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====车牌号===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("车牌号"); + m_newObj[120] = ("│"); + it = msg.find("CarNumber"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + m_newObj.clear(); + m_newObj[1] = ("├"); + + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====转出煤场===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("转出煤场"); + m_newObj[120] = ("│"); + it = msg.find("OUTCoalYard"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====转入煤场===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("转入煤场"); + m_newObj[120] = ("│"); + it = msg.find("INCoalYard"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====装载单位===================== + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("装载单位"); + m_newObj[120] = ("│"); + it = msg.find("Stevedor"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====承运单位===================== + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("承运单位"); + m_newObj[120] = ("│"); + it = msg.find("Transport"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[17] = ("┬"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //=========毛重====================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("毛重"); + m_newObj[120] = ("│"); + it = msg.find("GrossWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[384] = ("│"); + m_newObj[404] = ("吨"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[17] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //=========皮重====================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("皮重"); + m_newObj[120] = ("│"); + it = msg.find("TareWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[384] = ("│"); + m_newObj[404] = ("吨"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[17] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //=========净重====================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("净重"); + m_newObj[120] = ("│"); + it = msg.find("SuttleWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[384] = ("│"); + m_newObj[404] = ("吨"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[17] = ("┴"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //=========备注===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("备注"); + m_newObj[120] = ("│"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("└"); + m_newObj[6] = ("┴"); + m_newObj[23] = ("┘"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //打印、切纸 + m_PrintData.insert(m_PrintData.end(), {0x0C, 0x1D, 0x56, 0x01}); +} + +//北洋打印机打印绥阳大宗物资重磅票 +void MsgHandler::Print5_2(const std::map& msg) +{ + //这里组装打印输出内容 + std::string szTemp; + std::map::const_iterator it; + std::vector blTemp; + std::map m_newObj; + int x = 40; + int y = 0; + int dx = 590; + int dy = 850; + char s[12]; + + m_PrintData.clear(); + //初始化打印机 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x40}); + //设置中文模式 + m_PrintData.insert(m_PrintData.end(), {0x1C, 0x21, 0x00}); + + //设置打印区域 + memcpy(s, &x, 2); + memcpy(s + 2, &y, 2); + memcpy(s + 4, &dx, 2); + memcpy(s + 6, &dy, 2); + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x57}); + m_PrintData.insert(m_PrintData.end(), s, s+8); + + //设置居中 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x01}); + //设置1号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x11}); + + //打印 + szTemp=ot::UTF8ToGB2312("国家电投集团"); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + //打印名称 + it = msg.find("TitleCorp"); + if(it != msg.end()) + { + szTemp = ot::UTF8ToGB2312(it->second.c_str()); + } + m_PrintData.insert(m_PrintData.end(), {0x0A}); + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + szTemp=ot::UTF8ToGB2312("提货单"); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A, 0x0A}); + + //设置左对齐 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x00}); + + //设置页模式 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x4C}); + + //=============================内容===================================== + + //设置0号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x00}); + + //====票据号===================== + + m_newObj.clear(); + m_newObj[15] = ("NO:"); + it = msg.find("CoalNumber"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====品种===================== + + m_newObj.clear(); + m_newObj[15] = ("品种:"); + it = msg.find("GoodsType"); + if(it != msg.end()) + { + m_newObj[160] = it->second; + } + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //=========批号===================== + + m_newObj.clear(); + m_newObj[15] = ("批号:"); + it = msg.find("BatchNumber"); + if(it != msg.end()) + { + m_newObj[160] = it->second; + } + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //====司机===================== + + m_newObj.clear(); + m_newObj[15] = ("司机:"); + it = msg.find("Operator"); + if(it != msg.end()) + { + m_newObj[160] = it->second; + } + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====车牌号===================== + + m_newObj.clear(); + m_newObj[15] = ("车牌号:"); + it = msg.find("CarNumber"); + if(it != msg.end()) + { + m_newObj[160] = it->second; + } + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====供应商===================== + + m_newObj.clear(); + m_newObj[15] = ("供应商:"); + it = msg.find("Supplier"); + if(it != msg.end()) + { + m_newObj[160] = it->second; + } + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====目的地===================== + + m_newObj.clear(); + m_newObj[15] = ("目的地:"); + it = msg.find("Destination"); + if(it != msg.end()) + { + m_newObj[160] = it->second; + } + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====提货地===================== + + m_newObj.clear(); + m_newObj[15] = ("提货地:"); + m_newObj[160] = ("水泥分厂"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====毛重===================== + + m_newObj.clear(); + m_newObj[15] = ("毛重(t):"); + it = msg.find("GrossWeight"); + if(it != msg.end()) + { + m_newObj[160] = it->second; + } + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====皮重===================== + + m_newObj.clear(); + m_newObj[15] = ("皮重(t):"); + it = msg.find("TareWeight"); + if(it != msg.end()) + { + m_newObj[160] = it->second; + } + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====净重===================== + + m_newObj.clear(); + m_newObj[15] = ("净重(t):"); + it = msg.find("SuttleWeight"); + if(it != msg.end()) + { + m_newObj[160] = it->second; + } + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====扣重===================== + + m_newObj.clear(); + m_newObj[15] = ("扣重(t):"); + it = msg.find("RockWeight"); + if(it != msg.end()) + { + m_newObj[160] = it->second; + } + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====进厂时间===================== + + m_newObj.clear(); + m_newObj[15] = ("进厂时间:"); + it = msg.find("EnterTime"); + if(it != msg.end()) + { + m_newObj[160] = it->second; + } + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //====出厂时间===================== + + m_newObj.clear(); + m_newObj[15] = ("出厂时间:"); + it = msg.find("LeaveTime"); + if(it != msg.end()) + { + m_newObj[160] = it->second; + } + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //打印、切纸 + m_PrintData.insert(m_PrintData.end(), {0x0C, 0x1D, 0x56, 0x01}); +} + +//北洋打印机提货单发货单 +void MsgHandler::Print6_2(const std::map& msg) +{ + //这里组装打印输出内容 + std::string szTemp; + std::map::const_iterator it; + std::vector blTemp; + std::map m_newObj; + int x = 40; + int y = 0; + int dx = 590; + int dy = 750; + char s[12]; + + std::string title, title_corp; + std::string sender, receiver; + + it = msg.find("Title"); + if(it != msg.end()) + { + if(it->second == "提货单") + { + title = ot::UTF8ToGB2312("提货单"); + it = msg.find("Supplier"); + if(it != msg.end()) + { + sender = it->second; + } + it = msg.find("Customer"); + if(it != msg.end()) + { + receiver = it->second; + } + } + else + { + title = ot::UTF8ToGB2312("发货单"); + it = msg.find("Supplier"); + if(it != msg.end()) + { + receiver = it->second; + } + it = msg.find("Customer"); + if(it != msg.end()) + { + sender = it->second; + } + } + } + + it = msg.find("TitleCorp"); + if(it != msg.end()) + { + title_corp = ot::UTF8ToGB2312(it->second.c_str()); + } + + m_PrintData.clear(); + //初始化打印机 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x40}); + //设置中文模式 + m_PrintData.insert(m_PrintData.end(), {0x1C, 0x21, 0x00}); + + //设置打印区域 + memcpy(s, &x, 2); + memcpy(s + 2, &y, 2); + memcpy(s + 4, &dx, 2); + memcpy(s + 6, &dy, 2); + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x57}); + m_PrintData.insert(m_PrintData.end(), s, s+8); + + //设置居中 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x01}); + //设置1号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x11}); + + //打印标题 + m_PrintData.insert(m_PrintData.end(), {0x0A}); + m_PrintData.insert(m_PrintData.end(), title_corp.begin(), title_corp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + m_PrintData.insert(m_PrintData.end(), title.begin(), title.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //设置左对齐 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x00}); + + //设置页模式 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x4C}); + + //=============================内容===================================== + + std::vector names ={"NO:", "规格", "车牌号", "收货单位", "供货单位", "开票时间", "验收人"}; + std::vector items; + + it = msg.find("QueueID"); + if(it != msg.end()) + { + items.push_back(it->second); + } + it = msg.find("GoodsType"); + if(it != msg.end()) + { + items.push_back(it->second); + } + it = msg.find("CarNumber"); + if(it != msg.end()) + { + items.push_back(it->second); + } + items.push_back(receiver); + items.push_back(sender); + it = msg.find("DateTime"); + if(it != msg.end()) + { + items.push_back(it->second); + } + items.push_back(" "); + + //设置0号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x00}); + + //顶框线 + m_newObj.clear(); + m_newObj[1] = ("┌"); + m_newObj[23] = ("┐"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + for(int i = 0; i < names.size(); i++) + { + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = names[i]; + m_newObj[120] = ("│"); + m_newObj[145] = items[i]; + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + } + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[120] = ("│"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("备注"); + m_newObj[120] = ("│"); + m_newObj[280] = ("盖章处"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[120] = ("│"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //底框线 + m_newObj.clear(); + m_newObj[1] = ("└"); + m_newObj[6] = ("┴"); + m_newObj[23] = ("┘"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //打印、切纸 + m_PrintData.insert(m_PrintData.end(), {0x0C, 0x1D, 0x56, 0x01}); +} + +//HS-K33打印排队票 +void MsgHandler::Print1_3(const std::map& msg) +{ + //这里组装打印输出内容 + std::string szTemp; + std::map::const_iterator it; + std::vector blTemp; + std::map m_newObj; + + m_PrintData.clear(); + //初始化打印机 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x40}); + //设置中文模式 + m_PrintData.insert(m_PrintData.end(), {0x1C, 0x21, 0x00}); + //设置居中 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x01}); + //设置1号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x11}); + + //打印磅单 + m_newObj.clear(); + it = msg.find("TitleCorp"); + if(it != msg.end()) + { + m_newObj[340] = it->second + ("排队票"); //排队票 + } + blTemp = BuildStringLine_HSK33(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); //换行 + + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x4C, 0x30, 0x00}); + //设置居中 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x01}); + //设置1号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x11}); + + //车牌号 + m_newObj.clear(); + m_newObj[10] = ("车牌号:"); + it = msg.find("CarNumber"); + if(it != msg.end()) + { + m_newObj[190] = it->second; + } + blTemp = BuildStringLine_HSK33(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); //换行 + + //时间 + m_newObj.clear(); + m_newObj[600] = ("时间:"); + it = msg.find("DateTime"); + if(it != msg.end()) + { + m_newObj[740] = it->second; + } + blTemp = BuildStringLine_HSK33(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); //换行 + + //排队号 + m_newObj.clear(); + m_newObj[10] = ("排队号:"); + it = msg.find("QueueID"); + if(it != msg.end()) + { + m_newObj[180] = it->second; + } + blTemp = BuildStringLine_HSK33(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); //换行 + + //供应商 + m_newObj.clear(); + m_newObj[10] = ("供应商:"); + it = msg.find("Supplier"); + if(it != msg.end()) + { + m_newObj[190] = it->second; + } + blTemp = BuildStringLine_HSK33(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); //换行 + + //品种 + m_newObj.clear(); + m_newObj[10] = ("品 种:"); + it = msg.find("GoodsType"); + if(it != msg.end()) + { + m_newObj[190] = it->second; + } + blTemp = BuildStringLine_HSK33(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); //换行 + + //车道号 + m_newObj.clear(); + m_newObj[10] = ("车道号:"); + it = msg.find("VechileLaneNo"); + if(it != msg.end()) + { + m_newObj[190] = it->second; + } + blTemp = BuildStringLine_HSK33(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); //换行 + + //采样机号 + m_newObj.clear(); + m_newObj[10] = ("采样机:"); + it = msg.find("SampleID"); + if(it != msg.end()) + { + m_newObj[190] = it->second; + } + blTemp = BuildStringLine_HSK33(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); //换行 + + it = msg.find("SuttleWeight"); + if (it != msg.end()) + { + //需要打印发运净重 + //发运净重 + m_newObj.clear(); + m_newObj[10] = ("发运净重:"); + m_newObj[190] = it->second; + m_newObj[250] = ("吨"); + blTemp = BuildStringLine_HSK33(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); //换行 + } + + //打印、切纸 + m_PrintData.insert(m_PrintData.end(), {0x0C, 0x1D, 0x56 ,0x42, 0x00}); +} + +//HS-K33打印普安燃料轻磅票 +void MsgHandler::Print2_3(const std::map& msg) +{ + //这里组装打印输出内容 + std::string szTemp; + std::map::const_iterator it; + std::vector blTemp; + std::map m_newObj; + + m_PrintData.clear(); + //初始化打印机 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x40}); + //设置中文模式 + m_PrintData.insert(m_PrintData.end(), {0x1C, 0x21, 0x00}); + //设置居中 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x01}); + //设置1号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x11}); + + //打印磅单 + //打印抬头 + it = msg.find("TitleCorp"); + if(it != msg.end()) + { + szTemp = ot::UTF8ToGB2312(it->second.c_str()); + } + m_PrintData.insert(m_PrintData.end(), {0x0A}); + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + szTemp=ot::UTF8ToGB2312("燃料过磅单"); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //设置0号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x00}); + //设置左对齐 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x00}); + //设置页模式 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x4C}); + //设置左边空白量 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x4C, 0x3C, 0x00}); + + m_newObj.clear(); + m_newObj[430] = ("单位:吨"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //加顶框 + m_newObj.clear(); + m_newObj[1] = ("┌"); + m_newObj[6] = ("┬"); + m_newObj[23] = ("┐"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====票据号===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("编 号"); + m_newObj[120] = ("│"); + it = msg.find("CoalNumber"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //=========供应商===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("供应商"); + m_newObj[120] = ("│"); + it = msg.find("Supplier"); + if (it != msg.end()) + { + if (it->second.length() > 24) + { + szTemp = it->second.substr(0, 24); + m_newObj[145] = szTemp; + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[120] = ("│"); + szTemp=it->second.substr(24, it->second.length()-24); + m_newObj[145] = szTemp; + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + } + else + { + m_newObj[145] = it->second; + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + } + } + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //=========供应商识别名===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("供 应"); + m_newObj[120] = ("│"); + it = msg.find("SupplierTitle"); + if (it != msg.end()) + { + if (it->second.length() > 24) + { + szTemp = it->second.substr(0, 24); + m_newObj[145] = szTemp; + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("识别名"); + m_newObj[120] = ("│"); + szTemp=it->second.substr(24, it->second.length()-24); + m_newObj[145] = szTemp; + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + } + else + { + m_newObj[145] = it->second; + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("识别名"); + m_newObj[120] = ("│"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + } + } + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[12] = ("┬"); + m_newObj[17] = ("┬"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====品种车牌===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("品 种"); + m_newObj[120] = ("│"); + it = msg.find("GoodsType"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + + m_newObj[264] = ("│"); + m_newObj[289] = ("车 牌"); + m_newObj[383] = ("│"); + it = msg.find("CarNumber"); + if(it != msg.end()) + { + m_newObj[408] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[12] = ("┴"); + m_newObj[17] = ("┴"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //=========时间===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("时 间"); + m_newObj[120] = ("│"); + it = msg.find("DateTime"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[12] = ("┬"); + m_newObj[17] = ("┬"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====毛重皮重===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("毛 重"); + m_newObj[120] = ("│"); + it = msg.find("GrossWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + + m_newObj[264] = ("│"); + m_newObj[289] = ("皮 重"); + m_newObj[383] = ("│"); + it = msg.find("TareWeight"); + if(it != msg.end()) + { + m_newObj[408] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[12] = ("┼"); + m_newObj[17] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====扣矸扣水===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("扣 矸"); + m_newObj[120] = ("│"); + it = msg.find("RockWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + + m_newObj[264] = ("│"); + m_newObj[289] = ("扣 水"); + m_newObj[383] = ("│"); + it = msg.find("WaterWeight"); + if(it != msg.end()) + { + m_newObj[408] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[12] = ("┼"); + m_newObj[17] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //=========扣杂\净重====================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("扣 杂"); + m_newObj[120] = ("│"); + it = msg.find("OtherWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + + m_newObj[264] = ("│"); + m_newObj[289] = ("净 重"); + m_newObj[383] = ("│"); + it = msg.find("SuttleWeight"); + if(it != msg.end()) + { + m_newObj[408] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("└"); + m_newObj[6] = ("┴"); + m_newObj[12] = ("┴"); + m_newObj[17] = ("┴"); + m_newObj[23] = ("┘"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //设置章位置 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x4C, 0x7C, 0x01}); + m_PrintData.insert(m_PrintData.end(), {0x1C, 0x70, 0x01, 0x00}); + + //打印、切纸 + m_PrintData.insert(m_PrintData.end(), {0x0C, 0x1D, 0x56 ,0x42, 0x00}); +} + +//HS-K33打印转煤票 +void MsgHandler::Print4_3(const std::map& msg) +{ + //这里组装打印输出内容 + std::string szTemp; + std::map::const_iterator it; + std::vector blTemp; + std::map m_newObj; + + m_PrintData.clear(); + //初始化打印机 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x40}); + //设置中文模式 + m_PrintData.insert(m_PrintData.end(), {0x1C, 0x21, 0x00}); + //设置居中 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x01}); + //设置1号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x11}); + + //打印转煤单 + it = msg.find("TitleCorp"); + if(it != msg.end()) + { + szTemp = ot::UTF8ToGB2312(it->second.c_str()) + ot::UTF8ToGB2312("转煤单"); //转煤单 + } + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //设置0号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x00}); + szTemp=ot::UTF8ToGB2312(" "); + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + //设置左对齐 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x00}); + //设置页模式 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x4C}); + + //=============================开票时间===================================== + + //加顶框 + m_newObj[1] = ("┌"); + m_newObj[23] = ("┐"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //====票据号===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("称重编号"); + m_newObj[120] = ("│"); + it = msg.find("CoalNumber"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //=========时间===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("时间"); + m_newObj[120] = ("│"); + it = msg.find("DateTime"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //====车牌号===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("车牌号"); + m_newObj[120] = ("│"); + it = msg.find("CarNumber"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //====品种===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("品 种"); + m_newObj[120] = ("│"); + it = msg.find("GoodsType"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + m_newObj.clear(); + m_newObj[1] = ("├"); + + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //====转出煤场===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("转出煤场"); + m_newObj[120] = ("│"); + it = msg.find("OUTCoalYard"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //====转入煤场===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("转入煤场"); + m_newObj[120] = ("│"); + it = msg.find("INCoalYard"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + + m_newObj[6] = ("┼"); + m_newObj[17] = ("┬"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //=========毛重====================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("毛重"); + m_newObj[120] = ("│"); + + it = msg.find("GrossWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + + m_newObj[384] = ("│"); + m_newObj[404] = ("吨"); + + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[17] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + + //=========皮重====================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("皮重"); + m_newObj[120] = ("│"); + + it = msg.find("TareWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + + m_newObj[384] = ("│"); + m_newObj[404] = ("吨"); + + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[17] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //=========净重====================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("净重"); + m_newObj[120] = ("│"); + + it = msg.find("SuttleWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + + m_newObj[384] = ("│"); + m_newObj[404] = ("吨"); + + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[17] = ("┴"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //====磅号===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("磅号"); + m_newObj[120] = ("│"); + it = msg.find("DeviceName"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + + m_newObj[6] = ("┼"); + m_newObj[17] = ("┬"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //=========备注===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("备注"); + m_newObj[120] = ("│"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + m_newObj.clear(); + m_newObj[1] = ("└"); + m_newObj[6] = ("┴"); + m_newObj[23] = ("┘"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //打印、切纸 + m_PrintData.insert(m_PrintData.end(), {0x0C, 0x1D, 0x56 ,0x42, 0x00}); +} + +//HS-K33打印配煤票 +void MsgHandler::Print5_3(const std::map& msg) +{ + //这里组装打印输出内容 + std::string szTemp; + std::map::const_iterator it; + std::vector blTemp; + std::map m_newObj; + + m_PrintData.clear(); + //初始化打印机 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x40}); + //设置中文模式 + m_PrintData.insert(m_PrintData.end(), {0x1C, 0x21, 0x00}); + //设置居中 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x01}); + //设置1号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x11}); + + + //打印配煤票 + it = msg.find("CarNumber"); + if(it != msg.end()) + { + szTemp = ot::UTF8ToGB2312(it->second.c_str()) + ot::UTF8ToGB2312(" "); // 配煤票 + } + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + it = msg.find("Warning"); + if(it != msg.end()) + { + szTemp = ot::UTF8ToGB2312(it->second.c_str()); + } + m_PrintData.insert(m_PrintData.end(), {0x0A}); + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //设置居中 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61 ,0x01}); + //票据号 + it = msg.find("CoalNumber"); + if(it != msg.end()) + { + szTemp = ot::UTF8ToGB2312(it->second.c_str()); + } + + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x6B, 0x61, 0x08, 0x02, static_cast(szTemp.length()), static_cast(szTemp.length()>>8)}); + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //设置0号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x00}); + //设置居右 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x02}); + it = msg.find("GrossWeightTime"); + if(it != msg.end()) + { + szTemp = ot::UTF8ToGB2312(it->second.c_str()); + } + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //向前走纸行 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x64, 0x04}); + //打印、切纸 + m_PrintData.insert(m_PrintData.end(), {0x0C, 0x1D, 0x56 ,0x42, 0x00}); +} + +//HS-K33打印灰磅票 +void MsgHandler::Print6_3(const std::map& msg) +{ + //这里组装打印输出内容 + std::string szTemp; + std::map::const_iterator it; + std::vector blTemp; + std::map m_newObj; + + m_PrintData.clear(); + //初始化打印机 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x40}); + //设置中文模式 + m_PrintData.insert(m_PrintData.end(), {0x1C, 0x21, 0x00}); + //设置居中 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x01}); + //设置1号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x0F}); + + //打印抬头 + it = msg.find("TitleCorp"); + if(it != msg.end()) + { + szTemp = ot::UTF8ToGB2312("国家电投集团"); + } + m_PrintData.insert(m_PrintData.end(), {0x0A, 0x0A}); + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + it = msg.find("TitleCorp"); + if(it != msg.end()) + { + szTemp = ot::UTF8ToGB2312(it->second.c_str()) + ot::UTF8ToGB2312("提货单"); + } + m_PrintData.insert(m_PrintData.end(), {0x0A}); + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //设置左对齐 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x00}); + //设置页模式 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x4C}); + //换行 + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====票据号===================== + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[26] = ("No:"); + m_newObj[120] = (" "); + it = msg.find("CoalNumber"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[6] = (" "); + m_newObj[23] = (" "); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //====品种===================== + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[26] = ("品 种:"); + m_newObj[120] = (" "); + it = msg.find("GoodsType"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[6] = (" "); + m_newObj[23] = (" "); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //====批号===================== + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[26] = ("批 号:"); + m_newObj[120] = (" "); + it = msg.find("BatchNumber"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[6] = (" "); + m_newObj[23] = (" "); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //====司机===================== + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[26] = ("司 机:"); + m_newObj[120] = (" "); + it = msg.find("Operator"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[6] = (" "); + m_newObj[23] = (" "); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //====车牌号===================== + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[26] = ("车牌号:"); + m_newObj[120] = (" "); + it = msg.find("CarNumber"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[6] = (" "); + m_newObj[23] = (" "); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //====客户===================== + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[26] = ("客 户:"); + m_newObj[120] = (" "); + it = msg.find("Supplier"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[6] = (" "); + m_newObj[23] = (" "); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //====目的地===================== + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[26] = ("目的地:"); + m_newObj[120] = (" "); + it = msg.find("Destination"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[6] = (" "); + m_newObj[23] = (" "); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //====提货地===================== + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[26] = ("提货地:"); + m_newObj[120] = (" "); + m_newObj[145] = ("水泥分厂"); + m_newObj[528] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[6] = (" "); + m_newObj[23] = (" "); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //=========毛重====================== + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[26] = ("毛重(t):"); + m_newObj[120] = (" "); + + it = msg.find("GrossWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + + m_newObj[528] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[6] = (" "); + m_newObj[23] = (" "); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //=========皮重====================== + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[26] = ("皮重(t):"); + m_newObj[120] = (" "); + + it = msg.find("TareWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + + m_newObj[528] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[6] = (" "); + m_newObj[23] = (" "); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //=========净重====================== + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[26] = ("净重(t):"); + m_newObj[120] = (" "); + + it = msg.find("SuttleWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + + m_newObj[528] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[6] = (" "); + m_newObj[23] = (" "); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //====扣重===================== + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[26] = ("扣重(t):"); + m_newObj[120] = (" "); + + it = msg.find("RockWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + + m_newObj[528] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[6] = (" "); + m_newObj[23] = (" "); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //=========进厂时间===================== + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[26] = ("进厂时间:"); + m_newObj[120] = (" "); + it = msg.find("EnterTime"); + if(it != msg.end()) + { + m_newObj[160] = it->second; + } + m_newObj[528] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[6] = (" "); + m_newObj[23] = (" "); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //=========出厂时间===================== + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[26] = ("出厂时间:"); + m_newObj[120] = (" "); + it = msg.find("LeaveTime"); + if(it != msg.end()) + { + m_newObj[160] = it->second; + } + m_newObj[528] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[6] = (" "); + m_newObj[23] = (" "); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + + //=========备注===================== + + m_newObj.clear(); + m_newObj[1] = (" "); + m_newObj[26] = ("备注"); + m_newObj[120] = (" "); + m_newObj[145] = (" "); + m_newObj[528] = (" "); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //打印、切纸 + m_PrintData.insert(m_PrintData.end(), {0x0C, 0x1D, 0x56 ,0x42, 0x00}); +} + +//HS-K33打印机打印黔西过磅票 +void MsgHandler::Print8_3(const std::map& msg) +{ + //这里组装打印输出内容 + std::string szTemp; + std::map::const_iterator it; + std::vector blTemp; + std::map m_newObj; + + m_PrintData.clear(); + //初始化打印机 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x40}); + //设置中文模式 + m_PrintData.insert(m_PrintData.end(), {0x1C, 0x21, 0x00}); + //设置居中 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x01}); + //设置1号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x11}); + + //打印磅单 + //打印标题 + it = msg.find("TitleCorp"); + if(it != msg.end()) + { + szTemp = ot::UTF8ToGB2312(it->second.c_str()); + } + m_PrintData.insert(m_PrintData.end(), {0x0A}); + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + szTemp = ot::UTF8ToGB2312("过磅单(出厂)"); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + m_PrintData.insert(m_PrintData.end(), szTemp.begin(), szTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //设置0号字 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x21, 0x00}); + //设置左对齐 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x61, 0x00}); + //设置页模式 + m_PrintData.insert(m_PrintData.end(), {0x1B, 0x4C}); + //设置左边空白量 + m_PrintData.insert(m_PrintData.end(), {0x1D, 0x4C, 0x3C, 0x00}); + + //加顶框 + m_newObj.clear(); + m_newObj[1] = ("┌"); + m_newObj[6] = ("┬"); + m_newObj[23] = ("┐"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====票据号===================== + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("编号"); + m_newObj[120] = ("│"); + it = msg.find("CoalNumber"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //=========收货单位===================== + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("收货单位"); + m_newObj[120] = ("│"); + it = msg.find("Customer"); + if (it != msg.end()) + { + if (it->second.length() > 24) + { + m_newObj[145] = it->second.substr(0, 24); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); //换行 + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[120] = ("│"); + m_newObj[145] = it->second.substr(24, it->second.length() - 24); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); //换行 + } + else + { + m_newObj[145] = it->second; + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); //换行 + } + } + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); //换行 + + //=========供货单位===================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("供货单位"); + m_newObj[120] = ("│"); + it = msg.find("Supplier"); + if (it != msg.end()) + { + if (it->second.length() > 24) + { + m_newObj[145] = it->second.substr(0, 24); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); //换行 + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[120] = ("│"); + m_newObj[145] = it->second.substr(24, it->second.length() - 24); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); //换行 + } + else + { + m_newObj[145] = it->second; + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); //换行 + } + } + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); //换行 + + //====品种===================== + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("规格"); + m_newObj[120] = ("│"); + it = msg.find("GoodsType"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + //====车牌===================== + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("车牌"); + m_newObj[120] = ("│"); + it = msg.find("CarNumber"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[264] = ("│"); + m_newObj[289] = ("操作员"); + m_newObj[383] = ("│"); + it = msg.find("Operator"); + if(it != msg.end()) + { + m_newObj[408] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); //换行 + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[12] = ("┴"); + m_newObj[17] = ("┴"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); //换行 + + //====时间===================== + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("时间"); + m_newObj[120] = ("│"); + it = msg.find("DateTime"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[12] = ("┬"); + m_newObj[17] = ("┬"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); //换行 + + //====毛重皮重===================== + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("毛重(吨)"); + m_newObj[120] = ("│"); + it = msg.find("GrossWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + + m_newObj[264] = ("│"); + m_newObj[289] = ("皮重(吨)"); + m_newObj[383] = ("│"); + it = msg.find("TareWeight"); + if(it != msg.end()) + { + m_newObj[408] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); //换行 + + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[12] = ("┼"); + m_newObj[17] = ("┼"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); //换行 + + //=========扣杂\净重====================== + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("净重(吨)"); + m_newObj[120] = ("│"); + it = msg.find("SuttleWeight"); + if(it != msg.end()) + { + m_newObj[145] = it->second; + } + + m_newObj[264] = ("│"); + m_newObj[289] = ("扣重(吨)"); + m_newObj[383] = ("│"); + it = msg.find("RockWeight"); + if(it != msg.end()) + { + m_newObj[408] = it->second; + } + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); //换行 + + // 打印电子印章图片 + bool e_seal = true; //ElectChapter; + if(!e_seal) + { + m_newObj.clear(); + m_newObj[1] = ("├"); + m_newObj[6] = ("┼"); + m_newObj[12] = ("┴"); + m_newObj[17] = ("┴"); + m_newObj[23] = ("┤"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); //换行 + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[120] = ("│"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[26] = ("备注盖章"); + m_newObj[120] = ("│"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + m_newObj.clear(); + m_newObj[1] = ("│"); + m_newObj[120] = ("│"); + m_newObj[528] = ("│"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + } + + m_newObj.clear(); + m_newObj[1] = ("└"); + m_newObj[6] = ("┴"); + m_newObj[23] = ("┘"); + blTemp = BuildLine(24,m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); //换行 + + it = msg.find("e_seal"); + if(it != msg.end()) + { + m_newObj.clear(); + m_newObj[26] = ("盖章:"); + blTemp = BuildStringLine(m_newObj); + m_PrintData.insert(m_PrintData.end(), blTemp.begin(), blTemp.end()); + m_PrintData.insert(m_PrintData.end(), {0x0A}); + + // if(!PrintImage("image/qx-seal.bmp")) { + // m_PrintData.append(EnterChar).append(EnterChar).append(EnterChar).append(EnterChar).append(EnterChar); + // } + } + + //打印、切纸 + m_PrintData.insert(m_PrintData.end(), {0x0C, 0x1D, 0x56 ,0x42, 0x00}); +} \ No newline at end of file diff --git a/print/MsgHandler2.hpp b/print/MsgHandler2.hpp new file mode 100644 index 0000000..c22b589 --- /dev/null +++ b/print/MsgHandler2.hpp @@ -0,0 +1,65 @@ +#ifndef _MSGHANDLER_HPP_ +#define _MSGHANDLER_HPP_ + +#include +#include +#include +#include + +class MsgHandler { +public: + int fd; + std::string device; + std::vector m_PrintData; + + MsgHandler(); + ~MsgHandler() = default; + + void HandleDdsMsg(const std::map& msg); + void EncodeMsg(const std::map& msg); + bool SetDevice(const std::string& device); + + virtual bool OpenPort(const std::string& port, const std::string& baudrate); + virtual int SendDeviceMsg(const std::vector& data); + virtual int RecvDeviceMsg(std::vector& data, int timeoutMs); + int SendMsg(const std::vector& data); + int RecvMsg(std::vector& data, int timeoutMs); + bool isOpen() const { + return fd != -1; + } + void ClosePort(); + +private: + std::vector BuildLine(int m_max, const std::map& PointList, int no_line_min = 0, int no_line_max = 0); //行线条生成器 + std::vector BuildStringLine(std::map& PointList); //行线条生成器 + std::vector BuildStringLine_HSK33(std::map& PointList); //行线条生成器 + + void Page_ClearAndSet(std::vector& Data, char * h1h2h3h4); + void Page_ESCL (std::vector& Data, const char *n1n2, const char *x1x2x3x4, const char *y1y2y3y4, + const char *x5x6x7x8, const char *y5y6y7y8, char d, char w); + void Page_ESCPC(std::vector& Data, const char *n1n2, const char *x1x2x3x4, const char *y1y2y3y4, + char w, char h, char c, const char * r1r2, const char * s1s2); + void Page_ESCRC(std::vector& Data, const char *n1n2, const char *str); + void Page_ESCH(std::vector& Data, char n, char *x1x2x3x4, char *y1y2y3y4, char *bmp, int bmpsize); + void Page_Cut(std::vector& Data); + void Page_End(std::vector& Data); + void GtstrLength(int iVal, char *p); + + void Print1_1(const std::map& msg); + + void Print1_2(const std::map& msg); + void Print2_2(const std::map& msg); + void Print3_2(const std::map& msg); + void Print4_2(const std::map& msg); + void Print5_2(const std::map& msg); + void Print6_2(const std::map& msg); + + void Print1_3(const std::map& msg); + void Print2_3(const std::map& msg); + void Print4_3(const std::map& msg); + void Print5_3(const std::map& msg); + void Print6_3(const std::map& msg); + void Print8_3(const std::map& msg); +}; + +#endif \ No newline at end of file diff --git a/print/Publisher.cxx b/print/Publisher.cxx index d060459..945dc18 100644 --- a/print/Publisher.cxx +++ b/print/Publisher.cxx @@ -33,7 +33,7 @@ #include #include -#include "SystemPubSubTypes.hpp" +#include "WeighingDDSTypePubSubTypes.hpp" #include "msg.hpp" #include "MsgHandler.hpp" @@ -48,7 +48,7 @@ PublisherApp::PublisherApp( , publisher_(nullptr) , topic_(nullptr) , writer_(nullptr) - , type_(new InternalSystem::PrintRspPubSubType()) + , type_(new WeighingSystem::PrintRspPubSubType()) , matched_(0) , samples_sent_(0) , stop_(false) @@ -82,7 +82,7 @@ PublisherApp::PublisherApp( // Create the topic TopicQos topic_qos = TOPIC_QOS_DEFAULT; participant_->get_default_topic_qos(topic_qos); - topic_ = participant_->create_topic("PrintRspTopic", type_.get_type_name(), topic_qos); + topic_ = participant_->create_topic("PrintRsp", type_.get_type_name(), topic_qos); if (topic_ == nullptr) { throw std::runtime_error("InternalSystem::PrintRsp Topic initialization failed"); @@ -149,7 +149,7 @@ void PublisherApp::run(std::shared_ptr handler) { if(!MsgData::PrintReq_queue_.empty()) { - InternalSystem::PrintReq req = std::move(MsgData::PrintReq_queue_.front()); + WeighingSystem::PrintReq req = std::move(MsgData::PrintReq_queue_.front()); MsgData::PrintReq_queue_.pop(); lock.unlock(); @@ -189,7 +189,7 @@ bool PublisherApp::publish() if (!is_stopped()) { /* Initialize your structure here */ - InternalSystem::PrintReq sample_; + WeighingSystem::PrintReq sample_; ret = (RETCODE_OK == writer_->write(&sample_)); } return ret; @@ -204,4 +204,4 @@ void PublisherApp::stop() { stop_.store(true); cv_.notify_one(); -} \ No newline at end of file +} diff --git a/print/Subscriber.cxx b/print/Subscriber.cxx index 96d2f30..82594b2 100644 --- a/print/Subscriber.cxx +++ b/print/Subscriber.cxx @@ -32,7 +32,7 @@ #include #include -#include "SystemPubSubTypes.hpp" +#include "WeighingDDSTypePubSubTypes.hpp" #include "msg.hpp" #include "DEBUG.hpp" @@ -46,7 +46,7 @@ SubscriberApp::SubscriberApp( , subscriber_(nullptr) , topic_(nullptr) , reader_(nullptr) - , type_(new InternalSystem::PrintReqPubSubType()) + , type_(new WeighingSystem::PrintReqPubSubType()) , samples_received_(0) , stop_(false) { @@ -133,9 +133,12 @@ void SubscriberApp::on_data_available( std::string topic_name = reader->get_topicdescription()->get_name(); DEBUG(topic_name << " Topic receviced."); + // 在第136行之前添加: + std::cout << "[Print] DEBUG: topic_name from DDS = [" << topic_name << "]" << std::endl; + std::cout << "[Print] DEBUG: topic_name == PrintReq ? " << (topic_name == "PrintReq" ? "YES" : "NO") << std::endl; if (topic_name == "PrintReq") { - InternalSystem::PrintReq sample_; + WeighingSystem::PrintReq sample_; while ((!is_stopped()) && (RETCODE_OK == reader->take_next_sample(&sample_, &info))) { if ((info.instance_state == ALIVE_INSTANCE_STATE) && info.valid_data) @@ -143,10 +146,15 @@ void SubscriberApp::on_data_available( { std::unique_lock lock(MsgData::queue_cv_mtx_); MsgData::PrintReq_queue_.push(std::move(sample_)); + + std::cout << "[Print] DEBUG: PUSHING to PrintReq_queue_ (queue size before: " << MsgData::PrintReq_queue_.size() << ")" << std::endl; + + std::cout << "[Print] DEBUG: Publisher polling queue, empty() = " << MsgData::PrintReq_queue_.empty() << std::endl; lock.unlock(); } } } + std::cout << "[Print] DEBUG: HandleDdsMsg called successfully" << std::endl; } } @@ -168,4 +176,4 @@ void SubscriberApp::stop() { stop_.store(true); terminate_cv_.notify_all(); -} \ No newline at end of file +} diff --git a/print/Subscriber.hpp b/print/Subscriber.hpp index 81132dc..f6d8448 100644 --- a/print/Subscriber.hpp +++ b/print/Subscriber.hpp @@ -29,7 +29,7 @@ #include #include -#include "System.hpp" +#include "WeighingDDSType.hpp" class SubscriberApp : public eprosima::fastdds::dds::DataReaderListener { @@ -72,4 +72,4 @@ private: std::condition_variable terminate_cv_; }; -#endif // FAST_DDS_GENERATED__SUBSCRIBERAPP_HPP \ No newline at end of file +#endif // FAST_DDS_GENERATED__SUBSCRIBERAPP_HPP diff --git a/print/main.cxx b/print/main.cxx index e96bfec..2073f2d 100644 --- a/print/main.cxx +++ b/print/main.cxx @@ -63,7 +63,7 @@ std::string parse_signal( } } -std::queue MsgData::PrintReq_queue_; +std::queue MsgData::PrintReq_queue_; std::mutex MsgData::queue_cv_mtx_; int main(int argc, char** argv) diff --git a/print/msg.hpp b/print/msg.hpp index 6068f3d..170f8c8 100644 --- a/print/msg.hpp +++ b/print/msg.hpp @@ -3,12 +3,12 @@ #include #include -#include "System.hpp" +#include "WeighingDDSType.hpp" class MsgData { public: - static std::queue PrintReq_queue_; + static std::queue PrintReq_queue_; static std::mutex queue_cv_mtx_; }; -#endif \ No newline at end of file +#endif diff --git a/readcard.zip b/readcard.zip new file mode 100644 index 0000000..e9b304a Binary files /dev/null and b/readcard.zip differ diff --git a/readcard/MsgHandler.cxx b/readcard/MsgHandler.cxx new file mode 100644 index 0000000..52b4658 --- /dev/null +++ b/readcard/MsgHandler.cxx @@ -0,0 +1,1874 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "MsgHandler.hpp" +#include "DEBUG.hpp" +#include "../common/SerialMsgHandler.hpp" + +#include +#include + +#define BEEP_CARD 1 +#define FIND_CARD 2 +#define SET_PWD 3 +#define READ_CARD 4 +#define WRITE_CARD 5 +#define STOP_CARD 8 +#define WRITE_BLOCK_ID 0x04 // 写数据的块号 + +namespace +{ +const char* PendingCommandName(PendingCommand command) +{ + switch (command) + { + case PendingCommand::Find: return "FIND"; + case PendingCommand::SetPassword: return "SET_PASSWORD"; + case PendingCommand::ReadBlock: return "READ_BLOCK"; + case PendingCommand::WriteBlock: return "WRITE_BLOCK"; + case PendingCommand::Stop: return "STOP"; + case PendingCommand::Beep: return "BEEP"; + default: return "NONE"; + } +} + +uint16_t MapDeviceError(uint8_t command, uint8_t status) +{ + if (status == 0) return 0; + if (status == 0x0B) return 0x0012; // authentication failure + if (status == 0x0C) return command == READ_CARD ? 0x0013 : 0x0014; + if (status == 0x0A) return 0x001A; // invalid block + return command == WRITE_CARD ? 0x0014 : 0x0013; +} +std::string CardStateName(CardState state) +{ + switch (state) + { + case CardState::AUTO_FIND: return "AUTO_FIND"; + case CardState::WAIT_DDS_READ: return "WAIT_DDS_READ"; + case CardState::WAIT_DDS_WRITE: return "WAIT_DDS_WRITE"; + case CardState::WAIT_DDS_DECISION: return "WAIT_DDS_DECISION"; + case CardState::WAIT_DDS_WRITE_NEXT: return "WAIT_DDS_WRITE_NEXT"; + } + return "UNKNOWN"; +} + +std::string HexBytes(const std::vector& bytes) +{ + std::ostringstream out; + out << std::hex << std::uppercase << std::setfill('0'); + for (uint8_t byte : bytes) + { + out << std::setw(2) << static_cast(byte) << ' '; + } + return out.str(); +} +} + +MsgHandler::MsgHandler() : fd(-1), m_CardState(CardState::AUTO_FIND), + m_CurrentIndex(0), + m_ResultCode(0), m_BlockCount(0), + m_BlockOpStartTime(std::chrono::steady_clock::now()), + m_CurrentOperatingBlock(0), + m_PendingReadResponse(std::vector()), + OnCardDetected(nullptr) +{ + +} + +bool MsgHandler::OpenPort(const std::string& port, const std::string& baudrate) +{ + return true; +} + +void MsgHandler::ClosePort() +{ + if (fd != -1) + { + close(fd); + fd = -1; + } +} + +bool MsgHandler::SetDevice(const std::string& device) +{ + this->device = device; + return true; +} + +int MsgHandler::SendDeviceMsg(const std::vector& data) +{ + DEBUG("SERIAL TX device=" << this->device << " size=" << data.size() + << " bytes=" << HexBytes(data)); + + int bytesWritten = SendMsg(data); + DEBUG("SERIAL TX result=" << bytesWritten << "/" << data.size()); + return bytesWritten; +} + +int MsgHandler::RecvDeviceMsg(std::vector& data, int timeoutMs) +{ + int bytesRead = RecvMsg(data, timeoutMs); + + if (bytesRead > 0) + { + DEBUG("SERIAL RX device=" << this->device << " size=" << data.size() + << " bytes=" << HexBytes(data)); + } + return bytesRead; +} + +int MsgHandler::SendMsg(const std::vector& data) +{ + std::lock_guard lock(mtx_); + + if (fd == -1) + { + perror("设备未打开"); + return -1; + } + + size_t totalWritten = 0; + while (totalWritten < data.size()) + { + const ssize_t written = write(fd, data.data() + totalWritten, + data.size() - totalWritten); + if (written < 0) + { + perror("发送数据失败"); + return -1; + } + if (written == 0) + { + break; + } + totalWritten += static_cast(written); + } + + return static_cast(totalWritten); +} + +int MsgHandler::RecvMsg(std::vector& data, int timeoutMs) +{ + std::lock_guard lock(mtx_); + + if (fd == -1) + { + perror("设备未打开\n"); + return -1; + } + + const auto deadline = std::chrono::steady_clock::now() + + std::chrono::milliseconds(std::max(0, timeoutMs)); + + while (true) + { + if (TryExtractDeviceFrame(data)) + { + return static_cast(data.size()); + } + + const auto remaining = std::chrono::duration_cast( + deadline - std::chrono::steady_clock::now()).count(); + if (remaining <= 0) + { + // 兼容现场设备短读帧:只要块号和 16 字节数据已经到齐, + // 即 LEN + header + block + data 至少 21 字节,就交给读卡解析。 + if (m_ReceiveBuffer.size() >= 21U + && m_ReceiveBuffer[1] == 0x01U + && m_ReceiveBuffer[2] == READ_CARD + && m_ReceiveBuffer[3] == 0x00U) + { + data = m_ReceiveBuffer; + m_ReceiveBuffer.clear(); + DEBUG("SERIAL RX short READ_BLOCK frame accepted for data extraction, size=" + << data.size() << " bytes=" << HexBytes(data)); + return static_cast(data.size()); + } + // 兼容现场设备偶发的写应答短帧: + // 05 01 05 status crc_hi(缺少最后一个 CRC 字节)。 + // 只放行固定 5 字节写应答,ParseDeviceMsg 仍会检查 status。 + if (ALLOW_SHORT_WRITE_ACK + && m_ReceiveBuffer.size() == 5U + && m_ReceiveBuffer[0] == 0x05U + && m_ReceiveBuffer[1] == 0x01U + && m_ReceiveBuffer[2] == WRITE_CARD) + { + data = m_ReceiveBuffer; + m_ReceiveBuffer.clear(); + DEBUG("SERIAL RX short WRITE_BLOCK ACK accepted without final CRC byte, size=" + << data.size() << " bytes=" << HexBytes(data)); + return static_cast(data.size()); + } + if (!m_ReceiveBuffer.empty()) + { + const std::string incomplete = HexBytes(m_ReceiveBuffer); + const size_t bufferedSize = m_ReceiveBuffer.size(); + m_ReceiveBuffer.clear(); + DEBUG("SERIAL RX incomplete frame timeout buffered=" + << bufferedSize << " bytes=" << incomplete); + + + // 【新增】AUTO_FIND 下收不满一帧超时 → 直接触发重置 + if (m_CardState == CardState::AUTO_FIND) + { + DEBUG("AUTO_FIND: incomplete frame timeout — scheduling ResetSerialAndReinit"); + m_AutoFindNeedsReset = true; + } + + + bool retried = false; + if (m_PendingCommand == PendingCommand::WriteBlock) + { + DEBUG("Write incomplete frame, reverting to AUTO_FIND without retry"); + m_BlockOperationPending = false; + m_PendingCommand = PendingCommand::None; + m_AutoFindNeedsReset = true; + m_AutoFind = true; + m_FindIntervalMs = 5000; + m_LastFindTime = std::chrono::steady_clock::now() + - std::chrono::milliseconds(m_FindIntervalMs); + SetCardState(CardState::AUTO_FIND); + if (fd != -1) + tcflush(fd, TCIFLUSH); + } + else + { + // ★ 移除重试:读卡失败直接回 AUTO_FIND + DEBUG("Read incomplete frame, reverting to AUTO_FIND"); + m_BlockOperationPending = false; + m_PendingCommand = PendingCommand::None; + m_AutoFindNeedsReset = true; + m_AutoFind = true; + m_FindIntervalMs = 5000; + m_LastFindTime = std::chrono::steady_clock::now() + - std::chrono::milliseconds(m_FindIntervalMs); + SetCardState(CardState::AUTO_FIND); + if (fd != -1) + tcflush(fd, TCIFLUSH); + } + + + + + + } + return 0; + } + + fd_set readfds; + struct timeval tv; + FD_ZERO(&readfds); + FD_SET(fd, &readfds); + tv.tv_sec = static_cast(remaining / 1000); + tv.tv_usec = static_cast((remaining % 1000) * 1000); + + const int ret = select(fd + 1, &readfds, nullptr, nullptr, &tv); + if (ret < 0) + { + if (errno == EINTR) + { + continue; + } + perror("select错误"); + return -1; + } + if (ret == 0) + { + continue; + } + + int available = 0; + if (ioctl(fd, FIONREAD, &available) < 0) + { + perror("ioctl FIONREAD失败"); + return -1; + } + if (available <= 0) + { + continue; + } + + std::vector received(static_cast(available)); + const ssize_t bytesRead = read(fd, received.data(), received.size()); + if (bytesRead < 0) + { + if (errno == EINTR) + { + continue; + } + perror("读取数据失败"); + return -1; + } + if (bytesRead == 0) + { + continue; + } + + received.resize(static_cast(bytesRead)); + const auto rx_ms = std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); + DEBUG("SERIAL RX RAW t_ms=" << rx_ms << " available=" << available + << " read=" << bytesRead << " buffered_before=" << m_ReceiveBuffer.size() + << " bytes=" << HexBytes(received)); + + m_ReceiveBuffer.insert(m_ReceiveBuffer.end(), received.begin(), received.end()); + } +} + +bool MsgHandler::TryExtractDeviceFrame(std::vector& data) +{ + data.clear(); + + while (!m_ReceiveBuffer.empty()) + { + const size_t expectedSize = static_cast(m_ReceiveBuffer.front()) + 1U; + if (expectedSize < 6U || expectedSize > 256U) + { + DEBUG("Discarding invalid device frame length=" + << static_cast(m_ReceiveBuffer.front())); + m_ReceiveBuffer.erase(m_ReceiveBuffer.begin()); + continue; + } + + if (m_ReceiveBuffer.size() < expectedSize) + { + return false; + } + + std::vector frame(m_ReceiveBuffer.begin(), + m_ReceiveBuffer.begin() + expectedSize); + m_ReceiveBuffer.erase(m_ReceiveBuffer.begin(), + m_ReceiveBuffer.begin() + expectedSize); + + if (!IsValidDeviceFrame(frame)) + { + DEBUG("Discarding invalid device frame, length=" << frame.size() + << " bytes=" << HexBytes(frame)); + // ★ 移除重试:CRC 校验失败直接回 AUTO_FIND(与写卡 incomplete frame 处理一致) + if (frame.size() >= 4U + && frame[1] == 0x01U + && frame[2] == READ_CARD + && m_PendingCommand == PendingCommand::ReadBlock) + { + DEBUG("ReadCard CRC validation failure, reverting to AUTO_FIND"); + m_BlockOperationPending = false; + m_PendingCommand = PendingCommand::None; + m_AutoFindNeedsReset = true; + m_AutoFind = true; + m_FindIntervalMs = 5000; + m_LastFindTime = std::chrono::steady_clock::now() + - std::chrono::milliseconds(m_FindIntervalMs); + SetCardState(CardState::AUTO_FIND); + if (fd != -1) + tcflush(fd, TCIFLUSH); + return false; + } + + // 【新增】AUTO_FIND 状态下任意一帧 CRC/length 失败 → 直接触发重置 + if (m_CardState == CardState::AUTO_FIND) + { + DEBUG("AUTO_FIND: frame validation failure — scheduling ResetSerialAndReinit"); + m_AutoFindNeedsReset = true; + } + + + continue; + } + + data = std::move(frame); + + m_AutoFindNeedsReset = false; // 【新增】成功后清除重置标志 + + return true; + } + + return false; +} + +bool MsgHandler::RetryCurrentReadBlock(const char* reason) +{ + if (m_PendingCommand != PendingCommand::ReadBlock + || !m_BlockOperationPending + || m_ReadBlockRetryCount >= READ_BLOCK_MAX_RETRIES) + { + DEBUG("Read block retry unavailable: reason=" << reason + << " attempts=" << static_cast(m_ReadBlockRetryCount) + << " max=" << static_cast(READ_BLOCK_MAX_RETRIES)); + return false; + } + + const uint8_t block = m_PendingBlock; + ++m_ReadBlockRetryCount; + DEBUG("Retrying read block=" << static_cast(block) + << " attempt=" << static_cast(m_ReadBlockRetryCount) + << "/" << static_cast(READ_BLOCK_MAX_RETRIES) + << " reason=" << reason); + + std::this_thread::sleep_for(std::chrono::milliseconds(READ_BLOCK_RETRY_DELAY_MS)); + m_ReceiveBuffer.clear(); + if (fd != -1) + { + tcflush(fd, TCIFLUSH); + } + DEBUG("Read block retry buffer cleared, block=" << static_cast(block)); + ReadCard({block}); + return true; +} + +// ========== 新增:写卡失败重试 ========== +bool MsgHandler::RetryCurrentWriteBlock(const char* reason) +{ + if (m_PendingCommand != PendingCommand::WriteBlock + || !m_BlockOperationPending + || m_WriteBlockRetryCount >= WRITE_BLOCK_MAX_RETRIES) + { + DEBUG("Write block retry unavailable: reason=" << reason + << " attempts=" << static_cast(m_WriteBlockRetryCount) + << " max=" << static_cast(WRITE_BLOCK_MAX_RETRIES)); + return false; + } + + const uint8_t block = m_PendingWriteBlock; + + ++m_WriteBlockRetryCount; + DEBUG("Retrying write block=" << static_cast(block) + << " attempt=" << static_cast(m_WriteBlockRetryCount) + << "/" << static_cast(WRITE_BLOCK_MAX_RETRIES) + << " reason=" << reason); + + std::this_thread::sleep_for(std::chrono::milliseconds(WRITE_BLOCK_RETRY_DELAY_MS)); + m_ReceiveBuffer.clear(); + if (fd != -1) + { + tcflush(fd, TCIFLUSH); + } + + + // ★ 用保存的 block + value 重新构造数据帧并发送 + std::vector data; + data.push_back(m_PendingWriteBlock); + data.insert(data.end(), m_PendingWriteValue.begin(), m_PendingWriteValue.end()); + WriteCard(data); + return true; +} + + + +bool MsgHandler::HasActiveDeviceOperation() const +{ + return m_PendingCommand != PendingCommand::None || m_BlockOperationPending; +} + +int MsgHandler::HandleFindResponse(const std::vector& data, + WeighingSystem::ReadCardRsp& rsp) +{ + m_PendingCommand = PendingCommand::None; + + // ========== 新增:WAIT_DDS_READ 期间的 RF 喂送响应:不修改状态 ========== + if (m_CardState == CardState::WAIT_DDS_READ) + { + DEBUG("RF-feed FIND response ignored (card already selected, cardId=" << m_CardId << ")"); + return 0; + } + + if (data[3] != 0) + { + m_AutoFind = true; + m_FindIntervalMs = 500; + m_LastFindTime = std::chrono::steady_clock::now(); + SetCardState(CardState::AUTO_FIND); + rsp.msg()["find"].push_back(data[3]); + return 1; + } + if (data.size() < 10U) + { + DEBUG("FindCard success frame too short, size=" << data.size()); + m_AutoFind = true; + m_FindIntervalMs = 500; + m_LastFindTime = std::chrono::steady_clock::now(); + SetCardState(CardState::AUTO_FIND); + m_AutoFindNeedsReset = true; + return 0; + } + + const uint32_t cardIdValue = (data[4] << 24) | (data[5] << 16) + | (data[6] << 8) | data[7]; + std::stringstream ss; + ss << std::hex << std::uppercase << std::setw(8) << std::setfill('0') << cardIdValue; + m_CardId = ss.str(); + m_AutoFind = true; // ★ 改成 true,让 AutoFindTick 在等重量时继续喂 RF + m_FindIntervalMs = 2000; // ★ 显式设成 5 秒间隔(用现有逻辑) + m_LastFindTime = std::chrono::steady_clock::now(); + SetCardState(CardState::WAIT_DDS_READ); + rsp.msg()["find"].insert(rsp.msg()["find"].end(), data.begin() + 4, data.begin() + 8); + if (OnCardDetected) + { + OnCardDetected(m_CardId); + } + DEBUG("Card found: " << m_CardId << ", ready for DDS read or write command"); + return 1; +} + +bool MsgHandler::IsValidDeviceFrame(const std::vector& data) +{ + const bool shortWriteAck = ALLOW_SHORT_WRITE_ACK + && data.size() == 5U + && data[0] == 0x05U + && data[1] == 0x01U + && data[2] == WRITE_CARD; + if (data.size() < 6U && !shortWriteAck) + { + return false; + } + const bool shortReadFrame = data.size() >= 21U + && data[0] != static_cast(data.size() - 1U) + && data[1] == 0x01U + && data[2] == READ_CARD + && data[3] == 0x00U; + if (!shortReadFrame && !shortWriteAck + && data.size() != static_cast(data[0]) + 1U) + { + return false; + } + if (data[1] != 0x01) + { + DEBUG("Invalid device fixed byte=" << std::hex << static_cast(data[1])); + return false; + } + + if (shortWriteAck) + { + DEBUG("Accepting short WRITE_BLOCK ACK without final CRC byte, size=" + << data.size() << " status=0x" << std::hex << static_cast(data[3])); + return true; + } + + if (shortReadFrame) + { + DEBUG("Accepting short READ_BLOCK frame without length/CRC enforcement, size=" + << data.size()); + return true; + } + if (!VERIFY_DEVICE_CRC) + { + DEBUG("CRC_BYPASS device frame accepted, size=" << std::dec << data.size() + << " cmd=0x" << std::hex << static_cast(data[2])); + return true; + } + + std::vector crcData(data.begin(), data.end() - 2); + CRC16(crcData); + // 现场实帧确认:响应 CRC 与本地发送方向一致,高字节在前、低字节在后。 + const bool valid = crcData[crcData.size() - 2] == data[data.size() - 2] + && crcData[crcData.size() - 1] == data[data.size() - 1]; + if (!valid) + { + DEBUG("Invalid device CRC expected(high/low)=" + << std::hex << static_cast(crcData[crcData.size() - 2]) << "/" + << static_cast(crcData[crcData.size() - 1]) + << " actual(high/low)=" << static_cast(data[data.size() - 2]) + << "/" << static_cast(data[data.size() - 1])); + } + return valid; +} + +bool MsgHandler::IsDataBlock(uint8_t block) +{ + return block < 64U && (block % 4U) != 3U; +} + +void MsgHandler::HandleDdsMsg(const std::map>& msg, + unsigned long index) +{ + std::lock_guard lock(mtx_); + if (msg.size() != 1U) + { + DEBUG("Rejecting DDS command: expected exactly one msg key, actual=" << msg.size()); + return; + } + auto cmd = msg.begin(); + + DEBUG("HandleDdsMsg: cmd=" << cmd->first << ", index=" << index); + DEBUG("COMMAND state=" << CardStateName(m_CardState) + << " auto_find=" << m_AutoFind << " payload_size=" << cmd->second.size()); + + // ========== read 命令处理 ========== + if (cmd->first == "read") + { + // 【新增】如果在恢复序列执行期间收到了新命令,说明恢复被新命令打断 + // 此时要:1)停止旧恢复,2)清空旧状态,3)开始新命令 + if (m_IsInTimeoutRecovery) { + DEBUG("HandleDdsMsg: new read command arrived during timeout recovery, aborting old recovery"); + // 清除旧的恢复标志(让 SkipCurrentBlock 不要再发了) + m_IsInTimeoutRecovery = false; + } + + // 【新增】开始计时 + m_ReadStartTime = std::chrono::steady_clock::now(); + + + // ★ 修改:WAIT_DDS_DECISION / WAIT_DDS_WRITE_NEXT 也可以接收 read 命令 + if (m_CardState != CardState::WAIT_DDS_READ + && m_CardState != CardState::WAIT_DDS_DECISION + && m_CardState != CardState::WAIT_DDS_WRITE_NEXT) + { + DEBUG("Unexpected read command, current state=" << (int)m_CardState); + + if (m_CardState == CardState::AUTO_FIND) + { + DEBUG("read cmd during AUTO_FIND → scheduling reset"); + m_AutoFindNeedsReset = true; + } + + return; + } + if (HasActiveDeviceOperation()) + { + DEBUG("Rejecting read command: device operation is active"); + return; + } + + // 解析 read 请求协议: + // 版本(1) | 卡号长度(1) | 卡号ASCII | 块数量(1) | 块号列表 + const std::vector& data = cmd->second; + + DEBUG("DDS raw data: size=" << data.size()); + for (size_t i = 0; i < data.size() && i < 20; i++) { + std::cout << std::hex << std::setw(2) << std::setfill('0') + << (int)data[i] << " "; + } + std::cout << std::endl; + + if (data.size() < 3) + { + DEBUG("Invalid read request, size=" << data.size()); + return; + } + + uint8_t version = data[0]; + uint8_t cardIdLen = data[1]; + if (data.size() < static_cast(3U + cardIdLen)) + { + DEBUG("Invalid read request card ID length=" << static_cast(cardIdLen)); + return; + } + std::string reqCardId(data.begin() + 2, data.begin() + 2 + cardIdLen); + uint8_t blockCount = data[2 + cardIdLen]; + if (data.size() < static_cast(3U + cardIdLen + blockCount)) + { + DEBUG("Invalid read request block count=" << static_cast(blockCount)); + return; + } + + DEBUG("Read req: version=" << (int)version + << ", cardId=" << reqCardId + << ", blockCount=" << (int)blockCount); + + // 验证卡号(与检测到的卡号匹配) + if (reqCardId != m_CardId) + { + DEBUG("Card ID mismatch: req=" << reqCardId << ", found=" << m_CardId); + return; + } + + // 清空读卡缓冲区 + ClearReadBuffer(); + m_CardId = reqCardId; + + // 保存请求的块号列表。块 4、5 是扇区 1 的数据块,不能特殊跳过。 + m_RequestedBlocks.clear(); + for (int i = 0; i < blockCount; i++) + { + uint8_t blockNum = data[3 + cardIdLen + i]; + if (!IsDataBlock(blockNum)) + { + DEBUG("Rejecting sector trailer/control block " << static_cast(blockNum)); + ClearReadBuffer(); + m_AutoFind = true; + m_FindIntervalMs = 500; + m_LastFindTime = std::chrono::steady_clock::now(); + SetCardState(CardState::AUTO_FIND); + return; + } + m_RequestedBlocks.push_back(blockNum); + DEBUG("Queuing block " << (int)blockNum << " for reading"); + } + m_BlockCount = static_cast(m_RequestedBlocks.size()); + + if (m_RequestedBlocks.empty()) + { + DEBUG("Read request contains no blocks"); + return; + } + + // 【修改】只发送第一个读卡命令 + m_CurrentReadIndex = 0; + m_ReadBlockRetryCount = 0; + m_CurrentIndex = index; + if (!m_RequestedBlocks.empty()) + { + ReadCard({m_RequestedBlocks[0]}); + DEBUG("Sent first read command for block " << (int)m_RequestedBlocks[0]); + } + // 切换到等待读卡完成状态 + SetCardState(CardState::WAIT_DDS_READ); + m_StateEnterTime = std::chrono::steady_clock::now(); + // 保存 index 以便后续使用 + m_CurrentIndex = index; + return; + } + + // ========== write 命令处理 ========== + if (cmd->first == "write") + { + // 已寻到并验证卡号后,读和写都是独立 DDS 操作;写卡不要求先读卡。 + // ★ 修改:WAIT_DDS_DECISION / WAIT_DDS_WRITE_NEXT 也可以接收 write 命令 + if (m_CardState != CardState::WAIT_DDS_READ + && m_CardState != CardState::WAIT_DDS_DECISION + && m_CardState != CardState::WAIT_DDS_WRITE_NEXT) + { + DEBUG("Unexpected write command, current state=" << (int)m_CardState); + + if (m_CardState == CardState::AUTO_FIND) + { + DEBUG("write cmd during AUTO_FIND → scheduling reset"); + m_AutoFindNeedsReset = true; + } + + return; + } + if (HasActiveDeviceOperation()) + { + DEBUG("Rejecting write command: device operation is active"); + return; + } + + // 解析 write 请求协议: + // 版本(1) | 卡号长度(1) | 卡号ASCII | 块号(1) | 16字节块数据 + const std::vector& data = cmd->second; + if (data.size() < 3) + { + DEBUG("Invalid write request, size=" << data.size()); + return; + } + + uint8_t version = data[0]; + uint8_t cardIdLen = data[1]; + if (data.size() < static_cast(3U + cardIdLen + 16U)) + { + DEBUG("Invalid write request length=" << data.size() + << ", card ID length=" << static_cast(cardIdLen)); + return; + } + std::string reqCardId(data.begin() + 2, data.begin() + 2 + cardIdLen); + uint8_t blockNum = data[2 + cardIdLen]; + if (!IsDataBlock(blockNum)) + { + DEBUG("Rejecting sector trailer/control block " << static_cast(blockNum)); + m_AutoFind = true; + m_FindIntervalMs = 500; + m_LastFindTime = std::chrono::steady_clock::now(); + SetCardState(CardState::AUTO_FIND); + return; + } + + DEBUG("Write req: version=" << (int)version + << ", cardId=" << reqCardId + << ", block=" << (int)blockNum); + + // 验证卡号(先校验,校验通过再切状态) + if (reqCardId != m_CardId) + { + DEBUG("Card ID mismatch: req=" << reqCardId << ", found=" << m_CardId); + return; // ← 此时还是 WAIT_DDS_DECISION,状态不会卡死 + } + + // 校验通过,进入"等 RC522 写卡响应"状态 + m_CurrentIndex = index; + SetCardState(CardState::WAIT_DDS_WRITE); + + // 构造写卡数据(块号 + 16字节数据) + std::vector writeData; + writeData.push_back(blockNum); + writeData.insert(writeData.end(), + data.begin() + 3 + cardIdLen, + data.begin() + 3 + cardIdLen + 16); + + DEBUG("Writing block " << (int)blockNum); + + // ★ 修复:每次新 WRITE 命令入口清零(这是"新会话"的起点) + m_WriteBlockRetryCount = 0; + + WriteCard(writeData); + + return; + } + + // ========== 其他命令保持不变 ========== + if (cmd->first == "find") + { + if (HasActiveDeviceOperation()) + { + DEBUG("Ignoring find command while a device operation is active"); + return; + } + m_AutoFind = true; + m_PreCard.clear(); + m_CardId.clear(); + SetCardState(CardState::AUTO_FIND); + FindCard(); + m_FindIntervalMs = 5000; + m_LastFindTime = std::chrono::steady_clock::now(); + } + else if (cmd->first == "stop") + { + if (HasActiveDeviceOperation()) + { + DEBUG("Ignoring stop command while a device operation is active"); + return; + } + m_AutoFind = false; + SetCardState(CardState::AUTO_FIND); + StopCard(); + } + else if (cmd->first == "beep") + { + if (HasActiveDeviceOperation()) + { + DEBUG("Ignoring beep command while a device operation is active"); + return; + } + m_AutoFind = false; + BeepCard(cmd->second); + } + else if (cmd->first == "reset") + { + if (HasActiveDeviceOperation()) + { + DEBUG("Ignoring reset command while a device operation is active"); + return; + } + m_AutoFind = false; + SetCardState(CardState::AUTO_FIND); + ResetCard(); + } +} + + +int MsgHandler::HandleDeviceMsg(WeighingSystem::ReadCardRsp& rsp) +{ + std::lock_guard lock(mtx_); + std::vector m_RecvData; + + // ★ 新增:写操作给更长的读窗口,覆盖 RC522 auth fail 时清理 Crypto1 的延迟 + int timeout_ms = 200; + if (m_PendingCommand == PendingCommand::WriteBlock || + m_PendingCommand == PendingCommand::SetPassword) + { + timeout_ms = 500; // 或 800,根据 RC522 固件实测调 + } + if (RecvDeviceMsg(m_RecvData, timeout_ms) > 0) + { + return (ParseDeviceMsg(m_RecvData, rsp)); + } + return 0; +} + +void MsgHandler::CRC16(std::vector& data) +{ + uint8_t chCRCHi = 0xFF; + uint8_t chCRCLo = 0xFF; + + for (size_t i = 0; i < data.size(); i++) + { + uint8_t wIndex = chCRCLo ^ data[i]; + chCRCLo = chCRCHi ^ chCRCHTalbe[wIndex]; + chCRCHi = chCRCLTalbe[wIndex]; + } + // 保持当前运行环境既有 CRC 字节序:高字节在前、低字节在后。 + data.insert(data.end(), {chCRCHi, chCRCLo}); +} + + + + +int MsgHandler::ParseDeviceMsg(std::vector& data, WeighingSystem::ReadCardRsp& rsp) +{ + + // 【新增】清理之前的响应消息,避免键累积 + rsp.msg().clear(); + + // 仅接受已完整接收且通过协议校验的帧。 + if (!IsValidDeviceFrame(data)) + { + DEBUG("ParseDeviceMsg: invalid device frame, size=" << data.size()); + return 0; + } + + DEBUG("DEVICE FRAME seq=" << std::dec << m_OperationSequence + << " expected=" << PendingCommandName(m_PendingCommand) + << " cmd=0x" << std::hex << static_cast(data[2]) + << " status=0x" << static_cast(data[3]) + << " state=" << CardStateName(m_CardState) + << " dds_index=" << std::dec << m_CurrentIndex + << " pending_block=" << static_cast(m_CurrentOperatingBlock) + << " pending=" << m_BlockOperationPending); + + switch (data[2]) + { + case BEEP_CARD: + if (m_PendingCommand != PendingCommand::Beep) return 0; + m_PendingCommand = PendingCommand::None; + rsp.msg()["beep"].insert(rsp.msg()["beep"].end(), data[3]); + break; + case STOP_CARD: + // if (m_PendingCommand == PendingCommand::Find) + // { + // return HandleFindResponse(data, rsp); + // } + if (m_PendingCommand != PendingCommand::Stop) return 0; + m_PendingCommand = PendingCommand::None; + rsp.msg()["stop"].insert(rsp.msg()["stop"].end(), data[3]); + break; + case FIND_CARD: + if (m_PendingCommand != PendingCommand::Find) return 0; + return HandleFindResponse(data, rsp); + case READ_CARD: + { + if (m_PendingCommand != PendingCommand::ReadBlock) + { + DEBUG("Ignoring unmatched READ_CARD response"); + return 0; + } + const uint8_t status = data[3]; + if (status != 0) + { + DEBUG("ReadCard FAIL: error code=0x" << std::hex << static_cast(status)); + + std::vector rsp_data; + rsp_data.push_back(1); + const uint16_t error = MapDeviceError(READ_CARD, status); + rsp_data.push_back(static_cast(error >> 8)); + rsp_data.push_back(static_cast(error & 0xFF)); + rsp_data.push_back(static_cast(m_CardId.length())); + rsp_data.insert(rsp_data.end(), m_CardId.begin(), m_CardId.end()); + rsp_data.push_back(0); + + rsp.msg()["read"] = rsp_data; + ClearReadBuffer(); + m_CurrentOperatingBlock = 0; + m_BlockOperationPending = false; + m_PendingCommand = PendingCommand::None; + // ★ 新增:读卡 NACK 也走统一的 AUTO_FIND 异常恢复流程 + m_AutoFindNeedsReset = true; + m_AutoFind = true; + m_FindIntervalMs = 500; + m_LastFindTime = std::chrono::steady_clock::now(); + SetCardState(CardState::AUTO_FIND); + return 1; + } + + if (m_RequestedBlocks.empty() || m_CurrentReadIndex >= m_RequestedBlocks.size()) + { + DEBUG("ReadCard success without a pending requested block"); + return 0; + } + + const size_t payloadSize = data.size() - 6U; + uint8_t blockNum = m_RequestedBlocks[m_CurrentReadIndex]; + std::vector block16; + if (data.size() >= 21U) + { + // 兼容参考驱动的固定偏移:data[4] 为块号,data[5..20] 为 16 字节数据。 + const uint8_t responseBlock = data[4]; + if (responseBlock != blockNum) + { + DEBUG("ReadCard response block mismatch, expected=" << static_cast(blockNum) + << ", actual=" << static_cast(responseBlock)); + return 0; + } + block16.assign(data.begin() + 5, data.begin() + 21); + } + else if (payloadSize == 16U) + { + block16.assign(data.begin() + 4, data.begin() + 20); + } + else if (payloadSize == 17U) + { + const uint8_t responseBlock = data[4]; + if (responseBlock != blockNum) + { + // ★ 移除重试:块号不匹配直接回 AUTO_FIND + DEBUG("ReadCard response block mismatch, expected=" << static_cast(blockNum) + << ", actual=" << static_cast(responseBlock) + << " — reverting to AUTO_FIND"); + m_BlockOperationPending = false; + m_PendingCommand = PendingCommand::None; + m_AutoFindNeedsReset = true; + m_AutoFind = true; + m_FindIntervalMs = 5000; + m_LastFindTime = std::chrono::steady_clock::now() + - std::chrono::milliseconds(m_FindIntervalMs); + SetCardState(CardState::AUTO_FIND); + return 0; + } + block16.assign(data.begin() + 5, data.begin() + 21); + } + else + { + // ★ 移除重试:payload 长度无效直接回 AUTO_FIND + DEBUG("ReadCard success payload length invalid, size=" << payloadSize + << " — reverting to AUTO_FIND"); + m_BlockOperationPending = false; + m_PendingCommand = PendingCommand::None; + m_AutoFindNeedsReset = true; + m_AutoFind = true; + m_FindIntervalMs = 5000; + m_LastFindTime = std::chrono::steady_clock::now() + - std::chrono::milliseconds(m_FindIntervalMs); + SetCardState(CardState::AUTO_FIND); + return 0; + } + + m_BlockOpStartTime = std::chrono::steady_clock::now(); + m_CurrentOperatingBlock = 0; + m_BlockOperationPending = false; + m_PendingCommand = PendingCommand::None; + m_ReadBlockRetryCount = 0; + + DEBUG("ReadCard OK, block=" << (int)blockNum); + + m_BlockData.push_back({blockNum, block16}); + + if (m_BlockData.size() >= m_RequestedBlocks.size()) + { + // 所有块读取完成,构建完整 DDS 响应 + DEBUG("All blocks read, building complete DDS response"); + + std::vector rsp_data; + rsp_data.push_back(1); // 版本 + rsp_data.push_back(0x00); // 结果码高 + rsp_data.push_back(0x00); // 结果码低 + rsp_data.push_back(m_CardId.length()); // 卡号长度 + rsp_data.insert(rsp_data.end(), m_CardId.begin(), m_CardId.end()); // 卡号 + rsp_data.push_back(m_BlockData.size()); // 块数量 + + // 添加所有块的数据 + for (const auto& block : m_BlockData) + { + rsp_data.push_back(block.first); // 块号 + rsp_data.insert(rsp_data.end(), block.second.begin(), block.second.end()); // 16字节 + } + + rsp.msg()["read"] = rsp_data; + + // 清理并恢复状态 + m_BlockData.clear(); + m_RequestedBlocks.clear(); + m_CurrentReadIndex = 0; + // ★ 修改:读卡成功后切到 WAIT_DDS_DECISION,等待下一个 DDS 命令(20秒超时) + // SetCardState 会自动重置 m_StateEnterTime,超时重新计时 + m_AutoFind = false; // RF 保持关闭(前面 SummaryUpdate 后已经停掉了) + m_LastFindTime = std::chrono::steady_clock::now(); + SetCardState(CardState::WAIT_DDS_READ); + + + + // 【新增】结束计时并打印 + m_ReadEndTime = std::chrono::steady_clock::now(); + auto elapsed = std::chrono::duration_cast( + m_ReadEndTime - m_ReadStartTime).count(); + DEBUG("Read card elapsed: " << elapsed << " ms (" + << elapsed / 1000.0 << " seconds)"); + + return 1; // ← 返回1表示需要发布 DDS 响应 + } + + m_CurrentReadIndex++; + if (m_CurrentReadIndex < m_RequestedBlocks.size()) + { + uint8_t nextBlock = m_RequestedBlocks[m_CurrentReadIndex]; + DEBUG("Sending next read command for block " << (int)nextBlock); + m_ReadBlockRetryCount = 0; + ReadCard({nextBlock}); + std::this_thread::sleep_for(std::chrono::milliseconds(30)); + } + + return 0; // ← 未全部完成,不发布响应 + } + break; + case WRITE_CARD: + { + if (m_PendingCommand != PendingCommand::WriteBlock) + { + DEBUG("Ignoring unmatched WRITE_CARD response"); + return 0; + } + + if (data[3] == 0) // 写卡成功 + { + m_BlockOperationPending = false; + m_PendingCommand = PendingCommand::None; + m_WriteBlockRetryCount = 0; // ★ 新增:写卡成功后清零,给下次操作 + DEBUG("WriteCard OK: block=" << (int)m_PendingWriteBlock); + + // ★ 修改:写卡成功后切到 WAIT_DDS_WRITE_NEXT,等待下一个 DDS 命令(10秒超时) + // SetCardState 会自动重置 m_StateEnterTime,超时重新计时 + m_AutoFind = false; // RF 保持关闭 + SetCardState(CardState::WAIT_DDS_WRITE_NEXT); + DEBUG("Write complete, waiting for next DDS command"); + + // ★ 与 read 响应同协议:1 键 + vector + std::vector write_rsp; + write_rsp.push_back(1); // 版本 + write_rsp.push_back(0x00); // 结果码高 + write_rsp.push_back(0x00); // 结果码低(成功) + write_rsp.push_back((uint8_t)m_CardId.size()); // 卡号长度 + write_rsp.insert(write_rsp.end(), + m_CardId.begin(), m_CardId.end()); // 卡号 + write_rsp.push_back(1); // 块数量 = 1 + write_rsp.push_back(m_PendingWriteBlock); // 块号 + write_rsp.push_back(0x00); // 块结果码高 = 0(成功) + write_rsp.push_back(0x00); // 块结果码低 = 0(成功) // 块数量 = 0 + rsp.msg()["write"] = write_rsp; + + rsp.index(m_CurrentIndex); + + // ★ 新增:清理敏感数据,避免长期驻留内存 + std::fill(m_PendingWriteValue.begin(), m_PendingWriteValue.end(), 0); + m_PendingWriteValue.clear(); + m_PendingWriteBlock = 0; + + return 1; + } + else // 写卡失败 + { + DEBUG("WriteCard FAIL: block=" << (int)m_PendingWriteBlock + << " error code=0x" << std::hex << (int)data[3]); + + + // ========== 回 AUTO_FIND ========== + m_WriteBlockRetryCount = 0; // ★ 新增:清掉计数,给下次扫描用 + m_BlockOperationPending = false; + m_PendingCommand = PendingCommand::None; + m_AutoFindNeedsReset = true; // ★ 加这行 + m_AutoFind = true; + m_FindIntervalMs = 500; + m_LastFindTime = std::chrono::steady_clock::now(); + SetCardState(CardState::AUTO_FIND); + + // ========== 修复:失败响应包用与成功完全一致的格式 ========== + const uint16_t error = MapDeviceError(WRITE_CARD, data[3]); + std::vector write_rsp; + write_rsp.push_back(1); // 版本 + write_rsp.push_back(static_cast(error >> 8)); + write_rsp.push_back(static_cast(error & 0xFF)); // 结果码 + write_rsp.push_back(static_cast(m_CardId.size())); // ★ 新增:卡号长度(与成功分支一致) + write_rsp.insert(write_rsp.end(), + m_CardId.begin(), m_CardId.end()); // ★ 卡号:与成功分支一致(直接拼 8 字节,不带长度前缀) + write_rsp.push_back(1); // 块数量 = 1 + write_rsp.push_back(m_PendingWriteBlock); // 块号 + write_rsp.push_back(static_cast(error >> 8)); + write_rsp.push_back(static_cast(error & 0xFF)); // 块结果码 + rsp.msg()["write"] = write_rsp; + + rsp.index(m_CurrentIndex); + + // ★ 新增:清理敏感数据,避免长期驻留内存 + std::fill(m_PendingWriteValue.begin(), m_PendingWriteValue.end(), 0); + m_PendingWriteValue.clear(); + m_PendingWriteBlock = 0; + + return 1; + } + } + break; + default: + break; + } + + return 0; +} +void MsgHandler::StorePasswd(std::map>& data) +{ + m_PassWord = data; +} + +void MsgHandler::SetPasswd(const std::vector& data) +{ + + std::this_thread::sleep_for(std::chrono::milliseconds(50)); // 添加延迟 + + std::vector m_SendData; + m_PendingCommand = PendingCommand::SetPassword; + ++m_OperationSequence; + + m_SendData.insert(m_SendData.end(), {0x0C, 0x01, 0x03, 60, data[0]}); + auto it = m_PassWord.find(data[0]); + if (it != m_PassWord.end()) + { + m_SendData.insert(m_SendData.end(), it->second.begin(), it->second.end()); + } + + CRC16(m_SendData); + SendDeviceMsg(m_SendData); +} + +void MsgHandler::StopCard(void) +{ + std::vector m_SendData; + m_PendingCommand = PendingCommand::Stop; + ++m_OperationSequence; + + m_SendData.insert(m_SendData.end(), {0x04, 0x01, 0x08}); + CRC16(m_SendData); + SendDeviceMsg(m_SendData); +} + +void MsgHandler::FindCard(void) +{ + std::vector m_SendData; + m_PendingCommand = PendingCommand::Find; + ++m_OperationSequence; + + m_SendData.insert(m_SendData.end(), {0x04, 0x01, 0x02}); + CRC16(m_SendData); + SendDeviceMsg(m_SendData); +} + +// ★ 新增:RF 喂送专用寻卡 —— 只发字节,不修改 m_PendingCommand、不动 m_OperationSequence +// 响应回来时 ParseDeviceMsg 会因为 m_PendingCommand != Find 直接丢弃(return 0), +// 不会触发 HandleFindResponse 改状态,不会污染 HasActiveDeviceOperation() 判断。 +void MsgHandler::SendRfFeedFind(void) +{ + std::vector m_SendData; + m_SendData.insert(m_SendData.end(), {0x04, 0x01, 0x02}); + CRC16(m_SendData); + SendDeviceMsg(m_SendData); +} + + +void MsgHandler::ReadCard(const std::vector& data) +{ + std::vector m_SendData; + + + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + + + m_SendData.insert(m_SendData.end(), {0x05, 0x01, 0x04, data[0]}); + // ========== 新增:记录当前块操作开始时间 ========== + m_CurrentOperatingBlock = data[0]; + m_BlockOpStartTime = std::chrono::steady_clock::now(); + m_BlockOperationPending = true; + m_PendingCommand = PendingCommand::ReadBlock; + m_PendingBlock = data[0]; + ++m_OperationSequence; + + + CRC16(m_SendData); + + m_AutoFind = false; // ★ 关闭 RF-feed,防止 FindCard 响应干扰 + + SendDeviceMsg(m_SendData); + // 【新增】保护延时:给 RC522 和 STM32 固件留出处理时间 + // 原因:连续发读块命令时,RC522 内部认证状态可能丢失 + std::this_thread::sleep_for(std::chrono::milliseconds(100)); +} + +void MsgHandler::WriteCard(const std::vector& data) +{ + // ★ 在调串口之前先存请求参数(响应时要用) + // data = [blockNum(1)] + [16 字节块数据] + if (data.size() != 17U) + { + DEBUG("WriteCard rejected: expected block plus 16 data bytes, size=" << data.size()); + m_BlockOperationPending = false; + m_PendingCommand = PendingCommand::None; + return; + } + + // ★ 新增:发命令前延时,让 RC522 处理完上一条命令 + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + + m_PendingWriteBlock = data[0]; + m_PendingWriteValue.assign(data.begin() + 1, data.end()); + + DEBUG("WriteCard request block=" << static_cast(m_PendingWriteBlock) + << " data_size=" << m_PendingWriteValue.size() + << " data=" << HexBytes(m_PendingWriteValue)); + + // ========== 新增:记录当前块操作开始时间 ========== + m_CurrentOperatingBlock = data[0]; + m_BlockOpStartTime = std::chrono::steady_clock::now(); + m_BlockOperationPending = true; + m_PendingCommand = PendingCommand::WriteBlock; + m_PendingBlock = data[0]; + ++m_OperationSequence; + + + std::vector m_SendData; + m_SendData.insert(m_SendData.end(), {0x15, 0x01, 0x05}); + m_SendData.insert(m_SendData.end(), data.begin(), data.end()); + + DEBUG("WriteCard frame_without_crc size=" << m_SendData.size() + << " bytes=" << HexBytes(m_SendData)); + + CRC16(m_SendData); + + DEBUG("WriteCard frame_with_crc size=" << m_SendData.size() + << " bytes=" << HexBytes(m_SendData)); + + m_AutoFind = false; // ★ 关闭 RF-feed,防止 FindCard 响应干扰 + + SendDeviceMsg(m_SendData); + + // ★ 新增:发命令后延时,让 RC522 完成 Crypto1 重建(如果固件会重建) + std::this_thread::sleep_for(std::chrono::milliseconds(100)); +} + +void MsgHandler::BeepCard(const std::vector& data) +{ + std::vector m_SendData; + m_PendingCommand = PendingCommand::Beep; + ++m_OperationSequence; + + uint8_t duration = data.empty() ? 0x0F : data[0]; + m_SendData.insert(m_SendData.end(), {0x05, 0x01, 0x01, duration}); + CRC16(m_SendData); + SendDeviceMsg(m_SendData); +} + +void MsgHandler::ResetCard(void) +{ + if (fd != -1) + { + tcflush(fd, TCIOFLUSH); + } + m_ReceiveBuffer.clear(); + DEBUG("ResetCard: serial buffer flushed"); +} + + + +// ========== 重置串口并重新初始化 RC522 ========== +// 用于块操作超时后的恢复,因为 RC522 可能在某些情况下完全无响应 +bool MsgHandler::ResetSerialAndReinit() +{ + DEBUG("ResetSerialAndReinit: resetting serial port and RC522"); + m_ReceiveBuffer.clear(); + + // 第一步:关闭当前串口 + ClosePort(); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + + // 第二步:重新打开串口(使用保存的端口) + if (m_Port.empty()) + { + DEBUG("ResetSerialAndReinit: m_Port is empty, cannot reopen"); + return false; + } + std::string tty = "/dev/" + m_Port; + DEBUG("ResetSerialAndReinit: reopening " << tty << " with baudrate " << (int)m_Baudrate); + + fd = open(tty.c_str(), O_RDWR | O_NOCTTY | O_NDELAY); + if (fd == -1) + { + DEBUG("ResetSerialAndReinit: failed to reopen serial port " << tty); + return false; + } + + // 第三步:重新配置串口参数(使用保存的波特率) + struct termios options; + if (tcgetattr(fd, &options) != 0) + { + DEBUG("ResetSerialAndReinit: failed to get serial attributes"); + close(fd); + fd = -1; + return false; + } + + cfmakeraw(&options); + cfsetispeed(&options, m_Baudrate); + cfsetospeed(&options, m_Baudrate); + options.c_cflag |= CS8; + options.c_cflag &= ~PARENB; + options.c_cflag &= ~CSTOPB; + options.c_cflag &= ~CRTSCTS; + options.c_cc[VMIN] = 0; + options.c_cc[VTIME] = 10; + + tcflush(fd, TCIOFLUSH); + if (tcsetattr(fd, TCSANOW, &options) != 0) + { + DEBUG("ResetSerialAndReinit: failed to set serial attributes"); + close(fd); + fd = -1; + return false; + } + + DEBUG("ResetSerialAndReinit: serial port reopened successfully"); + + // 第四步:等待 RC522 准备好 + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + + // 第五步:清空 RC522 内部状态(直接发命令,不等待响应) + StopCard(); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + + // 第六步:重新下载所有扇区密码(直接发命令,不等待响应) + for (auto& kv : m_PassWord) { + SetPasswd({kv.first}); + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + + // 第七步:启动寻卡(直接发命令,不等待响应) + FindCard(); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + + DEBUG("ResetSerialAndReinit: commands sent, waiting for RC522 to recover..."); + + DEBUG("ResetSerialAndReinit: RC522 reinitialized successfully"); + return true; +} + + + + + +bool MsgHandler::WaitForResponse(uint8_t expected_cmd, int timeout_ms) +{ + int elapsed = 0; + const int poll_interval = 100; + + while (elapsed < timeout_ms) + { + std::vector data; + if (RecvDeviceMsg(data, poll_interval) > 0) + { + if (data.size() >= 4 && data[2] == expected_cmd && data[3] == 0x00) + { + return true; + } + } + elapsed += poll_interval; + } + + DEBUG("WaitForResponse timeout, expected_cmd=0x" + << std::hex << (int)expected_cmd); + return false; +} + +bool MsgHandler::InitSequence(void) +{ + // 第一步:停止寻卡 + StopCard(); + if (!WaitForResponse(STOP_CARD)) + { + DEBUG("InitSequence: StopCard failed"); + return false; + } + DEBUG("InitSequence: StopCard OK"); + + // 第二步:逐扇区下载密码(升序) + for (auto& kv : m_PassWord) + { + SetPasswd({kv.first}); + if (!WaitForResponse(SET_PWD)) + { + DEBUG("InitSequence: SetPasswd sector " + << (int)kv.first << " failed"); + return false; + } + DEBUG("InitSequence: SetPasswd sector " + << (int)kv.first << " OK"); + } + + // 第三步:启动寻卡 + FindCard(); + m_AutoFind = true; + m_FindIntervalMs = 5000; // 发送后5000ms超时保护 + m_LastFindTime = std::chrono::steady_clock::now(); + DEBUG("InitSequence: complete, auto-find enabled"); + + return true; +} + +void MsgHandler::AutoFindTick(void) +{ + std::lock_guard lock(mtx_); + + if (!m_AutoFind) + return; + + if (m_CardState != CardState::AUTO_FIND + && m_CardState != CardState::WAIT_DDS_READ) + return; + + const auto now = std::chrono::steady_clock::now(); + const auto elapsed = std::chrono::duration_cast( + now - m_LastFindTime).count(); + + if (elapsed >= m_FindIntervalMs) + { + if (m_CardState == CardState::AUTO_FIND) + { + DEBUG("AUTO_FIND tick elapsed_ms=" << elapsed + << " interval_ms=" << m_FindIntervalMs); + // AUTO_FIND 状态:响应回来后要切到 WAIT_DDS_READ,用普通 FindCard + FindCard(); + } + else + { + DEBUG("WAIT_DDS_READ RF-feed tick elapsed_ms=" << elapsed + << " interval_ms=" << m_FindIntervalMs); + // ★ WAIT_DDS_READ 状态:用 RF 喂送专用函数,m_PendingCommand 不动 + // 这样不会被 ParseDeviceMsg 当成 Find 响应,也不会被 HandleDdsMsg 当成设备忙拒掉 + SendRfFeedFind(); + } + + m_FindIntervalMs = (m_CardState == CardState::WAIT_DDS_READ) ? 2000 : 5000; + m_LastFindTime = now; + } +} + +void MsgHandler::SetCardState(CardState state) +{ + std::lock_guard lock(mtx_); + const CardState oldState = m_CardState; + m_CardState = state; + m_StateEnterTime = std::chrono::steady_clock::now(); + DEBUG("STATE " << CardStateName(oldState) << " -> " << CardStateName(state)); +} + +unsigned long MsgHandler::GetCurrentIndex() const +{ + std::lock_guard lock(mtx_); + return m_CurrentIndex; +} + +bool MsgHandler::IsTimeoutRecovery() const +{ + std::lock_guard lock(mtx_); + return m_IsInTimeoutRecovery; +} + +uint64_t MsgHandler::GetOperationSequence() const +{ + std::lock_guard lock(mtx_); + return m_OperationSequence; +} + +bool MsgHandler::IsReadResponseReady() const +{ + // 检查读卡响应是否准备好(块数据已累积完成) + return (m_CardState == CardState::WAIT_DDS_WRITE) && (m_BlockCount > 0); +} + +bool MsgHandler::IsWriteResponseReady() const +{ + // 写卡响应在每次写成功后立即可用 + return false; // 由 ParseDeviceMsg 实时处理 +} + +void MsgHandler::ClearReadBuffer() +{ + m_BlockData.clear(); + m_BlockCount = 0; + m_ResultCode = 0; + m_RequestedBlocks.clear(); // 【新增】清空块号列表 + m_SkippedBlocks.clear(); // 【新增】清空跳过的块记录 +} + +void MsgHandler::SetReadResult(uint8_t resultCode, const std::string& cardId, + uint8_t blockCount, + const std::vector>>& blockData) +{ + m_ResultCode = resultCode; + m_CardId = cardId; + m_BlockCount = blockCount; + m_BlockData = blockData; +} + +void MsgHandler::SetWriteResult(uint8_t resultCode, const std::string& cardId, uint8_t blockNum) +{ + m_ResultCode = resultCode; + m_CardId = cardId; + // blockNum 已在写卡命令中处理 +} + +int MsgHandler::CheckDdsTimeout() +{ + std::lock_guard lock(mtx_); + + // 设备读写事务期间不使用空闲超时,避免中断块序列。 + if (m_CardState == CardState::WAIT_DDS_READ) + { + if (m_BlockOperationPending || m_PendingCommand != PendingCommand::None) + return 0; + + const auto now = std::chrono::steady_clock::now(); + const auto elapsed = std::chrono::duration_cast( + now - m_StateEnterTime).count(); + if (elapsed >= CARD_READY_IDLE_TIMEOUT_MS) + { + DEBUG("Card ready idle timeout (" << CARD_READY_IDLE_TIMEOUT_MS + << "ms), reverting to AUTO_FIND"); + m_AutoFind = true; + m_FindIntervalMs = 500; + m_LastFindTime = now; + m_AutoFindNeedsReset = true; // ★ 与写卡超时路径保持一致 + SetCardState(CardState::AUTO_FIND); + return 1; + } + return 0; + } + + + // 【新增】WAIT_DDS_WRITE 写卡块操作超时:等 RC522 响应超过 2s 视为失败,回 AUTO_FIND + if (m_CardState == CardState::WAIT_DDS_WRITE) + { + if (!m_BlockOperationPending) + return 0; + const auto writeNow = std::chrono::steady_clock::now(); + const auto writeElapsed = std::chrono::duration_cast( + writeNow - m_BlockOpStartTime).count(); + if (writeElapsed >= WRITE_BLOCK_OPERATION_TIMEOUT_MS) + { + + // 【关键修复】:如果写块还有重试额度,交给 RecvMsg 的截断帧分支处理, + // 不要在 CheckDdsTimeout 里提前清掉 m_PendingCommand,导致 retry 失效。 + // if (m_WriteBlockRetryCount < WRITE_BLOCK_MAX_RETRIES) + // { + // DEBUG("CheckDdsTimeout: WAIT_DDS_WRITE timeout but retries remain (" + // << static_cast(m_WriteBlockRetryCount) << "/" + // << static_cast(WRITE_BLOCK_MAX_RETRIES) + // << "), skipping AUTO_FIND — RecvMsg incomplete handler will retry"); + // return 0; // ← 关键:不清状态,让截断帧处理分支优先 + // } + + + DEBUG("Write block operation timeout (" << WRITE_BLOCK_OPERATION_TIMEOUT_MS + << "ms), reverting to AUTO_FIND"); + // 清理 pending 标志 + m_BlockOperationPending = false; + m_PendingCommand = PendingCommand::None; + // 清串口残留帧(避免下个循环再拿到那 5 字节尾巴) + m_ReceiveBuffer.clear(); + if (fd != -1) + tcflush(fd, TCIFLUSH); + + // ★ 新增:标记需要 reset RC522,由 Publisher 主循环里的 + // ConsumeAutoFindNeedsReset() 统一触发 ResetSerialAndReinit() + // 与 RecvMsg 截断帧 / TryExtractDeviceFrame CRC 失败的处理路径一致。 + m_AutoFindNeedsReset = true; + + + // 恢复自动寻卡 + m_AutoFindNeedsReset = true; // ★ 加这行 + m_AutoFind = true; + m_FindIntervalMs = 5000; + //m_LastFindTime = writeNow; + m_LastFindTime = writeNow - std::chrono::milliseconds(m_FindIntervalMs); + SetCardState(CardState::AUTO_FIND); + return 1; + } + return 0; + } + + + if (m_CardState != CardState::WAIT_DDS_DECISION + && m_CardState != CardState::WAIT_DDS_WRITE_NEXT) + return 0; + + auto now = std::chrono::steady_clock::now(); + auto elapsed = std::chrono::duration_cast( + now - m_StateEnterTime).count(); + + // ★ 不同状态用不同的超时阈值 + int timeout_ms = DDS_TIMEOUT_MS; + if (m_CardState == CardState::WAIT_DDS_DECISION) + { + timeout_ms = DDS_DECISION_TIMEOUT_MS; + } + + else if (m_CardState == CardState::WAIT_DDS_WRITE_NEXT) // 【新增】 + { + timeout_ms = DDS_WRITE_TIMEOUT_MS; // 【新增】10秒 + } + + if (elapsed >= timeout_ms) + { + DEBUG("DDS timeout (" << timeout_ms << "ms), reverting to AUTO_FIND"); + + // 恢复自动寻卡 + m_AutoFind = true; + m_FindIntervalMs = 5000; + m_LastFindTime = now; + + // 清空读卡缓冲区 + ClearReadBuffer(); + + // ★ 新增:触发完整 RC522 重置路径,与 WAIT_DDS_READ / WAIT_DDS_WRITE 超时保持一致 + m_AutoFindNeedsReset = true; + + // 切换状态 + SetCardState(CardState::AUTO_FIND); + return 1; // 返回1表示触发了超时 + } + return 0; +} + +void MsgHandler::ResetWriteTimeout() +{ + if (m_CardState == CardState::WAIT_DDS_WRITE_NEXT) + m_StateEnterTime = std::chrono::steady_clock::now(); +} + +// ========== 单块操作超时控制实现 ========== + +int MsgHandler::GetBlockOpElapsed() const +{ + std::lock_guard lock(mtx_); + auto now = std::chrono::steady_clock::now(); + return std::chrono::duration_cast( + now - m_BlockOpStartTime).count(); +} + +uint8_t MsgHandler::GetCurrentOperatingBlock() const +{ + std::lock_guard lock(mtx_); + return m_CurrentOperatingBlock; +} + +bool MsgHandler::IsBlockOperationPending() const +{ + std::lock_guard lock(mtx_); + return m_BlockOperationPending; +} + +bool MsgHandler::HasPendingReadResponse() const +{ + return !m_PendingReadResponse.empty(); +} + +std::vector MsgHandler::GetPendingReadResponse() +{ + auto tmp = m_PendingReadResponse; + m_PendingReadResponse.clear(); + return tmp; +} + +void MsgHandler::SkipCurrentBlock() +{ + + + DEBUG("SkipCurrentBlock: state=" << (int)m_CardState + << ", index=" << (int)m_CurrentReadIndex + << ", total=" << (int)m_RequestedBlocks.size()); + + + // 【新增】标记正在恢复,防止 HandleDdsMsg 在此期间发新命令 + m_IsInTimeoutRecovery = true; + + + // ★ 修改:WAIT_DDS_DECISION / WAIT_DDS_WRITE_NEXT 也可以调用 SkipCurrentBlock + if (m_CardState != CardState::WAIT_DDS_READ + && m_CardState != CardState::WAIT_DDS_DECISION + && m_CardState != CardState::WAIT_DDS_WRITE_NEXT) + { + DEBUG("SkipCurrentBlock: not in WAIT_DDS_READ state, ignored"); + m_IsInTimeoutRecovery = false; + return; + } + + if (m_RequestedBlocks.empty() || m_CurrentReadIndex >= m_RequestedBlocks.size()) + { + DEBUG("SkipCurrentBlock: no more blocks to skip"); + m_IsInTimeoutRecovery = false; + return; + } + + uint8_t skipBlock = m_RequestedBlocks[m_CurrentReadIndex]; + DEBUG("Read block timeout, block=" << static_cast(skipBlock)); + + // 超时不是成功数据,使用 README 约定的设备超时错误码 0x0015。 + std::vector rsp_data; + rsp_data.push_back(1); + // README 约定:设备超时使用大端结果码 0x0015。 + rsp_data.push_back(0x00); + rsp_data.push_back(0x15); + rsp_data.push_back(static_cast(m_CardId.size())); + rsp_data.insert(rsp_data.end(), m_CardId.begin(), m_CardId.end()); + rsp_data.push_back(0); + + m_PendingReadResponse = rsp_data; + ClearReadBuffer(); + m_CurrentOperatingBlock = 0; + m_BlockOperationPending = false; + m_IsInTimeoutRecovery = false; + m_AutoFind = true; + m_FindIntervalMs = 500; + m_LastFindTime = std::chrono::steady_clock::now(); + SetCardState(CardState::AUTO_FIND); + DEBUG("Read block timeout response ready, block=" << static_cast(skipBlock)); + return; + + +} +CardState MsgHandler::GetCardState() const +{ + std::lock_guard lock(mtx_); + return m_CardState; +} + + +bool MsgHandler::ConsumeAutoFindNeedsReset() +{ + std::lock_guard lock(mtx_); + if (!m_AutoFindNeedsReset) + { + return false; + } + m_AutoFindNeedsReset = false; + return true; +} + +// 【新增】AUTO_FIND 恢复用的细粒度访问器 +void MsgHandler::SetAutoFind(bool on) +{ + std::lock_guard lock(mtx_); + m_AutoFind = on; +} +void MsgHandler::SetFindIntervalMs(int interval_ms) +{ + std::lock_guard lock(mtx_); + m_FindIntervalMs = interval_ms; +} +void MsgHandler::SetLastFindTimeToNow() +{ + std::lock_guard lock(mtx_); + m_LastFindTime = std::chrono::steady_clock::now(); +} +void MsgHandler::ClearPendingCommand() +{ + std::lock_guard lock(mtx_); + m_PendingCommand = PendingCommand::None; +} + + + + +// ========== refreshPort 默认实现 ========== +bool MsgHandler::refreshPort() +{ + DEBUG("MsgHandler::refreshPort: base class default implementation, no-op"); + return true; +} diff --git a/readcard/MsgHandler.hpp b/readcard/MsgHandler.hpp new file mode 100644 index 0000000..8ed7349 --- /dev/null +++ b/readcard/MsgHandler.hpp @@ -0,0 +1,267 @@ +#ifndef _MSGHANDLER_HPP_ +#define _MSGHANDLER_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "WeighingDDSType.hpp" +#include + +#define BEEP_CARD 1 +#define FIND_CARD 2 // 发送命令号 +#define FIND_CARD_RSP 0x08 // FindCard 响应命令号(固件返回0x08) +#define SET_PWD 3 +#define READ_CARD 4 +#define WRITE_CARD 5 +#define STOP_CARD 8 // 发送/响应命令号(Pause) + + +enum class CardState { + AUTO_FIND, // 自动寻卡状态 + WAIT_DDS_READ, // 等待 DDS read 命令 + WAIT_DDS_WRITE, // 等待 DDS write 命令 + WAIT_DDS_DECISION, // 读卡完成,等待 DDS 决定(write / stop / ack) + WAIT_DDS_WRITE_NEXT // 写卡成功,等待下一个 write 命令(10秒超时) +}; + +enum class PendingCommand : uint8_t { None, Find, SetPassword, ReadBlock, WriteBlock, Stop, Beep }; + + +class MsgHandler { +public: + int fd; + std::string device; + std::map> m_PassWord; + + MsgHandler(); + ~MsgHandler() = default; + + void HandleDdsMsg(const std::map>& msg, unsigned long index); + int HandleDeviceMsg(WeighingSystem::ReadCardRsp& rsp); + bool SetDevice(const std::string& device); + bool InitSequence(void); + void AutoFindTick(void); + + void StorePasswd(std::map>& data); + void SetPasswd(const std::vector& data); + void FindCard(void); + void ReadCard(const std::vector& data); + void WriteCard(const std::vector& data); + void StopCard(void); + void BeepCard(const std::vector& data); + void ResetCard(void); + + int ParseDeviceMsg(std::vector& data, WeighingSystem::ReadCardRsp& rsp); + + bool WaitForResponse(uint8_t expected_cmd, int timeout_ms = 3000); + + virtual bool OpenPort(const std::string& port, const std::string& baudrate); + virtual int SendDeviceMsg(const std::vector& data); + virtual int RecvDeviceMsg(std::vector& data, int timeoutMs); + int SendMsg(const std::vector& data); + int RecvMsg(std::vector& data, int timeoutMs); + bool isOpen() const { + return fd != -1; + } + void ClosePort(); + + + // 【新增】内部版本,不加锁,供 ParseDeviceMsg 的 drain 循环使用 + int RecvMsgInternal(std::vector& data, int timeoutMs); + + + + void SetCardState(CardState state); + unsigned long GetCurrentIndex() const; + bool IsTimeoutRecovery() const; + uint64_t GetOperationSequence() const; + bool IsReadResponseReady() const; + bool IsWriteResponseReady() const; + void ClearReadBuffer(); + void SetReadResult(uint8_t resultCode, const std::string& cardId, uint8_t blockCount, + const std::vector>>& blockData); + void SetWriteResult(uint8_t resultCode, const std::string& cardId, uint8_t blockNum); + int CheckDdsTimeout(); + + void ResetWriteTimeout(); + + std::function OnCardDetected; + + + // ========== 单块操作超时控制 ========== + int GetBlockOpElapsed() const; + static constexpr int BLOCK_OPERATION_TIMEOUT_MS = 3000; + static constexpr bool VERIFY_DEVICE_CRC = true; + // 现场部分设备的写应答偶尔只返回 LEN、命令、状态和一个 CRC 字节。 + // 允许兼容该固定 5 字节残帧,但仍必须检查状态码。 + static constexpr bool ALLOW_SHORT_WRITE_ACK = true; + // 通信帧不完整或 CRC/数据校验失败时,同一读块允许额外重发的次数。 + static constexpr uint8_t READ_BLOCK_MAX_RETRIES = 1; + static constexpr int READ_BLOCK_RETRY_DELAY_MS = 100; + uint8_t GetCurrentOperatingBlock() const; + bool IsBlockOperationPending() const; + void SkipCurrentBlock(); + bool HasPendingReadResponse() const; + std::vector GetPendingReadResponse(); + CardState GetCardState() const; + + // 【新增】标记:是否正在执行超时恢复序列 + // 原因:SkipCurrentBlock 发的恢复命令可能和 HandleDdsMsg 的新命令冲突 + bool m_IsInTimeoutRecovery = false; + + // 【新增】重置串口并重新初始化 RC522(用于块操作超时后的恢复) + bool ResetSerialAndReinit(); + + // 【新增】刷新串口配置(供 SkipCurrentBlock 使用) + bool refreshPort(); + + // 【新增】保存串口参数,供 ResetSerialAndReinit 使用 + std::string m_Port; // 端口名,如 "ttyS1" + speed_t m_Baudrate; // 波特率(speed_t 类型) + + // 【新增】AUTO_FIND 重置标志的读取+清零接口 + // 语义:返回 m_AutoFindNeedsReset 的当前值,并立刻置为 false(只触发一次)。 + bool ConsumeAutoFindNeedsReset(); + + // 【新增】AUTO_FIND 恢复用的细粒度访问器 + // 原因:m_AutoFind / m_FindIntervalMs / m_LastFindTime / m_PendingCommand 都是 private, + // Publisher 主循环里的恢复块必须走这些 setter 才能编译通过。 + void SetAutoFind(bool on); + void SetFindIntervalMs(int interval_ms); + void SetLastFindTimeToNow(); + void ClearPendingCommand(); + + + // ========== 新增:写卡块重试配置 ========== + static constexpr uint8_t WRITE_BLOCK_MAX_RETRIES = 2; // 写卡失败最多重试 2 次 + static constexpr int WRITE_BLOCK_RETRY_DELAY_MS = 150; // 重试前等待 150ms(>MIFARE 写后忙窗口) + uint8_t m_WriteBlockRetryCount = 0; // 当前写块重试计数 + + void SendRfFeedFind(); // ★ 新增:RF 喂送专用寻卡(不动 m_PendingCommand) + +private: + bool TryExtractDeviceFrame(std::vector& data); + bool IsValidDeviceFrame(const std::vector& data); + bool RetryCurrentReadBlock(const char* reason); + bool RetryCurrentWriteBlock(const char* reason); + bool HasActiveDeviceOperation() const; + int HandleFindResponse(const std::vector& data, + WeighingSystem::ReadCardRsp& rsp); + static bool IsDataBlock(uint8_t block); + + bool m_AutoFind = false; + int m_FindIntervalMs = 500; + std::chrono::steady_clock::time_point m_LastFindTime; + std::string m_PreCard; + + // 【新增】保存 WaitForResponse 接收到的 ReadCard 响应数据 + std::vector m_LastReadCardRsp; + + //std::mutex mtx_; // 添加这行 - 保护串口访问 + mutable std::recursive_mutex mtx_; + std::vector m_ReceiveBuffer; + + + CardState m_CardState; // 当前状态 + unsigned long m_CurrentIndex; // 保存收到的 index + std::chrono::steady_clock::time_point m_StateEnterTime; // 状态进入时间 + static constexpr int DDS_TIMEOUT_MS = 20000; // DDS 命令 10 秒超时 + static constexpr int DDS_DECISION_TIMEOUT_MS = 20000; // WAIT_DDS_DECISION 超时 + static constexpr int DDS_WRITE_TIMEOUT_MS = 10000; // 写卡序列 10 秒超时 + static constexpr int CARD_READY_IDLE_TIMEOUT_MS = 20000; // 卡就绪无任务后恢复寻卡 + static constexpr int WRITE_BLOCK_OPERATION_TIMEOUT_MS = 5000; + + + // 读卡结果缓存 + uint8_t m_ResultCode; // 结果码 + std::string m_CardId; // 当前操作的卡号 + uint8_t m_BlockCount; // 当前读取的块数量 + std::vector>> m_BlockData; // 块数据 + std::vector m_RequestedBlocks; // 【新增】请求的块号列表 + uint8_t m_CurrentReadIndex = 0; // 【新增】当前正在读取的块索引 + + std::chrono::steady_clock::time_point m_ReadStartTime; + std::chrono::steady_clock::time_point m_ReadEndTime; + + // 写卡请求的 pending 信息(响应时用) + uint8_t m_PendingWriteBlock = 0; + std::vector m_PendingWriteValue; + std::string m_WriteCardId; + + + // ========== 单块操作超时控制 ========== + std::chrono::steady_clock::time_point m_BlockOpStartTime; // 当前块操作开始时间 + uint8_t m_CurrentOperatingBlock = 0; // 当前正在操作的块号 + bool m_BlockOperationPending = false; // 当前是否存在待读写响应 + PendingCommand m_PendingCommand = PendingCommand::None; + uint8_t m_PendingBlock = 0; + uint8_t m_ReadBlockRetryCount = 0; + uint64_t m_OperationSequence = 0; + std::vector m_PendingReadResponse; // 超时跳转时准备的响应 + std::vector m_SkippedBlocks; // 【新增】记录跳过的超时块号 + + // AUTO_FIND 状态下检测到 CRC/length 异常或超时后, + // 通知主循环走 ResetSerialAndReinit() 重置 RC522(与 WAIT_DDS_WRITE 超时恢复并联)。 + bool m_AutoFindNeedsReset = false; + + + uint8_t chCRCHTalbe[256] = { + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40 + }; + + uint8_t chCRCLTalbe[256] = { + 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, + 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, + 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, + 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, + 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3, + 0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, + 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, + 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, + 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, + 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26, + 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1, + 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, + 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, + 0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, + 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5, + 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0, + 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, + 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, + 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, + 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C, + 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, + 0x41, 0x81, 0x80, 0x40 + }; + + void CRC16(std::vector& data); +}; + +#endif diff --git a/readcard/Publisher.cxx b/readcard/Publisher.cxx new file mode 100644 index 0000000..6bad97f --- /dev/null +++ b/readcard/Publisher.cxx @@ -0,0 +1,606 @@ +#include "Publisher.hpp" + +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + + +#include +#include +#include +#include +//#include +#include +#include +#include +#include + +#include "WeighingDDSTypePubSubTypes.hpp" + +#include "msg.hpp" +#include "MsgHandler.hpp" +#include "DEBUG.hpp" + +using namespace eprosima::fastdds::dds; + +PublisherApp::PublisherApp( + const int& domain_id) + : factory_(nullptr) + , participant_(nullptr) + , publisher_(nullptr) + , topic_(nullptr) + , writer_(nullptr) + , type_(new WeighingSystem::ReadCardRspPubSubType()) + , matched_(0) + , samples_sent_(0) + , stop_(false) + , scale_type_(new WeighingSystem::ScaleInfoPubSubType()) + , summary_type_(new WeighingSystem::SummaryUpdatePubSubType()) + , infrared_subscriber_(nullptr) + , infrared_topic_(nullptr) + , infrared_reader_(nullptr) + , infrared_type_(new WeighingSystem::InfraredUpdatePubSubType()) + , summary_pending_(false) +{ + // Create the participant + DomainParticipantQos pqos = PARTICIPANT_QOS_DEFAULT; + pqos.name("ReadCard_pub_participant"); + pqos.wire_protocol().builtin.discovery_config.leaseDuration = Duration_t(60, 0); + pqos.wire_protocol().builtin.discovery_config.leaseDuration_announcementperiod = Duration_t(30, 0); + factory_ = DomainParticipantFactory::get_shared_instance(); + participant_ = factory_->create_participant(domain_id, pqos, nullptr, StatusMask::none()); + if (participant_ == nullptr) + { + throw std::runtime_error("InternalSystem::ReadCardRsp Participant initialization failed"); + } + + // Register the type + type_.register_type(participant_); + + // Create the publisher + PublisherQos pub_qos = PUBLISHER_QOS_DEFAULT; + participant_->get_default_publisher_qos(pub_qos); + publisher_ = participant_->create_publisher(pub_qos, nullptr, StatusMask::none()); + if (publisher_ == nullptr) + { + throw std::runtime_error("InternalSystem::ReadCardRsp Publisher initialization failed"); + } + + // Create the topic + TopicQos topic_qos = TOPIC_QOS_DEFAULT; + participant_->get_default_topic_qos(topic_qos); + topic_ = participant_->create_topic("ReadCardRsp", type_.get_type_name(), topic_qos); + if (topic_ == nullptr) + { + throw std::runtime_error("InternalSystem::ReadCardRsp Topic initialization failed"); + } + + // Create the data writer + DataWriterQos writer_qos = DATAWRITER_QOS_DEFAULT; + publisher_->get_default_datawriter_qos(writer_qos); + writer_qos.reliability().kind = ReliabilityQosPolicyKind::RELIABLE_RELIABILITY_QOS; + writer_qos.durability().kind = DurabilityQosPolicyKind::VOLATILE_DURABILITY_QOS; + writer_qos.history().kind = HistoryQosPolicyKind::KEEP_LAST_HISTORY_QOS; + writer_ = publisher_->create_datawriter(topic_, writer_qos, this, StatusMask::all()); + if (writer_ == nullptr) + { + throw std::runtime_error("InternalSystem::ReadCardRsp DataWriter initialization failed"); + } + + // ── 创建 ScaleInfo 订阅者 ── + scale_type_ = TypeSupport(new WeighingSystem::ScaleInfoPubSubType()); + scale_type_.register_type(participant_); + + SubscriberQos scale_sub_qos = SUBSCRIBER_QOS_DEFAULT; + participant_->get_default_subscriber_qos(scale_sub_qos); + scale_subscriber_ = participant_->create_subscriber(scale_sub_qos, nullptr, StatusMask::none()); + + TopicQos scale_topic_qos = TOPIC_QOS_DEFAULT; + participant_->get_default_topic_qos(scale_topic_qos); + scale_topic_ = participant_->create_topic("ScaleInfo", scale_type_.get_type_name(), scale_topic_qos); + + DataReaderQos scale_reader_qos = DATAREADER_QOS_DEFAULT; + scale_subscriber_->get_default_datareader_qos(scale_reader_qos); + scale_reader_qos.reliability().kind = RELIABLE_RELIABILITY_QOS; + scale_reader_qos.durability().kind = VOLATILE_DURABILITY_QOS; + scale_reader_ = scale_subscriber_->create_datareader( + scale_topic_, scale_reader_qos, this, StatusMask::all()); + + // ── 创建 SummaryUpdate 发布者 ── + summary_type_ = TypeSupport(new WeighingSystem::SummaryUpdatePubSubType()); + summary_type_.register_type(participant_); + + PublisherQos summary_pub_qos = PUBLISHER_QOS_DEFAULT; + participant_->get_default_publisher_qos(summary_pub_qos); + summary_publisher_ = participant_->create_publisher(summary_pub_qos, nullptr, StatusMask::none()); + + TopicQos summary_topic_qos = TOPIC_QOS_DEFAULT; + participant_->get_default_topic_qos(summary_topic_qos); + summary_topic_ = participant_->create_topic("SummaryUpdate", summary_type_.get_type_name(), summary_topic_qos); + + DataWriterQos summary_writer_qos = DATAWRITER_QOS_DEFAULT; + summary_publisher_->get_default_datawriter_qos(summary_writer_qos); + summary_writer_qos.reliability().kind = RELIABLE_RELIABILITY_QOS; + summary_writer_qos.durability().kind = VOLATILE_DURABILITY_QOS; + summary_writer_ = summary_publisher_->create_datawriter( + summary_topic_, summary_writer_qos, this, StatusMask::all()); + + + + // ── 创建 InfraredUpdate 订阅者 ── + infrared_type_ = TypeSupport(new WeighingSystem::InfraredUpdatePubSubType()); + infrared_type_.register_type(participant_); + + SubscriberQos ir_sub_qos = SUBSCRIBER_QOS_DEFAULT; + participant_->get_default_subscriber_qos(ir_sub_qos); + infrared_subscriber_ = participant_->create_subscriber(ir_sub_qos, nullptr, StatusMask::none()); + + TopicQos ir_topic_qos = TOPIC_QOS_DEFAULT; + participant_->get_default_topic_qos(ir_topic_qos); + infrared_topic_ = participant_->create_topic("InfraredUpdate", infrared_type_.get_type_name(), ir_topic_qos); + + DataReaderQos ir_reader_qos = DATAREADER_QOS_DEFAULT; + infrared_subscriber_->get_default_datareader_qos(ir_reader_qos); + ir_reader_qos.reliability().kind = RELIABLE_RELIABILITY_QOS; + ir_reader_qos.durability().kind = VOLATILE_DURABILITY_QOS; + infrared_reader_ = infrared_subscriber_->create_datareader( + infrared_topic_, ir_reader_qos, this, StatusMask::all()); + + // 缓存 topic 名(fastdds 的 DataReader 没有 get_topic) ← 新增 + { + std::lock_guard lk(reader_topic_mtx_); + scale_topic_name_ = scale_topic_->get_name(); + infrared_topic_name_ = infrared_topic_->get_name(); + } + +} + +PublisherApp::~PublisherApp() +{ + if (nullptr != participant_) + { + // Delete DDS entities contained within the DomainParticipant + participant_->delete_contained_entities(); + + // Delete DomainParticipant + factory_->delete_participant(participant_); + } +} + +void PublisherApp::on_publication_matched( + DataWriter* writer, + const PublicationMatchedStatus& info) +{ + if (info.current_count_change == 1) + { + { + std::lock_guard lock(mutex_); + matched_ = info.current_count; + } + DEBUG(writer->get_topic()->get_name() << " Publisher matched."); + cv_.notify_one(); + } + else if (info.current_count_change == -1) + { + { + std::lock_guard lock(mutex_); + matched_ = info.current_count; + } + DEBUG(writer->get_topic()->get_name() << " Publisher unmatched."); + } + else + { + DEBUG(info.current_count_change << " is not a valid value for PublicationMatchedStatus current count change"); + } +} + +// void PublisherApp::run(std::shared_ptr handler) +// { +// InternalSystem::ReadCardRsp rsp; + +// while (!is_stopped()) +// { +// if (handler->isOpen() == true) +// { +// if (handler->HandleDeviceMsg(rsp)) +// { +// writer_->write(&rsp); +// rsp.msg().clear(); +// } +// handler->AutoFindTick(); +// } + +// // Wait for period or stop event +// std::unique_lock period_lock(mutex_); +// cv_.wait_for(period_lock, std::chrono::milliseconds(period_ms_), [this]() +// { +// return is_stopped(); +// }); +// } +// } + +void PublisherApp::run(std::shared_ptr handler) +{ + WeighingSystem::ReadCardRsp rsp; + + while (!is_stopped()) + { + if (handler->isOpen() == true) + { + // ========== 新增:检查单块操作超时 ========== + // 修复:必须在 WAIT_DDS_READ 状态 且真的在读块过程中才允许超时跳过 + //原因:weight 判断阶段(m_CurrentReadIndex=0, m_RequestedBlocks 空)时不该触发 SkipCurrentBlock + if (handler->GetCardState() == CardState::WAIT_DDS_READ + && handler->IsBlockOperationPending() + && handler->GetBlockOpElapsed() >= MsgHandler::BLOCK_OPERATION_TIMEOUT_MS + && !handler->m_IsInTimeoutRecovery) // 【新增】不在恢复中才检查 + { + DEBUG("Block operation timeout elapsed_ms=" << handler->GetBlockOpElapsed() + << " limit_ms=" << MsgHandler::BLOCK_OPERATION_TIMEOUT_MS + << " block=" << static_cast(handler->GetCurrentOperatingBlock())); + handler->SkipCurrentBlock(); + } + + // 处理设备消息 + if (handler->HandleDeviceMsg(rsp)) + { + rsp.index(handler->GetCurrentIndex()); + // ★ 用 count() 判断,不走 operator[],不碰脏 rsp.msg() + if (rsp.msg().count("read") > 0) + { + DEBUG("Publishing DDS response: read success, index=" << rsp.index() + << ", msg keys=" << rsp.msg().size() + << ", read data size=" << rsp.msg()["read"].size()); + } + else if (rsp.msg().count("write") > 0) + { + DEBUG("Publishing DDS response: write success, index=" << rsp.index() + << ", msg keys=" << rsp.msg().size() + << ", write data size=" << rsp.msg()["write"].size()); + } + writer_->write(&rsp); + rsp.msg().clear(); + + + + } + + // ========== 新增:如果有待发送的读卡响应,立即发布 ========== + if (handler->HasPendingReadResponse()) + { + auto pendingRsp = handler->GetPendingReadResponse(); + if (!pendingRsp.empty()) + { + rsp.msg()["read"] = pendingRsp; + rsp.index(handler->GetCurrentIndex()); + DEBUG("Publishing pending read response (from timeout skip)"); + writer_->write(&rsp); + rsp.msg().clear(); + } + } + + // ========== 检查 DDS 超时 ========== + if (handler->CheckDdsTimeout()) + { + // 超时触发了状态切换,重新启动寻卡 + DEBUG("DDS timeout, auto-find restored"); + } + + // ========== 检查是否需要发布 SummaryUpdate ========== + CheckAndPublishSummary(handler); + + + // ========== 【新增】AUTO_FIND 异常重置 ========== + // 检测 TryExtractDeviceFrame / RecvMsg 置位的 m_AutoFindNeedsReset。 + // 和你 WAIT_DDS_WRITE 超时的恢复走同一个套路:清串口 + 重置 RC522 + 恢复 AUTO_FIND。 + if (handler->ConsumeAutoFindNeedsReset()) + { + DEBUG("AUTO_FIND recovery: invoking ResetSerialAndReinit due to CRC/timeout failure"); + handler->SetAutoFind(false); + handler->ClearPendingCommand(); + // 清串口残留帧(避免下个循环再拿到 5 字节尾巴) + // 注意:m_ReceiveBuffer 是 private,需要走 ClearReadBuffer() + handler->ClearReadBuffer(); + // tcflush 走 ResetSerialAndReinit 内部已经做了,这里不必再调 + if (handler->ResetSerialAndReinit()) + { + DEBUG("AUTO_FIND recovery: succeeded, resuming"); + + handler->SetAutoFind(true); + handler->SetFindIntervalMs(5000); + handler->SetLastFindTimeToNow(); + handler->SetCardState(CardState::AUTO_FIND); + } + else + { + DEBUG("AUTO_FIND recovery: failed, will retry on next loop"); + + handler->SetAutoFind(true); + handler->SetFindIntervalMs(5000); + handler->SetLastFindTimeToNow(); + handler->SetCardState(CardState::AUTO_FIND); + } + } + + + // 自动寻卡 + handler->AutoFindTick(); + } + + std::unique_lock period_lock(mutex_); + cv_.wait_for(period_lock, std::chrono::milliseconds(10), [this]() + { + return is_stopped(); + }); + } +} + +bool PublisherApp::is_stopped() +{ + return stop_.load(); +} + + +// void PublisherApp::on_data_available( +// DataReader* reader) +// { +// SampleInfo info; +// WeighingSystem::ScaleInfo sample; + +// while ((!is_stopped()) && (RETCODE_OK == reader->take_next_sample(&sample, &info))) +// { +// if (info.instance_state == ALIVE_INSTANCE_STATE && info.valid_data) +// { +// std::unique_lock lock(MsgData::queue_cv_mtx_); +// MsgData::ScaleInfo_queue_.push(std::move(sample)); +// lock.unlock(); +// } +// } +// } +void PublisherApp::on_data_available(DataReader* reader) +{ + SampleInfo info; + + std::string topic_name; + { + std::lock_guard lk(reader_topic_mtx_); + if (reader == scale_reader_) topic_name = scale_topic_name_; + else if (reader == infrared_reader_) topic_name = infrared_topic_name_; + } + + if (topic_name == "ScaleInfo") + { + WeighingSystem::ScaleInfo sample; + while ((!is_stopped()) && (RETCODE_OK == reader->take_next_sample(&sample, &info))) + { + if (info.instance_state == ALIVE_INSTANCE_STATE && info.valid_data) + { + std::unique_lock lock(MsgData::queue_cv_mtx_); + MsgData::ScaleInfo_queue_.push(std::move(sample)); + lock.unlock(); + } + } + } + else if (topic_name == "InfraredUpdate") + { + WeighingSystem::InfraredUpdate sample; + while ((!is_stopped()) && (RETCODE_OK == reader->take_next_sample(&sample, &info))) + { + if (info.instance_state == ALIVE_INSTANCE_STATE && info.valid_data) + { + std::lock_guard lock(MsgData::infrared_mtx_); + MsgData::front_blocked_ = sample.FrontResistanceSignal(); + MsgData::back_blocked_ = sample.BackResistanceSignal(); + MsgData::infrared_ready_ = true; + } + } + } +} + + + + +// void PublisherApp::on_subscription_matched( +// DataReader* reader, +// const SubscriptionMatchedStatus& info) +// { +// if (info.current_count_change == 1) +// { +// DEBUG(reader->get_topicdescription()->get_name() << " Subscriber matched."); +// } +// else if (info.current_count_change == -1) +// { +// DEBUG(reader->get_topicdescription()->get_name() << " Subscriber unmatched."); +// } +// } +void PublisherApp::on_subscription_matched(DataReader* reader, const SubscriptionMatchedStatus& info) +{ + std::string topic_name; + { + std::lock_guard lk(reader_topic_mtx_); + if (reader == scale_reader_) topic_name = scale_topic_name_; + else if (reader == infrared_reader_) topic_name = infrared_topic_name_; + } + + if (info.current_count_change == 1) + { + DEBUG(topic_name << " Subscriber matched."); + } + else if (info.current_count_change == -1) + { + DEBUG(topic_name << " Subscriber unmatched."); + } +} + + + + + +void PublisherApp::stop() +{ + stop_.store(true); + cv_.notify_one(); +} + + +bool PublisherApp::is_infrared_blocked() +{ + std::lock_guard lock(MsgData::infrared_mtx_); + + // 还没收到过红外消息 → 当作未遮挡(不阻塞发卡) + if (!MsgData::infrared_ready_) + { + return false; + } + + // 只检查前红外(0=无遮挡,1=有遮挡) + return MsgData::front_blocked_; +} + + +void PublisherApp::PublishSummaryUpdate(const std::string& cardId, float weightTon) +{ + std::lock_guard lock(summary_mtx_); + pending_card_id_ = cardId; + summary_pending_ = true; + + // 注意:实际发布需要在 run 循环中执行,以避免线程问题 + // 这里只设置标志 +} + +void PublisherApp::CheckAndPublishSummary(std::shared_ptr handler) +{ + std::lock_guard lock(summary_mtx_); + if (summary_pending_) + { + // 从 ScaleInfo 队列获取最后一帧的实时重量 + float weightTon = default_weight_; + float currentValue = default_weight_; + bool hasNewFrame = false; + + // 检查 ScaleInfo 队列是否有新数据 + { + std::lock_guard scale_lock(MsgData::queue_cv_mtx_); + + // 只取队列最后一帧(最新的一帧) + while (!MsgData::ScaleInfo_queue_.empty()) + { + WeighingSystem::ScaleInfo scaleInfo = std::move(MsgData::ScaleInfo_queue_.front()); + MsgData::ScaleInfo_queue_.pop(); + + currentValue = scaleInfo.Value(); + hasNewFrame = true; + + DEBUG("Queue check: Value=" << currentValue + << ", StableValue=" << scaleInfo.StableValue()); + } + + // 如果有新帧,添加到历史记录 + if (hasNewFrame) + { + recentValues_.push_back(currentValue); + + // 限制最多保留 MAX_RECENT_FRAMES_ 帧 + if (recentValues_.size() > MAX_RECENT_FRAMES_) + { + recentValues_.erase( + recentValues_.begin(), + recentValues_.end() - MAX_RECENT_FRAMES_ + ); + } + DEBUG("History updated: size=" << recentValues_.size() + << ", last=" << recentValues_.back()); + } + } + + // ===== 稳定判断:最近3帧都相同 ===== + has_weight_ = false; + if (recentValues_.size() >= 3) + { + // 取最后3帧 + float v0 = recentValues_[recentValues_.size() - 3]; + float v1 = recentValues_[recentValues_.size() - 2]; + float v2 = recentValues_[recentValues_.size() - 1]; + + // 判断最后3帧是否都相同(保留2位小数比较) + v0 = std::round(v0 * 100.0f) / 100.0f; + v1 = std::round(v1 * 100.0f) / 100.0f; + v2 = std::round(v2 * 100.0f) / 100.0f; + + if (v0 == v1 && v1 == v2) + { + has_weight_ = true; + weightTon = currentValue; + DEBUG("Weight stable: last 3 frames all same = " << weightTon + << " (frames: " << v0 << ", " << v1 << ", " << v2 << ")"); + } + else + { + DEBUG("Weight not stable yet: last 3 frames = " + << v0 << ", " << v1 << ", " << v2); + } + } + else + { + DEBUG("Collecting weight data... (" << recentValues_.size() << "/3 frames)"); + } + + // ===== 新增:必须获取到有效稳定重量才发布 ===== + if (!has_weight_) + { + DEBUG("Waiting for stable weight..."); + return; // 等待下次检查 + } + + // ===== 新增:红外对射必须无遮挡 ===== + if (is_infrared_blocked()) + { + DEBUG("Waiting for infrared unblocked (front_blocked_=" + << MsgData::front_blocked_ << ")"); + return; // 等待下次检查 + } + + WeighingSystem::SummaryUpdate update; + + std::string cardIdDecimal = pending_card_id_; + + // 保留2位小数 + weightTon = std::round(weightTon * 100.0f) / 100.0f; + + update.License(cardIdDecimal); + + //update.License(pending_card_id_); + update.StableValue(weightTon); + + // ===== 打印转换后的卡号用于调试 ===== + DEBUG("Card ID decimal: " << cardIdDecimal); + + summary_writer_->write(&update); + DEBUG("Published SummaryUpdate: License=" << pending_card_id_ + << ", StableValue=" << weightTon << "吨"); + + // ★ 新增:SummaryUpdate 发完后立刻停 RF-feed,避免后续 DDS 读写时 RF 干扰 + handler->SetAutoFind(false); // 关掉定时喂 RF + //handler_->StopCard(); // 主动给 RC522 发停卡命令(让 RC522 释放 Crypto1) + + summary_pending_ = false; + recentValues_.clear(); // 新增:清空历史帧,避免下一辆车使用上一辆车的数据 + } +} + +void PublisherApp::RestoreAutoFind() +{ + // 这个方法可以在写卡完成后调用,恢复自动寻卡 + DEBUG("Restoring auto-find mode"); +} diff --git a/readcard/Publisher.hpp b/readcard/Publisher.hpp new file mode 100644 index 0000000..22f1490 --- /dev/null +++ b/readcard/Publisher.hpp @@ -0,0 +1,122 @@ +#ifndef FAST_DDS_GENERATED__PUBLISHERAPP_HPP +#define FAST_DDS_GENERATED__PUBLISHERAPP_HPP + +#include +#include + +#include +#include +#include +#include +#include + +#include "MsgHandler.hpp" + +class PublisherApp : public eprosima::fastdds::dds::DataWriterListener,public eprosima::fastdds::dds::DataReaderListener +{ +public: + + PublisherApp( + const int& domain_id); + + ~PublisherApp(); + + //! Publisher matched method + void on_publication_matched( + eprosima::fastdds::dds::DataWriter* writer, + const eprosima::fastdds::dds::PublicationMatchedStatus& info) override; + + //! Run publisher + void run(std::shared_ptr handler); + + //! Trigger the end of execution + void stop(); + + void on_data_available(eprosima::fastdds::dds::DataReader* reader) override; + void on_subscription_matched(eprosima::fastdds::dds::DataReader* reader,const eprosima::fastdds::dds::SubscriptionMatchedStatus& info) override; + + void PublishSummaryUpdate(const std::string& cardId, float weightTon); + //void CheckAndPublishSummary(); + void CheckAndPublishSummary(std::shared_ptr handler); + void RestoreAutoFind(); + +private: + + //! Return the current state of execution + bool is_stopped(); + + bool is_infrared_blocked(); // ← 新增这一行 + bool has_pending_send(); // ← 新增这一行(可选,统一判断) + + std::shared_ptr factory_; + eprosima::fastdds::dds::DomainParticipant* participant_; + eprosima::fastdds::dds::Publisher* publisher_; + eprosima::fastdds::dds::Topic* topic_; + eprosima::fastdds::dds::DataWriter* writer_; + eprosima::fastdds::dds::TypeSupport type_; + std::condition_variable cv_; + int32_t matched_; + std::mutex mutex_; + const uint32_t period_ms_ = 100; + uint16_t samples_sent_; + std::atomic stop_; + + + // ── SummaryUpdate 发布者 ── + eprosima::fastdds::dds::Publisher* summary_publisher_; + eprosima::fastdds::dds::Topic* summary_topic_; + eprosima::fastdds::dds::DataWriter* summary_writer_; + eprosima::fastdds::dds::TypeSupport summary_type_; + + // ── ScaleInfo 订阅者 ── + eprosima::fastdds::dds::Subscriber* scale_subscriber_; + eprosima::fastdds::dds::Topic* scale_topic_; + eprosima::fastdds::dds::DataReader* scale_reader_; + eprosima::fastdds::dds::TypeSupport scale_type_; + + + // ── 新增:等待重量用的状态变量 ── + float stable_weight_ = 0.0f; + bool has_weight_ = false; + float default_weight_ = 0.0f; // 默认重量(当没有稳定重量时使用) + + + + // ── InfraredUpdate 订阅者 ── + eprosima::fastdds::dds::Subscriber* infrared_subscriber_; + eprosima::fastdds::dds::Topic* infrared_topic_; + eprosima::fastdds::dds::DataReader* infrared_reader_; + eprosima::fastdds::dds::TypeSupport infrared_type_; + + // ── 最新红外状态缓存 ── + bool front_blocked_ = false; // 前红外当前是否被遮挡 + bool back_blocked_ = false; // 后红外当前是否被遮挡 + std::mutex infrared_mtx_; + + + // ── 用于在 on_data_available 里区分 reader 的 topic ── ← 新增 + std::mutex reader_topic_mtx_; + std::string scale_topic_name_; + std::string infrared_topic_name_; + + + bool write_test_done_ = false; // 写卡测试是否完成 + bool write_test_started_ = false; // 是否已经开始写卡测试 + + bool write_read_pending_ = false; // 写入完成后,等待再次刷卡验证的标志 + + + // 新增:保留历史重量帧(跨循环累积) + std::vector recentValues_; + const size_t MAX_RECENT_FRAMES_ = 10; + + + // 用于 SummaryUpdate 发布 + bool summary_pending_; + std::string pending_card_id_; + std::mutex summary_mtx_; + std::condition_variable summary_cv_; + +}; + +#endif // FAST_DDS_GENERATED__PUBLISHERAPP_HPP diff --git a/readcard/Subscriber.cxx b/readcard/Subscriber.cxx new file mode 100644 index 0000000..c20db87 --- /dev/null +++ b/readcard/Subscriber.cxx @@ -0,0 +1,168 @@ +#include "Subscriber.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "WeighingDDSTypePubSubTypes.hpp" + +#include "msg.hpp" +#include "DEBUG.hpp" + +using namespace eprosima::fastdds::dds; + +SubscriberApp::SubscriberApp( + const int& domain_id) + : factory_(nullptr) + , participant_(nullptr) + , subscriber_(nullptr) + , topic_(nullptr) + , reader_(nullptr) + , type_(new WeighingSystem::ReadCardReqPubSubType()) + , samples_received_(0) + , stop_(false) +{ + // Create the participant + DomainParticipantQos pqos = PARTICIPANT_QOS_DEFAULT; + pqos.name("ReadCard_sub_participant"); + pqos.wire_protocol().builtin.discovery_config.leaseDuration = Duration_t(60, 0); + pqos.wire_protocol().builtin.discovery_config.leaseDuration_announcementperiod = Duration_t(30, 0); + factory_ = DomainParticipantFactory::get_shared_instance(); + participant_ = factory_->create_participant(domain_id, pqos, nullptr, StatusMask::none()); + if (participant_ == nullptr) + { + throw std::runtime_error("InternalSystem::ReadCardReq Participant initialization failed"); + } + + // Register the type + type_.register_type(participant_); + + // Create the subscriber + SubscriberQos sub_qos = SUBSCRIBER_QOS_DEFAULT; + participant_->get_default_subscriber_qos(sub_qos); + subscriber_ = participant_->create_subscriber(sub_qos, nullptr, StatusMask::none()); + if (subscriber_ == nullptr) + { + throw std::runtime_error("InternalSystem::ReadCardReq Subscriber initialization failed"); + } + + // Create the topic + TopicQos topic_qos = TOPIC_QOS_DEFAULT; + participant_->get_default_topic_qos(topic_qos); + topic_ = participant_->create_topic("ReadCardReq", type_.get_type_name(), topic_qos); + if (topic_ == nullptr) + { + throw std::runtime_error("InternalSystem::ReadCardReq Topic initialization failed"); + } + + // Create the reader + DataReaderQos reader_qos = DATAREADER_QOS_DEFAULT; + subscriber_->get_default_datareader_qos(reader_qos); + reader_qos.reliability().kind = ReliabilityQosPolicyKind::RELIABLE_RELIABILITY_QOS; + reader_qos.durability().kind = DurabilityQosPolicyKind::VOLATILE_DURABILITY_QOS; + reader_qos.history().kind = HistoryQosPolicyKind::KEEP_LAST_HISTORY_QOS; + reader_ = subscriber_->create_datareader(topic_, reader_qos, this, StatusMask::all()); + if (reader_ == nullptr) + { + throw std::runtime_error("InternalSystem::ReadCardReq DataReader initialization failed"); + } +} + +SubscriberApp::~SubscriberApp() +{ + if (nullptr != participant_) + { + // Delete DDS entities contained within the DomainParticipant + participant_->delete_contained_entities(); + + // Delete DomainParticipant + factory_->delete_participant(participant_); + } +} + +void SubscriberApp::on_subscription_matched( + DataReader* reader, + const SubscriptionMatchedStatus& info) +{ + if (info.current_count_change == 1) + { + DEBUG(reader->get_topicdescription()->get_name() << " Subscriber matched."); + } + else if (info.current_count_change == -1) + { + DEBUG(reader->get_topicdescription()->get_name() << " Subscriber unmatched."); + } + else + { + DEBUG(info.current_count_change << " is not a valid value for SubscriptionMatchedStatus current count change"); + } +} + +void SubscriberApp::on_data_available( + DataReader* reader) +{ + SampleInfo info; + std::string topic_name = reader->get_topicdescription()->get_name(); + DEBUG(topic_name << " Topic receviced."); + + if (topic_name == "ReadCardReq") + { + WeighingSystem::ReadCardReq sample_; + while ((!is_stopped()) && (RETCODE_OK == reader->take_next_sample(&sample_, &info))) + { + if ((info.instance_state == ALIVE_INSTANCE_STATE) && info.valid_data) + { + { + std::unique_lock lock(MsgData::queue_cv_mtx_); + MsgData::ReadCardReq_queue_.push(std::move(sample_)); + lock.unlock(); + } + } + } + } +} + +void SubscriberApp::run(std::shared_ptr handler) +{ + while (!is_stopped()) + { + std::unique_lock lock(MsgData::queue_cv_mtx_, std::try_to_lock); + if (lock.owns_lock()) + { + if (!MsgData::ReadCardReq_queue_.empty()) + { + WeighingSystem::ReadCardReq req = std::move(MsgData::ReadCardReq_queue_.front()); + MsgData::ReadCardReq_queue_.pop(); + lock.unlock(); + handler->HandleDdsMsg(req.msg(), req.index()); + } + else + { + lock.unlock(); + } + } + + { + std::unique_lock period_lock(terminate_cv_mtx_); + terminate_cv_.wait_for(period_lock, std::chrono::milliseconds(period_ms_), [this](){return is_stopped();}); + } + } +} + +bool SubscriberApp::is_stopped() +{ + return stop_.load(); +} + +void SubscriberApp::stop() +{ + stop_.store(true); + terminate_cv_.notify_all(); +} diff --git a/readcard/Subscriber.hpp b/readcard/Subscriber.hpp new file mode 100644 index 0000000..8aa7fe8 --- /dev/null +++ b/readcard/Subscriber.hpp @@ -0,0 +1,56 @@ +#ifndef FAST_DDS_GENERATED__SUBSCRIBERAPP_HPP +#define FAST_DDS_GENERATED__SUBSCRIBERAPP_HPP + +#include + +#include +#include +#include +#include + +#include "WeighingDDSType.hpp" +#include "MsgHandler.hpp" + +class SubscriberApp : public eprosima::fastdds::dds::DataReaderListener +{ +public: + + SubscriberApp( + const int& domain_id); + + virtual ~SubscriberApp(); + + //! Subscription callback + void on_data_available( + eprosima::fastdds::dds::DataReader* reader) override; + + //! Subscriber matched method + void on_subscription_matched( + eprosima::fastdds::dds::DataReader* reader, + const eprosima::fastdds::dds::SubscriptionMatchedStatus& info) override; + + //! Run subscriber + void run(std::shared_ptr handler); + + //! Trigger the end of execution + void stop(); + +private: + + //! Return the current state of execution + bool is_stopped(); + + std::shared_ptr factory_; + eprosima::fastdds::dds::DomainParticipant* participant_; + eprosima::fastdds::dds::Subscriber* subscriber_; + eprosima::fastdds::dds::Topic* topic_; + eprosima::fastdds::dds::DataReader* reader_; + eprosima::fastdds::dds::TypeSupport type_; + uint16_t samples_received_; + std::atomic stop_; + uint32_t period_ms_ = 100; + mutable std::mutex terminate_cv_mtx_; + std::condition_variable terminate_cv_; +}; + +#endif // FAST_DDS_GENERATED__SUBSCRIBERAPP_HPP diff --git a/readcard/main.cxx b/readcard/main.cxx new file mode 100644 index 0000000..413f9ea --- /dev/null +++ b/readcard/main.cxx @@ -0,0 +1,197 @@ +#include +#include +#include +#include +#include +#include + +#include + +#include "Subscriber.hpp" +#include "Publisher.hpp" +#include "SerialMsgHandler.hpp" +#include "msg.hpp" +#include "DEBUG.hpp" + +using eprosima::fastdds::dds::Log; + +std::function stop_handler; +void signal_handler( + int signum) +{ + stop_handler(signum); +} + +std::string parse_signal( + const int& signum) +{ + switch (signum) + { + case SIGINT: + return "SIGINT"; + case SIGTERM: + return "SIGTERM"; +#ifndef _WIN32 + case SIGQUIT: + return "SIGQUIT"; + case SIGHUP: + return "SIGHUP"; +#endif // _WIN32 + default: + return "UNKNOWN SIGNAL"; + } +} + +std::queue MsgData::ReadCardReq_queue_; +std::mutex MsgData::queue_cv_mtx_; + +std::queue MsgData::ScaleInfo_queue_; +std::queue MsgData::InfraredUpdate_queue_; + +std::mutex MsgData::infrared_mtx_; +bool MsgData::front_blocked_ = false; +bool MsgData::back_blocked_ = false; +bool MsgData::infrared_ready_ = false; + +int main(int argc, char** argv) +{ + auto ret = EXIT_SUCCESS; + std::shared_ptr sub; + std::shared_ptr pub; + std::shared_ptr dev; + + int domain_id = 0; + const char* interface = "serial"; + const char* port = "ttyS1"; + const char* baudrate = "9600"; + const char* device = "RC522"; + + + + // std::map> password = { + // {0, {0x41, 0x55, 0x53, 0x45, 0x46, 0x54}}, // AUSEFT + // {1, {0x41, 0x55, 0x53, 0x45, 0x46, 0x54}}, + // {2, {0x41, 0x55, 0x53, 0x45, 0x46, 0x54}}, + // {3, {0x41, 0x55, 0x53, 0x45, 0x46, 0x54}}, + // {4, {0x41, 0x55, 0x53, 0x45, 0x46, 0x54}}, + // {5, {0x41, 0x55, 0x53, 0x45, 0x46, 0x54}}, + // {6, {0x41, 0x55, 0x53, 0x45, 0x46, 0x54}}, + // {10, {0x41, 0x55, 0x53, 0x45, 0x46, 0x54}}, + // }; + + std::map> password = { + {0, {0x42, 0x37, 0x4D, 0x4C, 0x35, 0x46}}, // B7ML5F + {1, {0x42, 0x37, 0x4D, 0x4C, 0x35, 0x46}}, + {2, {0x42, 0x37, 0x4D, 0x4C, 0x35, 0x46}}, + {3, {0x42, 0x37, 0x4D, 0x4C, 0x35, 0x46}}, + {4, {0x42, 0x37, 0x4D, 0x4C, 0x35, 0x46}}, + {5, {0x42, 0x37, 0x4D, 0x4C, 0x35, 0x46}}, + //{6, {0x42, 0x37, 0x4D, 0x4C, 0x35, 0x46}}, + {6, {0xB1, 0x0A, 0x23, 0xD1, 0x8F, 0x20}}, // B10A23D18F20 + {10, {0x42, 0x37, 0x4D, 0x4C, 0x35, 0x46}}, + }; + + + for (int i = 1; i < argc; i++) + { + if (strcmp(argv[i], "--domain") == 0 && i + 1 < argc) + { + domain_id = atoi(argv[++i]); + } + else if (strcmp(argv[i], "--interface") == 0 && i + 1 < argc) + { + interface = argv[++i]; + } + else if (strcmp(argv[i], "--port") == 0 && i + 1 < argc) + { + port = argv[++i]; + } + else if (strcmp(argv[i], "--baudrate") == 0 && i + 1 < argc) + { + baudrate = argv[++i]; + } + else if (strcmp(argv[i], "--device") == 0 && i + 1 < argc) + { + device = argv[++i]; + } + else if (strcmp(argv[i], "--version") == 0) + { + std::cout << "Vesrion: " << PROGRAM_VERSION << "\n"; + return EXIT_SUCCESS; + } + else if (strcmp(argv[i], "--help") == 0) + { + std::cout << "Usage: [options]\n" + << "Options:\n" + << " --domain Set domain ID\n" + << " --interface Set interface (e.g., serial)\n" + << " --baudrate Set baudrate (e.g., 9600)\n" + << " --port Set port name (e.g., ttyS1)\n" + << " --device Set device name (e.g., RC522)\n" + << " --version Show software Version\n" + << " --help Show this help message\n"; + return EXIT_SUCCESS; + } + else + { + std::cerr << "Unknown option: " << argv[i] << "\n"; + std::cout << "Usage: [options]\n" + << "Options:\n" + << " --domain Set domain ID\n" + << " --interface Set interface (e.g., serial)\n" + << " --baudrate Set baudrate (e.g., 9600)\n" + << " --port Set port name (e.g., ttyS1)\n" + << " --device Set device name (e.g., RC522)\n" + << " --version Show software Version\n" + << " --help Show this help message\n"; + return EXIT_FAILURE; + } + } + + sub = std::make_shared(domain_id); + pub = std::make_shared(domain_id); + dev = std::make_shared(); + + dev->OpenPort(port, baudrate); + dev->SetDevice(device); + dev->StorePasswd(password); + + // ========== 新增:保存端口名,供 SkipCurrentBlock 使用 ========== + dev->m_Port = port; + + // ========== 设置卡检测回调,触发 SummaryUpdate 发布 ========== + dev->OnCardDetected = [pub](const std::string& cardId) { + pub->PublishSummaryUpdate(cardId, 0.0f); // StableValue 暂时用 0.0f,后续从称重系统获取 + }; + + if (!dev->InitSequence()) + { + DEBUG("Device initialization failed, exiting."); + return EXIT_FAILURE; + } + + std::thread sub_thread(&SubscriberApp::run, sub, dev); + std::thread pub_thread(&PublisherApp::run, pub, dev); + + DEBUG("Program is running. Please press Ctrl+C to stop at any time."); + + stop_handler = [&](int signum) + { + std::cout << "\n" << parse_signal(signum) << " received, stopping execution." << std::endl; + sub->stop(); + pub->stop(); + }; + + signal(SIGINT, signal_handler); + signal(SIGTERM, signal_handler); +#ifndef _WIN32 + signal(SIGQUIT, signal_handler); + signal(SIGHUP, signal_handler); +#endif // _WIN32 + + sub_thread.join(); + pub_thread.join(); + + Log::Reset(); + return ret; +} diff --git a/readcard/msg.hpp b/readcard/msg.hpp new file mode 100644 index 0000000..4177eef --- /dev/null +++ b/readcard/msg.hpp @@ -0,0 +1,25 @@ +#ifndef _MSG_HPP_ +#define _MSG_HPP_ + +#include +#include +#include "WeighingDDSType.hpp" + +class MsgData { +public: + static std::queue ReadCardReq_queue_; + static std::mutex queue_cv_mtx_; + + static std::queue ScaleInfo_queue_; + + + static std::queue InfraredUpdate_queue_; + + // 最新一帧红外状态缓存 + static std::mutex infrared_mtx_; + static bool front_blocked_; + static bool back_blocked_; + static bool infrared_ready_; +}; + +#endif diff --git a/readcard/readcard.md b/readcard/readcard.md new file mode 100644 index 0000000..9598ab4 --- /dev/null +++ b/readcard/readcard.md @@ -0,0 +1,121 @@ +# ReadCard 程序流程文档 + +## 启动流程 + +``` +main() + │ + ├─ OpenPort(port, baudrate) 打开串口 + ├─ SetDevice(device) 设置设备名 + ├─ StorePasswd(password) 存储扇区密码表 + │ + ├─ InitSequence() 初始化序列(同步阻塞) + │ ├─ StopCard() → 等待应答 (3s超时) + │ ├─ SetPasswd(1) → 等待应答 + │ ├─ SetPasswd(2) → 等待应答 + │ ├─ SetPasswd(3) → 等待应答 + │ ├─ SetPasswd(4) → 等待应答 + │ ├─ SetPasswd(5) → 等待应答 + │ ├─ SetPasswd(10) → 等待应答 + │ └─ FindCard() 发出首次寻卡, AutoFind=true + │ (任一步失败 → 程序退出) + │ + ├─ 启动 sub_thread DDS命令接收线程 + └─ 启动 pub_thread 设备响应发布线程 +``` + +## 运行时两个线程 + +``` +sub_thread (DDS命令接收) pub_thread (设备响应发布, 100ms周期) + │ │ + │ 收到 ReadCardReq │ HandleDeviceMsg() + │ → HandleDdsMsg() │ → RecvDeviceMsg() 读串口 + │ │ → ParseDeviceMsg() 解析响应 + │ │ → 有数据则 writer_->write() 发布DDS + │ │ + │ │ AutoFindTick() + │ │ → AutoFind开启时按间隔发FindCard +``` + +## DDS 对外接口 + +### 订阅 Topic: `ReadCardReq` + +| 命令 | 参数 | 行为 | +|------|------|------| +| `"find"` | 无 | 清空重复卡记录,启动自动寻卡 | +| `"read"` | `{扇区号}` | 暂停自动寻卡,读指定扇区 | +| `"write"` | `{扇区号, 数据...}` | 暂停自动寻卡,写指定扇区 | +| `"stop"` | 无 | 停止自动寻卡 | +| `"beep"` | `{时长}` 或空 | 暂停自动寻卡,蜂鸣(默认0x0F) | +| `"reset"` | 无 | 暂停自动寻卡,清空串口缓冲区 | + +### 发布 Topic: `ReadCardRsp` + +| 响应 | 内容 | 说明 | +|------|------|------| +| `"find"` | 成功:`{卡号4字节}` 失败:`{错误码}` | 寻卡结果 | +| `"read"` | 成功:`{数据17字节}` 失败:`{错误码}` | 读卡结果 | +| `"write"` | `{状态码}` | 写卡结果 | +| `"stop"` | `{状态码}` | 停止结果 | +| `"beep"` | `{状态码}` | 蜂鸣结果 | + +## 自动寻卡状态机 + +``` + ┌──────────────────────────┐ + │ AutoFind = true │ + │ (自动寻卡运行中) │ + │ │ + │ AutoFindTick按间隔 │ + │ 发送FindCard │ + └──┬────────┬───────────┬──┘ + │ │ │ + 寻卡失败 │ 寻卡成功(新卡)│ 寻卡成功(重复卡) + interval=500ms│ AutoFind=false│ interval=5000ms + 继续重试 │ 发布卡号 │ 不发布,继续寻卡 + │ │ │ + │ ▼ │ + │ ┌────────────┐ │ + │ │AutoFind=false│ │ + │ │(等待业务处理)│ │ + │ └──┬─────┬───┘ │ + │ │ │ │ + │ DDS下发 DDS下发 │ + │ read write │ + │ │ │ │ + │ ▼ ▼ │ + │ 设备响应返回 │ + │ AutoFind=true │ + │ interval=500ms │ + │ │ │ + └──────┘──────────────┘ + (回到自动寻卡状态) + + 特殊命令: + "stop" → AutoFind=false, 完全停止寻卡 + "find" → AutoFind=true, 清空PreCard, 重新开始寻卡 + "beep"/"reset" → AutoFind=false, 暂停寻卡(需DDS重发find恢复) +``` + +## 定时间隔策略 + +| 时机 | 间隔 | 说明 | +|------|------|------| +| 发送FindCard后 | 5000ms | 超时保护,无应答则重发 | +| 寻卡失败 | 500ms | 快速重试 | +| 重复刷卡 | 5000ms | 同一张卡不重复处理 | +| 读写完成恢复 | 500ms | 业务结束后快速恢复寻卡 | + +## 启动参数 + +| 参数 | 默认值 | 说明 | +|------|--------|------| +| `--domain` | 0 | DDS域ID | +| `--interface` | serial | 接口类型 | +| `--port` | ttyS1 | 串口端口 | +| `--baudrate` | 9600 | 波特率 | +| `--device` | RC522 | 设备名称 | +| `--version` | - | 显示版本号 | +| `--help` | - | 显示帮助信息 | diff --git a/readme.txt b/readme.txt new file mode 100644 index 0000000..745b4cb --- /dev/null +++ b/readme.txt @@ -0,0 +1,51 @@ +./Weigh --port ttyS5 --device Keli +./Print --port ttyS2 --device NP80A +./Core --addr mqtt://192.168.1.1:1883 + + + +./Weigh --port ttyS3 --device Keli +./Print --port ttyS2 --device NP80A +./Core --addr mqtt://10.180.4.101:1883 + + +./print-test publisher + +{ + "bar_ctrl": + { + "FrontBar": "down", + "BackBar": "down" + } +} + +{ + "light_ctrl": + { + "FrontLED": "red", + "BackLED": "red" + } +} + + +ScaleInfo VOLATILE_DURABILITY_QOS +ScaleCommand VOLATILE_DURABILITY_QOS +WeightInfoOk VOLATILE_DURABILITY_QOS +WeightInfoError VOLATILE_DURABILITY_QOS +BarCommandUpdate VOLATILE_DURABILITY_QOS +LightsCommandUpdate VOLATILE_DURABILITY_QOS +InfraredCommandUpdate VOLATILE_DURABILITY_QOS +BarUpdate TRANSIENT_LOCAL_DURABILITY_QOS +LightsUpdate TRANSIENT_LOCAL_DURABILITY_QOS +InfraredUpdate TRANSIENT_LOCAL_DURABILITY_QOS +LicenseSnapUpdate VOLATILE_DURABILITY_QOS +Voice VOLATILE_DURABILITY_QOS +SummaryUpdate VOLATILE_DURABILITY_QOS + + + +./Core --domain 12 & +./GateCtrl --domain 12 & +./HttpServer --domain 12 --port 8081 & +./Print --domain 12 --port ttyS2 & +./Weigh --domain 12 --port ttyS3 & diff --git a/weigh/MsgHandler.cxx b/weigh/MsgHandler.cxx index cf0136c..5c05b52 100644 --- a/weigh/MsgHandler.cxx +++ b/weigh/MsgHandler.cxx @@ -127,7 +127,10 @@ int MsgHandler::RecvMsg(std::vector& data, int timeoutMs) } // 有数据可读 - uint8_t bytes; + //uint8_t bytes; + int bytes; + + if (ioctl(fd, FIONREAD, &bytes) < 0) { perror("ioctl FIONREAD失败"); @@ -141,6 +144,9 @@ int MsgHandler::RecvMsg(std::vector& data, int timeoutMs) return -1; } + data.resize(bytesRead); // 调整 data 大小为实际读取的字节数 + + return bytesRead; } @@ -171,7 +177,8 @@ bool MsgHandler::get_frame(std::vector& frame, uint8_t frame_size, uint } // 检查是否有足够的数据(至少一个完整帧) - if (m_WeightData.size() >= 12) + //if (m_WeightData.size() >= 12) + if (m_WeightData.size() >= frame_size) { // 检查结束字节 if (m_WeightData[frame_size - 1] == end) @@ -490,13 +497,44 @@ bool MsgHandler::get_weight_2(float& weight, std::vector& frame) } } - int decimalPos = frame[1]&0x07 - 2; - if (decimalPos < 0) + // ========== 新增:调试打印 weightDigits ========== + //std::cout << "[DEBUG] weightDigits='" << weightDigits << "' (len=" << weightDigits.size() << ")" << std::endl; + + + + // int decimalPos = frame[1]&0x07 - 2; + // if (decimalPos < 0) + // { + // decimalPos = 0; + // } + + // 判断是否为国产仿制协议: + // 特征:frame[1] == '1' 且 frame[2] == '0'(固定标识"10") + // 这种情况下没有小数点指示,整数就是 kg + int decimalPos = 0; + bool is_domestic_clone = (frame[1] == '1' && frame[2] == '0'); + if (!is_domestic_clone) { - decimalPos = 0; + // 标准 Toledo:按字节 [1] 的 ASCII 数字解析小数位数 + if (frame[1] >= '0' && frame[1] <= '4') + { + decimalPos = frame[1] - '0'; + } } + // 否则 decimalPos = 0(国产仿制视为整数) + // 防止 divisors 数组越界 + if (decimalPos < 0) decimalPos = 0; + if (decimalPos > 5) decimalPos = 5; + // ================================= + raw_value = std::stof(weightDigits); + + // ========== 新增:调试打印 raw_value ========== + //std::cout << "[DEBUG] raw_value=" << raw_value << " decimalPos=" << decimalPos << std::endl; + + + weight = raw_value / divisors[decimalPos]; if (frame[2] & 0x02) @@ -504,6 +542,9 @@ bool MsgHandler::get_weight_2(float& weight, std::vector& frame) weight = 0 - weight; } + + + return true; } @@ -515,6 +556,26 @@ bool MsgHandler::HandleDeviceMsg(T& msg) if (RecvDeviceMsg(m_Data, 100) > 0) { + + // 清空累积,避免错位数据影响 + m_WeightData.clear(); + + // ========== 新增:每次读取前重新配置串口 ========== + // SerialMsgHandler* serial = dynamic_cast(this); + // if (serial != nullptr) { + // serial->refreshPort(); + // } + + // ========== 新增:调试打印原始数据 ========== + // std::cout << "[DEBUG] Recv bytes: " << m_Data.size() << " Data: "; + // for (size_t i = 0; i < m_Data.size() && i < 32; i++) { + // std::cout << std::hex << std::setw(2) << std::setfill('0') << (int)m_Data[i] << " "; + // } + // std::cout << std::dec << std::endl; + // ========================================== + + + m_WeightData.insert(m_WeightData.end(), m_Data.begin(), m_Data.end()); } @@ -531,6 +592,14 @@ bool MsgHandler::HandleDeviceMsg(T& msg) { if (get_frame(frame, 17, STX, CR) == true) { + + // ========== 新增:调试打印 frame 内容 ========== + // std::cout << "[DEBUG] Frame extracted: "; + // for (size_t i = 0; i < frame.size(); i++) { + // std::cout << std::hex << std::setw(2) << std::setfill('0') << (int)frame[i] << " "; + // } + // std::cout << std::dec << " (size=" << frame.size() << ")" << std::endl; + return get_weight_2(msg, frame); } } diff --git a/weigh/Publisher.cxx b/weigh/Publisher.cxx index a138c50..bacb8fa 100644 --- a/weigh/Publisher.cxx +++ b/weigh/Publisher.cxx @@ -214,6 +214,11 @@ void PublisherApp::run(std::shared_ptr handler) if (handler->HandleDeviceMsg(weight) == true) { bool success = detector.processWeight(weight); + + // ========== 调试打印1:串口收到数据 ========== + //std::cout << "[DEBUG] Recv from ttyS3, weight=" << weight << std::endl; + + if (!success) { std::cout << "Failed to process weight!" << std::endl; @@ -253,18 +258,24 @@ void PublisherApp::run(std::shared_ptr handler) if (detector.isStable()) { info.WeightOK() = true; - info.Value() = weight; - info.StableValue() = weight; + info.Value() = weight / 1000.0f; + info.StableValue() = weight / 1000.0f; } else { info.WeightOK() = false; - info.Value() = weight; + info.Value() = weight / 1000.0f; info.StableValue() = 0; } if (send_time >= 50) { + + // ========== 调试打印2:DDS发布前 ========== + // std::cout << "[DEBUG] DDS Publish: Value=" << info.Value() + // << " StableValue=" << info.StableValue() + // << " HasVehicle=" << info.HasVehicle() << std::endl; + writer_->write(&info); send_time = 0; } @@ -276,6 +287,14 @@ void PublisherApp::run(std::shared_ptr handler) send_time = 50; } + + // ========== 调试打印3:主循环心跳 ========== + // static int heartbeat = 0; + // heartbeat++; + // if (heartbeat % 100 == 0) { + // std::cout << "[DEBUG] Main loop alive, heartbeat=" << heartbeat << std::endl; + // } + // Wait for period or stop event std::unique_lock period_lock(mutex_); cv_.wait_for(period_lock, std::chrono::milliseconds(period_ms_), [this]() diff --git a/yuqian.jpg b/yuqian.jpg new file mode 100644 index 0000000..bfbc3bf Binary files /dev/null and b/yuqian.jpg differ