<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by T Asato on Medium]]></title>
        <description><![CDATA[Stories by T Asato on Medium]]></description>
        <link>https://medium.com/@futail2a?source=rss-96e4227f1453------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*J2L_xpFT-MILPN-Kglkerw.jpeg</url>
            <title>Stories by T Asato on Medium</title>
            <link>https://medium.com/@futail2a?source=rss-96e4227f1453------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 04:46:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@futail2a/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Comparison of Rust and C++ variable/function call]]></title>
            <link>https://medium.com/@futail2a/comparison-of-rust-and-c-variable-function-call-99891679105f?source=rss-96e4227f1453------2</link>
            <guid isPermaLink="false">https://medium.com/p/99891679105f</guid>
            <dc:creator><![CDATA[T Asato]]></dc:creator>
            <pubDate>Tue, 20 Jan 2026 12:46:50 GMT</pubDate>
            <atom:updated>2026-01-20T12:46:50.031Z</atom:updated>
            <content:encoded><![CDATA[<h3>Motivation</h3><p>Recentrly I’m studying Rust just for my interest.</p><p>But I’m little bit confused how to define variable and pass it to function, because appearnce is similar with C++.</p><p>For my study I summarized the comparison usage of Rust and C++ variable and function call. <br>(Note that accuracy would be sacrificed because just compare them from usage point of view.)</p><h3>Variable</h3><p>Rust variables behave similarly to const variable in C++, i.e. you cannot change assumed value later.<br>(Rust also has <em>const </em>keyword, but it is used slightly different from normal unmutable variables)</p><p>If you want to change their value, you must add <em>mut </em>when declaring it.<br>Also, even if you don’t declare a type for a variable, the type will be assumed based on the assigned value, similar to <em>auto </em>in C++.</p><pre>fn main() {<br>    let x: i32 = 1; // C++, const int x = 1;<br>    let mut y = 1; // C++, auto y = 1; y += 1;<br>    y += 1;<br>    <br>    println!(&quot;{}, {}&quot;,x, y);<br>}</pre><h3>Function call</h3><h4>Move semantics</h4><p>Move semantics is an operation that moves the data contained in one variable to another variable.</p><p>In C++,</p><ul><li>Define a constructor or assignment operator that takes an rvalue reference type as an argument for the type you want to support move, and implement the data movement within it.</li><li>The caller can cast the variable to an rvalue reference type by calling std::move() on it.</li><li>If the function implements move semantics, the move will be performed.</li></ul><p>In other words, even if you pass a variable casting by std::move(), the move will not occur unless the function supports move semantics.</p><p>It means that the moved variable may change value or be deleted in the future, so you can still access the variable after it’s been moved (though this is not recommended).</p><p>In C++, it is not common to write a function that takes an rvalue reference as an argument other than a constructor or assignment operator, but it is possible to write a function that performs a move within the function as shown below.</p><pre>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br>using namespace std;<br><br>void print_string(string&amp;&amp; s){<br>    string y = &quot;&quot;;<br>    y = move(s);<br>    y.insert(y.size(),&quot; pushed&quot;);<br>    cout &lt;&lt; y &lt;&lt; endl; // Hello pushed<br>}<br>int main(){<br>    string x = &quot;Hello&quot;;<br>    print_string(move(x));<br>    cout &lt;&lt; x &lt;&lt; endl; // C++ allow to access moved variable but valid but unspecified state<br>}</pre><p>In Rust, when you pass a value to a function, a move occurs (it is called a transfer of ownership).</p><ul><li>But some primitive type like i32 will be copied and not moved</li></ul><p>Also, variables that have been moved cannot be accessed, so Rust is safer than C++.</p><pre>fn print_string(s: String) {<br>    println!(&quot;{}&quot;, s); // Hello<br>}<br>fn main() {<br>    let x = String::from(&quot;Hello&quot;);<br>    print_string(x);<br>    // println!(&quot;{}&quot;, x); // NG in Rust<br>}</pre><h4>Pass by reference with const</h4><p>In C++, when the value of a variable does not change but the cost of copying is high, you can pass it by reference with const.</p><pre>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br>using namespace std;<br>void print_string(const string&amp; s){<br>     cout &lt;&lt; s &lt;&lt; endl; <br>}<br><br>int main(){<br>    string x = &quot;Hello&quot;;<br>    print_string(x);<br>    cout &lt;&lt; x &lt;&lt; endl;<br>}</pre><p>In Rust, if you pass a reference of variable, you can access it after the function (called borrowing in Rust).</p><pre>fn print_string(s: &amp;String) {<br>    println!(&quot;{}&quot;, s);<br>}<br><br>fn main() {<br>    let x = String::from(&quot;hello&quot;);<br>    print_string(&amp;x);<br>    println!(&quot;{}&quot;, x); // OK<br>}</pre><p><strong>Notice: <br></strong>Some textbook explains that it is called “pass by reference”.</p><p>In Rust, arguments and parameter are the not same entities, so strictly speaking, it is not “pass by reference”.</p><p>In the Rust tutorial, parameter <em>s</em> is an entity which has a reference to ptr of another entity <em>s1</em>, i.e. <em>s</em> is not a alias of <em>s1</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*53zY5aIW2X6RqfFa" /></figure><p><a href="https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html">The Rust Programming Language</a></p><h4>Pass by reference</h4><p>In C++, if you want to change the variable in the function to which you pass it, you use pass by reference without adding const.</p><pre>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br>using namespace std;<br><br>void print_string(string&amp; s){<br>    s.insert(s.size(),&quot; pushed&quot;);<br>    cout &lt;&lt; s &lt;&lt; endl; <br>}<br>int main(){<br>    string x = &quot;Hello&quot;;<br>    print_string(x);<br>    cout &lt;&lt; x &lt;&lt; endl;<br>}</pre><p>In Rust, as mentioned above, you cannot change a value by simply passing a reference.</p><p>If you want to change the value at the destination, you need to add <em>mut </em>to the type of the variable and parameter you are passing to make it a mutable reference.</p><pre>fn print_string(s: &amp;mut String) {<br>    s.push_str(&quot; pushed&quot;);<br>    println!(&quot;{}&quot;, s);<br>}<br><br>fn main() {<br>    let mut x = String::from(&quot;hello&quot;);<br>    print_string(&amp;mut x);<br>    println!(&quot;{}&quot;, x);<br>}</pre><h4>Pass by value</h4><p>When you pass a variable by value to a function in C++, the variable is copied at the destination.</p><pre>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br>using namespace std;<br><br>void print_string(string s){<br>    s.insert(s.size(),&quot; pushed&quot;);<br>    cout &lt;&lt; s &lt;&lt; endl; // Hello pushed<br>}<br>int main(){<br>    string x = &quot;Hello&quot;;<br>    print_string(x);<br>    cout &lt;&lt; x &lt;&lt; endl;  // Hello<br>}</pre><p>`However, as mentioned above, when you pass a variable to a function in Rust, it is moved, so (basically) you cannot access that variable later.</p><p>Therefore, you need to use clone() to pass a copy of the variable to the function.</p><pre>fn print_string(mut s: String) {<br>    s.push_str(&quot; pushed&quot;);<br>    println!(&quot;{}&quot;, s); // Hello pushed<br>}<br><br>fn main() {<br>    let x = String::from(&quot;Hello&quot;);<br>    print_string(x.clone());<br>    println!(&quot;{}&quot;, x); // Hello<br>}</pre><p>However, some primitive types, such as i32, are automatically copied so no need to do this.</p><h3>Summary</h3><h4>Variable</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*WAhmnB694sQKvCSDlja7Kw.png" /></figure><h4>Function call</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aLljDCpoTJMsSSF7XVtA8Q.png" /></figure><p>* Rust doesn’t have pass by reference, see section pass by referece with const</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99891679105f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Run CI on GitHub and show Test Coverage]]></title>
            <link>https://medium.com/@futail2a/run-ci-on-github-and-show-test-coverage-e9f35aeedd97?source=rss-96e4227f1453------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9f35aeedd97</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[lcov]]></category>
            <category><![CDATA[codecov]]></category>
            <category><![CDATA[google-test]]></category>
            <dc:creator><![CDATA[T Asato]]></dc:creator>
            <pubDate>Sun, 28 Dec 2025 10:51:42 GMT</pubDate>
            <atom:updated>2025-12-28T10:51:42.048Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bacground</h3><p>In the previous post, I introduced SW unit testing tool (Google Test) into my private project.</p><p>Today, I want to..</p><ul><li>Run unit tests on GitHub when I push a commit</li><li>When tests are passed, show the latest coverage on the README</li></ul><h3>GithubActions</h3><p>GitHub provides a CI/CD tool called “Github Actions”, which can run jobs on the GitHub’s runner environment triggered by specific events, like push, pull request creation</p><p>If you use GitHub Actions for Public repository, you can use it for free</p><h4><strong>Set Up</strong></h4><p>Create .github/workflows/ directories from project root directory</p><p>Inside of the workflows directory, create yaml file and define CI jobs</p><pre>/<br>├ .github/<br>│  └ workflows/<br>│     └ ci.yaml<br>:</pre><p>Below link is an reference of GitHub Actions syntax</p><p>Basically, you can use it by defining ”name”, “on”, and “jobs”</p><p><a href="https://docs.github.com/ja/actions/reference/workflows-and-actions/workflow-syntax">GitHub Actions　のワークフロー構文 - GitHub ドキュメント</a></p><p><strong>name</strong></p><ul><li>Name of workflow and it appeares at the CI result, e.g.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/0*mFVTFapK3i3HGyMz" /></figure><p><strong>on</strong></p><ul><li>Definition of events trggering CI</li><li>You can set push and/or pull request for the trigger of CI</li></ul><p><strong>jobs</strong></p><ul><li>Definition of what CI carries out</li><li>jobs consist of one or more job, and it will be executed in parallel unless otherwise configured (so should not be necessary to create multiple flows if workflow is simple)</li><li>You can define execution environment and steps per job</li><li>Below example is installing dependencies</li></ul><pre>jobs:<br>  build:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>    - name: Checkout repository<br>      uses: actions/checkout@v4<br><br>    - name: Install dependencies<br>      run: |<br>        sudo apt update<br>        sudo apt install -y cmake g++ lcov libgtest-dev libgmock-dev \<br>            libbluetooth-dev libdbus-1-dev libmosquitto-dev libpoco-dev \<br>            libsystemd-dev<br>        if [ -d /usr/src/gtest ]; then<br>          cd /usr/src/gtest<br>          sudo cmake .<br>          sudo make<br>          sudo cp -v lib/*.a /usr/lib || true<br>        fi<br>        if [ -d /usr/src/gmock ]; then<br>          cd /usr/src/gmock<br>          sudo cmake .<br>          sudo make<br>          sudo cp -v lib/*.a /usr/lib || true<br>        fi</pre><p><strong>build</strong></p><ul><li>job name (so called “job_id”)</li></ul><p><strong>runs-on</strong></p><ul><li>Execution environment of the job</li><li>If you need to change it in the middle of your flow, you should define another job</li></ul><p><strong>steps</strong></p><ul><li>Define actions under steps</li><li>You can name a step by “ — name”</li><li>There are two type of step, “uses” for using predefined actions, and “run” for defining shell commands by yourselves</li></ul><p><strong>uses</strong></p><ul><li>You can use actions provided by e.g. public repositories</li><li>“actions/checkout@v4” is executed first, according to some articles, it is checking out your repository into the execution environment</li></ul><p><strong>run</strong></p><ul><li>Define shell commands executed during CI</li><li>You can use ‘|’ to define multiple lines</li></ul><p>Then you can write shell commands what usually doing on your local environment in the “run”</p><h3>codecov</h3><p>codecov is SaaS providing test coverage statistics reporting</p><p>If you link it with GitHub, you can obtain test coverage budge from coverage reports generated during GitHub Actions</p><ul><li>Sign up codecove and link with your GitHub account, then you can see a list of your repository</li><li>Choose a repository and open Coverage tab, then you will see a options which CI tool to be used</li><li>Now select GitHubActions</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w0C_lrjR1xM_mlzH" /></figure><p>Then follow instunctions in this page</p><p>Remarks</p><ul><li>Step 1 is a test tool installation steps. I already set up Google Test, so skipped it</li><li>As Step4 described, you need to update yaml file of GitHub Actions</li><li>If you want to use specific test coverage repport, add a line files: &lt;file path&gt;as below;</li></ul><pre>- name: Upload coverage to Codecov<br>  uses: codecov/codecov-action@v4<br>  with:<br>    token: ${{ secrets.CODECOV_TOKEN }}<br>    files: ./build/coverageFiltered.info<br>    fail_ci_if_error: true</pre><p>Finally, open Configuration tab and select “Badges &amp; Graphes”</p><p>Now you can see coverage report budge markdown, so copy&amp;paset it to the README.md of your repository</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JyUsfErNT3LeJHvy" /></figure><h3>Result</h3><p>README shows the latest test coverage report once you push or create pull request and pass the tests</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2SiJx358jziJnyr8" /></figure><h3>Reference</h3><p><a href="https://qiita.com/access3151fq/items/ac2d92ff5f2b7b0619e5">【GitHub Actions】DenoのカバレッジをCodecovで出す - Qiita</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9f35aeedd97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[DevLog] Introduce Google Test for my C++ project]]></title>
            <link>https://medium.com/@futail2a/devlog-introduce-google-test-for-my-c-project-e3e9c0ef000c?source=rss-96e4227f1453------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3e9c0ef000c</guid>
            <category><![CDATA[cmake]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[google-test]]></category>
            <dc:creator><![CDATA[T Asato]]></dc:creator>
            <pubDate>Sat, 15 Nov 2025 04:16:32 GMT</pubDate>
            <atom:updated>2025-11-15T04:16:32.363Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>In a previous post, I published a hub application for IoT devices.</p><p><a href="https://medium.com/@futail2a/iotdevicehub-iot-hub-application-on-raspberry-pi-46bb5bb39d3e">IotDeviceHub — IoT hub application on Raspberry Pi</a></p><p>Now my app can be possible to be used by people, so I think I have to write test codes to ensure minimum quality.</p><p>I adopt “Google Test/Mock” for the unit test tool, it is widly used for C++.</p><p>The reason is just I have used it in my work.</p><p>In this post, I will leave my notes when I introduced Google Test to my project</p><h3>Integrate Google Test</h3><p>CMake is useful to integrate Google Test into a C++ project.</p><p>In my project, I configured the folder structure as below;</p><pre>/<br>　├ src/<br>　│　├ CMakeLists.txt<br>　│　└ (test target code)<br>　├ test/<br>　│  ├ CMakeLists.txt<br>　│  ├ mocks/<br>　│  │  ├ CMakeLists.txt<br>　│  │  └ (mock files) <br>　│  └ unit-tests/<br>　│     ├ CMakeLists.txt<br>　│　　　└ (unit test code)<br>　└ CMakeLists.txt</pre><ul><li>Put source code to be tested under src/, and put test related fiels under test/</li><li>test/ is composed of mocks/ and unit-tests/</li><li>mock/ contains mock class files used for Google Mock, which provides mock features for Google Test</li><li>test/ contains test code written by Google Test</li></ul><p>Add below to CMakeLists.txt in tests/ to enable GoogleTest</p><pre>cmake_minimum_required(VERSION 3.14)<br><br>include(FetchContent)<br>FetchContent_Declare(<br>  googletest<br>  URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip<br>)<br>set(gtest_force_shared_crt ON CACHE BOOL &quot;&quot; FORCE)<br>FetchContent_MakeAvailable(googletest)<br>enable_testing()<br><br>set(GTEST_INCLUDE_PATH /usr/local/include/gtest)<br>set(GMOCK_INCLUDE_PATH /usr/local/include/gmock)</pre><p>Also add following to measure coverage</p><pre>set(CMAKE_CXX_FLAGS  &quot;${CMAKE_CXX_FLAGS} --coverage&quot;)<br>set(CMAKE_EXE_LINKER_FLAGS &quot;${CMAKE_EXE_LINKER_FLAGS} --coverage&quot;)<br><br>find_program(LCOV_EXECUTABLE lcov)<br>find_program(GENHTML_EXECUTABLE genhtml)<br>add_custom_target(coverage<br>    DEPENDS test<br>    COMMAND ${LCOV_EXECUTABLE} -d . -c -o coverage.info<br>    COMMAND ${LCOV_EXECUTABLE} -r coverage.info &quot;*/googletest/*&quot; &quot;*/googlemock/*&quot; &quot;*/tests/*&quot; &quot;*/c++/*&quot; -o coverageFiltered.info<br>    COMMAND ${GENHTML_EXECUTABLE} -o lcovHtml --num-spaces 4 -s --legend coverageFiltered.info<br>    WORKING_DIRECTORY ${CMAKE_BINARY_DIR}<br>)</pre><ul><li>COMMAND ${LCOV_EXECUTABLE} -r coverage.info &quot;*/googletest/*&quot; &quot;*/tests/*&quot; &quot;*/c++/*&quot; -o coverageFiltered.info<br>This line is excluding files matched the pattern from coverage report, and create new coverage report named coverageFiltered.info</li><li>If this line is missed, measure coverage also for test files</li></ul><p>Add below to the CMakeLists.txt in unit-tests/</p><ul><li>In ths example, it creates “ut” binary</li><li>When you execute this binary, run the unite tests</li><li>If mock class library (mention later) is needed, add it to target_link_librariesに追加する</li></ul><pre>find_package(Poco REQUIRED Foundation JSON Util)<br>set(TEST_SOURCES<br>    &lt;test code&gt;.cpp<br>)<br>file(GLOB TAEGET_SOURCE<br>    ${PROJECT_SOURCE_DIR}/src/&lt;target code&gt;.cpp<br>)<br>add_executable(ut ${TEST_SOURCES})<br>target_sources(ut<br>    PRIVATE<br>    ${TAEGET_SOURCE}<br>)<br>target_include_directories(ut_mqtt<br>    PUBLIC<br>    ${GTEST_INCLUDE_PATH}<br>    ${GMOCK_INCLUDE_PATH}<br>)<br>target_link_libraries(ut<br>    PRIVATE<br>    gtest<br>    gtest_main<br>)<br>target_link_libraries(ut<br>    PRIVATE<br>    &lt;Own mock&gt;<br>)<br>set_target_properties(ut PROPERTIES<br>    RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin<br>)</pre><h3>Write test code</h3><p>Simply put, Google Test’s code are like following</p><ul><li>Define test case and test name with TEST macro (test name to be unique for test case)</li><li>Call some function which you want to test inside of TEST</li><li>Evaluate return value or variables using Google Test’s assertion macro like EXPECT_EQ, EXPECT_STREQ</li><li>If evaluation is failed, test is considered as fail</li></ul><pre>#include &lt;gtest/gtest.h&gt;<br>#include &lt;gtest/internal/gtest-port.h&gt;<br>TEST(TestCaseName, TestName)<br>{<br>    // Call target function<br>    uint8_t hoge = some_function();<br>    EXPECT_EQ(hoge, 1U);<br>}</pre><h3>Write Mock class</h3><p>When you write test code, you want result from external moduels functions, and the return value to be configurable depending on test scenario.</p><p>In such case, you can use Google Mock to replace contents of the functions for the test scenario</p><p>If the external module have abstract class, you can just inheritate it and create mock class as a subclass</p><p>For example, there is an abstract class IIotEventManager, so it has several virtual functions.</p><pre>class IIotEventManager<br>{<br>public:<br>    IIotEventManager() = default;<br>    virtual ~IIotEventManager() = default;<br>    virtual void onEvent(const std::string&amp; eventName, const std::string&amp; eventData) = 0;<br>    virtual void registerEventHandler(const std::string&amp; eventName, std::function&lt;void(const std::string&amp;)&gt; handler) = 0;<br>    virtual void unregisterEventHandler(const std::string&amp; eventName) = 0;<br>};</pre><p>If you want to create mock class for it, you just create a class inheritating IIotEventManager as below;</p><pre>#include &quot;IIotEventManager.h&quot;<br>#include &lt;gmock/gmock.h&gt;<br>class IotEventManagerMock : public IIotEventManager<br>{<br>public:<br>    IotEventManagerMock() = default;<br>    ~IotEventManagerMock() override = default;<br>    MOCK_METHOD(void, onEvent, (const std::string&amp; eventName, const std::string&amp; eventData), (override));<br>    MOCK_METHOD(void, registerEventHandler,<br>                (const std::string&amp; eventName, std::function&lt;void(const std::string&amp;)&gt; handler), (override));<br>    MOCK_METHOD(void, unregisterEventHandler, (const std::string&amp; eventName), (override));<br>};</pre><p>Each method need to be defined with MOCK_METHOD macro, and pass retur value type, method name and argument types.</p><p>To use this mock class, you can create an instance of it in your test code, and pass it to EXPECT_CALL, which specifies what and how function to be called during the test.</p><pre>auto eventManagerMock = std::make_shared&lt;IotEventManagerMock&gt;();<br>mqttManager.setMediator(eventManagerMock);<br>EXPECT_CALL(*eventManagerMock, onEvent(testing::_, testing::_)).Times(1);<br>:<br>//call some function which will calls onEvent()<br>mqttManager.onMessageReceived(&amp;msg);</pre><ul><li>In this case, mqttManager receives a shared_ptr&lt;IIotEventManager&gt; and call IIotEventManager::onEvent from</li><li>EXPECT_CALL(*eventManagerMock, onEvent(testing::_, testing::_)).Times(1);means, it expects that onEvent in eventManagerMock instance only once</li><li>(testing::<em>, testing::_</em>) means argument can be any value (i.e. if you specify a certain value and this value is not passed when it is called, the test will fail)</li><li>EXPECT_CALL to be defined before the method is called</li></ul><p>The problem is when you want to create a mock for a class without abstract class.</p><p>In this case,</p><ol><li>Create a mock class which have methods corresponding to method you want to mocked</li><li>Define own implementation for the methods and call the mock class inside of it</li><li>Build a mock library with the implementation</li></ol><p>For example, MQTT library is written by C language, so it doesn’t have any abstract classes</p><p>So created below MosquittoMock class and define each methos calling the corresponding mock class methods</p><pre>#include &lt;mosquitto.h&gt;<br>#include &lt;gmock/gmock.h&gt;<br>class MosquittoMock;<br>extern MosquittoMock* gMosqMock;<br>class MosquittoMock<br>{<br>public:<br>    MosquittoMock() {gMosqMock = this;};<br>    ~MosquittoMock() {gMosqMock = nullptr;};<br>    MOCK_METHOD(int, mosquitto_lib_init, ()), (override);<br>    :<br>};</pre><pre>#include &quot;MosquittoMock.h&quot;<br>MosquittoMock* gMosqMock = nullptr;<br>extern &quot;C&quot; {<br>    int mosquitto_lib_init(void) {<br>        return gMosqMock ? gMosqMock-&gt;mosquitto_lib_init() : MOSQ_ERR_SUCCESS;<br>    }<br>    :<br>}</pre><p>Then build the mosquitto mock libary. Create mock code as MosquittoMock.cpp and add below CMakeLists under mock/ director</p><pre>add_library(MosquittoMock STATIC<br>    MosquittoMock.cpp<br>)<br>target_include_directories(MosquittoMock PUBLIC<br>    ${GTEST_INCLUDE_PATH}<br>    ${GMOCK_INCLUDE_PATH}<br>    ${CMAKE_SOURCE_DIR}/tests/mocks<br>    /usr/include/<br>)</pre><p>Add below to CMakeLists.txt for unit test code to load MosquittoMock library</p><pre>target_link_libraries(ut_mqtt<br>    PRIVATE<br>    ${DBUS_LIBRARIES}<br>    MosquittoMock<br>)</pre><p>Inside of test code, create an instance of the mock class, and define EXPECT_CALL with the mock</p><p>This case, it expects that mosquitto_lib_init() at once.</p><p>You also can define return value when it specified in the WillOnce() argument (MOSQ_ERR_SUCCESS in this case)</p><pre>MosquittoMock mosqMock;<br>EXPECT_CALL(mosqMock, mosquitto_lib_init())<br>    .WillOnce(testing::Return(MOSQ_ERR_SUCCESS));<br>:<br>mqttManager.init(&quot;iot_device_hub&quot;);</pre><h3>Result</h3><p>When you execute test binary, unit tests will run and show results.</p><p>If test passed, you can see OK, if failed, it shows the reason</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kYb5q-GilZ6LcXQ-" /></figure><p>When you run the coverage target defined in the test/ directory, the following HTML file will be generated, so you can check the current coverage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2gtwnV-zabAq0ygs" /></figure><h3>Reference</h3><p><a href="https://qiita.com/shohirose/items/30e39949d8bf990b0462">Google Testの使い方 - Qiita</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3e9c0ef000c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IotDeviceHub — IoT hub application on Raspberry Pi]]></title>
            <link>https://medium.com/@futail2a/iotdevicehub-iot-hub-application-on-raspberry-pi-46bb5bb39d3e?source=rss-96e4227f1453------2</link>
            <guid isPermaLink="false">https://medium.com/p/46bb5bb39d3e</guid>
            <dc:creator><![CDATA[T Asato]]></dc:creator>
            <pubDate>Mon, 03 Nov 2025 00:12:50 GMT</pubDate>
            <atom:updated>2025-11-03T00:12:50.660Z</atom:updated>
            <content:encoded><![CDATA[<h3>IotDeviceHub — IoT hub application on Raspberry Pi</h3><h3><strong>IoT Hub Application?</strong></h3><p>As smart appliances and smart homes have become more common, IoT devices are now widely available on the market.</p><p>To make such devices operate at specific times or under certain conditions, you need an application that acts as a hub — one that can group multiple IoT devices together and send commands to them according to predefined rules.</p><p>For example, with the Google Home app, you can register IoT devices compatible with Google Home (such as Google Nest Hub) and then schedule or coordinate their operations directly from the app.</p><p>Meanwhile, some IoT devices provide publicly available APIs.<br>For instance, SwitchBot publishes documentation for each of its products that describes what kinds of operations can be performed over BLE communication.</p><p><a href="https://github.com/OpenWonderLabs/SwitchBotAPI-BLE/tree/latest">GitHub - OpenWonderLabs/SwitchBotAPI-BLE: SwitchBot BLE open API</a></p><p>While these are more like communication specifications than formal APIs, I thought that by referring to them, it might be possible to build my own hub application.</p><p>So, using such APIs, I created an application that provides hub functionality for IoT devices running on microcontrollers such as the Raspberry Pi.<br>Since I’ve made it, I’d like to use this article to introduce how it works and how to use it.</p><h3>Repository</h3><p><a href="https://github.com/futail2a/IotDeviceHub">GitHub - futail2a/IotDeviceHub</a></p><h3>How to use</h3><h4>Set up</h4><ol><li>Configure BLE devices</li></ol><ul><li>Rename template_config.json under config/ directory config.json</li><li>Add MAC address of BLE decices which you want to connect to</li><li>(03/11/2025) Currently, support only SwitchBot smart bulb, bot, and motion sensor</li><li>Empty MAC if you don’t use it</li></ul><pre>  &quot;devices&quot;:<br>  {<br>    &quot;woBulb&quot;:<br>    {<br>      &quot;mac&quot;: &quot;xx:xx:xx:xx:xx:xx&quot;<br>    },<br>    &quot;woHand&quot;:<br>    {<br>      &quot;mac&quot;: &quot;xx:xx:xx:xx:xx:xx&quot;<br>    },<br>    &quot;woMotionSensor&quot;:<br>    {<br>      &quot;mac&quot;: &quot;xx:xx:xx:xx:xx:xx&quot;<br>    }<br>  },</pre><p>2. Configure MQTT broker</p><ul><li>Add MQTT broker settings to config/config.json</li><li>If you are only using it within a local network, it will be better to set up broker on the same micro controller. You can easily set up a broker using like Mosquitto.</li><li>IPv4 and port are mandatory</li><li>If you need to connect with TLS, add CA certification, client certification, and client key. If you don’t you TLS, empty them</li></ul><pre>  &quot;mqtt&quot;:<br>  {<br>    &quot;brokerIpv4&quot;: &quot;127.0.0.1&quot;,<br>    &quot;brokerPort&quot;: 1883,<br>    &quot;caCert&quot;: &quot;&quot;,<br>    &quot;clientCert&quot;: &quot;&quot;,<br>    &quot;clientKey&quot;: &quot;&quot;<br>  }</pre><p>3. Build and install</p><ul><li>At root directory, run below command to build IotDeviceHub</li></ul><pre>$ make</pre><p>Once build succeed, run below command to install it to iotdevicehub daemon</p><pre>$ make install</pre><p>To uninstall it, run below command</p><pre>$ make uninstall</pre><p>4. Run and sample command</p><p>You can start IotDeviceHub to execute IotDeviceHub binary, or start iotdevicehub service after install</p><pre>$ ./IotDeviceHub<br>#OR<br>$ systemctl daemon-reload<br>$ systemctl start iotdevicehub</pre><p>Then, when you publish ”exec_bot” topic to the MQTT broker, it operate switching function if the device installing IotDeviceHub connects to SwitchBot Bot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/0*cwYNkkNgZpuMc4Ev" /></figure><p>If you have Android smartphone, <em>IoT MQTT Panel</em> is easy to set up MQTT client</p><p>Once you configure MQTT broker address (and TLS settings), you can set up topic publish and subscription as widgets</p><p><a href="https://play.google.com/store/apps/details?id=snr.lab.iotmqttpanel.prod&amp;hl=ja">https://play.google.com/store/apps/details?id=snr.lab.iotmqttpanel.prod&amp;hl=ja</a></p><h3>Support devices</h3><p>SwitchBot</p><ul><li>Smart bulb</li><li>Bot</li><li>Motion sensor</li></ul><p>I will create another post to describe how to customize IotDeviceHub, e.g. add other own BLE devices and business logics</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46bb5bb39d3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Send BLE command triggered by MQTT publish message from Remote Broker]]></title>
            <link>https://medium.com/@futail2a/send-ble-command-triggered-by-mqtt-publish-message-from-remote-broker-831066702d25?source=rss-96e4227f1453------2</link>
            <guid isPermaLink="false">https://medium.com/p/831066702d25</guid>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[switch-bot]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[mqtt]]></category>
            <category><![CDATA[mosquitto]]></category>
            <dc:creator><![CDATA[T Asato]]></dc:creator>
            <pubDate>Thu, 25 Sep 2025 12:00:42 GMT</pubDate>
            <atom:updated>2025-09-25T12:00:42.935Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>In the previous post, I confirmed that a smart phone app can connect MQTT broker on a VPS server and can publish &amp; subscribe MQTT messages.</p><p><a href="https://medium.com/@futail2a/publish-mqtt-message-via-internet-using-vps-service-d2228605be3e">Publish MQTT message via Internet using VPS service</a></p><p>In this post, I connect the broker from Raspberry Pi and send some BLE commad.</p><p>I updated my IoT device hub application so that it can receive MQTT publish message and send BLE command to a IoT device.</p><p><a href="https://github.com/futail2a/IotDeviceHub/">GitHub - futail2a/IotDeviceHub</a></p><h3>libmosquitto settings</h3><p>Send CA certificate, client certificate and client key created in the previous post to RaspberryPi.<br>Any location would work if IotDeviceHub can access the directory, since certificats path can be set by mosquitto_tls_set().</p><p>Remote broker address and port also need to be configured. To aggregate configuration setting, created aJSON file so that IotDeviceHub can get all necessary configuration parameters.</p><pre>// IotDeviceHub/config/config.json<br>{<br>  &quot;mqtt&quot;:<br>  {<br>    &quot;brokerIpv4&quot;: &lt;address&gt;,<br>    &quot;brokerPort&quot;: &lt;port&gt;,<br>    &quot;caCert&quot;: &lt;caCertPath&gt;,<br>    &quot;clientCert&quot;: &lt;clientCertPath&gt;,<br>    &quot;clientKey&quot;: &lt;keyPath&gt;<br>  }<br>}</pre><p>Using POCO to parse JSON file. <br>The JSON is read at MQTT manager class constructor.</p><pre>MqttManager::MqttManager()<br>{<br>    try<br>    {<br>        Poco::Util::JSONConfiguration config = Poco::Util::JSONConfiguration(CONFIG_FILE_PATH);<br>        mBrokerIpv4 = config.getString(&quot;mqtt.brokerIpv4&quot;);<br>        std::cout &lt;&lt; &quot;MQTT broker address: &quot; &lt;&lt; mBrokerIpv4 &lt;&lt; std::endl;<br>        mBrokerPort = config.getUInt16(&quot;mqtt.brokerPort&quot;);<br>        std::cout &lt;&lt; &quot;MQTT broker port: &quot; &lt;&lt; mBrokerPort &lt;&lt; std::endl;<br>        mCaCertPath = config.getString(&quot;mqtt.caCert&quot;);<br>        std::cout &lt;&lt; &quot;MQTT CA cert path: &quot; &lt;&lt; mCaCertPath &lt;&lt; std::endl;<br>        mClientCertPath = config.getString(&quot;mqtt.clientCert&quot;);<br>        std::cout &lt;&lt; &quot;MQTT client cert path: &quot; &lt;&lt; mClientCertPath &lt;&lt; std::endl;<br>        mClientKeyPath = config.getString(&quot;mqtt.clientKey&quot;);<br>        std::cout &lt;&lt; &quot;MQTT client key path: &quot;&lt;&lt; mClientKeyPath &lt;&lt; std::endl;<br>    }<br>    catch (Poco::Exception&amp; ex)<br>    {<br>        std::cerr &lt;&lt; &quot;Error: &quot; &lt;&lt; ex.displayText() &lt;&lt; std::endl;<br>    }<br>}</pre><p>Setting certificates and broker address, etc. by mosquitto_tls_set() and mosquitto_connect_bind_v5().</p><pre>//IotDeviceHub/mqtt/MqttManager.cpp<br>auto ret = mosquitto_tls_set(m_mosq, mCaCertPath.c_str(), NULL, mClientCertPath.c_str(), mClientKeyPath.c_str(), NULL);<br>:<br>ret = mosquitto_connect_bind_v5(m_mosq, mBrokerIpv4.c_str(), mBrokerPort, 60, nullptr, nullptr);</pre><h3>Setting callback messages for MQTT messages</h3><p>When IotDeviceHub receives MQTT Publish messages, it should send respective BLE commands to device from a callback function registered before.</p><p>In libmosquitto, you can set callback function via mosquitto_message_v5_callback_set(). However, libmosquitto is C library and cannot bind a member function and its class instance. <br>As a workaround, pass <em>this </em>pointer when it create mosquitto client instance. By doing so, <em>this </em>will be assinged in <em>obj </em>argument of the callback functin, so it can access public member function of the class.</p><pre>//bool MqttManager::init(std::string client_id)<br> m_mosq = mosquitto_new(client_id.c_str(), true, this);</pre><pre>void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg, const mosquitto_property *props)<br>{<br>    auto *manager = static_cast&lt;MqttManager*&gt;(obj);<br>    if(manager)<br>    {<br>        manager-&gt;onMessageReceived(msg);<br>    }<br><br>}</pre><p>Side info, IotDeviceHub is using Mediator pattern for event handling (see below post).<br>So in this case, using MQTT topic name as a event name and payload as a event data.</p><pre>void MqttManager::onMessageReceived(const struct mosquitto_message *msg)<br>{<br>    if(mMediator)<br>    {<br>        std::string eventData=&quot;&quot;;<br>        if(msg-&gt;payload == nullptr || msg-&gt;payloadlen == 0)<br>        {<br>            std::cerr &lt;&lt; &quot;Received empty message on topic &quot; &lt;&lt; msg-&gt;topic &lt;&lt; std::endl;<br>        }<br>        else<br>        {<br>            eventData=std::string((char *)msg-&gt;payload, msg-&gt;payloadlen);<br>        }<br>        mMediator-&gt;onEvent(msg-&gt;topic, eventData);<br>    }<br>    else<br>    {<br>        std::cerr &lt;&lt; &quot;Mediator not set, cannot handle message on topic &quot; &lt;&lt; msg-&gt;topic &lt;&lt; std::endl;<br>    }<br>}</pre><p>In a client of MQTT manager (who send BLE command to devices), it subscribe “exec_bot”, and register it as a Mediator”s event.<br>When this topic is received, a lambda expression is executed to send a command to the BLE device (mBotDevice).</p><pre>//bool IotDeviceHubManager::init()<br>mMqtt-&gt;subscribe(&quot;exec_bot&quot;);<br>mEventManager-&gt;registerEventHandler(&quot;exec_bot&quot;, [this](const std::string&amp; eventData)<br>{<br>    std::cout &lt;&lt; &quot;Event: exec_bot&quot; &lt;&lt; std::endl;<br>    auto command = mBotDevice-&gt;getExecActionCommand();<br>    mBle-&gt;sendBleCommand(command);<br>}<br>);<br>mMqtt-&gt;setMediator(mEventManager);</pre><h3>Experiment</h3><p>As an experiment, I checked whether the Switchbot Bot execution could be performed via MQTT.</p><p>First, attach the Switchbot Bot to my AC controller.<br>If you don’t attach it properly, the Bot will move when it’s turned on and you won’t be able to press the buttons, so attach it firmly with masking tape.<br>This has a fatal flaw in that you won’t be able to see the screen on the controller, but I ignore that for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_DN3jsXKTdPZJ5FS" /></figure><p>After that, set up a button panel to publish the “exec_bot” topic in the smartphone app introduced in the first article, and press the button.</p><h3>Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/0*cSTrFilRHkPPA1vl" /></figure><p>When I published the “exec_bot” topic from the smartphone app, the bot worked. <br>Of course, this still doesn’t allow for normal use, so more mechanical improvements are needed, but now that I can control indoor devices via the Internet, I think it’s starting to feel more like IoT.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=831066702d25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Publish MQTT message via Internet using VPS service]]></title>
            <link>https://medium.com/@futail2a/publish-mqtt-message-via-internet-using-vps-service-d2228605be3e?source=rss-96e4227f1453------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2228605be3e</guid>
            <category><![CDATA[mosquito]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[mqtt]]></category>
            <category><![CDATA[vps-hosting]]></category>
            <dc:creator><![CDATA[T Asato]]></dc:creator>
            <pubDate>Sun, 07 Sep 2025 11:39:18 GMT</pubDate>
            <atom:updated>2025-09-07T11:39:18.806Z</atom:updated>
            <content:encoded><![CDATA[<h3>Motivation</h3><ul><li>I want to send MQTT messages to my Raspberry Pi in a home network from outside</li><li>e.g. Send some requests to Raspberry Pi via MQTT, and Raspberry Pi send a command to IoT devices in my room (e.g. turn on a light)</li><li>There are public MQTT brokers, but I want my own borker because I cannot assess risk when topic is collided</li><li>So I want to set up my own MQTT broker on the Internet using Virtual Private Server</li></ul><h3>VPS Set Up</h3><p>I decided to use <em>WebArena Indigo®</em> provided by NTTPC Communications, Inc.</p><p><a href="https://web.arena.ne.jp/lp/indigo/english/">English(WebARENA Indigo) | NTTPC</a></p><p>Since I only need it as an MQTT broker, a minimal setup will be sufficient. Under those conditions, it can be used for ¥449 per month (as of September 2025), so I decided to try it.</p><ul><li>Credit card registration during account sign up is only available on weekdays during daytime hours</li><li>Be prepared for a sudden ¥10,000 charge during credit card registration — this is a credit check and should be refunded later.</li></ul><p>After account creation, you can set up SSH keys, and create instances from “Service Management” -&gt; “Service in use” -&gt; “Go to control panel”</p><p>I created an instance with ubuntu24.04 1GB RAM</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2-4IviBCVAwE51OU" /></figure><h3>User management</h3><p>Delete default user “ubuntu” and create own user.</p><p>Execute below command to create my user, and then add it to “sudo” group so that it can execute sudo command</p><pre># create own user<br>sudo adduser &lt;your user&gt;<br>sudo gpasswd -a &lt;your user&gt; sudo</pre><p>Then, login with the user again and remove “ubuntu” user</p><pre># logout from ubuntu user<br>exit<br># ssh connection with created user <br>ssh &lt;your user&gt;@&lt;ip address&gt; -p 22<br># delete ubuntu user<br>sudo userdel -r ubuntu</pre><h3>SSH setting</h3><p>Then setup SSH configuration. Update /etc/ssh/sshd_config as below</p><pre># Change ssh port from well-known port 22 to your prefered number<br>Port &lt;your prefered ssh port&gt;<br>:<br># Prohibit login with root user<br>PermitRootLogin no<br>:<br># Prohibit password authentication<br>PasswordAuthentication no</pre><p>After that restart ssh and confirm if you can connect server with ssh.</p><pre>sudo systemctl restart ssh</pre><p>In my case, I cannot connect SSH after that. <br>This is because ssh.socket configuration is also need to be updated from the latest Ubuntu24.04.<br>To update ssh.socket, you need to set ssh port number to <em>ListenStream </em>in /lib/systemd/system/ssh.socket.</p><pre>[Socket]<br>ListenStream=&lt;your prefered port&gt;<br>Accept=no</pre><p>Then reload systemd and restart ssh.socket. After that you should be able to connect sshる。</p><pre>sudo systemctl daemon-reload<br>sudo systemctl restart ssh.socket</pre><h3>mosquitto settings</h3><p>Install mosquitto</p><pre>sudo apt-get update<br>sudo apt-get install mosquitto</pre><p>Then update /etc/mosquitto/mosquitto.conf to change MQTT port for TLS</p><ul><li>Port number should be different from SSH port</li><li>Explain other settings later</li></ul><pre>listener &lt;your prefered mqtt port&gt;</pre><p>After install MQTT, update Firewall to allow only SSH and MQTT ports</p><pre>sudo ufw disable<br>sudo ufw default deny<br>sudo ufw allow &lt;ssh port&gt;<br>sudo ufw allow &lt;mqtt port&gt;<br>sudo ufw enable</pre><h3>TLS settings using MQTT</h3><p>In the previous post, I described how to setup MQTT broker and client authentication. So basically just need to follow it to setup.</p><p><a href="https://medium.com/@futail2a/how-to-connect-mosquitto-broker-with-client-authentication-and-what-i-got-stuck-with-8e3164a586ac">How to connect Mosquitto broker with client authentication, and what I got stuck with</a></p><p>But need to be careful that; CN to be set for each certificates, SAN to be added to server certificate</p><p>I reffered this site for SAN settings (Japanese)</p><p><a href="https://zenn.dev/yoshida12/articles/62b44dad6d73b9">OpenSSLで自己署名証明書を作成する（複数ホスト名：SAN／Subject Alternative Name設定付き）</a></p><h3>CA certificate</h3><p>I created my own CA since this broker is only for myself.</p><pre>openssl req -new -x509 -days 365 -extensions v3_ca -keyout ca.key -out ca.crt</pre><h3>Server certificate</h3><p>Before create server certificate, need to create a file defines SAN.<br>Since I don’t take own domain, added only IP address.</p><pre># san.txt<br>subjectAltName = IP:&lt;ip address&gt;</pre><p>Then create server cert as below.</p><pre>openssl genrsa -out server.key 2048<br>openssl req -out server.csr -key server.key -new<br>openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 365 -extfile san.txt</pre><h3>Register certificates to mosquitto</h3><p>After CA and server certificates, need to deploy them to mosquitto folders.</p><p>I moved CA cert to /etc/mosquitto/ca_certificates, and moved server.crt and server.key to /etc/mosquitto/certs.<br>Check owner of server.crt and server.key, and change it to mosquitto if it is other ser.</p><pre>sudo chown mosquitto:mosquitto server.crt<br>sudo chown mosquitto:mosquitto server.key</pre><p>Change /etc/mosquitto/mosquitto.conf as below, then restart mosquitto by sudo systemctl restart mosquitto</p><pre>listener &lt;your prefered port&gt;<br>allow_anonymous false<br>use_identity_as_username true<br>cafile   /etc/mosquitto/ca_certificates/ca.crt<br>certfile /etc/mosquitto/certs/server.crt<br>keyfile  /etc/mosquitto/certs/server.key<br>require_certificate true<br>tls_version tlsv1.2</pre><h3>Client certificate</h3><p>Create client certificate as below.</p><pre>openssl genrsa -out client.key 2048<br>openssl req -out client.csr -key client.key -new<br>openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 365</pre><p>I also created PKCS12 file because some MQTT mobile application supports only this format.</p><pre>openssl pkcs12 -export -inkey client.key  -in client.crt  -certfile ca.crt -out client.p12</pre><h3>App settings</h3><p>I used Android “IoT MQTT Panel” application as a MQTT client.<br>I used it because this application surpports MQTT with TLS using certification authentication.</p><p><a href="https://play.google.com/store/apps/details?id=snr.lab.iotmqttpanel.prod&amp;hl=ja">https://play.google.com/store/apps/details?id=snr.lab.iotmqttpanel.prod&amp;hl=ja</a></p><p>Download ca.crt and client.p12 from the server, and transfer them to Android smartphone.</p><ul><li>When I download them from Windows, security blocked it</li><li>In this case, you need to turn off a setting of folder access from Windows security control pannel</li></ul><p>Launch IoT MQTT Panel app, open Connections screen, and create new connection by click + button on the right bottom corner.</p><ul><li>When you select Network protocol to TCP-SSL, you can choos CA cert and client cert, so register as below;</li><li>CA certificate: ca.crt</li><li>Client certificate: client.p12</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wi06pm5BAb_Vswnm" /></figure><p>When you click save, it starts connection.<br>If it can connect to broker, it opens dashboard and you can setup panel widgets</p><p>I created Button and Test Log panel for a test</p><ul><li>Button publishes ”button” topic with ”hello world”</li><li>Text Log subscribes ”button” topic and show payload</li></ul><p>When I click “Test” button, it sends publish to borker, and broker send it to subscriber; i.e. Test log panel shows the payload as below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T7r-jZmHZRAJicAF" /></figure><h3>Summary</h3><p>I confirmed that I could publish and subscribe to MQTT by setting up a personal MQTT broker on the Internet using a VPS.<br>In this article, I used the same smartphone app for both publishing and subscribing, but if you connect an app on a Raspberry Pi to this broker, you should be able to send messages to the Raspberry Pi inside your home over the Internet.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2228605be3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[DevLog] Using Poco::Timer in C++ application]]></title>
            <link>https://medium.com/@futail2a/devlog-using-poco-timer-in-c-application-ec25c38b87ee?source=rss-96e4227f1453------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec25c38b87ee</guid>
            <category><![CDATA[poco]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[T Asato]]></dc:creator>
            <pubDate>Sun, 24 Aug 2025 00:38:50 GMT</pubDate>
            <atom:updated>2025-08-24T00:38:50.973Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>I’m creating a programm that turns on a SwitchBot smart color bulb for few seconds when a SwitchBot motion sensor detects human motion on Raspberry Pi5.</p><p>In a previous post, designed the programm as <br>(1) When the sensor detects human motion, it sends turn on command to the bulb via BLE<br>(2) Then set a few seconds timer <br>(3) When timer expired, sends turn off command to the bulb<br>Also extend timer when sensor detects motion sequentially.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l8RANupbrEhGocIE" /></figure><p><a href="https://medium.com/@futail2a/devlog-design-ble-advertisement-packet-sniffing-connection-program-on-raspberry-pi-bfda801c5ff5">[DevLog] Design BLE advertisement packet sniffing &amp; connection program on Raspberry Pi</a></p><p>I have diecided to use some external library for timer implementation. <br>In this time, I use POCO library.</p><h3>POCO</h3><p>POCO is C++ library that provides many basic functions like threading, file system, network managment .<br>FYI, POCO is stand for POrtable COmponents.</p><p><a href="https://pocoproject.org/">POCO C++ Libraries - Simplify C++ Development</a></p><p>The reason why I adopt POCO is POCO has been used in IoT application development.<br>For expamle, one of the IoT application development platform “macchina.io” uses POCO, and I thought it would be a good to get familiar with POCO in case I create something for macchina.io in the future.</p><h3>POCO set up</h3><p>Official site introduces How To install POCO.</p><p><a href="https://pocoproject.org/download.html#building">POCO C++ Libraries - Downloads</a></p><p>There are several options e.g. using conan, but I built and installed POCO from source code because my porject doesn’t managed by package management tool.</p><p>To download, build and install, I executed below commands;</p><pre>$ git clone -b poco-1.14.2-release https://github.com/pocoproject/poco.git<br>$ cd poco<br>$ mkdir cmake-build<br>$ cd cmake-build<br>$ cmake .. &amp;&amp; cmake --build .<br>$ sudo cmake --build . --target install</pre><p>Unfortunetely, I cannot found .pc file in POCO repository, so cannot use pkg-config.<br>As far as this GitHub issue, there had been .pc file, but not sure the reason why no longer exist.</p><p><a href="https://github.com/pocoproject/poco/issues/2037">Add pkg-config support · Issue #2037 · pocoproject/poco</a></p><p>So you need to specify POCO library path in Makefile directly.<br>If you followed above build &amp; install steps, POCO header and library is installed under /usr/local/include/Poco and /usr/local/lib</p><pre>INCLUDES += -I/usr/local/include/Poco<br>CFLAGS += $(INCLUDES)<br>LDFLAGS += -lPocoFoundation -Wl,-rpath,/usr/local/lib<br><br>$(DEFAULT_TARGET): $(DEFAULT_SRCS)<br> $(CC) -o $@ $^ $(CFLAGS) $(LDFLAGS)</pre><h3>Usage of Poco::Timer</h3><p>POCO provides a thread based timer function.<br>There are other similar timer functions, but I used Poco::Timer because it looks the most simplest timer.</p><p><a href="https://docs.pocoproject.org/current/Poco.Timer.html">Poco</a></p><ul><li>You can start and stop the time with start() and stop().</li><li>Callback function called when timer expir can be set from start() argument.</li><li>Time out interval is set from Timer constructor, and there are two types of interval; startInterval and periodicInterval<br>* When start() is called, callback will be called after the startInterval elapse<br>* After startInterval elapse, callback will be called periodicaly in periodicInterval<br>* If periodicInterval is set 0, timer will run only once</li></ul><p>Callback function will be passed to Timer calss wrapped with Poco::TimerCallback class.</p><p><a href="https://docs.pocoproject.org/current/Poco.TimerCallback.html">Poco</a></p><p>You need to specify type of object which have the callback in TimerCallback’s template, and create instance with object pointer and callback function pointer</p><p>As you can see, the Timer class is simple and easy to use, but I have to implement the timer reset myself.</p><p>For example, if motion is detected while the timer is running, I want to reset the timer.<br>There is Timer::reset(), but it is for periodicInterval, thus I need to implement reset logic</p><p>This is realized by</p><ul><li>BLE management class has a Timer class instance as unique_ptr, and create and destroy the instance every timer running and stop</li><li>Before it starts timer, it checks the instance existence<br>* If it already exist, call stop() and start() to restart the timer<br>* If not, create a new instance and call start()<br>* When callback is triggered, destroy the timer</li></ul><p>Below is implementation</p><pre>// This code snipet removed unrelated functions and variables<br>class IotDeviceHubManager<br>{<br>private:<br>    std::unique_ptr&lt;Poco::Timer&gt; mLightTimer;<br>    void onLightTimeout(Poco::Timer&amp; timer);<br>};<br><br>void IotDeviceHubManager::onLightTimeout(Poco::Timer&amp; timer)<br>{<br>    std::cout &lt;&lt; &quot;Light timer expired, turning off the light&quot; &lt;&lt; std::endl;<br>    auto command = mBulbDevice-&gt;getTurnOffCommand();<br>    mBle-&gt;sendBleCommand(command);<br>    mLightTimer.reset();<br>}<br><br>void IotDeviceHubManager::onMotionUpdate(std::vector&lt;uint8_t&gt; data)<br>{<br>  std::cout &lt;&lt; &quot;Motion data received&quot; &lt;&lt;std::endl;<br>  auto command = mBulbDevice-&gt;getTurnOnCommand();<br>  mBle-&gt;sendBleCommand(command);<br>  if(mLightTimer)<br>  {<br>    std::cout &lt;&lt; &quot;Detected motion again, extend light on timer&quot; &lt;&lt;std::endl;<br>    mLightTimer-&gt;stop();<br>    mLightTimer-&gt;start(Poco::TimerCallback&lt;IotDeviceHubManager&gt;(*this, &amp;IotDeviceHubManager::onLightTimeout));<br>  }<br>  else<br>  {<br>    mLightTimer = std::make_unique&lt;Poco::Timer&gt;(DEFAULT_LIGHT_INTERVAL, 0);<br>    mLightTimer-&gt;start(Poco::TimerCallback&lt;IotDeviceHubManager&gt;(*this, &amp;IotDeviceHubManager::onLightTimeout));<br>  }</pre><h3>Result</h3><p>When light is turned on, wait DEFAULT_LIGHT_INTERVAL time and then send turn off command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*yvoP2pmuE_d8NB8j" /></figure><h3>Future tasks</h3><p>Now I have achieved all the functionality I originally wanted. <br>Next, I would like to write test code and extend it to support more use cases.</p><h3>Repository</h3><p><a href="https://github.com/futail2a/IotDeviceHub/tree/main">GitHub - futail2a/IotDeviceHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec25c38b87ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[DevLog] libdbus in C++ is difficult]]></title>
            <link>https://medium.com/@futail2a/devlog-libdbus-in-c-is-difficult-6175b123ed8e?source=rss-96e4227f1453------2</link>
            <guid isPermaLink="false">https://medium.com/p/6175b123ed8e</guid>
            <dc:creator><![CDATA[T Asato]]></dc:creator>
            <pubDate>Sun, 10 Aug 2025 01:44:35 GMT</pubDate>
            <atom:updated>2025-08-10T01:44:35.823Z</atom:updated>
            <content:encoded><![CDATA[<p>From the last post, I’m implementing C++ programm which connects to IoT devices via BLE.</p><p><a href="https://medium.com/@futail2a/devlog-design-ble-advertisement-packet-sniffing-connection-program-on-raspberry-pi-bfda801c5ff5">[DevLog] Design BLE advertisement packet sniffing &amp; connection program on Raspberry Pi</a></p><p>However, I’m getting stuck in libdbus part and not making progress so much.</p><p>I just want to share which part is blocker at the moment.</p><p>Currently I’m stuck at the point where I’m trying to send a BLE connection request asynchronously from DBus.</p><ul><li>libdbus library has a function called dbus_connection_send_with_reply, which allows you to add a message you want to send asynchronously to a queue</li><li>The reply to this message can be obtained through an object called a DBusPendingCall</li><li>When dbus_connection_send_with_reply is executed, it returns a DBusPendingCall, which you can then associate with a callback function using dbus_pending_call_set_notify</li><li>Subsequently, when the dbus_connection_read_write_dispatch function is called, the message in the queue is sent.</li></ul><p>Now I’m tring to send BLE Connection request to IoT device, but the callback function won’t be called.</p><pre>// Created connection msg before<br>DBusPendingCall* pending = nullptr;<br>if (!dbus_connection_send_with_reply(mConn.get(), msg, &amp;pending, -1))<br>{<br>  std::cerr &lt;&lt; &quot;Failed to send connection message&quot; &lt;&lt; std::endl;<br>  dbus_message_unref(msg);return;<br>}<br>if (!pending)<br>{<br>  std::cerr &lt;&lt; &quot;Pending call is null&quot; &lt;&lt; std::endl;dbus_message_unref(msg);return;<br>}<br>else<br>{<br>  std::cout &lt;&lt; &quot;Connection request sent for &quot; &lt;&lt; handler.first-&gt;getMacAddr() &lt;&lt; std::endl;<br>  handler.first-&gt;setState(BleDeviceState::CONNECTING);<br>}<br><br>dbus_pending_call_set_notify(pending, &amp;BleDbusConnectionManager::connectionCb, new std::shared_ptr&lt;BleDeviceHandler&gt;(handler.first),<br> [](void* data) { delete static_cast&lt;std::shared_ptr&lt;BleDeviceHandler&gt;*&gt;(data); });<br>dbus_message_unref(msg);<br><br>dbus_connection_read_write_dispatch(mConn.get(), -1);</pre><p>I could connect to the device when I send a request synchronously, so something worng in this code snipet.<br>dbus_connection_read_write_dispatch is inside of this function because it is called periodically, but maybe I need to create a new thread to call it periodically.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6175b123ed8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[DevLog] Design BLE advertisement packet sniffing & connection program on Raspberry Pi]]></title>
            <link>https://medium.com/@futail2a/devlog-design-ble-advertisement-packet-sniffing-connection-program-on-raspberry-pi-bfda801c5ff5?source=rss-96e4227f1453------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfda801c5ff5</guid>
            <dc:creator><![CDATA[T Asato]]></dc:creator>
            <pubDate>Fri, 18 Jul 2025 03:43:46 GMT</pubDate>
            <atom:updated>2025-07-18T03:45:21.568Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m currently developing a BLE device management program that runs on a Raspberry Pi.</p><p>Up until now, the system design only supported use cases where sensor devices broadcast their data via advertisement packets, and the program simply received that data. However, I now want to extend the functionality to support scenarios where, depending on the received data, commands can be sent to other IoT devices.</p><p>Specifically, I want to implement a feature where a motion sensor detects the presence of a person and triggers a smart bulb to turn on.</p><p>The previous design, as described below, was not capable of handling BLE connections or command transmission, so a significant redesign is now required.</p><p><a href="https://medium.com/@futail2a/dev-note-create-raspberry-pi-app-distributing-info-from-iot-device-publish-data-via-mqtt-f00d95743372">Dev Note: Create Raspberry Pi App distributing info from IoT device — Publish data via MQTT</a></p><h3>Concept of the Design Change</h3><p>There are three major points in the new design:</p><h4>1. Separation of BLE Advertisement Reception and BLE Connection Functionality</h4><p>In the previous design, all BLE-related functionality was consolidated into a single BleAbstractLayer class.<br> However, based on past experiments, it has become clear that to receive BLE advertisement packets frequently and with minimal latency, it is better to access data directly via HCI sockets rather than through DBus.</p><p>On the other hand, sending commands to BLE devices is difficult to achieve using only HCI. While it is possible to establish a BLE connection via HCI, GATT communication requires a higher-level protocol than HCI.<br> Since use cases involving command transmission are expected to be much less frequent compared to receiving advertisement packets from sensors, I plan to implement this functionality using DBus.</p><p>To accommodate this, the BleAbstractLayer class will be restructured to hold two abstract components: BleScanManager for monitoring advertisement packets, and BleConnectionManager for handling connections.<br> Concrete implementations will include BleSockScanManager (which uses HCI sockets) and BleDbusConnectionManager (which uses DBus).</p><h4>2. Introduction of an Event Management Class</h4><p>In the previous design, data from sensors was published via MQTT.<br> However, the new use case I’m implementing operates entirely within the local process, and using MQTT would introduce unnecessary overhead.</p><p>To address this, I will adopt the <a href="https://en.wikipedia.org/wiki/Mediator_pattern">Mediator pattern</a>. Sensors will notify a Mediator of events, and the Mediator will trigger appropriate actions based on the event content.<br> Specifically, I will implement a class called IotEventManager to act as the Mediator, and register it with the classes corresponding to each BLE device.</p><p>When a BLE device detects a significant event based on sensor values, it will notify the IotEventManager, which will then execute the logic associated with that event.<br> If command transmission over BLE is necessary, the device-specific class will retrieve the required GATT service and characteristic information and send the command via the BleDbusConnectionManager.</p><h3>Design — Sequence diagrams</h3><h4>Initialization</h4><p>The initialization process proceeds as follows:</p><ul><li>The main class, IotDeviceHub, creates an instance of the BleAbstractLayer class.</li><li>At that time, it specifies the classes to be used for receiving advertisement packets and for BLE connections.</li><li>Inside the constructor of BleAbstractLayer, it creates instances of BleSockScanManager and BleDbusConnectionManager, which in turn establish connections with the HCI socket and DBus, respectively.</li><li>Next, the required BLE device classes are instantiated.</li><li>If advertisement packets from a device should be monitored, that device instance is passed to BleSockScanManager via the registerScannedDevice() method of BleAbstractLayer.</li><li>If a BLE connection with the device is needed, that instance is passed to BleDbusConnectionManager via the registerConnectionDevice() method of BleAbstractLayer.</li><li>Finally, each BLE device instance registers the IotEventManager.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dP5-FFtOZDu3lZGE" /></figure><h4>Main Loop</h4><p>After entering the main loop, the following steps occur:</p><ul><li>The BleSockScanManager starts BLE scanning.</li><li>Once scanning begins, a separate thread called scanning is created to monitor advertisement packets.</li><li>Advertisement packets received via the HCI socket are processed to check whether the MAC address matches any of the registered BLE devices.</li><li>If a matching MAC address is found, the corresponding device class’s onAdvPacketReceived() callback is invoked.</li><li>Meanwhile, in the main thread, a loop runs continuously until a termination signal is received.<br>* Within this loop, the BLE connection routine — explained in the next section — is executed.<br>* Depending on future use cases, this connection routine might also be moved to a separate thread.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KxNBDyNB9C40z4u4" /></figure><h3>BLE Connection</h3><ul><li>Within the main thread loop, the system periodically checks the connection status of registered BLE devices and attempts to connect if any are disconnected.<br>* The BleDbusConnectionManager checks the connection status of the registered devices.<br> * If a device is found to be disconnected, it sends a connection request via DBus.<br> * After that, the thread sleeps for a defined interval.</li><li>Connection status updates are received asynchronously.<br> * When a connection notification is received, the device’s status is updated to “connected”; when a disconnection notification is received, it is updated to “disconnected.”</li><li>Since these status updates are asynchronous, the checking and updating of states are placed within a critical section to avoid race conditions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/0*P3P7Zk5DdJJoBTWF" /></figure><h3>Event Handling</h3><ul><li>When a BLE device detects an event, it notifies the IotEventManager.<br>* In the current use case, when the motion sensor detects someone, it sends an event notification if more than 30 seconds have passed since the last detection.</li><li>Upon receiving the notification, the IotEventManager triggers an action based on the event.<br>* For the current use case, upon receiving a someone_detected event, it retrieves the necessary information from the BLE device class responsible for the smart bulb and sends a power-on command via the BleConnectionManager.</li><li>Since we want the power to turn off after a fixed period, a timer is set.<br> If a timer is already active, it will be reset.<br>* When the timer expires, the system retrieves the necessary information from the smart bulb class to send a power-off command, and sends it via the BleConnectionManager.</li><li>The exact implementation of the timer has not yet been finalized, but it will need to support starting and stopping the timer, and notifying the caller when the timer expires.<br>* We could implement this ourselves, but would prefer to reuse an existing solution if available.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XDFQ0Id5gVFAX9vN" /></figure><h3>Termination</h3><ul><li>When either SIGINT or SIGTERM is received, the process begins termination.</li><li>The main loop’s exit flag is set to true, and the system waits for the loop to break.</li><li>Then, BleScanManager is instructed to stop scanning, the scanning thread’s stop flag is set, and the system waits for the thread to join.</li><li>Once the thread exits its loop, it joins cleanly, and the process terminates.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*68tSmdL9KsNvtT8_" /></figure><p>A key point to consider is how long it takes to exit each loop.<br> If exiting takes too long, the process may be forcefully terminated with SIGKILL, so we must examine whether any parts could introduce delays.</p><ul><li>In the main loop, the connection status of BLE devices is checked and connection requests are sent to DBus.<br>* The critical section only handles state checking and updating, so it should exit quickly — no issue there.<br>* Sending requests to DBus is done via blocking calls, but the responses are received asynchronously, so this should not result in significant delays.<br> If there is any concern, a timeout can be set on the request.</li><li>The scanning thread receives data via the HCI socket and triggers event notifications when relevant packets are found.<br>* Since the data is received using read(), it will block until data becomes available.<br> * Therefore, a timeout must be set using setsockopt() when opening the socket.</li><li>In the event-notification sequence, the current use case involves sending a command via DBus and setting a timer.<br>* Command transmission via DBus should not be a problem as long as a timeout is specified on the request.<br>* The timer implementation is still undecided, but it will likely use something like condition_variable.<br> Care will be taken to ensure the timer can terminate immediately when needed.</li></ul><h3>Next Steps</h3><p>At this point, only the design has been drafted.<br> Implementation will begin from here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfda801c5ff5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[DevLog] Control SwitchBot Color Bulb via BLE from Raspberry Pi 5]]></title>
            <link>https://medium.com/@futail2a/devlog-control-switchbot-color-bulb-via-ble-from-raspberry-pi-5-14b053f45380?source=rss-96e4227f1453------2</link>
            <guid isPermaLink="false">https://medium.com/p/14b053f45380</guid>
            <dc:creator><![CDATA[T Asato]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 12:33:25 GMT</pubDate>
            <atom:updated>2025-07-02T12:33:25.852Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.switchbot.jp/products/switchbot-color-bulb">SwitchBot スマート電球 E26</a></p><p>I bought SwitchBot Color bulb and want to control it from Raspberry Pi 5</p><p>So far, I have been making a program to read advertising packet data from IoT devices</p><p>However, this bulb requires command via GATT communication and then need to connect with BLE</p><p>In a previous post, I updated my program to read advertising packet from HCI socket</p><p><a href="https://medium.com/@futail2a/access-bluez-in-raspberry-pi-using-socket-c332bc9e70c5">Access Bluez in Raspberry Pi using socket</a></p><p>However, as the following article shows, HCI is an interface between the Controller, which consists of the physical layer and the link layer, and the Host, which contains GATT, etc.</p><p><a href="https://pcng.medium.com/ble-protocol-stack-controller-2d2d5371deec">BLE Protocol Stack — Controller</a></p><p>If you just want to see the contents of the advertisement packets, you could just parse the data coming from the Controller through HCI</p><p>It is also possible to connect BLE via HCI, but if you want to use GATT, HCI doesn’t support it and need to think of another way</p><p>I made my app to read advertising data from HCI directly because advertising packet update is somehow delayed when I tried to get it from Bluez-DBus</p><p>But use cases of the bulb control should’t be so frequent, so I think Bluez-DBus is still useful to make connection and send contorl commands</p><p>As an experiment, I created a sample code that connect the bulb with BLE, and repeats to send powe on/off command at a certain interval</p><p><strong>cycle()</strong></p><ul><li>A method to be called 3 sec interval</li><li>If the device is not connected (static bool isConnected == false), attempt BLE connection</li><li>Send “Connect” method to device path (/org/bluez/hci0/dev_XX_XX_XX_XX_XX_XX, XX.. is MAC of the bulb)</li><li>If it is already connected, call command() and send power on/off commands</li><li>ChatGPT told me that there is sdbus-c++ library, which provides DBus operation for C++, so tried to used it</li></ul><p><a href="https://github.com/Kistler-Group/sdbus-cpp/blob/master/docs/using-sdbus-c++.md#design-of-sdbus-c">sdbus-cpp/docs/using-sdbus-c++.md at master · Kistler-Group/sdbus-cpp</a></p><ul><li>Connetion is the class that handles the connection to DBus, and Proxy seems to be the class that actually handles the objects on DBus that it wants to manipulate from the client side</li><li>Each of them has a create API and returns an instance as a unique pointer</li></ul><pre>#include &lt;sdbus-c++/sdbus-c++.h&gt;<br>void BluezSockLayer::cycle()<br>{<br>    static bool isConnected = false;<br>    if (isConnected) {<br>        command();<br>        return;<br>    }<br>    std::string device_path = &quot;/org/bluez/hci0/dev_dev_XX_XX_XX_XX_XX_XX&quot;;<br>    try {<br>        m_connection = sdbus::createSystemBusConnection();<br>        auto proxy = sdbus::createProxy(*m_connection, &quot;org.bluez&quot;, device_path);<br>        proxy-&gt;callMethod(&quot;Connect&quot;)<br>            .onInterface(&quot;org.bluez.Device1&quot;);<br>        std::cout &lt;&lt; &quot;Successfully sent Connect command to device: &quot; &lt;&lt; mac &lt;&lt; std::endl;<br>        isConnected = true;<br>    } catch (const sdbus::Error&amp; e) {<br>        std::cerr &lt;&lt; &quot;DBus error: &quot; &lt;&lt; e.getName() &lt;&lt; &quot; - &quot; &lt;&lt; e.getMessage() &lt;&lt; std::endl;<br>    }<br>}</pre><p><strong>command()</strong></p><ul><li>A method that sends On if the previous command sent was Off, and Off if it was On</li><li>GATT services and characteristics were hardcoded, because I’m lazy to find a way to parse them</li><li>To check them manually, you can use bluetoothctl</li><li>After connected with device by bluetoothctl, do list-attributes</li></ul><pre> $ bluetoothctl<br> scan on <br> connect &lt;MAC&gt;<br> list-attributes </pre><ul><li>Then you can see the list of GATT attributes, and find UUID: ‘cba20002–224d-11e6–9fb8–0002a5d5c51b’ mentioned in the offical document</li><li>On Off commands details also described in the doc</li></ul><pre>: <br>Characteristic (Handle 0x0000)<br>/org/bluez/hci0/dev_XX_XX_XX_XX_XX_XX/serviceYYYY/charZZZZ<br>cba20002-224d-11e6-9fb8-0002a5d5c51b <br>Vendor specific</pre><p><a href="https://github.com/OpenWonderLabs/SwitchBotAPI-BLE/blob/latest/devicetypes/colorbulb.md#example">SwitchBotAPI-BLE/devicetypes/colorbulb.md at latest · OpenWonderLabs/SwitchBotAPI-BLE</a></p><pre>void command()<br>{<br>    static bool toggle = false;<br>    std::string dev_path = &quot;/org/bluez/hci0/dev_XX_XX_XX_XX_XX_XX&quot; + &quot;/serviceYYYY/charZZZZ&quot;; //<br>    auto proxy = sdbus::createProxy(*connection, &quot;org.bluez&quot;, dev_path);std::vector&lt;uint8_t&gt; turn_on_cmd = {0x57, 0x0F, 0x47, 0x01, 0x01};<br>    std::vector&lt;uint8_t&gt; turn_off_cmd = {0x57, 0x0F, 0x47, 0x01, 0x02};<br>    std::map&lt;std::string, sdbus::Variant&gt; options;<br>    if(toggle)<br>    {<br>        proxy-&gt;callMethod(&quot;WriteValue&quot;)<br>            .onInterface(&quot;org.bluez.GattCharacteristic1&quot;)<br>            .withArguments(turn_off_cmd, options);<br>        std::cout &lt;&lt; &quot;Turn Off command sent via DBus.&quot; &lt;&lt; std::endl;<br>        toggle = false; // Toggle the state for next command<br>    }<br>    else<br>    {<br>        proxy-&gt;callMethod(&quot;WriteValue&quot;)<br>            .onInterface(&quot;org.bluez.GattCharacteristic1&quot;)<br>            .withArguments(turn_on_cmd, options);<br>        std::cout &lt;&lt; &quot;Turn On command sent via DBus.&quot; &lt;&lt; std::endl;<br>        toggle = true; // Toggle the state for next command<br>    }<br>}</pre><p><strong>Result</strong><br>I can LED blink with raspi</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/0*g1R7oiKtw_lXJudD" /></figure><p>I just created a program to make it blink from Raspi, so next time I want to think about the design properly</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14b053f45380" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>