~aleteoryx/muditaos

ref: f7ad63c951d6b8c8378126405eb6d16d739505cb muditaos/module-bluetooth/Bluetooth/interface/profiles/HSP/HSP.cpp -rw-r--r-- 13.6 KiB
f7ad63c9 — Lukasz Mastalerz [BH-1412] Fix services dependencies 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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
// Copyright (c) 2017-2023, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include <log/log.hpp>
#include "HSPImpl.hpp"
#include "HSP.hpp"

#include <Bluetooth/Result.hpp>
#include <service-evtmgr/ServiceEventManagerName.hpp>
#include <BluetoothWorker.hpp>
#include <module-bluetooth/Bluetooth/interface/profiles/SCO/ScoUtils.hpp>
#include <service-audio/AudioMessage.hpp>
#include <service-bluetooth/ServiceBluetoothName.hpp>
#include <service-bluetooth/messages/AudioVolume.hpp>
#include <service-bluetooth/messages/Connect.hpp>
#include <service-bluetooth/messages/Disconnect.hpp>

extern "C"
{
#include "btstack.h"
#include "btstack_run_loop_freertos.h"
#include <btstack_defines.h>
}

namespace bluetooth
{
    HSP::HSP() : pimpl(std::make_unique<HSPImpl>(HSPImpl()))
    {}

    HSP::HSP(HSP &&other) noexcept : pimpl(std::move(other.pimpl))
    {}

    auto HSP::operator=(HSP &&other) noexcept -> HSP &
    {
        if (&other == this) {
            return *this;
        }
        pimpl = std::move(other.pimpl);
        return *this;
    }

    auto HSP::init() -> Result::Code
    {
        return pimpl->init();
    }

    void HSP::setDevice(const Devicei &device)
    {
        pimpl->setDevice(device);
    }

    void HSP::setOwnerService(sys::Service *service)
    {
        pimpl->setOwnerService(service);
    }

    void HSP::connect()
    {
        pimpl->connect();
    }

    void HSP::disconnect()
    {
        pimpl->disconnect();
    }

    void HSP::setAudioDevice(std::shared_ptr<bluetooth::BluetoothAudioDevice> audioDevice)
    {
        pimpl->setAudioDevice(audioDevice);
    }

    auto HSP::setIncomingCallNumber([[maybe_unused]] const std::string &num) const noexcept -> Result::Code
    {
        return Result::Code::Success;
    }

    auto HSP::setSignalStrength([[maybe_unused]] int bars) const noexcept -> Result::Code
    {
        return Result::Code::Success;
    }

    auto HSP::setOperatorName([[maybe_unused]] const std::string_view &name) const noexcept -> Result::Code
    {
        return Result::Code::Success;
    }

    auto HSP::setBatteryLevel([[maybe_unused]] const BatteryLevel &name) const noexcept -> Result::Code
    {
        return Result::Code::Success;
    }

    auto HSP::incomingCallStarted() const noexcept -> Result::Code
    {
        return pimpl->incomingCallStarted();
    }

    auto HSP::outgoingCallStarted(const std::string &number) const noexcept -> Result::Code
    {
        return pimpl->outgoingCallStarted(number);
    }

    auto HSP::incomingCallAnswered() const noexcept -> Result::Code
    {
        return pimpl->incomingCallAnswered();
    }

    auto HSP::outgoingCallAnswered() const noexcept -> Result::Code
    {
        return pimpl->outgoingCallAnswered();
    }

    auto HSP::callTerminated() const noexcept -> Result::Code
    {
        return pimpl->callTerminated();
    }

    auto HSP::callMissed() const noexcept -> Result::Code
    {
        return pimpl->callMissed();
    }

    auto HSP::setNetworkRegistrationStatus([[maybe_unused]] bool registered) const noexcept -> Result::Code
    {
        return Result::Code::Success;
    }

    auto HSP::setRoamingStatus([[maybe_unused]] bool enabled) const noexcept -> Result::Code
    {
        return Result::Code::Success;
    }

    HSP::~HSP() = default;

    std::uint16_t HSP::HSPImpl::scoHandle = HCI_CON_HANDLE_INVALID;
    std::uint8_t HSP::HSPImpl::serviceBuffer[serviceBufferSize];

    const char *HSP::HSPImpl::agServiceName = "Mudita Pure HSP";

    std::unique_ptr<SCO> HSP::HSPImpl::sco;
    std::shared_ptr<CVSDAudioDevice> HSP::HSPImpl::audioDevice;

    std::unique_ptr<CellularInterface> HSP::HSPImpl::cellularInterface = nullptr;
    std::unique_ptr<AudioInterface> HSP::HSPImpl::audioInterface       = nullptr;

    sys::Service *HSP::HSPImpl::ownerService;
    Devicei HSP::HSPImpl::device;

    btstack_packet_callback_registration_t HSP::HSPImpl::hciEventCallbackRegistration;
    char HSP::HSPImpl::ATCommandBuffer[commandBufferSize];
    HSP::HSPImpl::HSPState HSP::HSPImpl::state = HSPState::RfcommDisconnected;

