~aleteoryx/muditaos

ref: c8e65453c5b2ce03a7f87609ed1a729dddc470de muditaos/module-services/service-desktop/message-common/include/endpoints/message/Common.hpp -rw-r--r-- 1.9 KiB
c8e65453 — Mateusz Piesta [BH-891] Alarm popup fix 4 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#pragma once

#include <log.hpp>
#include <string>
#include <json11.hpp>

namespace sdesktop::endpoints::message
{

    inline constexpr auto size_length = 9U;
    inline constexpr auto size_header = size_length + 1;

    inline constexpr auto endpointChar = '#';
    inline constexpr auto rawDataChar  = '$';

    inline void removeHeader(std::string &msg)
    {
        msg.erase(msg.begin(), msg.begin() + size_header);
    }

    inline unsigned long calcPayloadLength(const std::string &header)
    {
        try {
            return std::stol(header.substr(1, std::string::npos));
        }
        catch (const std::exception &e) {
            LOG_ERROR("[PARSER FSM] Cant calculate payload length: %s", e.what());
            return 0;
        }
    }

    inline std::string getHeader(const std::string &msg)
    {
        return msg.substr(0, size_header);
    }

    inline void eraseFront(std::string &msg, size_t pos)
    {
        msg.erase(msg.begin(), msg.begin() + pos);
    }
    inline std::string extractPayload(std::string &msg, size_t payloadLength)
    {
        if (msg.size() > payloadLength) {
            return msg.substr(0, payloadLength);
        }
        else {
            return msg;
        }
    }

    inline std::unique_ptr<std::string> buildResponse(const json11::Json &msg)
    {
        const auto jsonStr                 = msg.dump();
        const auto pos                     = 0;
        const auto count                   = 1;
        std::string responsePayloadSizeStr = std::to_string(jsonStr.size());

        while (responsePayloadSizeStr.length() < message::size_length) {
            responsePayloadSizeStr.insert(pos, count, '0');
        }

        return std::make_unique<std::string>(message::endpointChar + responsePayloadSizeStr + jsonStr);
    }

} // namespace sdesktop::endpoints::message