与三菱PLC通信走MC协议,看了一下三菱通信方面文档,用QT写了一个通信类,目前实现读取M,X,Y,D区数据,写入M和D区数据(都可批量读写)
根据三菱 MELSEC iQ-FFX5用户手册(SLMP篇) 实现
具体需要看三菱文档
代码实现:
//读D区数据实现
int nAllLen = 9;
QByteArray data;
QByteArray revData;
data = build(address,size,READ,SUB_WORD,D);
socket->write(data);
socket->waitForBytesWritten();
if(socket->waitForReadyRead()) {
revData = socket->readAll();
}
int nLen = ResDataLen(revData);
nAllLen += nLen;
if(0 != ResError(revData)) {
return 1;
}
memcpy(pData,revData.data()+11,nLen-2);
//读M区数据实现
int nAllLen = 9;
QByteArray data;
QByteArray revData;
int sizeM = size;
if(sizeM <= 2) {
sizeM = 1;
}else {
if(sizeM%2 == 0) {
sizeM = sizeM/2;
}else {
sizeM = (sizeM + 1)/2;
}
}
data = build(address,size,READ,SUB_BIT,M);
socket->write(data);
socket->waitForBytesWritten();
if(socket->waitForReadyRead()) {
revData = socket->readAll();
}
int nLen = ResDataLen(revData);
nAllLen += nLen;
if(0 != ResError(revData)) {
return 1;
}
uint8_t *dataTemp = new uint8_t[sizeM];
uint8_t *dataM = new uint8_t[size];
memcpy(dataTemp,revData.data()+11,nLen-2);
int nNum = 0;
for(int i = 0; i < sizeM; i++) {
uint8_t firstFourBits = (dataTemp[i] >> 4) & 0x0F; //firstFourBits
uint8_t lastFourBits = dataTemp[i] & 0x0F; //lastFourBits
if(0 == i) {
memcpy(dataM+nNum,&firstFourBits,1);
nNum += 1;
if(nNum < size) {
memcpy(dataM+nNum,&lastFourBits,1);
}
} else {
memcpy(dataM+nNum,&firstFourBits,1);
nNum += 1;
if((nNum) < size) {
memcpy(dataM+nNum,&lastFourBits,1);
}
}
nNum++;
}
memcpy(pData,dataM,size);
delete [] dataM;
delete [] dataTemp;