半导体:Gem/Secs基本协议库的开发(5)

2023-12-16 17:36

本文主要是介绍半导体:Gem/Secs基本协议库的开发(5),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

此篇是1-4 《半导体》的会和处啦,我们有了协议库,也有了通讯库,这不得快乐的玩一把~

一、先创建一个从站,也就是我们的Equipment端

QT -= guiCONFIG += c++11 console
CONFIG -= app_bundle
CONFIG += no_debug_release         # 不会生成debug 和 release 文件目录DESTDIR = $${PWD}/../../deploy/bin
OBJECTS_DIR = $${PWD}/../../build/sample/Equipment/tmp/obj
MOC_DIR = $${PWD}/../../build/sample/Equipment/tmp/obj
UI_DIR = $${PWD}/../../build/sample/Equipment/tmp/obj# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0SOURCES += \main.cpp# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += targetwin32:CONFIG(release, debug|release){win32: LIBS += -L$$PWD/../../deploy/lib/Release -lJC_Commucationwin32: LIBS += -L$$PWD/../../deploy/lib/Release -lJcHsms
}
else:win32:CONFIG(debug, debug|release){win32: LIBS += -L$$PWD/../../deploy/lib/Debug -lJC_Commucationwin32: LIBS += -L$$PWD/../../deploy/lib/Debug -lJcHsms
}INCLUDEPATH += $$PWD/../../deploy/include
DEPENDPATH += $$PWD/../../deploy/include
#include <QCoreApplication>
#include <QDebug>
#include <iostream>
#include <QByteArray>
#include <string>
#include <QTimer>
using namespace std;#include "../../SemiGeneralStandardLibrary/JcGemSecsLibrary/Commucation/commucation.h"
#include "../../SemiGeneralStandardLibrary/JcGemSecsLibrary/Driver/JcHsms/hsmsincludes.h"/*** @brief OnStateChanged 连接状态改变回调事件* @param pComm* @param nState        0: 连接  1:断开连接* @param cSocket*/
void OnStateChanged(ICommucation* pComm, __int32 nState, void *cSocket)
{SOCKET* c = (SOCKET*) cSocket;std::string str = nState == 0 ? std::string("  connected to ") : std::string("  disconnected from ");std::cout << "[OnStateChanged Event] : " << c <<  str << (void*)pComm << std::endl;
}/// 无符号字节数组转16进制字符串
std::string bytesToHexString(const char* bytes,const int length)
{if (bytes == NULL) return "";std::string buff;const int len = length;for (int j = 0; j < len; j++) {int high = bytes[j]/16, low = bytes[j]%16;buff += (high<10) ? ('0' + high) : ('a' + high - 10);buff += (low<10) ? ('0' + low) : ('a' + low - 10);buff += " ";}return buff;
}/*!* \brief onMessageRecived  接收到消息的回调事件* \param pComm* \param recvedMsg* \param cSocket*/
void onMessageRecived(ICommucation* pComm,  char* message,int iRecvSize, void * cSocket)
{JcHsms ho(0,QString("JC Gem/Secs Test"),QString("1.0.1"));HsmsMessage hmsg = ho.interpretMessage(QByteArray(message,iRecvSize));HsmsMessage rsp = hmsg.dispatch();QByteArray responseByteArray = rsp.toByteArray();QString smlString = rsp.SmlString();string rHexString = bytesToHexString(message,iRecvSize);// qDebug().noquote() << "recv message ==> " << QString::fromStdString(rHexString);// qDebug().noquote() << "send message ==> " << responseByteArray.toHex(' ');qDebug().noquote() << QString("RECV S%1F%2 SystemBytes=%3").arg(QString::number((int)hmsg.GetHeader().Getstream()),QString::number((int)hmsg.GetHeader().Getfunction()),QString::number(hmsg.GetHeader().GetSystemBytes()));qDebug().noquote() << hmsg.SmlString();qDebug().noquote() << QString("SEND S%1F%2 SystemBytes=%3").arg(QString::number((int)rsp.GetHeader().Getstream()),QString::number((int)rsp.GetHeader().Getfunction()),QString::number( rsp.GetHeader().GetSystemBytes()));qDebug().noquote() << rsp.SmlString();int slen = responseByteArray.length();if(slen){int rslen = pComm->SendData(*((SOCKET*) cSocket),responseByteArray.data(),responseByteArray.length());if(rslen <= 0) {qDebug() << "Send Reply Message failed.";}}}/*!* \brief OnAsyncMsgTimeout  消息超时* \param pComm* \param nTransfer          消息ID* \param pClientData*/
void OnAsyncMsgTimeout(ICommucation* pComm, __int32 nTransfer, void *pClientData)
{}int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);const char* comm_dll_version = JC_CommDllVersion();qDebug() << comm_dll_version;/// [1] 建立通讯连接(以单个通讯连接对象为例)CommucationParam setting;EthernetCommucationParam eParam = {45000,10000,5000,10000,5000,  /* timeout */0                             /* PASSIVE */,5555,                         /*  port  */1                             /* DEVID */,"Device Host","127.0.0.1"};SerialCommucationParam sParam = {2,9600,'N',8,1};setting.eParam = eParam;setting.sParam = sParam;/// 创建通讯对象ICommucation* o = NULL;o = JC_CreatCommObject(TcpServer,setting);/// 为通讯连接对象注册事件回调JC_SetEventCallBack(o,onMessageRecived,OnStateChanged,OnAsyncMsgTimeout);/// 启动监听JC_RunListenThread(o);/// 测试修改 Selected Equipment Status Data(SSD),线程安全float x[] = {12.3025,55.12,56.478,63.54};QTimer timer;timer.setInterval(300);QObject::connect(&timer,&QTimer::timeout,[&x](){static int i = 0;HsmsDataManager::Instance().UpdateSsdMap(1022,HsmsDataManager::ESD{F4,QVariant(x[++i%4])});});timer.start();QObject::connect(qApp,&QCoreApplication::aboutToQuit,[&o](){/// 释放通讯连接对象,结束通讯连接JC_ReleaseCommObject(o);});return a.exec();
}

