modbus_rtu_test/global.h

153 lines
4.0 KiB
C++

#ifndef GLOBAL_H
#define GLOBAL_H
#include "Qss.h"
#include <QWidget>
#include <QDebug>
#include <QMutex>
#include <QDateTime>
extern "C"{
#include "libmodbus/modbus.h"
}
typedef struct {
int addr;
float val1;
QString time;
bool succ;
}CapData;
typedef struct{
uint16_t addr;
uint16_t len;
}Req;
typedef struct T_Config{
QString com;
int baurate;
int addr;
int rate;
QList<Req> req;
}Config;
class ASyncReadData :public QSSASyncProcess{
public:
ASyncReadData(QWidget *parent)
:QSSASyncProcess(parent){
}
~ASyncReadData(){
if(mMod)
modbus_close(mMod);
}
void Stop(){
mRuning = false;
}
void AddMonitor(QString addr){
}
void AddConfig(Config *c){
if(nullptr != c){
mMux.lock();
for(auto itr = mConf.begin();itr != mConf.end();
itr++){
if (c == *itr){
mMux.unlock();
return;
}
}
this->mConf.append(c);
mMux.unlock();
}
}
void Run(void *v) override{
// 读取1
float x = 0;
while(mRuning){
int count = 0;
for(int it = 0;it < mConf.size();it++) {
auto itr = mConf.at(it);
uint16_t dat[10] = {0};
mMod = modbus_new_rtu(itr->com.toStdString().c_str(),
itr->baurate, 'N', 8, 1); //相同的端口只能同时打开一个
modbus_set_debug(mMod,true);
modbus_set_slave(mMod,itr->addr); //设置modbus从机地址
modbus_connect(mMod);
modbus_set_response_timeout(mMod,1,1000);
QThread::msleep(300);
for(auto s = 0;s < itr->req.length();s++){
QThread::msleep(1000);
int ret = modbus_read_registers(mMod,itr->req[s].addr,itr->req[s].len,dat);
mMux.lock();
bool succ = true;
if(mListData.contains(itr->addr)){
if(ret < 0){
succ = false;
}
mListData[itr->addr]->push_front(new CapData{
itr->req[s].addr,
float(float(dat[0])),
QDateTime::currentDateTime().toString("yyyy-mm-dd hh:MM:ss"),
true
});
}else{
mListData[itr->addr] = new QList<CapData *>;
mListData[itr->addr]->push_front(new CapData{
itr->req[s].addr,
float(float(dat[0])),
QDateTime::currentDateTime().toString("yyyy-mm-dd hh:MM:ss"),
succ
});
}
mMux.unlock();
}
modbus_close(mMod);
}
qDebug()<<"keep alive";
QThread::msleep(100);
}
// 读取2
}
int TakeLast(int addr,CapData **p){
if(this->mListData.contains(addr)){
mMux.lock();
if(mListData[addr]->size() > 0){
*p = (CapData *)mListData[addr]->takeLast();
mMux.unlock();
return 0;
}else{
mMux.unlock();
return -1;
}
}else{
return -1;
}
}
QMap<int,QList<CapData *>*> mListData;
QMutex mMux;
modbus_t* mMod;
bool mRuning;
QList<Config*> mConf;
};
extern ASyncReadData *gAsyncData;
#endif // GLOBAL_H