半导体: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!!!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/278896.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

“降价提质”的呼声中,零食行业还是需回归供应链?

近年来&#xff0c;尽管消费行业经历了投融资的低迷期&#xff0c;但零食量贩店却一直颇受资本关注。 据不完全统计&#xff0c;从2021年至今&#xff0c;零食量贩店相关的融资事件就有十余起&#xff0c;背后不乏红杉、高榕等明星资本。比如&#xff0c;至今零食有鸣已完成6轮…

【Logback技术专题】「入门到精通系列教程」深入探索Logback日志框架的原理分析和开发实战技术指南(中篇)

深入探索Logback日志框架的原理分析和开发实战技术指南&#xff08;下篇&#xff09; Logback日志框架slf4j和logback的关系slf4jSlf4j的核心代码getLogger方法LoggerFactory的bind()方法 slf4j logback配置 log4j和logback的关系Logback的配置文件配置文件读取顺序 Logback配置…

人工智能计算机视觉:解析现状与未来趋势

导言 随着人工智能的迅速发展&#xff0c;计算机视觉技术逐渐成为引领创新的关键领域。本文将深入探讨人工智能在计算机视觉方面的最新进展、关键挑战以及未来可能的趋势。 1. 简介 计算机视觉是人工智能的一个重要分支&#xff0c;其目标是使机器具备类似于人类视觉的能力。这…

【C++】POCO学习总结(十七):日志系统(级别、通道、格式化、记录流)

【C】郭老二博文之&#xff1a;C目录 1、Poco::Message 日志消息 1.1 说明 所有日志消息都在Poco::Message对象中存储和传输。 头文件&#xff1a;#include “Poco/Message.h” 一条消息包含如下内容&#xff1a;优先级、来源、一个文本、一个时间戳、进程和线程标识符、可选…

git 常见错误总结(会不断更新中。。)

常见错误 1. 配置部署key后git clone还是拉不下代码 执行以下命令 先添加 SSH 密钥到 SSH 代理&#xff1a; 如果你使用 SSH 代理&#xff08;例如 ssh-agent&#xff09;&#xff0c;将生成的私钥添加到代理中。 ssh-add ~/.ssh/gstplatrontend/id_rsa如果报错以下错误信息…

武林风云之linux组软raid0

小y可喜欢玩文明系列的游戏了&#xff0c;因为小y也一直喜欢造轮子&#xff0c;属于自己的轮子。 每次小y听到”要向雄鹰一样&#xff0c;定要遨游于天际。”感觉自己给自己打了一针强心剂&#xff0c;要求自己拼搏进取。 众所周知&#xff0c;文明是个原生的linux游戏&#xf…

大数据技术14:FlinkCDC数据变更捕获

前言&#xff1a;Flink CDC是Flink社区开发的flink-cdc-connectors 组件&#xff0c;这是⼀个可以直接从 MySQL、PostgreSQL 等数据库直接读取全量数据和增量变更数据的 source 组件。 https://github.com/ververica/flink-cdc-connectors 一、CDC 概述 CDC 的全称是 Change …

Spring深入学习

1 Bean创建的生命周期 Spring bean是Spring运行时管理的对象。Spring Bean的生命周期指的是Bean从创建到初始化再到销毁的过程&#xff0c;这个过程由IOC容器管理。 IOC即控制反转&#xff0c;是面向对象编程中的一种设计原则&#xff0c;通过依赖注入&#xff08;DI&#xf…

高级前端开发工程师

岗位需求 熟练掌握前端主流框架Vue、React、Angular,至少熟练掌控Vue全家桶 文章目录 岗位需求前言一、Vue框架二、React框架三、Angular框架四、什么是Vue全家桶前言 -那就看你表哥的电脑里有没有硬盘 -我不敲键盘 一、Vue框架 Vue(读音为/vjuː/,类似于"view"…

Python:如何将MCD12Q1\MOD11A2\MOD13A2原始数据集批量输出为TIFF文件(镶嵌/重投影/)?

博客已同步微信公众号&#xff1a;GIS茄子&#xff1b;若博客出现纰漏或有更多问题交流欢迎关注GIS茄子&#xff0c;或者邮箱联系(推荐-见主页). 00 前言 之前一段时间一直使用ENVI IDL处理遥感数据&#xff0c;但是确实对于一些比较新鲜的东西IDL并没有python那么好的及时性&…

uniGUI学习之Cookie

UniApplication.Cookies.SetCookie( const ACookieName: string, const AValue: string, AExpires: TDateTime 0, ASecure: Boolean False, AHTTPOnly: Boolean False, const APath: string / )

MySQL数据库遇到不规范建表问题解决方案

简介&#xff1a; 需要建立的关联表如上图所示。 问题发现&#xff1a; 好&#xff0c;问题来了&#xff0c;大伙儿请看&#xff1a;我们的organizations表中的Industry字段居然存储了两个IndustryName&#xff0c;这就很恶心了&#xff0c;就需要我们进行拆分和去重后放到In…