~aleteoryx/muditaos

ref: 4ae3d9e4748cb819405fb68310154bcceeb6ef30 muditaos/module-services/service-desktop/WorkerDesktop.cpp -rw-r--r-- 8.7 KiB
4ae3d9e4 — Dawid Wojtas [CP-2014] Fix file list isn't always loaded 2 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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// Copyright (c) 2017-2023, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "service-desktop/ServiceDesktop.hpp"
#include "service-desktop/WorkerDesktop.hpp"
#include "service-desktop/DeviceColour.hpp"
#include <endpoints/EndpointFactory.hpp>
#include <service-desktop/DesktopMessages.hpp>
#include <endpoints/message/Sender.hpp>
#include <MessageHandler.hpp>
#include "Timers/TimerFactory.hpp"

#include <bsp/usb/usb.hpp>
#include <log/log.hpp>
#include <crc32.h>

#include <utility>
#include <vector>
#include <filesystem>
#include "system/messages/SentinelRegistrationMessage.hpp"

inline constexpr auto uploadFailedMessage = "file upload terminated before all data transferred";

WorkerDesktop::WorkerDesktop(sys::Service *ownerServicePtr,
                             std::function<void()> messageProcessedCallback,
                             const sdesktop::USBSecurityModel &securityModel,
                             const std::string &serialNumber,
                             const std::string &caseColour,
                             const std::string &rootPath)
    : sys::Worker(ownerServicePtr, sdesktop::worker_stack), securityModel(securityModel), serialNumber(serialNumber),
      caseColour(caseColour), rootPath{rootPath}, ownerService(ownerServicePtr), parser(ownerServicePtr),
      messageProcessedCallback(std::move(messageProcessedCallback))
{}

bool WorkerDesktop::init(std::list<sys::WorkerQueueInfo> queues)
{
    if (initialized) {
        return true;
    }

    Worker::init(queues);

    irqQueue     = Worker::getQueueHandleByName(sdesktop::IRQ_QUEUE_BUFFER_NAME);
    receiveQueue = Worker::getQueueHandleByName(sdesktop::RECEIVE_QUEUE_BUFFER_NAME);
    sdesktop::endpoints::sender::setSendQueueHandle(Worker::getQueueHandleByName(sdesktop::SEND_QUEUE_BUFFER_NAME));

    cpuSentinel                  = std::make_shared<sys::CpuSentinel>("WorkerDesktop", ownerService);
    auto sentinelRegistrationMsg = std::make_shared<sys::SentinelRegistrationMessage>(cpuSentinel);
    ownerService->bus.sendUnicast(sentinelRegistrationMsg, service::name::system_manager);

    const bsp::usbInitParams initParams = {
        receiveQueue, irqQueue, serialNumber, device_colour::getColourVersion(caseColour), rootPath};

    initialized = bsp::usbInit(initParams) == 0;

    cpuSentinel->HoldMinimumFrequency(bsp::CpuFrequencyMHz::Level_4);

    return initialized;
}

void WorkerDesktop::closeWorker(void)
{
    if (!initialized) {
        return;
    }

    unsigned int maxcount = 10;
    while (parser.getCurrentState() != sdesktop::endpoints::State::NoMsg && --maxcount > 0) {
        vTaskDelay(300);
    }

    initialized = false;
    LOG_INFO("we can deinit worker now");

    /// additional wait to flush on serial - we should wait for data sent...
    vTaskDelay(500);

    bsp::usbDeinit();

    this->close();

    cpuSentinel->ReleaseMinimumFrequency();
    auto sentinelRemoveMsg = std::make_shared<sys::SentinelRemovalMessage>("WorkerDesktop");
    auto result            = ownerService->bus.sendUnicastSync(sentinelRemoveMsg, service::name::system_manager, 1000);
    if (result.first != sys::ReturnCodes::Success) {
        LOG_ERROR("Sentinel %s could not be removed!", cpuSentinel->GetName().c_str());
    }
    cpuSentinel.reset();

    LOG_DEBUG("deinit end");
}

void WorkerDesktop::reset()
{
    initialized = false;
    usbStatus   = bsp::USBDeviceStatus::Disconnected;
    bsp::usbDeinit();

    bsp::usbInitParams initParams = {
        receiveQueue, irqQueue, serialNumber, device_colour::getColourVersion(caseColour), rootPath};
    initialized = bsp::usbInit(initParams) >= 0;
    if (initialized) {
        usbStatus = bsp::USBDeviceStatus::Connected;
        ownerService->bus.sendMulticast(std::make_shared<sdesktop::usb::USBConnected>(),
                                        sys::BusChannel::USBNotifications);
    }
}

void WorkerDesktop::notify(Signal command)
{
    if (auto queue = getQueueByName(sdesktop::SIGNALLING_QUEUE_BUFFER_NAME); !queue->Overwrite(&command)) {
        LOG_ERROR("Unable to overwrite the command in the commands queue.");
    }
}

