/*! * * Copyright (c) 2019-2020 Diality Inc. - All Rights Reserved. * \copyright * THIS CODE MAY NOT BE COPIED OR REPRODUCED IN ANY FORM, * IN PART OR IN WHOLE, * WITHOUT THE EXPLICIT PERMISSION OF THE COPYRIGHT OWNER. * * \file messagepacker.cpp * \date 12/9/2019 * \author Behrouz NematiPour * */ #include "messagedispatcher.h" // Qt #include #include // Project #include "logger.h" #include "applicationcontroller.h" #include "frameinterface.h" #include "messageacknowmodel.h" //#define DEBUG_ACKBACK_HD_TO_UI //#define DEBUG_OUT_OF_SYNC using namespace Can; /*! * \brief MessageDispatcher::MessageDispatcher * \details Constructor * \param parent - QObject parent owner object. * Qt handles the children destruction by their parent objects life-cycle. */ MessageDispatcher::MessageDispatcher(QObject *parent) : QObject(parent) { } /*! * \brief Message Handler initializer */ bool MessageDispatcher::init() { if ( _init ) return false; _init = true; // runs in USBWatcher thread initConnections(); LOG_EVENT("UI," + tr("%1 Initialized").arg(metaObject()->className())); return true; } /*! * \brief MessageDispatcher::init * \details Initialized the Class by calling the init() method first * And initializes the thread vThread by calling initThread * on success init(). * \param vThread - the thread * \return returns the return value of the init() method */ bool MessageDispatcher::init(QThread &vThread) { if ( ! init() ) return false; initThread(vThread); return true; } /*! * \brief MessageDispatcher::quit * \details quits the class * Calls quitThread */ void MessageDispatcher::quit() { // coco begin validated: Application termination is not correctly done in coco!!! // it has been tested and works perfectly fine in normal run. quitThread(); // validated } // coco end /*! * \brief Message Handler connections definition * \details Initializes the required signal/slot connection between this class and other objects * to be able to communicate. */ void MessageDispatcher::initConnections() { // From GUI connect(&_ApplicationController, SIGNAL(didActionTransmit(GuiActionType , const QVariantList &)), this , SLOT( onActionTransmit(GuiActionType , const QVariantList &))); // From HD connect(&_FrameInterface , SIGNAL(didFrameReceive (Can_Id , const QByteArray &)), this , SLOT( onFrameReceive (Can_Id , const QByteArray &))); // From Message Acknow Model timer timeout. connect(&_MessageAcknowModel , SIGNAL(didFramesTransmit(Can_Id, Sequence, const FrameList &)), this , SLOT( onFramesTransmit(Can_Id, Sequence, const FrameList &))); connect(&_MessageAcknowModel , SIGNAL(didFailedTransmit( Sequence )), this , SLOT( onFailedTransmit( Sequence ))); // ---- Signal/Slots ADJUST_TRANSMT_MODEL_BRIDGE_CONNECTIONS(_ApplicationController) ACTION_RECEIVE_MODEL_BRIDGE_CONNECTIONS(_interpreter ) } /*! * \brief ApplicationController::initThread * \details Moves this object into the thread vThread. * And checks that this method is called from main thread. * Also connects quitThread to application aboutToQuit. * \param vThread - the thread */ void MessageDispatcher::initThread(QThread &vThread) { // runs in main thread Q_ASSERT_X(QThread::currentThread() == qApp->thread() , __func__, "The Class initialization must be done in Main Thread" ); _thread = &vThread; _thread->setObjectName(QString("%1_Thread").arg(metaObject()->className())); connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(quit())); _thread->start(); moveToThread(_thread); } /*! * \brief MessageDispatcher::quitThread * \details Moves this object to main thread to be handled by QApplicaiton * And to be destroyed there. */ void MessageDispatcher::quitThread() { // coco begin validated: Application termination is not correctly done in coco!!! // it has been tested and works perfectly fine in normal run. if ( ! _thread ) return; // runs in thread moveToThread(qApp->thread()); // validated } // coco end /*! * \brief MessageDispatcher::onFrameReceive * \details Upon message has been received over CANBUS this slot will be called * by FrameInterface::didFrameReceive signal to process the frame * Upon completion of collected all the required frames * on successful interpretation of the message, emits didActionReceived signal. * The message will be removed from list of the channel vCan_Id messages. * \param vCan_Id - CANBUS channel of the frame * \param vPayload - Payload of the frame */ void MessageDispatcher::onFrameReceive(Can_Id vCan_Id, const QByteArray &vPayload) { // Append a message to the list // coco begin validated: if empty (first condition) is true, it must never check for the complete (second condition) // because if the list is empty there is no last() item if (_messageList[vCan_Id].isEmpty() || _messageList[vCan_Id].last().isComplete()) { // coco end _messageList[vCan_Id].append(Message()); } // build the message and check. if (! buildMessage(vCan_Id, vPayload)) { return; } Message mMessage = _messageList[vCan_Id].last(); // TODO : must be moved to a MessageModel class if (mMessage.isComplete()) { rxCount(); #ifdef DEBUG_OUT_OF_SYNC if (_rxSequence != mMessage.sequence) { qDebug() << tr("Out of Sync : %1 , %2").arg(_rxSequence).arg(mMessage.sequence); } #endif interpretMessage(mMessage); } } /*! * \brief MessageDispatcher::onFramesTransmit * \details this slots calls the framesTransmit to emit the didFrameTransmit signal * to queue the frame(s) to be sent * \param vSequence - sequence of the message which is going to be resent. (not used) * \param vFrameList - frame(s) to be sent */ void MessageDispatcher::onFramesTransmit(Can_Id vCan_Id, Sequence vSequence, const FrameList &vFrameList) { Q_UNUSED(vSequence) framesTransmit(vCan_Id, vFrameList); } void MessageDispatcher::onFailedTransmit(Sequence vSequence) { // coco begin validated: Is a placeholder and has not beed implemented yet Q_UNUSED(vSequence) // may requires showing an alarm screen // but we don't know yet. } // coco end /*! * \brief MessageDispatcher::onActionTransmit * \details This slot will be called by ApplicationController::didActionTransmit * upon UI message transmit request and calls MessageDispatcher::actionTransmit method. * \param vActionId - The ActionID of the message * \param vData - The data of the Message */ void MessageDispatcher::onActionTransmit(GuiActionType vActionId, const QVariantList &vData) { actionTransmit(vActionId, vData); } /*! * \brief MessageDispatcher::onAdjustment * \details This method transmits the Blood/Dialysate Adjustment Denali message. * \param vData - Data model contains Blood Flow Rate and Dialysate Flow Rate * \return void */ void MessageDispatcher::onAdjustment(const AdjustBloodDialysateRequestData &vData) { QVariantList mData; mData += vData.bloodFlow; mData += vData.dialysateFlow; onActionTransmit(GuiActionType::ID_AdjustBloodDialysateReq, mData); } /*! * \brief MessageDispatcher::onAdjustment * \details This method transmits the treatment duration Adjustment Denali message. * \param vData - Data model contains treatment duration adjustment value in minuts * \return void */ void MessageDispatcher::onAdjustment(const AdjustDurationRequestData &vData) { QVariantList mData; mData += vData.duration; onActionTransmit(GuiActionType::ID_AdjustDurationReq, mData); } /*! * \brief MessageDispatcher::onAdjustment * \details This method transmits the Ultrafiltration State Adjustment Denali message. * \param vData - Data model contains treatment ultrafiltration state adjustment * \return void */ void MessageDispatcher::onAdjustment(const AdjustUltrafiltrationStateRequestData &vData) { QVariantList mData; mData += vData.requestedState; actionTransmit(GuiActionType::ID_AdjustUltrafiltrationStateReq, mData); } /*! * \brief MessageDispatcher::onAdjustment * \details This method transmits the Ultrafiltration Adjustment Denali message. * \param vData - Data model contains treatment ultrafiltration adjustment volume * \return void */ void MessageDispatcher::onAdjustment(const AdjustUltrafiltrationEditRequestData &vData) { QVariantList mData; mData += vData.volume; onActionTransmit(GuiActionType::ID_AdjustUltrafiltrationEditReq, mData); } /*! * \brief MessageDispatcher::onAdjustment * \details This method transmits the Ultrafiltration Adjustment User Selected Option Denali message. * \param vData - Data model contains treatment ultrafiltration adjustment volume and user selected option. * \return void */ void MessageDispatcher::onAdjustment(const AdjustUltrafiltrationConfirmRequestData &vData) { QVariantList mData; mData += vData.volume; mData += vData.option; onActionTransmit(GuiActionType::ID_AdjustUltrafiltrationConfirmReq, mData); } /*! * \brief MessageDispatcher::actionTransmit * \details This method is called by slot MessageDispatcher::onActionTransmit * which emits didFrameTransmit on successful interpretation of the requested message * and successfully creating of frame(s). * \param vActionId - The ActionID of the message * \param vData - The data of the Message */ void MessageDispatcher::actionTransmit(GuiActionType vActionId, const QVariantList &vData, Sequence vSequence) { txCount(); if (vSequence == 0) { // initialize // it's obvious that this assignment does not effect outside of the function. // but is make it easier to just assume the correct value has been passed // and still using the same variable (function parameter) as a local variable. vSequence = _txSequence; } QByteArray mData; if (! _interpreter.interpretMessage(vActionId, vData, mData)) { LOG_ERROR(tr("Incorrect Message, can't be interpreted")); // TODO : LOGGINF IMPROVEMENT return; } // TODO : Create a buildFrames method FrameList frameList; Sequence mSequence = vSequence; bool mNeedsAcknow = needsAcknow(vActionId); if (mNeedsAcknow) { mSequence = -mSequence; LOG_EVENT(tr("UI,Ack Req, Sq:%1, ID:%2").arg(mSequence).arg(Format::toHexString(vActionId))); #ifdef DEBUG_ACKBACK_HD_TO_UI qDebug() << tr(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ UI AckReq : %1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ").arg(mSequence); #endif } if ( ! _builder.buildFrames(vActionId, mData, frameList, mSequence) ) { LOG_ERROR(tr("Incorrect Message can't be built")); // TODO : LOGGINF IMPROVEMENT return; } if (mNeedsAcknow) { // NOTE : here vSequence should be used which is not negative // because when we get the Acknow it is not the negative // since it does not need Re-Acknow // and this is the sequence number which will be used // to remove the message from the Acknow list. emit didAcknowTransmit(eChlid_UI_HD, vSequence, frameList); } framesTransmit(eChlid_UI_HD, frameList); } /*! * \brief MessageDispatcher::framesTransmit * \details iterates through all the frames and emits to send the frames * \param vCan_Id - The channel to send the frames to * \param vFrameList - List of the frames to be sent */ void MessageDispatcher::framesTransmit(Can_Id vCan_Id, const FrameList &vFrameList) { for (const auto &frame : vFrameList) { emit didFrameTransmit(vCan_Id, frame); } } /*! * \brief MessageDispatcher::buildMessage * \details Calls the messageBuilder buildMessage method. * \param vCan_Id - CANBUS channel of the frame * \param vPayload - Payload of the frame * \return false on error */ bool MessageDispatcher::buildMessage(Can_Id vCan_Id, const QByteArray &vPayload) { if (vPayload.length() < eLenCanFrame) { // Each frame has to have exactly 8 (eLenCanFrame) bytes of data and not used bytes should be passed as 00. LOG_ERROR(tr("Incorrect frame length. Exp:%1,got:%2").arg(eLenCanFrame).arg(vPayload.length())); return false; } if (! _builder.buildMessage(vPayload, _messageList[vCan_Id].last(), vCan_Id)) { _messageList[vCan_Id].removeLast(); return false; } return true; } /*! * \brief MessageDispatcher::interpretMessage * \details Calls the MessageInterpreter interpretMessage method * Regarding the Message Id and the sequence emit different signals * to handle the normal or acknowledge messages. * \param vMessage - The Message * \return false on error */ bool MessageDispatcher::interpretMessage(const Message &vMessage) { bool ok = false; QVariantList mData; Sequence mSequence = vMessage.sequence; if (_interpreter.interpretMessage(vMessage, mData)) { ok = true; GuiActionType mActionId = vMessage.actionId; switch (mActionId) { case GuiActionType::ID_Acknow: LOG_EVENT(tr("HD,Ack Bak, Sq:%1").arg(mSequence)); #ifdef DEBUG_ACKBACK_HD_TO_UI qDebug() << tr(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ HD AckBak : %1 %2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ").arg(mSequence).arg(vMessage.actionId); #endif emit didAcknowReceive(mSequence); break; default: if (mSequence < 0) { LOG_EVENT(tr("HD,Ack Req, Sq:%1, ID:%2").arg(mSequence).arg(Format::toHexString(mActionId))); #ifdef DEBUG_ACKBACK_HD_TO_UI qDebug() << tr(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ HD AckReq : %1 %2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ").arg(mSequence).arg(vMessage.actionId); #endif // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ UI AckBak is immediately handled at the same place. actionTransmit(GuiActionType::ID_Acknow, {}, -mSequence); LOG_EVENT(tr("UI,Ack Bak, Sq:%1").arg(-mSequence)); #ifdef DEBUG_ACKBACK_HD_TO_UI qDebug() << tr(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ UI AckBak : %1 %2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ").arg(-mSequence).arg(vMessage.actionId); #endif } emit didActionReceive(mActionId, mData); break; } } _messageList[vMessage.can_id].removeLast(); return ok; } /*! * \brief MessageDispatcher::rxCount * \details count received messages up the size of the Sequence type size * \return message count */ Sequence MessageDispatcher::rxCount() { // coco begin validated: has been manually validated since it requires so many received messages to reset the seq if ( _rxSequence < SEQUENCE_MAX ) { ++_rxSequence; } else { _rxSequence = 1; } return _rxSequence; } // coco end /*! * \brief MessageDispatcher::txCount * \details count transmitted messages up the size of the Sequence type size * \return message count */ Sequence MessageDispatcher::txCount() { // coco begin validated: has been manually validated since it requires so many received messages to reset the seq if ( _txSequence < SEQUENCE_MAX ) { ++_txSequence; } else { _txSequence = 1; } return _txSequence; } // coco end /*! * \brief MessageDispatcher::needsAcknow * \details List of the Action types which need Acknow * \param vActionId - Action Type id * \return true if needs an Acknow */ bool MessageDispatcher::needsAcknow(GuiActionType vActionId) { return _needsAcknow.contains(vActionId); }