diff options
author | Sven Gothel <[email protected]> | 2022-11-27 14:04:40 +0100 |
---|---|---|
committer | Sven Gothel <[email protected]> | 2022-11-27 14:04:40 +0100 |
commit | 5998a10ae6d20704569a4c4f4de35dd78d4ca163 (patch) | |
tree | 33626c0bc0f2468d5fbb960486d53f0467352463 /src | |
parent | cc49c8bf94b5b9b557cb2caf7b379df0660604af (diff) |
clang-tidy fixes part-1
Details
- Use 'size_type' instead of 'int',
propagate same 'size_type' into 'darray' etc.
- Use 'std::make_shared', 'std::make_unique'
- Use range-based for loops
- Remove redundant 'virtual', use 'override' in derived classes
- Use 'nullptr'
- Use default impl for dtor, ctor (incomplete)
- Use copy and std::move (incomplete)
- Explcitly catch std::bad_alloc in 'new' in 'noexcept' -> 'abort'
- 'abort' was issued implicitly in noexcept methods
- L2CAPServer, L2CAPClient, NopGattServerHandler,
DBGattServerHandler, FwdGattServerHandler
- Use local close_impl(), usable in virtual destructor
- L2CAPClient::read, HCIComm::read
- preset 'poll' result 'n', avoid garbage comparison
- BTAdapter::enableListening
- loop through addMgmtEventCallback() result
- JNI code
- explicit size_type is cast to jsize or jint w/o check
- unchanged semantics
Diffstat (limited to 'src')
-rw-r--r-- | src/direct_bt/BTAdapter.cpp | 62 | ||||
-rw-r--r-- | src/direct_bt/BTDevice.cpp | 30 | ||||
-rw-r--r-- | src/direct_bt/BTDeviceRegistry.cpp | 3 | ||||
-rw-r--r-- | src/direct_bt/BTGattChar.cpp | 7 | ||||
-rw-r--r-- | src/direct_bt/BTGattHandler.cpp | 122 | ||||
-rw-r--r-- | src/direct_bt/BTGattServerHandler.cpp | 125 | ||||
-rw-r--r-- | src/direct_bt/BTManager.cpp | 30 | ||||
-rw-r--r-- | src/direct_bt/BTTypes0.cpp | 30 | ||||
-rw-r--r-- | src/direct_bt/DBGattServer.cpp | 2 | ||||
-rw-r--r-- | src/direct_bt/HCIComm.cpp | 4 | ||||
-rw-r--r-- | src/direct_bt/HCIHandler.cpp | 59 | ||||
-rw-r--r-- | src/direct_bt/L2CAPComm.cpp | 6 | ||||
-rw-r--r-- | src/direct_bt/SMPHandler.cpp | 6 | ||||
-rw-r--r-- | src/direct_bt/SMPKeyBin.cpp | 5 | ||||
-rw-r--r-- | src/direct_bt/ieee11073/DataTypes.cpp | 16 |
15 files changed, 275 insertions, 232 deletions
diff --git a/src/direct_bt/BTAdapter.cpp b/src/direct_bt/BTAdapter.cpp index ab872f7b..cb15b09f 100644 --- a/src/direct_bt/BTAdapter.cpp +++ b/src/direct_bt/BTAdapter.cpp @@ -211,13 +211,13 @@ bool BTAdapter::removeConnectedDevice(const BTDevice & device) noexcept { return false; } -int BTAdapter::disconnectAllDevices(const HCIStatusCode reason) noexcept { +BTAdapter::size_type BTAdapter::disconnectAllDevices(const HCIStatusCode reason) noexcept { device_list_t devices; { jau::sc_atomic_critical sync(sync_data); // SC-DRF via atomic acquire & release devices = connectedDevices; // copy! } - const int count = devices.size(); + const size_type count = devices.size(); auto end = devices.end(); for (auto it = devices.begin(); it != end; ++it) { if( nullptr != *it ) { @@ -298,6 +298,7 @@ bool BTAdapter::initialSetup() noexcept { hci.resetAllStates(false); WORDY_PRINT("BTAdapter::initialSetup: Adapter[%d]: Not POWERED: %s", dev_id, adapterInfo.toString().c_str()); } + // NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall) WORDY_PRINT("BTAdapter::initialSetup: Adapter[%d]: Done: %s - %s", dev_id, adapterInfo.toString().c_str(), toString().c_str()); return true; @@ -322,14 +323,14 @@ bool BTAdapter::enableListening(const bool enable) noexcept { ok = mgmt->addMgmtEventCallback(dev_id, MgmtEvent::Opcode::DISCOVERING, jau::bind_member(this, &BTAdapter::mgmtEvDeviceDiscoveringMgmt)) && ok; ok = mgmt->addMgmtEventCallback(dev_id, MgmtEvent::Opcode::NEW_SETTINGS, jau::bind_member(this, &BTAdapter::mgmtEvNewSettingsMgmt)) && ok; ok = mgmt->addMgmtEventCallback(dev_id, MgmtEvent::Opcode::LOCAL_NAME_CHANGED, jau::bind_member(this, &BTAdapter::mgmtEvLocalNameChangedMgmt)) && ok; - ok = mgmt->addMgmtEventCallback(dev_id, MgmtEvent::Opcode::PIN_CODE_REQUEST, jau::bind_member(this, &BTAdapter::mgmtEvPinCodeRequestMgmt)); - ok = mgmt->addMgmtEventCallback(dev_id, MgmtEvent::Opcode::USER_CONFIRM_REQUEST, jau::bind_member(this, &BTAdapter::mgmtEvUserConfirmRequestMgmt)); - ok = mgmt->addMgmtEventCallback(dev_id, MgmtEvent::Opcode::USER_PASSKEY_REQUEST, jau::bind_member(this, &BTAdapter::mgmtEvUserPasskeyRequestMgmt)); - ok = mgmt->addMgmtEventCallback(dev_id, MgmtEvent::Opcode::AUTH_FAILED, jau::bind_member(this, &BTAdapter::mgmtEvAuthFailedMgmt)); - ok = mgmt->addMgmtEventCallback(dev_id, MgmtEvent::Opcode::DEVICE_UNPAIRED, jau::bind_member(this, &BTAdapter::mgmtEvDeviceUnpairedMgmt)); - ok = mgmt->addMgmtEventCallback(dev_id, MgmtEvent::Opcode::PAIR_DEVICE_COMPLETE, jau::bind_member(this, &BTAdapter::mgmtEvPairDeviceCompleteMgmt)); - ok = mgmt->addMgmtEventCallback(dev_id, MgmtEvent::Opcode::NEW_LONG_TERM_KEY, jau::bind_member(this, &BTAdapter::mgmtEvNewLongTermKeyMgmt)); - ok = mgmt->addMgmtEventCallback(dev_id, MgmtEvent::Opcode::NEW_LINK_KEY, jau::bind_member(this, &BTAdapter::mgmtEvNewLinkKeyMgmt)); + ok = mgmt->addMgmtEventCallback(dev_id, MgmtEvent::Opcode::PIN_CODE_REQUEST, jau::bind_member(this, &BTAdapter::mgmtEvPinCodeRequestMgmt)) && ok; + ok = mgmt->addMgmtEventCallback(dev_id, MgmtEvent::Opcode::USER_CONFIRM_REQUEST, jau::bind_member(this, &BTAdapter::mgmtEvUserConfirmRequestMgmt)) && ok; + ok = mgmt->addMgmtEventCallback(dev_id, MgmtEvent::Opcode::USER_PASSKEY_REQUEST, jau::bind_member(this, &BTAdapter::mgmtEvUserPasskeyRequestMgmt)) && ok; + ok = mgmt->addMgmtEventCallback(dev_id, MgmtEvent::Opcode::AUTH_FAILED, jau::bind_member(this, &BTAdapter::mgmtEvAuthFailedMgmt)) && ok; + ok = mgmt->addMgmtEventCallback(dev_id, MgmtEvent::Opcode::DEVICE_UNPAIRED, jau::bind_member(this, &BTAdapter::mgmtEvDeviceUnpairedMgmt)) && ok; + ok = mgmt->addMgmtEventCallback(dev_id, MgmtEvent::Opcode::PAIR_DEVICE_COMPLETE, jau::bind_member(this, &BTAdapter::mgmtEvPairDeviceCompleteMgmt)) && ok; + ok = mgmt->addMgmtEventCallback(dev_id, MgmtEvent::Opcode::NEW_LONG_TERM_KEY, jau::bind_member(this, &BTAdapter::mgmtEvNewLongTermKeyMgmt)) && ok; + ok = mgmt->addMgmtEventCallback(dev_id, MgmtEvent::Opcode::NEW_LINK_KEY, jau::bind_member(this, &BTAdapter::mgmtEvNewLinkKeyMgmt)) && ok; if( !ok ) { ERR_PRINT("Could not add all required MgmtEventCallbacks to DBTManager: %s", toString().c_str()); @@ -370,11 +371,11 @@ bool BTAdapter::enableListening(const bool enable) noexcept { return true; } -BTAdapter::BTAdapter(const BTAdapter::ctor_cookie& cc, const BTManagerRef& mgmt_, const AdapterInfo& adapterInfo_) noexcept +BTAdapter::BTAdapter(const BTAdapter::ctor_cookie& cc, BTManagerRef mgmt_, AdapterInfo adapterInfo_) noexcept : debug_event(jau::environment::getBooleanProperty("direct_bt.debug.adapter.event", false)), debug_lock(jau::environment::getBooleanProperty("direct_bt.debug.adapter.lock", false)), - mgmt( mgmt_ ), - adapterInfo( adapterInfo_ ), + mgmt( std::move(mgmt_) ), + adapterInfo( std::move(adapterInfo_) ), adapter_initialized( false ), adapter_poweredon_at_init( false ), le_features( LE_Features::NONE ), hci_uses_ext_scan( false ), hci_uses_ext_conn( false ), hci_uses_ext_adv( false ), @@ -412,6 +413,7 @@ BTAdapter::~BTAdapter() noexcept { hci.clearAllCallbacks(); return; } + // NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall) DBG_PRINT("BTAdapter::dtor: ... %p %s", this, toString().c_str()); close(); @@ -427,13 +429,14 @@ void BTAdapter::close() noexcept { DBG_PRINT("BTAdapter::close: dev_id %d, invalid, %p", dev_id, this); return; } + // NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall) DBG_PRINT("BTAdapter::close: ... %p %s", this, toString().c_str()); discovery_policy = DiscoveryPolicy::AUTO_OFF; // mute all listener first { - int count = mgmt->removeMgmtEventCallback(dev_id); - DBG_PRINT("BTAdapter::close removeMgmtEventCallback: %d callbacks", count); + size_type count = mgmt->removeMgmtEventCallback(dev_id); + DBG_PRINT("BTAdapter::close removeMgmtEventCallback: %zu callbacks", (size_t)count); } hci.clearAllCallbacks(); statusListenerList.clear(); @@ -980,7 +983,7 @@ bool BTAdapter::removeStatusListener(const AdapterStatusListenerRef& l) noexcept ERR_PRINT("AdapterStatusListener ref is null"); return false; } - const int count = statusListenerList.erase_matching(StatusListenerPair{l, std::weak_ptr<BTDevice>{}}, + const size_type count = statusListenerList.erase_matching(StatusListenerPair{l, std::weak_ptr<BTDevice>{}}, false /* all_matching */, adapterStatusListenerRefEqComparator); if( _print_device_lists || jau::environment::get().verbose ) { @@ -1014,11 +1017,10 @@ bool BTAdapter::removeStatusListener(const AdapterStatusListener * l) noexcept { return res; } -int BTAdapter::removeAllStatusListener(const BTDevice& d) noexcept { - int count = 0; +BTAdapter::size_type BTAdapter::removeAllStatusListener(const BTDevice& d) noexcept { + size_type count = 0; - int res = statusListenerList.size(); - if( 0 < res ) { + if( 0 < statusListenerList.size() ) { auto begin = statusListenerList.begin(); auto it = begin.end(); do { @@ -1037,8 +1039,8 @@ int BTAdapter::removeAllStatusListener(const BTDevice& d) noexcept { return count; } -int BTAdapter::removeAllStatusListener() noexcept { - int count = statusListenerList.size(); +BTAdapter::size_type BTAdapter::removeAllStatusListener() noexcept { + const size_type count = statusListenerList.size(); statusListenerList.clear(); return count; } @@ -1316,8 +1318,8 @@ bool BTAdapter::removeDiscoveredDevice(const BDAddressAndType & addressAndType) return false; } -int BTAdapter::removeDiscoveredDevices() noexcept { - int res; +BTAdapter::size_type BTAdapter::removeDiscoveredDevices() noexcept { + size_type res; { const std::lock_guard<std::mutex> lock(mtx_discoveredDevices); // RAII-style acquire and relinquish via destructor @@ -1335,7 +1337,7 @@ int BTAdapter::removeDiscoveredDevices() noexcept { } } if( _print_device_lists || jau::environment::get().verbose ) { - jau::PLAIN_PRINT(true, "BTAdapter::removeDiscoveredDevices: End: %d, %s", res, toString().c_str()); + jau::PLAIN_PRINT(true, "BTAdapter::removeDiscoveredDevices: End: %zu, %s", (size_t)res, toString().c_str()); printDeviceLists(); } return res; @@ -1368,7 +1370,7 @@ void BTAdapter::removeSharedDevice(const BTDevice & device) noexcept { const std::lock_guard<std::mutex> lock(mtx_sharedDevices); // RAII-style acquire and relinquish via destructor for (auto it = sharedDevices.begin(); it != sharedDevices.end(); ) { if ( nullptr != *it && device == **it ) { - it = sharedDevices.erase(it); + sharedDevices.erase(it); return; // unique set } else { ++it; @@ -1588,9 +1590,8 @@ std::string BTAdapter::toString(bool includeDiscoveredDevices) const noexcept { device_list_t devices = getDiscoveredDevices(); if( devices.size() > 0 ) { out.append("\n"); - for(auto it = devices.begin(); it != devices.end(); it++) { - BTDeviceRef p = *it; - if( nullptr != p ) { + for(auto p : devices) { + if( nullptr != p ) { out.append(" ").append(p->toString()).append("\n"); } } @@ -1757,7 +1758,7 @@ void BTAdapter::updateAdapterSettings(const bool off_thread, const AdapterSettin COND_PRINT(debug_event, "BTAdapter::updateAdapterSettings: %s -> %s, changes %s: %s, sendEvent %d, offThread %d", to_string(old_settings_).c_str(), to_string(new_settings).c_str(), - to_string(changes).c_str(), toString().c_str(), sendEvent, off_thread ); + to_string(changes).c_str(), toString().c_str(), sendEvent, off_thread ); // NOLINT(clang-analyzer-optin.cplusplus.VirtualCall) updateDataFromAdapterInfo(); @@ -2348,6 +2349,7 @@ void BTAdapter::mgmtEvDeviceFoundHCI(const MgmtEvent& e) noexcept { if( nullptr == eir ) { // Sourced from Linux Mgmt, which we don't support ABORT("BTAdapter:hci:DeviceFound: Not sourced from LE_ADVERTISING_REPORT: %s", deviceFoundEvent.toString().c_str()); + return; // unreachable } // else: Sourced from HCIHandler via LE_ADVERTISING_REPORT (default!) /** diff --git a/src/direct_bt/BTDevice.cpp b/src/direct_bt/BTDevice.cpp index 5a902215..966411a4 100644 --- a/src/direct_bt/BTDevice.cpp +++ b/src/direct_bt/BTDevice.cpp @@ -81,13 +81,13 @@ BTDevice::BTDevice(const ctor_cookie& cc, BTAdapter & a, EInfoReport const & r) const BLERandomAddressType leRandomAddressType = addressAndType.getBLERandomAddressType(); if( BDAddressType::BDADDR_LE_RANDOM == addressAndType.type ) { if( BLERandomAddressType::UNDEFINED == leRandomAddressType ) { - throw jau::IllegalArgumentException("BDADDR_LE_RANDOM: Invalid BLERandomAddressType "+ - to_string(leRandomAddressType)+": "+toString(), E_FILE_LINE); + // NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall) + throw jau::IllegalArgumentException("BDADDR_LE_RANDOM: Invalid BLERandomAddressType "+to_string(leRandomAddressType)+": "+toString(), E_FILE_LINE); } } else { if( BLERandomAddressType::UNDEFINED != leRandomAddressType ) { - throw jau::IllegalArgumentException("Not BDADDR_LE_RANDOM: Invalid given native BLERandomAddressType "+ - to_string(leRandomAddressType)+": "+toString(), E_FILE_LINE); + // NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall) + throw jau::IllegalArgumentException("Not BDADDR_LE_RANDOM: Invalid given native BLERandomAddressType "+to_string(leRandomAddressType)+": "+toString(), E_FILE_LINE); } } } @@ -197,14 +197,14 @@ EIRDataType BTDevice::update(EInfoReport const & data) noexcept { ts_last_update = data.getTimestamp(); if( data.isSet(EIRDataType::BDADDR) ) { if( data.getAddress() != this->addressAndType.address ) { - WARN_PRINT("BDADDR update not supported: %s for %s", - data.toString().c_str(), this->toString().c_str()); + // NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall) + WARN_PRINT("BDADDR update not supported: %s for %s", data.toString().c_str(), this->toString().c_str()); } } if( data.isSet(EIRDataType::BDADDR_TYPE) ) { if( data.getAddressType() != this->addressAndType.type ) { - WARN_PRINT("BDADDR_TYPE update not supported: %s for %s", - data.toString().c_str(), this->toString().c_str()); + // NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall) + WARN_PRINT("BDADDR_TYPE update not supported: %s for %s", data.toString().c_str(), this->toString().c_str()); } } if( data.isSet(EIRDataType::NAME) ) { @@ -452,6 +452,7 @@ HCIStatusCode BTDevice::connectLE(const uint16_t le_scan_interval, const uint16_ } else if( SMPPairingState::COMPLETED == pstate ) { DBG_PRINT("BTDevice::connectLE: SEC AUTO.%d.X Done: %s", smp_auto_count, toString().c_str()); smp_auto_done = true; + (void)smp_auto_done; break; } else if( SMPPairingState::FAILED == pstate ) { if( !smp_auto_done ) { // not last one @@ -610,7 +611,7 @@ void BTDevice::processL2CAPSetup(std::shared_ptr<BTDevice> sthis) { sec_level = BTSecurityLevel::ENC_ONLY; // no auth w/o I/O } else if( adapter.hasSecureConnections() ) { sec_level = BTSecurityLevel::ENC_AUTH_FIPS; - } else if( responderLikesEncryption ) { + } else { sec_level = BTSecurityLevel::ENC_AUTH; } } else { @@ -1801,6 +1802,7 @@ void BTDevice::clearSMPStates(const bool connected) noexcept { // notifyDisconnect() will be called at all times, even if disconnect() fails! const std::unique_lock<std::recursive_mutex> lock_pairing(mtx_pairing); // RAII-style acquire and relinquish via destructor + // NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall) DBG_PRINT("BTDevice::clearSMPStates(connected %d): %s", connected, toString().c_str()); if( !connected ) { @@ -1949,7 +1951,7 @@ std::shared_ptr<BTGattHandler> BTDevice::getGattHandler() noexcept { return gattHandler; } -jau::darray<BTGattServiceRef> BTDevice::getGattServices() noexcept { +BTDevice::GattServiceList_t BTDevice::getGattServices() noexcept { std::shared_ptr<BTGattHandler> gh = getGattHandler(); if( nullptr == gh ) { ERR_PRINT("GATTHandler nullptr: %s", toString().c_str()); @@ -1970,7 +1972,7 @@ jau::darray<BTGattServiceRef> BTDevice::getGattServices() noexcept { return gh->getServices(); // copy previous discovery result } - jau::darray<BTGattServiceRef> result = gh->getServices(); // copy + GattServiceList_t result = gh->getServices(); // copy if( result.size() == 0 ) { // nothing discovered, actually a redundant check done @ BTGattHandler::initClientGatt() 1st ERR_PRINT2("No primary services discovered"); return jau::darray<BTGattServiceRef>(); // return zero size @@ -2104,7 +2106,7 @@ bool BTDevice::removeCharListener(const BTGattCharListenerRef& l) noexcept { return gatt->removeCharListener(l); } -int BTDevice::removeAllAssociatedCharListener(const BTGattCharRef& associatedCharacteristic) noexcept { +BTDevice::size_type BTDevice::removeAllAssociatedCharListener(const BTGattCharRef& associatedCharacteristic) noexcept { std::shared_ptr<BTGattHandler> gatt = getGattHandler(); if( nullptr == gatt ) { // OK to have GATTHandler being shutdown @ disable @@ -2114,7 +2116,7 @@ int BTDevice::removeAllAssociatedCharListener(const BTGattCharRef& associatedCha return gatt->removeAllAssociatedCharListener( associatedCharacteristic ); } -int BTDevice::removeAllAssociatedCharListener(const BTGattChar * associatedCharacteristic) noexcept { +BTDevice::size_type BTDevice::removeAllAssociatedCharListener(const BTGattChar * associatedCharacteristic) noexcept { std::shared_ptr<BTGattHandler> gatt = getGattHandler(); if( nullptr == gatt ) { // OK to have GATTHandler being shutdown @ disable @@ -2124,7 +2126,7 @@ int BTDevice::removeAllAssociatedCharListener(const BTGattChar * associatedChara return gatt->removeAllAssociatedCharListener( associatedCharacteristic ); } -int BTDevice::removeAllCharListener() noexcept { +BTDevice::size_type BTDevice::removeAllCharListener() noexcept { std::shared_ptr<BTGattHandler> gatt = getGattHandler(); if( nullptr == gatt ) { // OK to have GATTHandler being shutdown @ disable diff --git a/src/direct_bt/BTDeviceRegistry.cpp b/src/direct_bt/BTDeviceRegistry.cpp index de1a62ea..ef1f8de8 100644 --- a/src/direct_bt/BTDeviceRegistry.cpp +++ b/src/direct_bt/BTDeviceRegistry.cpp @@ -122,8 +122,7 @@ namespace direct_bt::BTDeviceRegistry { bool areAllDevicesProcessed(DeviceQueryMatchFunc m) noexcept { const std::lock_guard<std::recursive_mutex> lock(mtx_devicesProcessed); // RAII-style acquire and relinquish via destructor - for (auto it1 = waitForDevices.cbegin(); it1 != waitForDevices.cend(); ++it1) { - const DeviceQuery& q = *it1; + for (const auto & q : waitForDevices) { auto it2 = devicesProcessed.cbegin(); while ( it2 != devicesProcessed.cend() ) { const DeviceID& id = *it2; diff --git a/src/direct_bt/BTGattChar.cpp b/src/direct_bt/BTGattChar.cpp index c618cae4..4f5fcf61 100644 --- a/src/direct_bt/BTGattChar.cpp +++ b/src/direct_bt/BTGattChar.cpp @@ -128,9 +128,8 @@ std::string BTGattChar::toString() const noexcept { if( 0 < descriptorList.size() ) { bool comma = false; desc_str = ", descr["; - for(size_t i=0; i<descriptorList.size(); i++) { - const BTGattDescRef cd = descriptorList[i]; - if( comma ) { + for(auto cd : descriptorList) { + if( comma ) { desc_str += ", "; } desc_str += "handle "+to_hexstring(cd->handle); @@ -292,7 +291,7 @@ bool BTGattChar::removeCharListener(const BTGattCharListenerRef& l) noexcept { return device->removeCharListener(l); } -int BTGattChar::removeAllAssociatedCharListener(bool shallDisableIndicationNotification) noexcept { +BTGattChar::size_type BTGattChar::removeAllAssociatedCharListener(bool shallDisableIndicationNotification) noexcept { if( shallDisableIndicationNotification ) { disableIndicationNotification(); } diff --git a/src/direct_bt/BTGattHandler.cpp b/src/direct_bt/BTGattHandler.cpp index ebe92357..70d9e019 100644 --- a/src/direct_bt/BTGattHandler.cpp +++ b/src/direct_bt/BTGattHandler.cpp @@ -132,7 +132,7 @@ bool BTGattHandler::removeCharListener(const BTGattCharListenerRef& l) noexcept ERR_PRINT("GATTCharacteristicListener ref is null"); return false; } - const int count = gattCharListenerList.erase_matching(GattCharListenerPair{l, std::weak_ptr<BTGattChar>{}}, + const size_type count = gattCharListenerList.erase_matching(GattCharListenerPair{l, std::weak_ptr<BTGattChar>{}}, false /* all_matching */, gattCharListenerRefEqComparator); return count > 0; @@ -170,7 +170,7 @@ bool BTGattHandler::removeCharListener(const BTGattHandler::NativeGattCharListen ERR_PRINT("NativeGattCharListener ref is null"); return false; } - const int count = nativeGattCharListenerList.erase_matching(l, false /* all_matching */, _nativeGattCharListenerRefEqComparator); + const size_type count = nativeGattCharListenerList.erase_matching(l, false /* all_matching */, _nativeGattCharListenerRefEqComparator); return count > 0; } @@ -193,7 +193,7 @@ void BTGattHandler::printCharListener() noexcept { } } -int BTGattHandler::removeAllAssociatedCharListener(const BTGattCharRef& associatedCharacteristic) noexcept { +BTGattHandler::size_type BTGattHandler::removeAllAssociatedCharListener(const BTGattCharRef& associatedCharacteristic) noexcept { if( nullptr == associatedCharacteristic ) { ERR_PRINT("Given GATTCharacteristic ref is null"); return false; @@ -201,12 +201,12 @@ int BTGattHandler::removeAllAssociatedCharListener(const BTGattCharRef& associat return removeAllAssociatedCharListener( associatedCharacteristic.get() ); } -int BTGattHandler::removeAllAssociatedCharListener(const BTGattChar * associatedCharacteristic) noexcept { +BTGattHandler::size_type BTGattHandler::removeAllAssociatedCharListener(const BTGattChar * associatedCharacteristic) noexcept { if( nullptr == associatedCharacteristic ) { ERR_PRINT("Given GATTCharacteristic ref is null"); return false; } - int count = 0; + size_type count = 0; auto it = gattCharListenerList.begin(); // lock mutex and copy_store while( !it.is_end() ) { if ( it->match(*associatedCharacteristic) ) { @@ -222,8 +222,8 @@ int BTGattHandler::removeAllAssociatedCharListener(const BTGattChar * associated return count; } -int BTGattHandler::removeAllCharListener() noexcept { - int count = gattCharListenerList.size(); +BTGattHandler::size_type BTGattHandler::removeAllCharListener() noexcept { + size_type count = gattCharListenerList.size(); gattCharListenerList.clear(); count += nativeGattCharListenerList.size(); nativeGattCharListenerList.clear(); @@ -883,8 +883,8 @@ bool BTGattHandler::sendIndication(const uint16_t char_value_handle, const jau:: } BTGattCharRef BTGattHandler::findCharacterisicsByValueHandle(const jau::darray<BTGattServiceRef> &services_, const uint16_t charValueHandle) noexcept { - for(auto it = services_.cbegin(); it != services_.cend(); it++) { - BTGattCharRef decl = findCharacterisicsByValueHandle(*it, charValueHandle); + for(const auto & service : services_) { + BTGattCharRef decl = findCharacterisicsByValueHandle(service, charValueHandle); if( nullptr != decl ) { return decl; } @@ -893,8 +893,7 @@ BTGattCharRef BTGattHandler::findCharacterisicsByValueHandle(const jau::darray<B } BTGattCharRef BTGattHandler::findCharacterisicsByValueHandle(const BTGattServiceRef service, const uint16_t charValueHandle) noexcept { - for(auto it = service->characteristicList.begin(); it != service->characteristicList.end(); it++) { - BTGattCharRef decl = *it; + for(auto decl : service->characteristicList) { if( charValueHandle == decl->value_handle ) { return decl; } @@ -965,8 +964,7 @@ bool BTGattHandler::discoverCompletePrimaryServices(std::shared_ptr<BTGattHandle if( !discoverPrimaryServices(shared_this, services) ) { return false; } - for(auto it = services.begin(); it != services.end(); it++) { - BTGattServiceRef primSrv = *it; + for(auto primSrv : services) { if( !discoverCharacteristics(primSrv) ) { return false; } @@ -1015,16 +1013,21 @@ bool BTGattHandler::discoverPrimaryServices(std::shared_ptr<BTGattHandler> share if( pdu->getOpcode() == AttPDUMsg::Opcode::READ_BY_GROUP_TYPE_RSP ) { const AttReadByGroupTypeRsp * p = static_cast<const AttReadByGroupTypeRsp*>(pdu.get()); - const int esz = p->getElementSize(); - const int count = p->getElementCount(); - - for(int i=0; i<count; i++) { - const int ePDUOffset = p->getElementPDUOffset(i); - result.push_back( BTGattServiceRef( new BTGattService( shared_this, true, - p->pdu.get_uint16(ePDUOffset), // start-handle - p->pdu.get_uint16(ePDUOffset + 2), // end-handle - p->pdu.get_uuid( ePDUOffset + 2 + 2, jau::uuid_t::toTypeSize(esz-2-2) ) // uuid - ) ) ); + const size_type esz = p->getElementSize(); + const size_type count = p->getElementCount(); + + for(size_type i=0; i<count; ++i) { + const size_type ePDUOffset = p->getElementPDUOffset(i); + try { + result.push_back( std::make_shared<BTGattService>( shared_this, true, + p->pdu.get_uint16(ePDUOffset), // start-handle + p->pdu.get_uint16(ePDUOffset + 2), // end-handle + p->pdu.get_uuid( ePDUOffset + 2 + 2, jau::uuid_t::toTypeSize(esz-2-2) ) // uuid + ) ); + } catch (const std::bad_alloc &e) { + ABORT("Error: bad_alloc: BTGattServiceRef allocation failed"); + return false; // unreachable + } COND_PRINT(env.DEBUG_DATA, "GATT PRIM SRV discovered[%d/%d]: %s on %s", i, count, result.at(result.size()-1)->toString().c_str(), toString().c_str()); } @@ -1078,19 +1081,24 @@ bool BTGattHandler::discoverCharacteristics(BTGattServiceRef & service) noexcept if( pdu->getOpcode() == AttPDUMsg::Opcode::READ_BY_TYPE_RSP ) { const AttReadByTypeRsp * p = static_cast<const AttReadByTypeRsp*>(pdu.get()); - const int esz = p->getElementSize(); - const int e_count = p->getElementCount(); + const size_type esz = p->getElementSize(); + const size_type e_count = p->getElementCount(); - for(int e_iter=0; e_iter<e_count; e_iter++) { + for(size_type e_iter=0; e_iter<e_count; ++e_iter) { // handle: handle for the Characteristics declaration // value: Characteristics Property, Characteristics Value Handle _and_ Characteristics UUID - const int ePDUOffset = p->getElementPDUOffset(e_iter); - service->characteristicList.push_back( BTGattCharRef( new BTGattChar( - service, - p->getElementHandle(e_iter), // Characteristic Handle - static_cast<BTGattChar::PropertyBitVal>(p->pdu.get_uint8(ePDUOffset + 2)), // Characteristics Property - p->pdu.get_uint16(ePDUOffset + 2 + 1), // Characteristics Value Handle - p->pdu.get_uuid(ePDUOffset + 2 + 1 + 2, jau::uuid_t::toTypeSize(esz-2-1-2) ) ) ) ); // Characteristics Value Type UUID + const size_type ePDUOffset = p->getElementPDUOffset(e_iter); + try { + service->characteristicList.push_back( std::make_shared<BTGattChar>( + service, + p->getElementHandle(e_iter), // Characteristic Handle + static_cast<BTGattChar::PropertyBitVal>(p->pdu.get_uint8(ePDUOffset + 2)), // Characteristics Property + p->pdu.get_uint16(ePDUOffset + 2 + 1), // Characteristics Value Handle + p->pdu.get_uuid(ePDUOffset + 2 + 1 + 2, jau::uuid_t::toTypeSize(esz-2-1-2) ) ) ); // Characteristics Value Type UUID + } catch (const std::bad_alloc &e) { + ABORT("Error: bad_alloc: BTGattCharRef allocation failed"); + return false; // unreachable + } COND_PRINT(env.DEBUG_DATA, "GATT C discovered[%d/%d]: char%s on %s", e_iter, e_count, service->characteristicList.at(service->characteristicList.size()-1)->toString().c_str(), toString().c_str()); } @@ -1124,8 +1132,8 @@ bool BTGattHandler::discoverDescriptors(BTGattServiceRef & service) noexcept { const std::lock_guard<std::recursive_mutex> lock(mtx_command); // RAII-style acquire and relinquish via destructor PERF_TS_T0(); - const int charCount = service->characteristicList.size(); - for(int charIter=0; charIter < charCount; charIter++ ) { + const size_type charCount = service->characteristicList.size(); + for(size_type charIter=0; charIter < charCount; ++charIter ) { BTGattCharRef charDecl = service->characteristicList[charIter]; charDecl->clearDescriptors(); COND_PRINT(env.DEBUG_DATA, "GATT discoverDescriptors Characteristic[%d/%d]: %s on %s", charIter, charCount, charDecl->toString().c_str(), toString().c_str()); @@ -1153,9 +1161,9 @@ bool BTGattHandler::discoverDescriptors(BTGattServiceRef & service) noexcept { if( pdu->getOpcode() == AttPDUMsg::Opcode::FIND_INFORMATION_RSP ) { const AttFindInfoRsp * p = static_cast<const AttFindInfoRsp*>(pdu.get()); - const int e_count = p->getElementCount(); + const size_type e_count = p->getElementCount(); - for(int e_iter=0; e_iter<e_count; e_iter++) { + for(size_type e_iter=0; e_iter<e_count; ++e_iter) { // handle: handle of Characteristic Descriptor. // value: Characteristic Descriptor UUID. const uint16_t cd_handle = p->getElementHandle(e_iter); @@ -1178,9 +1186,9 @@ bool BTGattHandler::discoverDescriptors(BTGattServiceRef & service) noexcept { break; } if( cd->isClientCharConfig() ) { - charDecl->clientCharConfigIndex = charDecl->descriptorList.size(); + charDecl->clientCharConfigIndex = (BTGattChar::ssize_type) charDecl->descriptorList.size(); } else if( cd->isUserDescription() ) { - charDecl->userDescriptionIndex = charDecl->descriptorList.size(); + charDecl->userDescriptionIndex = (BTGattChar::ssize_type) charDecl->descriptorList.size(); } charDecl->descriptorList.push_back(cd); COND_PRINT(env.DEBUG_DATA, "GATT CD discovered[%d/%d]: %s", e_iter, e_count, cd->toString().c_str()); @@ -1204,8 +1212,8 @@ bool BTGattHandler::discoverDescriptors(BTGattServiceRef & service) noexcept { return true; } -bool BTGattHandler::readDescriptorValue(BTGattDesc & desc, int expectedLength) noexcept { - COND_PRINT(env.DEBUG_DATA, "GATTHandler::readDescriptorValue expLen %d, desc %s", expectedLength, desc.toString().c_str()); +bool BTGattHandler::readDescriptorValue(BTGattDesc & desc, ssize_type expectedLength) noexcept { + COND_PRINT(env.DEBUG_DATA, "GATTHandler::readDescriptorValue expLen %zd, desc %s", (size_t)expectedLength, desc.toString().c_str()); const bool res = readValue(desc.handle, desc.value, expectedLength); if( !res ) { WORDY_PRINT("GATT readDescriptorValue error on desc%s within char%s from %s", @@ -1214,8 +1222,8 @@ bool BTGattHandler::readDescriptorValue(BTGattDesc & desc, int expectedLength) n return res; } -bool BTGattHandler::readCharacteristicValue(const BTGattChar & decl, jau::POctets & resValue, int expectedLength) noexcept { - COND_PRINT(env.DEBUG_DATA, "GATTHandler::readCharacteristicValue expLen %d, decl %s", expectedLength, decl.toString().c_str()); +bool BTGattHandler::readCharacteristicValue(const BTGattChar & decl, jau::POctets & resValue, ssize_type expectedLength) noexcept { + COND_PRINT(env.DEBUG_DATA, "GATTHandler::readCharacteristicValue expLen %zd, decl %s", (size_t)expectedLength, decl.toString().c_str()); const bool res = readValue(decl.value_handle, resValue, expectedLength); if( !res ) { WORDY_PRINT("GATT readCharacteristicValue error on char%s from %s", decl.toString().c_str(), toString().c_str()); @@ -1223,19 +1231,19 @@ bool BTGattHandler::readCharacteristicValue(const BTGattChar & decl, jau::POctet return res; } -bool BTGattHandler::readValue(const uint16_t handle, jau::POctets & res, int expectedLength) noexcept { +bool BTGattHandler::readValue(const uint16_t handle, jau::POctets & res, ssize_type expectedLength) noexcept { /* BT Core Spec v5.2: Vol 3, Part G GATT: 4.8.1 Read Characteristic Value */ /* BT Core Spec v5.2: Vol 3, Part G GATT: 4.8.3 Read Long Characteristic Value */ const std::lock_guard<std::recursive_mutex> lock(mtx_command); // RAII-style acquire and relinquish via destructor PERF2_TS_T0(); bool done=false; - int offset=0; + size_type offset=0; - COND_PRINT(env.DEBUG_DATA, "GATTHandler::readValue expLen %d, handle %s from %s", expectedLength, jau::to_hexstring(handle).c_str(), toString().c_str()); + COND_PRINT(env.DEBUG_DATA, "GATTHandler::readValue expLen %zd, handle %s from %s", (size_t)expectedLength, jau::to_hexstring(handle).c_str(), toString().c_str()); while(!done) { - if( 0 < expectedLength && expectedLength <= offset ) { + if( 0 < expectedLength && (size_type)expectedLength <= offset ) { break; // done } else if( 0 == expectedLength && 0 < offset ) { break; // done w/ only one request @@ -1425,8 +1433,8 @@ std::shared_ptr<GattGenericAccessSvc> BTGattHandler::getGenericAccess(jau::darra const std::lock_guard<std::recursive_mutex> lock(mtx_command); // RAII-style acquire and relinquish via destructor - for(size_t i=0; i<genericAccessCharDeclList.size(); i++) { - const BTGattChar & charDecl = *genericAccessCharDeclList.at(i); + for(auto & i : genericAccessCharDeclList) { + const BTGattChar & charDecl = *i; std::shared_ptr<BTGattService> service = charDecl.getServiceUnchecked(); if( nullptr == service || _GENERIC_ACCESS != *(service->type) ) { continue; @@ -1452,10 +1460,10 @@ std::shared_ptr<GattGenericAccessSvc> BTGattHandler::getGenericAccess(jau::darra } std::shared_ptr<GattGenericAccessSvc> BTGattHandler::getGenericAccess(jau::darray<BTGattServiceRef> & primServices) noexcept { - for(size_t i=0; i<primServices.size(); i++) { - BTGattServiceRef service = primServices.at(i); + for(auto & primService : primServices) { + BTGattServiceRef service = primService; if( _GENERIC_ACCESS == *service->type ) { - return getGenericAccess(primServices.at(i)->characteristicList); + return getGenericAccess(primService->characteristicList); } } return nullptr; @@ -1510,8 +1518,8 @@ std::shared_ptr<GattDeviceInformationSvc> BTGattHandler::getDeviceInformation(ja const std::lock_guard<std::recursive_mutex> lock(mtx_command); // RAII-style acquire and relinquish via destructor - for(size_t i=0; i<characteristicDeclList.size(); i++) { - const BTGattChar & charDecl = *characteristicDeclList.at(i); + for(auto & i : characteristicDeclList) { + const BTGattChar & charDecl = *i; std::shared_ptr<BTGattService> service = charDecl.getServiceUnchecked(); if( nullptr == service || _DEVICE_INFORMATION != *(service->type) ) { continue; @@ -1564,10 +1572,10 @@ std::shared_ptr<GattDeviceInformationSvc> BTGattHandler::getDeviceInformation(ja } std::shared_ptr<GattDeviceInformationSvc> BTGattHandler::getDeviceInformation(jau::darray<BTGattServiceRef> & primServices) noexcept { - for(size_t i=0; i<primServices.size(); i++) { - BTGattServiceRef service = primServices.at(i); + for(auto & primService : primServices) { + BTGattServiceRef service = primService; if( _DEVICE_INFORMATION == *service->type ) { - return getDeviceInformation(primServices.at(i)->characteristicList); + return getDeviceInformation(primService->characteristicList); } } return nullptr; diff --git a/src/direct_bt/BTGattServerHandler.cpp b/src/direct_bt/BTGattServerHandler.cpp index 9c2eb899..b9c049f6 100644 --- a/src/direct_bt/BTGattServerHandler.cpp +++ b/src/direct_bt/BTGattServerHandler.cpp @@ -56,10 +56,15 @@ extern "C" { using namespace direct_bt; class NopGattServerHandler : public BTGattHandler::GattServerHandler { + private: + void close_impl() noexcept {} + public: - NopGattServerHandler() noexcept {} + NopGattServerHandler() noexcept = default; + + ~NopGattServerHandler() override { close_impl(); } - void close() noexcept override {} + void close() noexcept override { close_impl(); } DBGattServer::Mode getMode() noexcept override { return DBGattServer::Mode::NOP; } @@ -107,10 +112,35 @@ class DBGattServerHandler : public BTGattHandler::GattServerHandler { jau::darray<AttPrepWrite> writeDataQueue; jau::darray<uint16_t> writeDataQueueHandles; + void close_impl() noexcept { + BTDeviceRef device = gh.getDeviceUnchecked(); + if( nullptr == device ) { + ERR_PRINT("null device: %s", gh.toString().c_str()); + } else { + int i=0; + jau::for_each_fidelity(gattServerData->listener(), [&](DBGattServer::ListenerRef &l) { + try { + l->disconnected(device); + } catch (std::exception &e) { + ERR_PRINT("%d/%zd: %s: Caught exception %s", + i+1, gattServerData->listener().size(), + gh.toString().c_str(), e.what()); + } + i++; + }); + } + writeDataQueue.clear(); + writeDataQueueHandles.clear(); + } + public: DBGattServerHandler(BTGattHandler& gh_, DBGattServerRef gsd) noexcept : gh(gh_), gattServerData(gsd) {} + ~DBGattServerHandler() override { close_impl(); } + + void close() noexcept override { close_impl(); } + private: bool hasServerHandle(const uint16_t handle) noexcept { for(DBGattServiceRef& s : gattServerData->getServices()) { @@ -322,27 +352,6 @@ class DBGattServerHandler : public BTGattHandler::GattServerHandler { public: - void close() noexcept override { - BTDeviceRef device = gh.getDeviceUnchecked(); - if( nullptr == device ) { - ERR_PRINT("null device: %s", gh.toString().c_str()); - } else { - int i=0; - jau::for_each_fidelity(gattServerData->listener(), [&](DBGattServer::ListenerRef &l) { - try { - l->disconnected(device); - } catch (std::exception &e) { - ERR_PRINT("%d/%zd: %s: Caught exception %s", - i+1, gattServerData->listener().size(), - gh.toString().c_str(), e.what()); - } - i++; - }); - } - writeDataQueue.clear(); - writeDataQueueHandles.clear(); - } - DBGattServer::Mode getMode() noexcept override { return DBGattServer::Mode::DB; } bool replyExchangeMTUReq(const AttExchangeMTU * pdu) noexcept override { @@ -719,38 +728,49 @@ class DBGattServerHandler : public BTGattHandler::GattServerHandler { req_group_type = 0; } - // const jau::nsize_t rspMaxSize = std::min<jau::nsize_t>(255, getUsedMTU()-2); AttFindByTypeValueRsp rsp(gh.getUsedMTU()); // maximum size - jau::nsize_t rspSize = 0; + // jau::nsize_t rspSize = 0; jau::nsize_t rspCount = 0; - const jau::nsize_t size = 2 + 2; + try { + // const jau::nsize_t size = 2 + 2; - for(DBGattServiceRef& s : gattServerData->getServices()) { - if( start_handle <= s->getHandle() && s->getHandle() <= end_handle ) { - if( ( ( GattAttributeType::PRIMARY_SERVICE == req_group_type && s->isPrimary() ) || - ( GattAttributeType::SECONDARY_SERVICE == req_group_type && !s->isPrimary() ) - ) && - s->getType()->equivalent(*att_value) ) - { - rsp.setElementHandles(rspCount, s->getHandle(), s->getEndHandle()); - rspSize += size; - ++rspCount; - COND_PRINT(gh.env.DEBUG_DATA, "GATT-Req: TYPEVALUE.4: %s -> %s from %s", pdu->toString().c_str(), rsp.toString().c_str(), gh.toString().c_str()); - return gh.send(rsp); // done + for(DBGattServiceRef& s : gattServerData->getServices()) { + if( start_handle <= s->getHandle() && s->getHandle() <= end_handle ) { + if( ( ( GattAttributeType::PRIMARY_SERVICE == req_group_type && s->isPrimary() ) || + ( GattAttributeType::SECONDARY_SERVICE == req_group_type && !s->isPrimary() ) + ) && + s->getType()->equivalent(*att_value) ) + { + rsp.setElementHandles(rspCount, s->getHandle(), s->getEndHandle()); + // rspSize += size; + ++rspCount; + COND_PRINT(gh.env.DEBUG_DATA, "GATT-Req: TYPEVALUE.4: %s -> %s from %s", pdu->toString().c_str(), rsp.toString().c_str(), gh.toString().c_str()); + return gh.send(rsp); // done + } } } + if( 0 < rspCount ) { // loop completed, elements added and all fitting in ATT_MTU + rsp.setElementCount(rspCount); + COND_PRINT(gh.env.DEBUG_DATA, "GATT-Req: TYPEVALUE.5: %s -> %s from %s", pdu->toString().c_str(), rsp.toString().c_str(), gh.toString().c_str()); + return gh.send(rsp); + } + } catch (const jau::ExceptionBase &e) { + ERR_PRINT("invalid att uuid: %s", e.message().c_str()); + } catch (...) { + ERR_PRINT("invalid att uuid: Unknown exception"); } - (void)rspSize; // not yet used - if( 0 < rspCount ) { // loop completed, elements added and all fitting in ATT_MTU - rsp.setElementCount(rspCount); - COND_PRINT(gh.env.DEBUG_DATA, "GATT-Req: TYPEVALUE.5: %s -> %s from %s", pdu->toString().c_str(), rsp.toString().c_str(), gh.toString().c_str()); - return gh.send(rsp); + try { + AttErrorRsp err(AttErrorRsp::ErrorCode::ATTRIBUTE_NOT_FOUND, pdu->getOpcode(), start_handle); + COND_PRINT(gh.env.DEBUG_DATA, "GATT-Req: TYPEVALUE.6: %s -> %s from %s", pdu->toString().c_str(), err.toString().c_str(), gh.toString().c_str()); + return gh.send(err); + } catch (const jau::ExceptionBase &e) { + ERR_PRINT("invalid att uuid: %s", e.message().c_str()); + } catch (...) { + ERR_PRINT("invalid att uuid: Unknown exception"); } - AttErrorRsp err(AttErrorRsp::ErrorCode::ATTRIBUTE_NOT_FOUND, pdu->getOpcode(), start_handle); - COND_PRINT(gh.env.DEBUG_DATA, "GATT-Req: TYPEVALUE.6: %s -> %s from %s", pdu->toString().c_str(), err.toString().c_str(), gh.toString().c_str()); - return gh.send(err); + return false; } bool replyReadByTypeReq(const AttReadByNTypeReq * pdu) noexcept override { @@ -814,6 +834,7 @@ class DBGattServerHandler : public BTGattHandler::GattServerHandler { ePDUOffset += c->getValueType()->getTypeSizeInt(); rspSize += size; ++rspCount; + (void)ePDUOffset; } } } @@ -928,16 +949,20 @@ class FwdGattServerHandler : public BTGattHandler::GattServerHandler { jau::darray<AttPrepWrite> writeDataQueue; jau::darray<uint16_t> writeDataQueueHandles; + void close_impl() noexcept { + writeDataQueue.clear(); + writeDataQueueHandles.clear(); + } + public: FwdGattServerHandler(BTGattHandler& gh_, BTDeviceRef fwdServer_) noexcept : gh(gh_), fwdServer(fwdServer_) { fwd_gh = fwdServer->getGattHandler(); } - void close() noexcept override { - writeDataQueue.clear(); - writeDataQueueHandles.clear(); - } + ~FwdGattServerHandler() override { close_impl(); } + + void close() noexcept override { close_impl(); } DBGattServer::Mode getMode() noexcept override { return DBGattServer::Mode::FWD; } diff --git a/src/direct_bt/BTManager.cpp b/src/direct_bt/BTManager.cpp index e20e67ac..f21eac48 100644 --- a/src/direct_bt/BTManager.cpp +++ b/src/direct_bt/BTManager.cpp @@ -516,6 +516,7 @@ void BTManager::close() noexcept { if( !allowClose.compare_exchange_strong(expConn, false) ) { // not open const bool mgmt_service_stopped = mgmt_reader_service.join(); // [data] race: wait until disconnecting thread has stopped service + // NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall) DBG_PRINT("BTManager::close: Not open: stopped %d, %s", mgmt_service_stopped, toString().c_str()); return; } @@ -968,7 +969,7 @@ bool BTManager::addDeviceToWhitelist(const uint16_t dev_id, const BDAddressAndTy return false; } -int BTManager::removeAllDevicesFromWhitelist() noexcept { +BTManager::size_type BTManager::removeAllDevicesFromWhitelist() noexcept { #if 0 jau::darray<std::shared_ptr<WhitelistElem>> whitelist_copy = whitelist; int count = 0; @@ -980,7 +981,7 @@ int BTManager::removeAllDevicesFromWhitelist() noexcept { ++count; } #else - int count = 0; + size_type count = 0; DBG_PRINT("BTManager::removeAllDevicesFromWhitelist.B: Start %d elements", count); whitelist.clear(); jau::for_each_const(adapters, [&](const std::shared_ptr<BTAdapter> & a) { @@ -990,8 +991,8 @@ int BTManager::removeAllDevicesFromWhitelist() noexcept { }); #endif - DBG_PRINT("BTManager::removeAllDevicesFromWhitelist: End: Removed %d elements, remaining %zd elements", - count, whitelist.size()); + DBG_PRINT("BTManager::removeAllDevicesFromWhitelist: End: Removed %zu elements, remaining %zd elements", + (size_t)count, whitelist.size()); return count; } @@ -1075,7 +1076,7 @@ bool BTManager::addMgmtEventCallback(const int dev_id, const MgmtEvent::Opcode o /* const bool added = */ l.push_back_unique(MgmtAdapterEventCallback(dev_id, opc, cb), _mgmtAdapterEventCallbackEqComp_ID_CB); return true; } -int BTManager::removeMgmtEventCallback(const MgmtEvent::Opcode opc, const MgmtEventCallback &cb) noexcept { +BTManager::size_type BTManager::removeMgmtEventCallback(const MgmtEvent::Opcode opc, const MgmtEventCallback &cb) noexcept { if( !isValidMgmtEventCallbackListsIndex(opc) ) { ERR_PRINT("Opcode %s >= %d", MgmtEvent::getOpcodeString(opc).c_str(), mgmtAdapterEventCallbackLists.size()); return 0; @@ -1084,14 +1085,13 @@ int BTManager::removeMgmtEventCallback(const MgmtEvent::Opcode opc, const MgmtEv return l.erase_matching( MgmtAdapterEventCallback( 0, MgmtEvent::Opcode::INVALID, cb ), true /* all_matching */, _mgmtAdapterEventCallbackEqComp_CB); } -int BTManager::removeMgmtEventCallback(const int dev_id) noexcept { +BTManager::size_type BTManager::removeMgmtEventCallback(const int dev_id) noexcept { if( 0 > dev_id ) { // skip dev_id -1 case, use clearAllMgmtEventCallbacks() here return 0; } - int count = 0; - for(size_t i=0; i<mgmtAdapterEventCallbackLists.size(); i++) { - MgmtAdapterEventCallbackList &l = mgmtAdapterEventCallbackLists[i]; + size_type count = 0; + for(auto & l : mgmtAdapterEventCallbackLists) { count += l.erase_matching( MgmtAdapterEventCallback( dev_id, MgmtEvent::Opcode::INVALID, MgmtEventCallback() ), true /* all_matching */, _mgmtAdapterEventCallbackEqComp_ID); } @@ -1105,8 +1105,8 @@ void BTManager::clearMgmtEventCallbacks(const MgmtEvent::Opcode opc) noexcept { mgmtAdapterEventCallbackLists[static_cast<uint16_t>(opc)].clear(); } void BTManager::clearAllCallbacks() noexcept { - for(size_t i=0; i<mgmtAdapterEventCallbackLists.size(); i++) { - mgmtAdapterEventCallbackLists[i].clear(); + for(auto & mgmtAdapterEventCallbackList : mgmtAdapterEventCallbackLists) { + mgmtAdapterEventCallbackList.clear(); } mgmtChangedAdapterSetCallbackList.clear(); } @@ -1185,7 +1185,7 @@ void BTManager::addChangedAdapterSetCallback(const ChangedAdapterSetCallback & l (*l_p)(true /* added */, ai); }); } -int BTManager::removeChangedAdapterSetCallback(const ChangedAdapterSetCallback & l) { +BTManager::size_type BTManager::removeChangedAdapterSetCallback(const ChangedAdapterSetCallback & l) { return mgmtChangedAdapterSetCallbackList.erase_matching(l, true /* all_matching */, _changedAdapterSetCallbackEqComp); } @@ -1193,13 +1193,13 @@ void BTManager::addChangedAdapterSetCallback(ChangedAdapterSetFunc f) { addChangedAdapterSetCallback( ChangedAdapterSetCallback( jau::bind_free(f) ) ); } -int BTManager::removeChangedAdapterSetCallback(ChangedAdapterSetFunc f) { +BTManager::size_type BTManager::removeChangedAdapterSetCallback(ChangedAdapterSetFunc f) { ChangedAdapterSetCallback l( jau::bind_free(f) ); return mgmtChangedAdapterSetCallbackList.erase_matching(l, true /* all_matching */, _changedAdapterSetCallbackEqComp); } -int BTManager::removeAllChangedAdapterSetCallbacks() noexcept { - const int count = mgmtChangedAdapterSetCallbackList.size(); +BTManager::size_type BTManager::removeAllChangedAdapterSetCallbacks() noexcept { + const size_type count = mgmtChangedAdapterSetCallbackList.size(); mgmtChangedAdapterSetCallbackList.clear(); return count; } diff --git a/src/direct_bt/BTTypes0.cpp b/src/direct_bt/BTTypes0.cpp index ad053008..135271e7 100644 --- a/src/direct_bt/BTTypes0.cpp +++ b/src/direct_bt/BTTypes0.cpp @@ -690,8 +690,7 @@ EIRDataType EInfoReport::set(const EInfoReport& eir) noexcept { if( eir.isSet( EIRDataType::SERVICE_UUID) ) { const jau::darray<std::shared_ptr<const jau::uuid_t>>& services_ = eir.getServices(); bool added = false; - for(size_t j=0; j<services_.size(); j++) { - const std::shared_ptr<const jau::uuid_t> uuid = services_[j]; + for(auto uuid : services_) { added = addService(uuid) | added; } if( added ) { @@ -748,13 +747,13 @@ EIRDataType EInfoReport::set(const EInfoReport& eir) noexcept { return res; } -int EInfoReport::findService(const jau::uuid_t& uuid) const noexcept +EInfoReport::ssize_type EInfoReport::findService(const jau::uuid_t& uuid) const noexcept { - const size_t size = services.size(); - for (size_t i = 0; i < size; i++) { + const size_type size = services.size(); + for (size_type i = 0; i < size; ++i) { const std::shared_ptr<const jau::uuid_t> & e = services[i]; if ( nullptr != e && uuid.equivalent(*e) ) { - return i; + return (ssize_type)i; } } return -1; @@ -908,8 +907,7 @@ std::string EInfoReport::toString(const bool includeServices) const noexcept { if( includeServices && services.size() > 0 && isSet(EIRDataType::SERVICE_UUID) ) { out.append("\n"); - for(auto it = services.begin(); it != services.end(); it++) { - std::shared_ptr<const jau::uuid_t> p = *it; + for(auto p : services) { out.append(" ").append(p->toUUID128String()).append(", ").append(std::to_string(static_cast<int>(p->getTypeSize()))).append(" bytes\n"); } } @@ -950,7 +948,7 @@ bool EInfoReport::operator==(const EInfoReport& o) const noexcept { } std::string EInfoReport::getDeviceIDModalias() const noexcept { - char *cstr = NULL; + char *cstr = nullptr; int length; switch (did_source) { @@ -965,7 +963,7 @@ std::string EInfoReport::getDeviceIDModalias() const noexcept { break; } if( 0 >= length ) { - if( NULL != cstr ) { + if( nullptr != cstr ) { free(cstr); } return std::string(); @@ -1206,8 +1204,7 @@ jau::nsize_t EInfoReport::write_data(EIRDataType write_mask, uint8_t * data, jau } if( is_set(mask, EIRDataType::SERVICE_UUID) ) { jau::darray<std::shared_ptr<const jau::uuid_t>> uuid16s, uuid32s, uuid128s; - for(auto it = services.begin(); it != services.end(); it++) { - std::shared_ptr<const jau::uuid_t> p = *it; + for(auto p : services) { switch( p->getTypeSizeInt() ) { case 2: uuid16s.push_back(p); @@ -1231,8 +1228,7 @@ jau::nsize_t EInfoReport::write_data(EIRDataType write_mask, uint8_t * data, jau count += ad_sz + 1; *data_i++ = ad_sz; *data_i++ = direct_bt::number(services_complete ? GAP_T::UUID16_COMPLETE : GAP_T::UUID16_INCOMPLETE); - for(auto it = uuid16s.begin(); it != uuid16s.end(); it++) { - std::shared_ptr<const jau::uuid_t> p = *it; + for(auto p : uuid16s) { data_i += p->put(data_i, 0, true /* le */); } } @@ -1245,8 +1241,7 @@ jau::nsize_t EInfoReport::write_data(EIRDataType write_mask, uint8_t * data, jau count += ad_sz + 1; *data_i++ = ad_sz; *data_i++ = direct_bt::number(services_complete ? GAP_T::UUID32_COMPLETE : GAP_T::UUID32_INCOMPLETE); - for(auto it = uuid32s.begin(); it != uuid32s.end(); it++) { - std::shared_ptr<const jau::uuid_t> p = *it; + for(auto p : uuid32s) { data_i += p->put(data_i, 0, true /* le */); } } @@ -1259,8 +1254,7 @@ jau::nsize_t EInfoReport::write_data(EIRDataType write_mask, uint8_t * data, jau count += ad_sz + 1; *data_i++ = ad_sz; *data_i++ = direct_bt::number(services_complete ? GAP_T::UUID128_COMPLETE : GAP_T::UUID128_INCOMPLETE); - for(auto it = uuid128s.begin(); it != uuid128s.end(); it++) { - std::shared_ptr<const jau::uuid_t> p = *it; + for(auto p : uuid128s) { data_i += p->put(data_i, 0, true /* le */); } } diff --git a/src/direct_bt/DBGattServer.cpp b/src/direct_bt/DBGattServer.cpp index fd37ad6d..80a136e1 100644 --- a/src/direct_bt/DBGattServer.cpp +++ b/src/direct_bt/DBGattServer.cpp @@ -96,7 +96,7 @@ bool DBGattServer::removeListener(ListenerRef l) { ERR_PRINT("Listener ref is null"); return false; } - const int count = listenerList.erase_matching(l, false /* all_matching */, _listenerRefEqComparator); + const auto count = listenerList.erase_matching(l, false /* all_matching */, _listenerRefEqComparator); return count > 0; } diff --git a/src/direct_bt/HCIComm.cpp b/src/direct_bt/HCIComm.cpp index 192d7b0f..c3ab62aa 100644 --- a/src/direct_bt/HCIComm.cpp +++ b/src/direct_bt/HCIComm.cpp @@ -156,8 +156,8 @@ jau::snsize_t HCIComm::read(uint8_t* buffer, const jau::nsize_t capacity, const if( !timeout.is_zero() ) { struct pollfd p; - int n; - const int32_t timeoutMS = timeout.to_num_of(jau::fractions_i64::milli); + int n = 1; + const int32_t timeoutMS = (int32_t) timeout.to_num_of(jau::fractions_i64::milli); p.fd = socket_descriptor; p.events = POLLIN; while ( !interrupted() && (n = ::poll(&p, 1, timeoutMS)) < 0 ) { diff --git a/src/direct_bt/HCIHandler.cpp b/src/direct_bt/HCIHandler.cpp index 6af291ca..82f5f27d 100644 --- a/src/direct_bt/HCIHandler.cpp +++ b/src/direct_bt/HCIHandler.cpp @@ -101,9 +101,14 @@ HCIHandler::HCIConnectionRef HCIHandler::addOrUpdateHCIConnection(jau::darray<HC return conn; // done } } - HCIConnectionRef res( new HCIConnection(addressAndType, handle) ); - list.push_back( res ); - return res; + try { + HCIConnectionRef res( std::make_shared<HCIConnection>(addressAndType, handle) ); + list.push_back( res ); + return res; + } catch (const std::bad_alloc &e) { + ABORT("Error: bad_alloc: HCIConnectionRef allocation failed"); + return nullptr; // unreachable + } } HCIHandler::HCIConnectionRef HCIHandler::findHCIConnection(jau::darray<HCIConnectionRef> &list, const BDAddressAndType& addressAndType) noexcept { @@ -142,18 +147,17 @@ HCIHandler::HCIConnectionRef HCIHandler::removeTrackerConnection(const HCIConnec } return nullptr; } -int HCIHandler::countPendingTrackerConnections() noexcept { +HCIHandler::size_type HCIHandler::countPendingTrackerConnections() noexcept { const std::lock_guard<std::recursive_mutex> lock(mtx_connectionList); // RAII-style acquire and relinquish via destructor - int count = 0; - for (auto it = connectionList.begin(); it != connectionList.end(); it++) { - HCIConnectionRef e = *it; + size_type count = 0; + for (auto e : connectionList) { if ( e->getHandle() == 0 ) { count++; } } return count; } -int HCIHandler::getTrackerConnectionCount() noexcept { +HCIHandler::size_type HCIHandler::getTrackerConnectionCount() noexcept { const std::lock_guard<std::recursive_mutex> lock(mtx_connectionList); // RAII-style acquire and relinquish via destructor return connectionList.size(); } @@ -303,9 +307,14 @@ std::unique_ptr<MgmtEvent> HCIHandler::translate(HCIEvent& ev) noexcept { advertisingEnabled = false; return std::make_unique<MgmtEvtDeviceConnected>(dev_id, conn->getAddressAndType(), conn->getHandle()); } else { - std::unique_ptr<MgmtEvent> res( new MgmtEvtDeviceConnectFailed(dev_id, conn->getAddressAndType(),status) ); - removeTrackerConnection(conn); - return res; + try { + std::unique_ptr<MgmtEvent> res( std::make_unique<MgmtEvtDeviceConnectFailed>(dev_id, conn->getAddressAndType(),status) ); + removeTrackerConnection(conn); + return res; + } catch (const std::bad_alloc &e) { + ABORT("Error: bad_alloc: MgmtEvtDeviceConnectFailedRef allocation failed"); + return nullptr; // unreachable + } } } case HCIEventType::DISCONN_COMPLETE: { @@ -1284,9 +1293,9 @@ HCIStatusCode HCIHandler::le_create_conn(const EUI48 &peer_bdaddr, dev_id, 1.25f * (float)conn_interval_min, 1.25f * (float)conn_interval_max, conn_latency, supervision_timeout*10, toString().c_str()); - int pendingConnections = countPendingTrackerConnections(); + size_type pendingConnections = countPendingTrackerConnections(); if( 0 < pendingConnections ) { - DBG_PRINT("HCIHandler<%u>::le_create_conn: %d connections pending - %s", dev_id, pendingConnections, toString().c_str()); + DBG_PRINT("HCIHandler<%u>::le_create_conn: %zu connections pending - %s", dev_id, (size_t)pendingConnections, toString().c_str()); jau::fraction_i64 td = 0_s; while( env.HCI_COMMAND_COMPLETE_REPLY_TIMEOUT > td && 0 < pendingConnections ) { sleep_for(env.HCI_COMMAND_POLL_PERIOD); @@ -1294,7 +1303,7 @@ HCIStatusCode HCIHandler::le_create_conn(const EUI48 &peer_bdaddr, pendingConnections = countPendingTrackerConnections(); } if( 0 < pendingConnections ) { - WARN_PRINT("%d connections pending after %" PRIi64 " ms - %s", pendingConnections, td.to_ms(), toString().c_str()); + WARN_PRINT("%zu connections pending after %" PRIi64 " ms - %s", (size_t)pendingConnections, td.to_ms(), toString().c_str()); } else { DBG_PRINT("HCIHandler<%u>::le_create_conn: pending connections resolved after %" PRIi64 " ms - %s", dev_id, td.to_ms(), toString().c_str()); } @@ -1413,9 +1422,9 @@ HCIStatusCode HCIHandler::create_conn(const EUI48 &bdaddr, cp->clock_offset = jau::cpu_to_le(clock_offset); cp->role_switch = role_switch; - int pendingConnections = countPendingTrackerConnections(); + size_type pendingConnections = countPendingTrackerConnections(); if( 0 < pendingConnections ) { - DBG_PRINT("HCIHandler<%u>::create_conn: %d connections pending - %s", dev_id, pendingConnections, toString().c_str()); + DBG_PRINT("HCIHandler<%u>::create_conn: %zu connections pending - %s", dev_id, (size_t)pendingConnections, toString().c_str()); jau::fraction_i64 td = 0_s; while( env.HCI_COMMAND_COMPLETE_REPLY_TIMEOUT > td && 0 < pendingConnections ) { sleep_for(env.HCI_COMMAND_POLL_PERIOD); @@ -1423,7 +1432,7 @@ HCIStatusCode HCIHandler::create_conn(const EUI48 &bdaddr, pendingConnections = countPendingTrackerConnections(); } if( 0 < pendingConnections ) { - WARN_PRINT("%d connections pending after %" PRIi64 " ms - %s", pendingConnections, td.to_ms(), toString().c_str()); + WARN_PRINT("%zu connections pending after %" PRIi64 " ms - %s", (size_t)pendingConnections, td.to_ms(), toString().c_str()); } else { DBG_PRINT("HCIHandler<%u>::create_conn: pending connections resolved after %" PRIi64 " ms - %s", dev_id, td.to_ms(), toString().c_str()); } @@ -1776,9 +1785,9 @@ HCIStatusCode HCIHandler::le_enable_adv(const bool enable) noexcept { WARN_PRINT("Not allowed (scan enabled): %s", toString().c_str()); return HCIStatusCode::COMMAND_DISALLOWED; } - const int connCount = getTrackerConnectionCount(); + const size_type connCount = getTrackerConnectionCount(); if( 0 < connCount ) { - WARN_PRINT("Not allowed (%d connections open/pending): %s", connCount, toString().c_str()); + WARN_PRINT("Not allowed (%zu connections open/pending): %s", (size_t)connCount, toString().c_str()); return HCIStatusCode::COMMAND_DISALLOWED; } } @@ -1854,9 +1863,9 @@ HCIStatusCode HCIHandler::le_start_adv(const EInfoReport &eir, WARN_PRINT("Not allowed (scan enabled): %s", toString().c_str()); return HCIStatusCode::COMMAND_DISALLOWED; } - const int connCount = getTrackerConnectionCount(); + const size_type connCount = getTrackerConnectionCount(); if( 0 < connCount ) { - WARN_PRINT("Not allowed (%d connections open/pending): %s", connCount, toString().c_str()); + WARN_PRINT("Not allowed (%zu connections open/pending): %s", (size_t)connCount, toString().c_str()); return HCIStatusCode::COMMAND_DISALLOWED; } @@ -2066,7 +2075,7 @@ bool HCIHandler::addMgmtEventCallback(const MgmtEvent::Opcode opc, const MgmtEve /* const bool added = */ l.push_back_unique(cb, _mgmtEventCallbackEqComparator); return true; } -int HCIHandler::removeMgmtEventCallback(const MgmtEvent::Opcode opc, const MgmtEventCallback &cb) noexcept { +HCIHandler::size_type HCIHandler::removeMgmtEventCallback(const MgmtEvent::Opcode opc, const MgmtEventCallback &cb) noexcept { if( !isValidMgmtEventCallbackListsIndex(opc) ) { ERR_PRINT("Opcode %s >= %d - %s", MgmtEvent::getOpcodeString(opc).c_str(), mgmtEventCallbackLists.size(), toString().c_str()); return 0; @@ -2082,8 +2091,8 @@ void HCIHandler::clearMgmtEventCallbacks(const MgmtEvent::Opcode opc) noexcept { mgmtEventCallbackLists[static_cast<uint16_t>(opc)].clear(); } void HCIHandler::clearAllCallbacks() noexcept { - for(size_t i=0; i<mgmtEventCallbackLists.size(); i++) { - mgmtEventCallbackLists[i].clear(); + for(auto & mgmtEventCallbackList : mgmtEventCallbackLists) { + mgmtEventCallbackList.clear(); } hciSMPMsgCallbackList.clear(); } @@ -2099,7 +2108,7 @@ static HCISMPMsgCallbackList::equal_comparator _changedHCISMPMsgCallbackEqComp = void HCIHandler::addSMPMsgCallback(const HCISMPMsgCallback & l) { hciSMPMsgCallbackList.push_back(l); } -int HCIHandler::removeSMPMsgCallback(const HCISMPMsgCallback & l) { +HCIHandler::size_type HCIHandler::removeSMPMsgCallback(const HCISMPMsgCallback & l) { return hciSMPMsgCallbackList.erase_matching(l, true /* all_matching */, _changedHCISMPMsgCallbackEqComp); } diff --git a/src/direct_bt/L2CAPComm.cpp b/src/direct_bt/L2CAPComm.cpp index 5cd14fda..cb8bbc22 100644 --- a/src/direct_bt/L2CAPComm.cpp +++ b/src/direct_bt/L2CAPComm.cpp @@ -394,7 +394,7 @@ failure: return false; } -bool L2CAPClient::close() noexcept { +bool L2CAPClient::close_impl() noexcept { bool expOpen = true; // C++11, exp as value since C++20 if( !is_open_.compare_exchange_strong(expOpen, false) ) { DBG_PRINT("L2CAPClient::close: Not connected: dev_id %u, dd %d, %s, psm %s, cid %s; %s", @@ -543,7 +543,7 @@ jau::snsize_t L2CAPClient::read(uint8_t* buffer, const jau::nsize_t capacity) no if( timeoutMS ) { struct pollfd p; - int n; + int n = 1; p.fd = socket_; p.events = POLLIN; while ( is_open_ && !interrupted() && ( n = ::poll( &p, 1, timeoutMS ) ) < 0 ) { @@ -770,7 +770,7 @@ failure: return false; } -bool L2CAPServer::close() noexcept { +bool L2CAPServer::close_impl() noexcept { bool expOpen = true; // C++11, exp as value since C++20 if( !is_open_.compare_exchange_strong(expOpen, false) ) { DBG_PRINT("L2CAPServer::close: Not connected: dev_id %u, dd %d, psm %s, cid %s, local %s", diff --git a/src/direct_bt/SMPHandler.cpp b/src/direct_bt/SMPHandler.cpp index 40c3b4a5..469886f0 100644 --- a/src/direct_bt/SMPHandler.cpp +++ b/src/direct_bt/SMPHandler.cpp @@ -300,14 +300,14 @@ std::unique_ptr<const SMPPDUMsg> SMPHandler::sendWithReply(const SMPPDUMsg & msg * SMPSecurityReqCallback handling */ -static SMPSecurityReqCallbackList::equal_comparator _changedSMPSecurityReqCallbackEqComp = - [](const SMPSecurityReqCallback& a, const SMPSecurityReqCallback& b) -> bool { return a == b; }; +static SMPHandler::SMPSecurityReqCallbackList::equal_comparator _changedSMPSecurityReqCallbackEqComp = + [](const SMPHandler::SMPSecurityReqCallback& a, const SMPHandler::SMPSecurityReqCallback& b) -> bool { return a == b; }; void SMPHandler::addSMPSecurityReqCallback(const SMPSecurityReqCallback & l) { smpSecurityReqCallbackList.push_back(l); } -int SMPHandler::removeSMPSecurityReqCallback(const SMPSecurityReqCallback & l) { +SMPHandler::size_type SMPHandler::removeSMPSecurityReqCallback(const SMPSecurityReqCallback & l) { return smpSecurityReqCallbackList.erase_matching(l, true /* all_matching */, _changedSMPSecurityReqCallbackEqComp); } diff --git a/src/direct_bt/SMPKeyBin.cpp b/src/direct_bt/SMPKeyBin.cpp index e0f8be85..8e34b799 100644 --- a/src/direct_bt/SMPKeyBin.cpp +++ b/src/direct_bt/SMPKeyBin.cpp @@ -23,6 +23,7 @@ */ #include <cstring> +#include <limits> #include <string> #include <memory> #include <cstdint> @@ -169,6 +170,7 @@ std::string SMPKeyBin::toString() const noexcept { res += csrk_init.toString(); comma = true; } + // NOLINTBEGIN(clang-analyzer-deadcode.DeadStores) if( hasLKInit() ) { if( comma ) { res += ", "; @@ -204,6 +206,7 @@ std::string SMPKeyBin::toString() const noexcept { comma = true; } res += "], "; + // NOLINTEND(clang-analyzer-deadcode.DeadStores) } res += "ver["+jau::to_hexstring(version)+", ok "+std::to_string( isVersionValid() )+ "], size["+std::to_string(size); @@ -213,7 +216,7 @@ std::string SMPKeyBin::toString() const noexcept { res += ", valid "+std::to_string( isSizeValid() )+ "], "; { - jau::fraction_timespec t0( ts_creation_sec, 0 ); + jau::fraction_timespec t0( (int64_t) std::min<uint64_t>(ts_creation_sec, std::numeric_limits<int64_t>::max()), 0 ); res += t0.to_iso8601_string(); } res += ", valid "+std::to_string( isValid() )+"]"; diff --git a/src/direct_bt/ieee11073/DataTypes.cpp b/src/direct_bt/ieee11073/DataTypes.cpp index 0cb47265..5473a225 100644 --- a/src/direct_bt/ieee11073/DataTypes.cpp +++ b/src/direct_bt/ieee11073/DataTypes.cpp @@ -41,7 +41,7 @@ AbsoluteTime::AbsoluteTime(const uint8_t * data_le, const int size) { } int i=0; if( 2 > size ) return; - year = data_le[i+0] | data_le[i+1] << 8; + year = (int16_t) ( data_le[i+0] | data_le[i+1] << 8 ); i+=2; if( 3 > size ) return; month = static_cast<int8_t>(data_le[i++]); @@ -76,12 +76,14 @@ static const uint32_t FIRST_S_RESERVED_VALUE = FloatTypes::ReservedSFloatValues: static const float reserved_float_values[5] = {INFINITY, NAN, NAN, NAN, -INFINITY}; +using namespace jau::int_literals; + float FloatTypes::float16_IEEE11073_to_IEEE754(const uint16_t raw_bt_float16_le) { uint16_t mantissa = raw_bt_float16_le & 0x0FFF; - int8_t exponent = raw_bt_float16_le >> 12; + int8_t exponent = (int8_t) ( ( raw_bt_float16_le >> 12 ) & 0xFF ); if( exponent >= 0x0008) { - exponent = - ( (0x000F + 1) - exponent ); + exponent = (int8_t) ( - ( (0x000F + 1) - (int)exponent ) ); } if( mantissa >= FIRST_S_RESERVED_VALUE && @@ -91,12 +93,12 @@ float FloatTypes::float16_IEEE11073_to_IEEE754(const uint16_t raw_bt_float16_le) if ( mantissa >= 0x0800 ) { mantissa = - ( ( 0x0FFF + 1 ) - mantissa ); } - return mantissa * powf(10.0f, exponent); + return (float)mantissa * ::powf(10.0f, (float)exponent); } float FloatTypes::float32_IEEE11073_to_IEEE754(const uint32_t raw_bt_float32_le) { - int32_t mantissa = raw_bt_float32_le & 0xFFFFFF; - int8_t expoent = raw_bt_float32_le >> 24; + int32_t mantissa = (int32_t) ( raw_bt_float32_le & 0xFFFFFF ); + int8_t exponent = (int8_t) ( ( raw_bt_float32_le >> 24 ) & 0xFF ); if( mantissa >= FIRST_RESERVED_VALUE && mantissa <= ReservedFloatValues::MDER_NEGATIVE_INFINITY ) { @@ -105,5 +107,5 @@ float FloatTypes::float32_IEEE11073_to_IEEE754(const uint32_t raw_bt_float32_le) if( mantissa >= 0x800000 ) { mantissa = - ( ( 0xFFFFFF + 1 ) - mantissa ); } - return mantissa * powf(10.0f, expoent); + return (float)mantissa * ::powf(10.0f, (float)exponent); } |