C

Qt Quick Ultralite Automotive Cluster Demo

// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial
#include "connectivityservice.h"

#ifdef ENABLE_CANBUS
#include <canbusdevice.h>
#include "hmi_input/hmi_input.h"

void msgHandler(unsigned int msgId,
                CanBus::CanBusDevice::CanFrameType type,
                const unsigned char *payload,
                unsigned char payloadLength,
                void *userData)
{
    if (msgId == 0x01 && type == CanBus::CanBusDevice::DataFrame && payloadLength == 1) {
        const unsigned char keyCodeMask = 0x07;
        const HMIInputEvent::Key keyCode = (HMIInputEvent::Key)(payload[0] & keyCodeMask);
        const HMIInputEvent::Type keyEventType = static_cast<HMIInputEvent::Type>(payload[0] >> 3);

        HMIInput::instance().postEvent(HMIInputEvent(keyCode, keyEventType));
    }
}

struct PendingDataHandler
{
    void operator()() { CanBus::CanBusDevice::instance().processPendingData(); }
};
#endif

ConnectivityService::ConnectivityService()
{
    clusterMode.setValue(NoneMode);
    currentMenu.setValue(None);
    mediaPlayback.setValue(false);
    enableDriveModeChange.setValue(false);
    ongoingCall.setValue(false);

#ifdef ENABLE_CANBUS
    CanBus::CanBusDevice *canBusDevice = &CanBus::CanBusDevice::instance();
    if (canBusDevice) {
        canBusDevice->registerRawMessageHandler(0x1, msgHandler, this);
        canBusDevice->bitrate.setValue(50000);
        canBusDevice->connect();

        pendingDataTimer.onTimeout(PendingDataHandler());
        pendingDataTimer.start(0);
    }
#endif
}

void ConnectivityService::sendHeartBeat()
{
#ifdef ENABLE_CANBUS
    CanBus::CanBusDevice *canBusDevice = &CanBus::CanBusDevice::instance();
    if (canBusDevice) {
        unsigned char payload = static_cast<unsigned char>(clusterMode.value())
                                | static_cast<unsigned char>(currentMenu.value()) << 2;
        if (mediaPlayback.value()) {
            payload |= 0x20;
        }
        if (enableDriveModeChange.value()) {
            payload |= 0x40;
        }
        if (ongoingCall.value()) {
            payload |= 0x80;
        }
        canBusDevice->sendRawMessage(0x2, CanBus::CanBusDevice::DataFrame, &payload, 1);
    }
#endif
}