新的例子代码,更加简洁。
template <typename Type>
bool common_kit::RemoteControlHelper::readRequest(int varid, int vartype, Type &data, int offset /*= 0*/)
{
if (m_dataStream.isNull())
{
Q_ASSERT(false);
return false;
}
if (gdp::core::INVALID_ID == m_mtManualId)
{
Q_ASSERT(false);
return false;
}
mn::common_title common_title_;
mn::common_title_item common_title_item_;
common_title_item_.varid = varid;
common_title_item_.offset = offset;
common_title_item_.vartype = vartype;
common_title_item_.length = sizeof(data);
common_title_.items.push_back(common_title_item_);
bool bOk = false;
QMutex mutex;
QMutexLocker mutexLocker(&mutex);
QWaitCondition wc;
int ret = m_dataStream->mt_post_common_read_request_by_id(m_mtManualId, common_title_, [&](uint32_t mtManualId, const void *pdata){
QMutexLocker mutextLocker(&mutex);
[&](){
if (mtManualId != m_mtManualId)
{
qDebug() << Q_FUNC_INFO << "\nmt manual id is not match!mtManualId:" << mtManualId << "\tm_mtManualId:" << m_mtManualId
<< "\tvarid:" << varid << "\tvartype:" << vartype << "\toffset:" << offset;
return;
}
if (Q_NULLPTR == pdata)
{
qDebug() << Q_FUNC_INFO << "\npdata is null!mtManualId:" << mtManualId
<< "\tvarid:" << varid << "\tvartype:" << vartype << "\toffset:" << offset;
return;
}
mn::asio_t *pasio_t = (mn::asio_t *)pdata;
if (Q_NULLPTR == pasio_t)
{
qDebug() << Q_FUNC_INFO << "\npasio_t is null!mtManualId:" << mtManualId
<< "\tvarid:" << varid << "\tvartype:" << vartype << "\toffset:" << offset;
return;
}
int err_ = pasio_t->err_;
if (err_ < 0)
{
qDebug() << Q_FUNC_INFO << "\nread request failed!mtManualId:" << mtManualId
<< "\terr_:" << err_ << "\tvarid:" << varid << "\tvartype:" << vartype
<< "\toffset:" << offset;
return;
}
mn::common_data *pcommon_data = (mn::common_data *)pdata;
if (Q_NULLPTR == pcommon_data)
{
qDebug() << Q_FUNC_INFO << "\npcommon_data is null!mtManualId:" << mtManualId
<< "\tvarid:" << varid << "\tvartype:" << vartype << "\toffset:" << offset;
return;
}
if (pcommon_data->items.empty())
{
qDebug() << Q_FUNC_INFO << "\npcommon_data's items is empty!mtManualId:" << mtManualId
<< "\tvarid:" << varid << "\tvartype:" << vartype << "\toffset:" << offset;
return;
}
mn::common_data_item ack = pcommon_data->items[0];
char *pack_data = (char *)(ack.data.data());
if (Q_NULLPTR == pack_data)
{
qDebug() << Q_FUNC_INFO << "\npack_data is null!mtManualId:" << mtManualId
<< "\tvarid:" << varid << "\tvartype:" << vartype << "\toffset:" << offset;
return;
}
data = *(Type *)pack_data;
bOk = true;
}();
wc.wakeAll();
});
if (ret < 0)
{
return false;
}
if (!wc.wait(&mutex, READ_REQUEST_TIMEOUT))
{
qDebug() << Q_FUNC_INFO << "\nQWaitCondition wait failed!m_mtManualId:" << m_mtManualId;
return false;
}
return bOk;
}