    void HSP::HSPImpl::sendAudioEvent(audio::EventType event, audio::Event::DeviceState deviceState)
    {
        auto evt       = std::make_shared<audio::Event>(event, deviceState);
        auto msg       = std::make_shared<AudioEventRequest>(std::move(evt));
        ownerService->bus.sendUnicast(std::move(msg), service::name::evt_manager);
    }

    void HSP::HSPImpl::packetHandler(std::uint8_t packetType,
                                     [[maybe_unused]] std::uint16_t channel,
                                     std::uint8_t *event,
                                     std::uint16_t eventSize)
    {
        switch (packetType) {
        case HCI_SCO_DATA_PACKET:
            if (READ_SCO_CONNECTION_HANDLE(event) != scoHandle) {
                break;
            }
            if (audioDevice != nullptr) {
                audioDevice->receiveCVSD(audio::AbstractStream::Span{.data = event, .dataSize = eventSize});
            }
            break;

        case HCI_EVENT_PACKET:
            processHCIEvent(event);
            break;

        default:
            break;
        }
    }

    void HSP::HSPImpl::processHCIEvent(std::uint8_t *event)
    {
        switch (hci_event_packet_get_type(event)) {
        case HCI_EVENT_SCO_CAN_SEND_NOW:
            if (audioDevice != nullptr) {
                audioDevice->onDataSend(scoHandle);
            }
            else {
                sco::utils::sendZeros(scoHandle);
            }
            break;

        case HCI_EVENT_HSP_META:
            processHSPEvent(event);
            break;

        default:
            break;
        }
    }

    void HSP::HSPImpl::processHSPEvent(std::uint8_t *event)
    {
        switch (hci_event_hsp_meta_get_subevent_code(event)) {
        case HSP_SUBEVENT_RFCOMM_CONNECTION_COMPLETE: {
            if (hsp_subevent_rfcomm_connection_complete_get_status(event) != ERROR_CODE_SUCCESS) {
                LOG_ERROR("RFCOMM connection failed, status: 0x%02X",
                          hsp_subevent_rfcomm_connection_complete_get_status(event));
                sendAudioEvent(audio::EventType::BluetoothHSPDeviceState, audio::Event::DeviceState::Disconnected);
                state = HSPState::RfcommDisconnected;
                break;
            }

            LOG_INFO("RFCOMM connection established");
            sendAudioEvent(audio::EventType::BluetoothHSPDeviceState, audio::Event::DeviceState::Connected);
            state              = HSPState::RfcommConnected;
            device.deviceState = DeviceState::ConnectedVoice;

            using message::bluetooth::ConnectResult;
            ownerService->bus.sendUnicast(std::make_shared<ConnectResult>(device, ConnectResult::Result::Success),
                                          service::name::bluetooth);
        } break;

        case HSP_SUBEVENT_RFCOMM_DISCONNECTION_COMPLETE: {
            LOG_INFO("RFCOMM disconnected");
            sendAudioEvent(audio::EventType::BluetoothHSPDeviceState, audio::Event::DeviceState::Disconnected);
            state = HSPState::RfcommDisconnected;
            ownerService->bus.sendUnicast(std::make_shared<message::bluetooth::DisconnectResult>(device),
                                          service::name::bluetooth);
        } break;

        case HSP_SUBEVENT_AUDIO_CONNECTION_COMPLETE: {
            const auto status = hsp_subevent_audio_connection_complete_get_status(event);
            if (status != ERROR_CODE_SUCCESS) {
                LOG_ERROR("Audio connection establishment failed, status: 0x%02X", status);
                state = HSPState::RfcommDisconnected;
                audioDevice.reset();
                break;
            }

            scoHandle = hsp_subevent_audio_connection_complete_get_sco_handle(event);
            LOG_INFO("Audio connection established with SCO handle 0x%04X", scoHandle);
            state = HSPState::Answered;

            audioInterface->startAudioRouting(ownerService);
            hci_request_sco_can_send_now_event();
        } break;

        case HSP_SUBEVENT_AUDIO_DISCONNECTION_COMPLETE: {
            scoHandle = HCI_CON_HANDLE_INVALID;
            audioDevice.reset();
            state = HSPState::RfcommConnected;
            LOG_INFO("Audio disconnected");
        } break;

        case HSP_SUBEVENT_MICROPHONE_GAIN_CHANGED: {
            LOG_INFO("Received microphone gain change: %d", hsp_subevent_microphone_gain_changed_get_gain(event));
        } break;

        case HSP_SUBEVENT_SPEAKER_GAIN_CHANGED: {
            const auto volume = hsp_subevent_speaker_gain_changed_get_gain(event);
            LOG_INFO("Received speaker gain change: %d", hsp_subevent_speaker_gain_changed_get_gain(event));
            ownerService->bus.sendUnicast(std::make_shared<message::bluetooth::HSPVolume>(volume),
                                          service::name::bluetooth);
        } break;

        case HSP_SUBEVENT_HS_CALL_ANSWER:
            LOG_INFO("HSP call answer");
            cellularInterface->answerIncomingCall(ownerService);
            break;

        case HSP_SUBEVENT_HS_CALL_HANGUP:
            LOG_INFO("HSP call hangup");
            cellularInterface->hangupCall(ownerService);
            break;

        case HSP_SUBEVENT_HS_COMMAND: {
            const std::size_t cmdLength = hsp_subevent_hs_command_get_value_length(event);
            const auto size             = std::min(cmdLength, sizeof(ATCommandBuffer));
            const auto commandValue     = hsp_subevent_hs_command_get_value(event);

            std::memset(ATCommandBuffer, 0, sizeof(ATCommandBuffer));
            std::memcpy(ATCommandBuffer, commandValue, size - 1);

            LOG_INFO("Received custom command: '%s'", ATCommandBuffer);
            break;
        }

        case HSP_SUBEVENT_BUTTON_PRESSED: {
            if ((scoHandle == HCI_CON_HANDLE_INVALID) && (state == HSPState::Ringing)) {
                LOG_INFO("Received button event in ringing state, answering call");
                cellularInterface->answerIncomingCall(ownerService);
                break;
            }

            if (state == HSPState::Answered) {
                LOG_INFO("Received button event in answered state, hanging up call");
                cellularInterface->hangupCall(ownerService);
            }
        } break;

        default:
            LOG_INFO("Event not handled: 0x%02X", hci_event_hsp_meta_get_subevent_code(event));
            break;
        }
    }

