~aleteoryx/muditaos

ref: e6213e94077379e7d1ae6908dc2a6769fa406ccb muditaos/module-sys/Service/Bus.cpp -rw-r--r-- 7.2 KiB
e6213e94 — Lucjan Bryndza [EGD-5737] Merge master into experimental 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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
// Copyright (c) 2017-2020, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "Bus.hpp"
#include "thread.hpp"
#include "ticks.hpp"
#include "critical.hpp"
#include "Service.hpp"
#include "Message.hpp"
#include <algorithm>
#include <cassert>

namespace sys
{

    using namespace cpp_freertos;
    using namespace std;

    Bus::Bus()
    {}

    Bus::~Bus()
    {}

    void Bus::Add(std::shared_ptr<Service> service)
    {
        CriticalSection::Enter();
        for (auto &w : service->busChannels) {
            channels[w].m_services.insert(service);
        }
        servicesRegistered[service->GetName()] = service;
        CriticalSection::Exit();
    }

    void Bus::Remove(std::shared_ptr<Service> service)
    {
        CriticalSection::Enter();
        for (auto &w : service->busChannels) {

            auto it = std::find_if(channels[w].m_services.begin(),
                                   channels[w].m_services.end(),
                                   [&](std::shared_ptr<Service> const &s) { return s == service; });
            if (it != channels[w].m_services.end()) {
                channels[w].m_services.erase(it);
            }
            else {
            }
        }

        auto ele = servicesRegistered.find(service->GetName());
        if (ele != servicesRegistered.end()) {
            servicesRegistered.erase(service->GetName());
        }
        else {
            // error!, trying to remove non-existing service
        }

        CriticalSection::Exit();
    }

    void Bus::SendResponse(std::shared_ptr<Message> response, std::shared_ptr<Message> request, Service *sender)
    {
        assert(response != nullptr);
        assert(request != nullptr);
        assert(sender != nullptr);

        response->id        = uniqueMsgId++;
        response->uniID     = request->uniID;
        response->sender    = sender->GetName();
        response->transType = Message::TransmissionType ::Unicast;
        if (servicesRegistered.find(request->sender) != servicesRegistered.end()) {
            servicesRegistered[request->sender]->mailbox.push(response);
        }
        else {
            // silently drop it
        }
    }

    bool Bus::SendUnicast(std::shared_ptr<Message> msg, const std::string &service, Service *s)
    {
        CriticalSection::Enter();
        msg->id    = uniqueMsgId++;
        msg->uniID = unicastMsgId++;
        CriticalSection::Exit();

        msg->sender    = s->GetName();
        msg->transType = Message::TransmissionType ::Unicast;

        auto ele = servicesRegistered.find(service);
        if (ele != servicesRegistered.end()) {
            servicesRegistered[service]->mailbox.push(msg);
        }
        else {
            LOG_ERROR("Service %s doesn't exist", service.c_str());
            return false;
        }

        return true;
    }

    SendResult Bus::SendUnicast(std::shared_ptr<Message> msg, const std::string &service, Service *s, uint32_t timeout)
    {
        std::vector<std::shared_ptr<Message>> tempMsg;
        tempMsg.reserve(4); // reserve space for 4 elements to avoid costly memory allocations

        CriticalSection::Enter();
        uint64_t unicastID = unicastMsgId;
        msg->id            = uniqueMsgId++;
        msg->uniID         = unicastMsgId++;
        CriticalSection::Exit();

        msg->sender    = s->GetName();
        msg->transType = Message::TransmissionType ::Unicast;

        auto ele = servicesRegistered.find(service);
        if (ele != servicesRegistered.end()) {
            servicesRegistered[service]->mailbox.push(msg);
        }
        else {
            LOG_ERROR("Service %s doesn't exist", service.c_str());
            return std::make_pair(ReturnCodes::ServiceDoesntExist, nullptr);
        }

        uint32_t currentTime   = cpp_freertos::Ticks::GetTicks();
        uint32_t timeoutNeeded = currentTime + timeout;
        uint32_t timeElapsed   = currentTime;

        while (1) {
            // timeout
            if (timeElapsed >= timeoutNeeded) {

                // Push messages collected during waiting for response to processing queue
                for (const auto &w : tempMsg) {
                    s->mailbox.push(w);
                }

                // Register that we didn't receive response. Even if it arrives it will be dropped
                s->staleUniqueMsg.push_back(std::make_pair(unicastID, cpp_freertos::Ticks::GetTicks()));
                return std::make_pair(ReturnCodes::Timeout, nullptr);
            }

            // Immediately block on rx queue
            auto rxmsg = s->mailbox.pop(timeoutNeeded - timeElapsed);

            timeElapsed = cpp_freertos::Ticks::GetTicks();

            // check for timeout
            if (rxmsg == nullptr) {

                // Push messages collected during waiting for response to processing queue
                for (const auto &w : tempMsg) {
                    s->mailbox.push(w);
                }

                // Register that we didn't receive response. Even if it arrives it will be dropped
                s->staleUniqueMsg.push_back(std::make_pair(unicastID, cpp_freertos::Ticks::GetTicks()));
                return CreateSendResult(ReturnCodes::Timeout, nullptr);
            }

            // Received response
            if ((rxmsg->uniID == unicastID) && (msg->sender == s->GetName())) {

                // Push messages collected during waiting for response to processing queue
                for (const auto &w : tempMsg) {
                    s->mailbox.push(w);
                }

                return CreateSendResult(ReturnCodes::Success, rxmsg);
            }
            // Check for system messages
            else if (rxmsg->type == Message::Type::System) {

                SystemMessage *sysmsg = static_cast<SystemMessage *>(rxmsg.get());

                if (sysmsg->systemMessageType == SystemMessageType::Ping) {
                    rxmsg->Execute(s);
                }
                else {
                    tempMsg.push_back(rxmsg);
                }
            }
            // Plain data message, save it for later
            else {
                tempMsg.push_back(rxmsg);
            }
        }
    }

    void Bus::SendMulticast(std::shared_ptr<Message> msg, BusChannels channel, Service *source)
    {
        CriticalSection::Enter();
        msg->id      = uniqueMsgId++;
        msg->channel = channel;
        CriticalSection::Exit();

        msg->transType = Message::TransmissionType ::Multicast;
        msg->sender    = source->GetName();

        for (auto const &w : channels[channel].m_services) {
            w->mailbox.push(msg);
        }
    }

    void Bus::SendBroadcast(std::shared_ptr<Message> msg, Service *source)
    {
        CriticalSection::Enter();
        msg->id = uniqueMsgId++;
        CriticalSection::Exit();

        msg->transType = Message::TransmissionType ::Broadcast;
        msg->sender    = source->GetName();

        for (auto const &w : servicesRegistered) {
            w.second->mailbox.push(msg);
        }
    }

    std::map<BusChannels, Channel> Bus::channels;
    std::map<std::string, std::shared_ptr<Service>> Bus::servicesRegistered;
    uint64_t Bus::uniqueMsgId;
    uint64_t Bus::unicastMsgId;

} // namespace sys