~aleteoryx/muditaos

ref: ea27e6871615172000db8664a9d11d1b6103c562 muditaos/module-cellular/Modem/TS0710/DLC_channel.cpp -rw-r--r-- 6.2 KiB
ea27e687 — Maciej Janicki [EGD-5748] Remake Cellular flow 5 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "DLC_channel.h"

#include "TS0710_DATA.h"
#include "TS0710_DLC_RELEASE.h"
#include "TS0710_Frame.h"

#include <module-utils/log/log.hpp>
#include <ticks.hpp>
#include <Utils.hpp>

#include <magic_enum.hpp>

DLC_channel::DLC_channel(DLCI_t DLCI, const std::string &name, bsp::Cellular *cellular, const Callback_t &callback)
    : Channel{new uint8_t[at::defaultReceiveBufferSize]}, pv_name{name}, pv_DLCI{DLCI}, pv_cellular{cellular}
{
    LOG_DEBUG("Creating DLCI %i channel \"%s\"", DLCI, name.c_str());

    if (callback != nullptr) {
        pv_callback = callback;
    }

    chanParams.TypeOfFrame             = TypeOfFrame_e::SABM;
    chanParams.ConvergenceLayer        = 1;
    chanParams.Priority                = 1;
    chanParams.AckTime                 = 100; // 100ms default
    chanParams.MaxFrameSize            = 128;
    chanParams.MaxNumOfRetransmissions = 3; // default 3
    chanParams.ErrRecovWindowSize      = 2; // default 2

    responseBuffer = xMessageBufferCreate(at::defaultMessageBufferSize);
}

bool DLC_channel::init()
{
    active = establish();
    LOG_INFO("create channel %s: %s", pv_name.c_str(), active ? "TRUE" : "FALSE");

    return active;
}

DLC_channel::~DLC_channel()
{
    TS0710_DLC_RELEASE release = TS0710_DLC_RELEASE(pv_DLCI);
}

void DLC_channel::SendData(std::vector<uint8_t> &data)
{
    TS0710_DATA _data = TS0710_DATA(pv_DLCI, chanParams, data, pv_cellular);
}

bool DLC_channel::establish()
{
    LOG_DEBUG("Sending %s frame to DLCI %i", TypeOfFrame_text[chanParams.TypeOfFrame].c_str(), pv_DLCI);

    TS0710_Frame frame_c(TS0710_Frame::frame_t(static_cast<uint8_t>(pv_DLCI << 2) | (1 << 1),
                                               static_cast<uint8_t>(chanParams.TypeOfFrame)));

    awaitingResponseFlag.set();

    bool result = false;

    for (int retries = 0; retries < chanParams.MaxNumOfRetransmissions; ++retries) {
        pv_cellular->write(static_cast<void *>(frame_c.getSerData().data()), frame_c.getSerData().size());

        auto startTime = std::chrono::steady_clock::now();
        auto endTime   = startTime + std::chrono::milliseconds{300};

        // Wait for response:
        while (true) {
            if (std::chrono::steady_clock::now() > endTime) {
                break;
            }

            if (size_t bytesRead = cmd_receive(receiveBuffer.get(), std::chrono::milliseconds{0}); bytesRead > 0) {
                auto cellularResult = bsp::cellular::CellularResult{receiveBuffer.get(), bytesRead};
                if (evaluateEstablishResponse(cellularResult)) {
                    result = true;
                    break;
                }
            }
        }
    }

    awaitingResponseFlag.clear();

    return result;
}

void DLC_channel::cmd_init()
{}

void DLC_channel::cmd_send(std::string cmd)
{
    std::vector<uint8_t> data(cmd.begin(), cmd.end());
    SendData(data);
}

size_t DLC_channel::cmd_receive(uint8_t *result, std::chrono::milliseconds timeout)
{
    return xMessageBufferReceive(responseBuffer, result, 2 * chanParams.MaxFrameSize, pdMS_TO_TICKS(timeout.count()));
}

void DLC_channel::cmd_post()
{}

std::vector<std::string> DLC_channel::SendCommandPrompt(const char *cmd,
                                                        size_t rxCount,
                                                        std::chrono::milliseconds timeout)
{
    std::vector<std::string> tokens;

    LOG_DEBUG("SendCommandPrompt start");

    awaitingResponseFlag.set();

    at::Result result;

    cmd_init();
    std::string cmdFixed = formatCommand(cmd);
    cmd_send(cmdFixed);

    auto startTime = std::chrono::steady_clock::now();
    auto endTime   = startTime + timeout;

    LOG_DEBUG("SendCommandPrompt cmd sent");
    // Wait for response:
    while (true) {
        if (std::chrono::steady_clock::now() > endTime) {
            result.code = at::Result::Code::TIMEOUT;
            LOG_DEBUG("SendCommandPrompt cmd timeout");
            break;
        }

        if (size_t bytesRead = cmd_receive(receiveBuffer.get(), std::chrono::milliseconds{0}); bytesRead > 0) {
            auto cellularResult = bsp::cellular::CellularResult{receiveBuffer.get(), bytesRead};
            auto str            = cellularResult.getDataAsString();
            LOG_DEBUG("SendCommandPrompt got response");

            auto cellResult = checkResult(cellularResult.getResultCode());
            if (cellResult.code != at::Result::Code::OK) {
                LOG_DEBUG("SendCommandPrompt cmd response code: %s",
                          std::string(magic_enum::enum_name(cellResult.code)).c_str());
                break;
            }

            // tokenize responseBuffer
            auto pos = str.find('>');
            if (pos != std::string::npos) {
                tokens.push_back(str.substr(pos, strlen(">")));
                break;
            }
            if (tokens.size() >= rxCount) {
                break;
            }
        }
    }

    LOG_DEBUG("SendCommandPrompt end");
    cmdLog(cmdFixed, result, timeout);
    cmd_post();

    awaitingResponseFlag.clear();

    return tokens;
}

at::Result DLC_channel::ParseInputData(bsp::cellular::CellularResult *cellularResult)
{
    at::Result result;

    if (awaitingResponseFlag.state()) {
        if (!xMessageBufferSend(responseBuffer,
                                (void *)cellularResult->getSerialized().get(),
                                cellularResult->getSerializedSize(),
                                pdMS_TO_TICKS(at::defaultBufferTimeoutMs.count()))) {
            LOG_DEBUG("[DLC] Message buffer full!");
            result.code = at::Result::Code::FULL_MSG_BUFFER;
        }
    }
    else if (pv_callback != nullptr) {
        std::string receivedData = cellularResult->getDataAsString();
        pv_callback(receivedData);
    }
    else {
        result.code = at::Result::Code::DATA_NOT_USED;
    }

    return result;
}

bool DLC_channel::evaluateEstablishResponse(bsp::cellular::CellularResult &response) const
{
    auto frame = TS0710_Frame{response.getData()};
    return (frame.getFrameDLCI() == pv_DLCI &&
            (frame.getFrame().Control == (static_cast<uint8_t>(TypeOfFrame_e::UA) & ~(1 << 4))));
}