    auto HSP::HSPImpl::init() -> Result::Code
    {
        sco = std::make_unique<SCO>();
        sco->setOwnerService(ownerService);
        sco->init();

        cellularInterface = std::make_unique<CellularInterfaceImpl>();
        audioInterface    = std::make_unique<AudioInterfaceImpl>();

        Profile::initL2cap();
        Profile::initSdp();

        std::memset(serviceBuffer, 0, sizeof(serviceBuffer));

        hsp_ag_create_sdp_record(serviceBuffer, hspSdpRecordHandle, rfcommChannelNr, agServiceName);

        if (const auto status = sdp_register_service(serviceBuffer); status != ERROR_CODE_SUCCESS) {
            LOG_ERROR("Can't register service, status: 0x%02X", status);
        }

        rfcomm_init();

        hsp_ag_init(rfcommChannelNr);

        hciEventCallbackRegistration.callback = &packetHandler;
        hci_add_event_handler(&hciEventCallbackRegistration);
        hsp_ag_register_packet_handler(&packetHandler);
        hci_register_sco_packet_handler(&packetHandler);

        LOG_INFO("HSP initialized!");
        return bluetooth::Result::Code::Success;
    }

    void HSP::HSPImpl::connect()
    {
        if (state != HSPState::RfcommDisconnected) {
            disconnect();
        }
        hsp_ag_connect(device.address);
    }

    void HSP::HSPImpl::disconnect()
    {
        hsp_ag_release_audio_connection();
        hsp_ag_disconnect();
        ownerService->bus.sendUnicast(std::make_shared<message::bluetooth::DisconnectResult>(device),
                                      service::name::bluetooth);
    }

    void HSP::HSPImpl::setDevice(const Devicei &dev)
    {
        device = dev;
        LOG_DEBUG("Device set!");
    }

    void HSP::HSPImpl::setAudioDevice(std::shared_ptr<bluetooth::BluetoothAudioDevice> audioDev)
    {
        HSP::HSPImpl::audioDevice = std::static_pointer_cast<CVSDAudioDevice>(audioDev);
    }

    void HSP::HSPImpl::setOwnerService(sys::Service *service)
    {
        ownerService = service;
    }

    auto HSP::HSPImpl::incomingCallStarted() const noexcept -> Result::Code
    {
        LOG_DEBUG("Incoming call started");
        hsp_ag_start_ringing();
        state = HSPState::Ringing;
        return Result::Code::Success;
    }

    auto HSP::HSPImpl::outgoingCallStarted([[maybe_unused]] const std::string &number) const noexcept -> Result::Code
    {
        LOG_DEBUG("Outgoing call started");
        hsp_ag_establish_audio_connection();
        return Result::Code::Success;
    }

    auto HSP::HSPImpl::incomingCallAnswered() const noexcept -> Result::Code
    {
        LOG_DEBUG("Incoming call answered");
        hsp_ag_stop_ringing();
        hsp_ag_establish_audio_connection();
        return Result::Code::Success;
    }

    auto HSP::HSPImpl::outgoingCallAnswered() const noexcept -> Result::Code
    {
        LOG_DEBUG("Outgoing call answered");
        return Result::Code::Success;
    }

    auto HSP::HSPImpl::callTerminated() const noexcept -> Result::Code
    {
        LOG_DEBUG("Call terminated");
        hsp_ag_stop_ringing();
        hsp_ag_release_audio_connection();
        state = HSPState::RfcommConnected;
        return Result::Code::Success;
    }

    auto HSP::HSPImpl::callMissed() const noexcept -> Result::Code
    {
        return callTerminated();
    }
} // namespace bluetooth