二、创建一个主站,也就是我们的Host端

QT       += core gui networkgreaterThan(QT_MAJOR_VERSION, 4): QT += widgetsCONFIG += c++11DESTDIR = $${PWD}/../../deploy/bin
OBJECTS_DIR = $${PWD}/../../build/sample/Host/tmp/obj
MOC_DIR = $${PWD}/../../build/sample/Host/tmp/obj
UI_DIR = $${PWD}/../../build/sample/Host/tmp/obj# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0SOURCES += \main.cpp \mcwidget.cppHEADERS += \mcwidget.h# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += targetwin32:CONFIG(release, debug|release){win32: LIBS += -L$$PWD/../../deploy/lib/Release -lJC_Commucationwin32: LIBS += -L$$PWD/../../deploy/lib/Release -lJcHsms
}
else:win32:CONFIG(debug, debug|release){win32: LIBS += -L$$PWD/../../deploy/lib/Debug -lJC_Commucationwin32: LIBS += -L$$PWD/../../deploy/lib/Debug -lJcHsms
}INCLUDEPATH += $$PWD/../../deploy/include
DEPENDPATH += $$PWD/../../deploy/include
// mcwidget.h
#ifndef MCWIDGET_H
#define MCWIDGET_H#include <QWidget>
#include <QTcpServer>
#include <QLabel>
#include <QHBoxLayout>
#include <QTimer>
#include <iostream>
#include <QDebug>
#include <string>
#include <QByteArray>
#include <QList>
#include "../../SemiGeneralStandardLibrary/JcGemSecsLibrary/Commucation/commucation.h"
#include  "../../SemiGeneralStandardLibrary/JcGemSecsLibrary/Driver/JcHsms/hsmsincludes.h"class TransHelper: public QObject
{Q_OBJECT
public:TransHelper(){qRegisterMetaType<HsmsMessage>("qRegisterMetaType");//qRegisterMetaType<HsmsMessage>("qRegisterMetaType&");}void RecivedMsgObject(HsmsMessage msg){emit RecivedMsgObjectSig(msg);}
signals:void RecivedMsgObjectSig(HsmsMessage);
};class MyLabel : public QWidget
{Q_OBJECT
public:MyLabel(QString labName,QString labval,QWidget* parent = nullptr):m_labname(labName),m_labVal(labval),QWidget(parent){m_nameLab = new QLabel(m_labname);m_valLab = new QLabel(m_labVal);m_nameLab->setFixedWidth(200);m_valLab->setFixedWidth(100);QHBoxLayout* ly = new QHBoxLayout;ly->addWidget(m_nameLab);ly->addWidget(m_valLab);ly->setContentsMargins(0,0,0,0);this->setContentsMargins(0,0,0,0);setLayout(ly);}void setValue(QString val){m_labVal = val;m_valLab->setText(m_labVal);}
private:QString m_labname;QString m_labVal;QLabel* m_nameLab;QLabel* m_valLab;
};class McWidget : public QWidget
{Q_OBJECTpublic:McWidget(QWidget *parent = nullptr);~McWidget();void initUi();static TransHelper transhelper;private:ICommucation* o = NULL;QTimer linktesttimer;QTimer s1f3Rqtimer;QList<MyLabel*> llabs;
};
#endif // MCWIDGET_H
// mcwidget.cpp#include "mcwidget.h"
#include <QDebug>
#include <functional>
#include <QVBoxLayout>TransHelper McWidget::transhelper;/*** @brief OnStateChanged 连接状态改变回调事件* @param pComm* @param nState        0: 连接  1:断开连接* @param cSocket*/
void OnStateChanged(ICommucation* pComm, __int32 nState, void *cSocket)
{SOCKET* c= (SOCKET*) cSocket;std::string str = nState == 0 ? std::string("  connected to ") : std::string("  disconnected from ");std::cout << "[OnStateChanged ] : " << c <<  str << (void*)pComm << str << std::endl;
}/*!* \brief onMessageRecived  接收到消息的回调事件* \param pComm* \param recvedMsg* \param cSocket*/
void onMessageRecived(ICommucation* pComm,char* recvedMsg, int iRecvsize,void * cSocket)
{SOCKET* c= (SOCKET*) cSocket;// std::cout << "[onMessageRecived ] : " << (void*)pComm << " <-- "  << c  << "  : "//           << recvedMsg  <<  "  len=" << iRecvsize << std::endl;/// 通过gemsecs的协议进行解析和应答JcHsms ho(0,QString("JC Gem/Secs Test"),QString("1.0.1"));HsmsMessage hmsg = ho.interpretMessage(QByteArray(recvedMsg,iRecvsize));if(hmsg.GetHeader().Getstream() == 0x1&& hmsg.GetHeader().Getfunction() == 0x4){ // S1F4McWidget::transhelper.RecivedMsgObject(hmsg);}
}/*!* \brief OnAsyncMsgTimeout  消息超时* \param pComm* \param nTransfer          消息ID* \param pClientData*/
void OnAsyncMsgTimeout(ICommucation* pComm, __int32 nTransfer, void *pClientData)
{qDebug() << QStringLiteral("同步发送请求消息超时");
}McWidget::McWidget(QWidget *parent): QWidget(parent)
{initUi();CommucationParam setting;EthernetCommucationParam eParam = {45000,10000,5000,10000,5000, /* timeout */0                            /* PASSIVE */,5555,                        /*  port  */1                            /* DEVID */,"Device Host","127.0.0.1"};SerialCommucationParam sParam = {2,9600,'N',8,1};setting.eParam = eParam;setting.sParam = sParam;o = JC_CreatCommObject(TcpClient,setting);/// 注册回调事件JC_SetEventCallBack(o,onMessageRecived,OnStateChanged,OnAsyncMsgTimeout);/// 启动监听JC_RunListenThread(o);/// 发送 select.req 请求JcHsms ho(0,QString("JC Gem/Secs Test"),QString("1.0.1"));HsmsMessage srmsg = HsmsMessageDispatcher::selectReq(ho.unique_sessionID);QByteArray srbytes =  srmsg.toByteArray();std::string rbuf;bool ok = o->SendSyncMessage(srbytes.toStdString(),true,rbuf,10);std::cout << "recv reply buf :" << rbuf << std::endl;qDebug("send status:%s\n",ok ? "success" : "failed");std::function<void()> flinktest = [=](){HsmsMessage lktestMgr = HsmsMessageDispatcher::linktestReq();QByteArray lktestBytes = lktestMgr.toByteArray();#if 0   /// 同步发送/接收消息std::string rbuf;bool ok = o->SendSyncMessage(lktestBytes.toStdString(),true,rbuf,10);std::cout << "recv reply buf :" << rbuf << std::endl;qDebug("send status:%s\n",ok ? "success" : "failed");
#else/// 异步发送接收消息(消息接收回调事件)o->SendData(0,lktestBytes.constData(),lktestBytes.length());
#endif};/// 立即执行一次if(ok) flinktest();/// 定时触发linktesttimer.setInterval(10000);// 10sQObject::connect(&linktesttimer,&QTimer::timeout,flinktest);linktesttimer.start();/// 定时发送S1F3 请求最新SSDstd::function<void()> fs1f3Rq = [=,&ho](){HsmsMessage s1f3ReqtMgr = HsmsMessageDispatcher::S1F3(ho.unique_sessionID);QByteArray s1f3ReqBytes = s1f3ReqtMgr.toByteArray();#if 0   /// 同步发送/接收消息std::string rbuf;bool ok = o->SendSyncMessage(lktestBytes.toStdString(),true,rbuf,10);std::cout << "recv reply buf :" << rbuf << std::endl;qDebug("send status:%s\n",ok ? "success" : "failed");
#else/// 异步发送接收消息(消息接收回调事件)o->SendData(0,s1f3ReqBytes.constData(),s1f3ReqBytes.length());
#endif};s1f3Rqtimer.setInterval(30);QObject::connect(&s1f3Rqtimer,&QTimer::timeout,fs1f3Rq);s1f3Rqtimer.start();/// S1F4 Recivedconnect(&transhelper,&TransHelper::RecivedMsgObjectSig,[=](HsmsMessage hm){Secs2Item item = hm.GetItem();QVector<Secs2Item> v = item.GetItems();if(v.isEmpty() || v.length() != 23 ) return;llabs[0]->setValue(QString::number( v[0].toInt32().first()));for(int i =1;i<=3;++i){ // boolllabs[i]->setValue(QString::number(v[i].toBoolean().first()));}for(int i =4;i<=20;++i){ // int32llabs[i]->setValue(QString::number(v[i].toInt32().first()));}for(int i = 21;i <= 22;++i){ // floatllabs[i]->setValue(QString::number(v[i].toFloat().first()));}});}McWidget::~McWidget()
{}void McWidget::initUi()
{llabs.clear();QVBoxLayout* vly = new QVBoxLayout;for(int i = 1001;i <= 1023; ++i){MyLabel* labptr = new MyLabel(QString::number(i),QString("0"));llabs.append(labptr);labptr->setFixedHeight(30);labptr->setFixedWidth(300);vly->addWidget(labptr);}setLayout(vly);
}
// main.cpp#include "mcwidget.h"
#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);McWidget w;w.show();return a.exec();
}

三、演示结果

在这里插入图片描述
perfect!!!

这篇关于半导体:Gem/Secs基本协议库的开发(5)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/501313

相关文章

mysql中insert into的基本用法和一些示例

《mysql中insertinto的基本用法和一些示例》INSERTINTO用于向MySQL表插入新行,支持单行/多行及部分列插入,下面给大家介绍mysql中insertinto的基本用法和一些示例... 目录基本语法插入单行数据插入多行数据插入部分列的数据插入默认值注意事项在mysql中,INSERT I

mapstruct中的@Mapper注解的基本用法

《mapstruct中的@Mapper注解的基本用法》在MapStruct中,@Mapper注解是核心注解之一,用于标记一个接口或抽象类为MapStruct的映射器(Mapper),本文给大家介绍ma... 目录1. 基本用法2. 常用属性3. 高级用法4. 注意事项5. 总结6. 编译异常处理在MapSt

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

使用Python开发一个现代化屏幕取色器

《使用Python开发一个现代化屏幕取色器》在UI设计、网页开发等场景中,颜色拾取是高频需求,:本文主要介绍如何使用Python开发一个现代化屏幕取色器,有需要的小伙伴可以参考一下... 目录一、项目概述二、核心功能解析2.1 实时颜色追踪2.2 智能颜色显示三、效果展示四、实现步骤详解4.1 环境配置4.

MyBatis ResultMap 的基本用法示例详解

《MyBatisResultMap的基本用法示例详解》在MyBatis中,resultMap用于定义数据库查询结果到Java对象属性的映射关系,本文给大家介绍MyBatisResultMap的基本... 目录MyBATis 中的 resultMap1. resultMap 的基本语法2. 简单的 resul

Python使用smtplib库开发一个邮件自动发送工具

《Python使用smtplib库开发一个邮件自动发送工具》在现代软件开发中,自动化邮件发送是一个非常实用的功能,无论是系统通知、营销邮件、还是日常工作报告,Python的smtplib库都能帮助我们... 目录代码实现与知识点解析1. 导入必要的库2. 配置邮件服务器参数3. 创建邮件发送类4. 实现邮件

Java 枚举的基本使用方法及实际使用场景

《Java枚举的基本使用方法及实际使用场景》枚举是Java中一种特殊的类,用于定义一组固定的常量,枚举类型提供了更好的类型安全性和可读性,适用于需要定义一组有限且固定的值的场景,本文给大家介绍Jav... 目录一、什么是枚举?二、枚举的基本使用方法定义枚举三、实际使用场景代替常量状态机四、更多用法1.实现接

git stash命令基本用法详解

《gitstash命令基本用法详解》gitstash是Git中一个非常有用的命令,它可以临时保存当前工作区的修改,让你可以切换到其他分支或者处理其他任务,而不需要提交这些还未完成的修改,这篇文章主要... 目录一、基本用法1. 保存当前修改(包括暂存区和工作区的内容)2. 查看保存了哪些 stash3. 恢

基于Python开发一个有趣的工作时长计算器

《基于Python开发一个有趣的工作时长计算器》随着远程办公和弹性工作制的兴起,个人及团队对于工作时长的准确统计需求日益增长,本文将使用Python和PyQt5打造一个工作时长计算器,感兴趣的小伙伴可... 目录概述功能介绍界面展示php软件使用步骤说明代码详解1.窗口初始化与布局2.工作时长计算核心逻辑3

python web 开发之Flask中间件与请求处理钩子的最佳实践

《pythonweb开发之Flask中间件与请求处理钩子的最佳实践》Flask作为轻量级Web框架,提供了灵活的请求处理机制,中间件和请求钩子允许开发者在请求处理的不同阶段插入自定义逻辑,实现诸如... 目录Flask中间件与请求处理钩子完全指南1. 引言2. 请求处理生命周期概述3. 请求钩子详解3.1