bool WorkerDesktop::handleMessage(std::uint32_t queueID)
{
    bool result       = false;
    auto &queue       = queues[queueID];
    const auto &qname = queue->GetQueueName();

    if (qname == sdesktop::RECEIVE_QUEUE_BUFFER_NAME) {
        result = handleReceiveQueueMessage(queue);
    }
    else if (qname == sdesktop::SEND_QUEUE_BUFFER_NAME) {
        result = handleSendQueueMessage(queue);
    }
    else if (qname == SERVICE_QUEUE_NAME) {
        result = handleServiceQueueMessage(queue);
    }
    else if (qname == sdesktop::IRQ_QUEUE_BUFFER_NAME) {
        result = handleIrqQueueMessage(queue);
    }
    else if (qname == sdesktop::SIGNALLING_QUEUE_BUFFER_NAME) {
        result = handleSignallingQueueMessage(queue);
    }
    else {
        LOG_INFO("handeMessage got message on an unhandled queue");
    }

    return result;
}

bool WorkerDesktop::handleReceiveQueueMessage(std::shared_ptr<sys::WorkerQueue> &queue)
{
    if (!initialized) {
        return false;
    }
    std::string *receivedMsg = nullptr;
    if (!queue->Dequeue(&receivedMsg, 0)) {
        LOG_ERROR("handleMessage failed to receive from \"%s\"", sdesktop::RECEIVE_QUEUE_BUFFER_NAME);
        return false;
    }

    using namespace sdesktop::endpoints;
    auto factory = EndpointFactory::create(securityModel.getEndpointSecurity().access);
    auto handler = std::make_unique<MessageHandler>(ownerService, messageProcessedCallback, std::move(factory));

    parser.setMessageHandler(std::move(handler));
    parser.processMessage(std::move(*receivedMsg));

    delete receivedMsg;
    return true;
}
bool WorkerDesktop::handleSendQueueMessage(std::shared_ptr<sys::WorkerQueue> &queue)
{
    if (!initialized) {
        return false;
    }
    std::string *sendMsg = nullptr;
    if (!queue->Dequeue(&sendMsg, 0)) {
        LOG_ERROR("handleMessage xQueueReceive failed for %s.", sdesktop::SEND_QUEUE_BUFFER_NAME);
        return false;
    }

    bsp::usbCDCSend(sendMsg);
    delete sendMsg;
    return true;
}
bool WorkerDesktop::handleServiceQueueMessage(std::shared_ptr<sys::WorkerQueue> &queue)
{
    if (!initialized) {
        return false;
    }
    auto &serviceQueue = getServiceQueue();
    sys::WorkerCommand cmd;

    if (serviceQueue.Dequeue(&cmd, 0)) {
        LOG_DEBUG("Received cmd: %d", static_cast<int>(cmd.command));
#if defined(DEBUG)
        assert(false);
#endif
    }
    else {
        LOG_ERROR("handleMessage xQueueReceive failed for %s.", SERVICE_QUEUE_NAME.c_str());
        return false;
    }
    return true;
}
bool WorkerDesktop::handleIrqQueueMessage(std::shared_ptr<sys::WorkerQueue> &queue)
{
    bsp::USBDeviceStatus notification = bsp::USBDeviceStatus::Disconnected;
    if (!queue->Dequeue(&notification, 0)) {
        LOG_ERROR("handleMessage xQueueReceive failed for %s.", sdesktop::IRQ_QUEUE_BUFFER_NAME);
        return false;
    }

    if (notification == bsp::USBDeviceStatus::Connected) {
        LOG_DEBUG("USB status: Connected");
        ownerService->bus.sendMulticast(std::make_shared<sdesktop::usb::USBConnected>(),
                                        sys::BusChannel::USBNotifications);
        usbStatus = bsp::USBDeviceStatus::Connected;
    }
    else if (notification == bsp::USBDeviceStatus::Configured) {
        LOG_DEBUG("USB status: Configured");
        ownerService->bus.sendMulticast(std::make_shared<sdesktop::usb::USBConfigured>(),
                                        sys::BusChannel::USBNotifications);
        usbStatus = bsp::USBDeviceStatus::Configured;
    }
    else if (notification == bsp::USBDeviceStatus::Disconnected) {
        LOG_DEBUG("USB status: Disconnected");
        ownerService->bus.sendMulticast(std::make_shared<sdesktop::usb::USBDisconnected>(),
                                        sys::BusChannel::USBNotifications);
        usbStatus = bsp::USBDeviceStatus::Disconnected;
    }
    else if (notification == bsp::USBDeviceStatus::DataReceived) {
        bsp::usbHandleDataReceived();
    }
    else if (notification == bsp::USBDeviceStatus::Reset) {
        LOG_DEBUG("USB status: Reset");
    }
    return true;
}

bool WorkerDesktop::handleSignallingQueueMessage(std::shared_ptr<sys::WorkerQueue> &queue)
{
    if (!initialized) {
        return false;
    }
    sys::WorkerCommand command;
    if (!queue->Dequeue(&command, 0)) {
        LOG_ERROR("handleMessage failed to receive from \"%s\"", sdesktop::SIGNALLING_QUEUE_BUFFER_NAME);
        return false;
    }

    switch (static_cast<Signal>(command.command)) {
    case Signal::unlockMTP:
        bsp::usbUnlockMTP();
        break;
    default:
        LOG_ERROR("Command not valid.");
        return false;
    }
    return true;
}