<?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 Yiond on Medium]]></title>
        <description><![CDATA[Stories by Yiond on Medium]]></description>
        <link>https://medium.com/@juanmartincas?source=rss-28c883f5974c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*cxoSZAVGUM9qJjs7</url>
            <title>Stories by Yiond on Medium</title>
            <link>https://medium.com/@juanmartincas?source=rss-28c883f5974c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:28:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@juanmartincas/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[Made a simple password agenda as a DBus service]]></title>
            <link>https://medium.com/@juanmartincas/made-a-simple-password-agenda-as-a-dbus-service-926cabab47a6?source=rss-28c883f5974c------2</link>
            <guid isPermaLink="false">https://medium.com/p/926cabab47a6</guid>
            <category><![CDATA[dbus]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[passwords]]></category>
            <category><![CDATA[cpp-programming]]></category>
            <dc:creator><![CDATA[Yiond]]></dc:creator>
            <pubDate>Sun, 23 Aug 2026 17:15:37 GMT</pubDate>
            <atom:updated>2026-08-23T21:31:44.992Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YpakidzMWoEFePH11mZVrA.jpeg" /><figcaption><a href="https://news.wsu.edu/news/2023/01/13/steps-to-create-a-strong-password/">https://news.wsu.edu/news/2023/01/13/steps-to-create-a-strong-password/</a></figcaption></figure><p>So, I have this typical problem where I always forget my passwords, more considering that I use different passwords for different platforms and all of them being long and hard passwords. Recently I was looking into Rust tutorial book and wanted to do a first project using Rust, and decided to do a password agenda or something like that, and I know, this is some normal project for people is learning about programming, but is a really cool project because involves hashing and encrypting stuff so why not creating my own password agenda. And for just study purposes and keep my brain working, I decided to not use any AI tool (besides, you know, writing the readmes and stuffs…) At the end, conclusion and future works for this application will be discussed.</p><h4>Assumptions</h4><p>This is not a tutorial, but just showing off the thinking process of developing an application. I will show some lines of codes of the most interesting parts in my opinion and explain its functionality. The rest of the code will be in the repositories I will be sharing.</p><h4><strong>Functionalities</strong></h4><p>First, lets define what this application should do:</p><ul><li>The application has to be accessible from terminal</li><li>By now it will only work in Linux environment</li><li>Can create different users</li><li>It will contain the password, platform, the username for that platform and a distinct name</li></ul><h4>Architecture</h4><p>Now, with the functions defined, lets discuss the architecture. This could be simple as just one piece of code that manages everything, but I like to do things complicated, so lets discuss the alternatives.</p><ul><li>Using a file: This is a simple approach, A software can create a file with a certain format containing the passwords and this file is encrypted with all the passwords inside, and only accessible through a secret phrase (or password). This is an easy and simple implementation. An architecture diagram could look like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*f6EgrL-QLOBDDOxI6fKOCA.png" /></figure><ul><li>Using a dedicated backend: For this apporach there are two software that have to be developed, the one for the terminal and the one that runs in the background. For this case we have to consider the posibility to use a database, or continuing with the file approach. The advantage of using this architecture is that you, the reader, can implement later a different UI system and using the API through the communication protocol implement your own password agenda. This is the approach I decided to go with.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*bUYZnh361zCtJJSr51s0qg.png" /></figure><h4>Communication protocol</h4><p>To be able to use the background application we need to communicate the fronted to the back-end system. These are some options:</p><ul><li>TCP: using TCP sockets is a reliable way to communicate this two processes, and is a protocol widely used and we can establish our own application layer protocol.</li><li>HTTP: is the most used (at least, what I know) application layer protocol where we can create a REST API.</li><li>UDP: is a fast but not reliable protocol, different from TCP where we can ensure that the network packets arrives correctly.</li></ul><p>These were network protocol, but for my own sake I wanted to manage this application locally, for now, this is not a thing i want to manage in a server and just want to have the back-end service running in my machine, so an IPC (Inter Process Communication) protocol is more than enough, sure we can use the network protocols to manage the application locally as well.</p><p>The IPC protocol selected is DBus (mostly because I wrote a basic article recently using C and Go ;) <a href="https://medium.com/@juanmartincas/basic-dbus-tutorial-d740dc790ce8?sharedUserId=juanmartincas">https://medium.com/@juanmartincas/basic-dbus-tutorial-d740dc790ce8?sharedUserId=juanmartincas</a>) and I select this protocol because I just want to have some practice again implementing it.</p><h4>Front-end and back-end</h4><p>For the front-end, as mentioned at the beginning of the article has to run in the terminal, I use Ubuntu daily for my personal stuff and development, so I wanted an easy access through a terminal. I want to execute a binary and open a command terminal (something like those Cisco switches and routers interfaces):</p><pre>&gt;</pre><p>and type a commands to get a password, like this:</p><pre>&gt; get password test_discord<br>[password information]<br>&gt;</pre><p>For this, I selected C++ as my terminal application, first because It is the language I have most used and second because of a “CLI development framework” called ConsoleIF ;) ;) (<a href="https://github.com/juamarCas/ConsoleIF">https://github.com/juamarCas/ConsoleIF</a>) I developed some time ago that is used to create these types of interface I mentioned earlier.</p><p>For the back-end I decided to use Rust, because I was learning it and wanted to develop something with it. This program will be running the DBus service and expose methods and run in the background. For last I will be using a database (PostgreSQL specifically) instead of a file because this application could expand, and a file is harder to scale.</p><p>Lets see the Back-end and Front-end implementations.</p><h4>Back-end</h4><p>Lets first discuss the basic functionalities and then the DBus API implementation.</p><p>Passwords for the user of the application are stored as hashes, since those really we don’t need to recover but to compare with what comes, for this I decided to use Argon2 algorithm, that is used for password hasing, this is the implementation in Rust:</p><pre>pub fn hash_password(password: &amp;str) -&gt; Result&lt;String, Error&gt; {<br>    let salt = SaltString::generate(&amp;mut OsRng);<br>    let argon2 = Argon2::default();<br><br>    let password_hash = match argon2.hash_password(password.as_bytes(), &amp;salt) {<br>        Result::Ok(val) =&gt; val,<br>        Result::Err(err) =&gt; return Err(Error::other(format!(&quot;Failed to hash: {}&quot;, err))),<br>    };<br><br>    return Ok(password_hash.to_string());<br>}</pre><p>The argon algorithm creates hashes from random seeds, and the way it verifies it, is because the output follows an structure:</p><pre>$argon2id$v=19$m=65536,t=3,p=1$c29tZS1yYW5kb20tc2FsdA$y2D9oDqBpkvL7mM4CsNXhseDtcSoo9i6g0iUcH19xGI</pre><p>Using those parameters, later will verify the password. This is the function for verifying:</p><pre>pub fn verify_password(password: &amp;str, hash: &amp;str) -&gt; Result&lt;bool, Error&gt; {<br>    let parse = match PasswordHash::new(hash) {<br>        Result::Ok(p) =&gt; p,<br>        Result::Err(err) =&gt; return Err(Error::other(format!(&quot;Error verifying: {}&quot;, err))),<br>    };<br><br>    return Ok(Argon2::default()<br>        .verify_password(password.as_bytes(), &amp;parse)<br>        .is_ok());<br>}</pre><p>Other hashing algorithms uses secrets to creats and verify these hashes, Argon2 uses random numbers and a structure what makes it interesting.</p><p>Now, encrypting passwords are another story, we need to secure the passwords we save but we need them later in plain text to know what password we need! so we don’t want to hash them but to encrypt them, for this something called chacha20poly1305 that is a cipher algorithm that uses unique numbers for every new entry (this is simplifying, these stuffs are much more complicated). This algorithm works using a secret, you can hardcoded or store it in a file, in my case I generate the file with a random passphrase and store it somewhere in my machine if it does not exist, if exist it takes it. This function will load or create this file:</p><pre>pub fn load_or_generate_key_file(path: &amp;str) -&gt; Result&lt;[u8; 32], Error&gt; {<br>    let path = Path::new(path);<br><br>    if path.exists() {<br>        let mut file = File::open(path)?;<br>        let mut key = [0_u8; 32];<br><br>        file.read_exact(&amp;mut key)?;<br><br>        let mut extra = [0_u8; 1];<br>        return match file.read(&amp;mut extra) {<br>            Ok(0) =&gt; Ok(key),<br>            Ok(_) =&gt; Err(Error::new(<br>                ErrorKind::InvalidData,<br>                format!(&quot;Key file {} must contain exactly 32 bytes.&quot;, path.display()),<br>            )),<br>            Err(err) =&gt; Err(err),<br>        };<br>    } else {<br>        if let Some(parent) = path.parent() {<br>            if !parent.as_os_str().is_empty() {<br>                fs::create_dir_all(parent)?;<br>            }<br>        }<br><br>        let mut key = [0_u8; 32];<br>        OsRng.fill_bytes(&amp;mut key);<br><br>        let mut file = File::create(path)?;<br>        file.write_all(&amp;key)?;<br><br>        return Ok(key);<br>    }<br>}</pre><p>The length of 32 is because ChaCha20Poly1305 requres a secret of 32 bytes to generate a encryption key. The encryption implementation would be like:</p><pre>pub fn encrypt(key: &amp;[u8; 32], plain_text: &amp;str) -&gt; Result&lt;String, Error&gt; {<br>    let cipher = ChaCha20Poly1305::new(key.into());<br>    let nonce = Nonce::generate();<br>    let cipher_text = match cipher.encrypt(&amp;nonce, plain_text.as_bytes().as_ref()) {<br>        Result::Err(err) =&gt; return Err(Error::other(format!(&quot;Error encrypting: {}&quot;, err))),<br>        Result::Ok(c) =&gt; c,<br>    };<br><br>    let mut combined = Vec::with_capacity(12 + cipher_text.len());<br>    combined.extend_from_slice(&amp;nonce);<br>    combined.extend_from_slice(&amp;cipher_text);<br><br>    return Ok(hex::encode(combined));<br>}</pre><p>It generate the nonce (number used once) randomly and creates a vector with the size of the nonce and the cipher text, so later when we want to decrypt we have the nonce again. Talking about the decrypt function, this is its implementation:</p><pre><br>pub fn decrypt(key: &amp;[u8; 32], encrypted_str: &amp;str) -&gt; Result&lt;String, Error&gt; {<br>    let combined = match hex::decode(encrypted_str) {<br>        Result::Err(err) =&gt; return Err(Error::other(format!(&quot;Error decrypting: {}&quot;, err))),<br>        Result::Ok(bytes) =&gt; bytes,<br>    };<br><br>    if combined.len() &lt; 12 {<br>        return Err(Error::other(&quot;Data is too short&quot;));<br>    }<br><br>    let (nonce_raw, ciphertext) = combined.split_at(12);<br>    let cipher = ChaCha20Poly1305::new(key.into());<br>    let nonce = match Nonce::try_from(nonce_raw) {<br>        Result::Err(err) =&gt; return Err(Error::other(&quot;Error generating nonce in decrypt&quot;)),<br>        Result::Ok(n) =&gt; n,<br>    };<br><br>    let plaintext = match cipher.decrypt(&amp;nonce, ciphertext) {<br>        Result::Err(err) =&gt; return Err(Error::other(format!(&quot;Error decrypting cipher: {}&quot;, err))),<br>        Result::Ok(t) =&gt; t,<br>    };<br><br>    match String::from_utf8(plaintext) {<br>        Result::Err(err) =&gt; return Err(Error::other(format!(&quot;Invalid UTF 8: {}&quot;, err))),<br>        Result::Ok(text) =&gt; return Ok(text),<br>    }<br>}</pre><p>It takes the hex number stored, decodes it and split the resultant vector into the nonce and the encrypted password and with the key it gets the original password in plain text.</p><p>For Authorization I used JWT to be simple on it, the idea is to send this token through one of the parameters of the method and with this authenticate the user. There is an article where I learned more about it here: <a href="https://arielweinberger.medium.com/json-web-token-jwt-the-only-explanation-youll-ever-need-cf53f0822f50">https://arielweinberger.medium.com/json-web-token-jwt-the-only-explanation-youll-ever-need-cf53f0822f50</a>.</p><p>So, with all the security part explained, lets look the DBus service implementation and some examples, the rest of the implementation can be seen in the code, (All of my repositories for this project will be shared at the end if you want to see right now).</p><p>To implement DBus in Rust I used a library called zbus that makes it easy to interact with the bus (unlike in the front-end where I implemented it with the low level API, I explained it in the article i wrote i shared earlier)</p><p>Lets declare an simple interface, in this case a greeter just to see that the DBus service is running:</p><pre>#[zbus::interface(name = &quot;co.esloth.PasswordKeeper1.Greeter&quot;)]<br>impl GreetingApi {<br>    fn greeting(&amp;self) -&gt; &amp;&#39;static str {<br>        return &quot;Hello from Password Keeper!&quot;;<br>    }<br>}</pre><p>In this way we implemented the interface co.esloth.PasswordKeeper1.Greeter with the method Greeting, so at the end you will be calling something like: co.esloth.PasswordKeeper1.Greeter.Greeting. If you run the code and start the service and execute this command:</p><pre>gdbus call --system \<br>  --dest co.esloth.PasswordKeeper1 \<br>  --object-path /co/esloth/PasswordKeeper1 \<br>  --method co.esloth.PasswordKeeper1.Greeter.Greeting</pre><p>You will receive a message. Lets see it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JYu_bTtc0qUXtkCbDxPYLg.png" /></figure><p>So like that we have implemented an interface with its method!</p><p>This is the way to serve every interface I have implemented for the API</p><pre>let _connection = connection::Builder::system()?<br>        .name(SERVICE_NAME)?<br>        .serve_at(OBJECT_PATH, GreetingApi)?<br>        .serve_at(<br>            OBJECT_PATH,<br>            LoginApi::new(Arc::clone(&amp;database), Arc::clone(&amp;jwt_secret)),<br>        )?<br>        .serve_at(OBJECT_PATH, UserApi::new(Arc::clone(&amp;database)))?<br>        .serve_at(<br>            OBJECT_PATH,<br>            PlatformAPI::new(Arc::clone(&amp;database), Arc::clone(&amp;jwt_secret)),<br>        )?<br>        .serve_at(OBJECT_PATH, PasswordAPI::new(database, jwt_secret))?<br>        .build()?;</pre><p>Greeting, Login, Password and so on, are implemented similar to the piece of code I shared earlier for the greeting method. Lets see for example the User endpoints for registering:</p><pre>#[zbus::interface(name = &quot;co.esloth.PasswordKeeper1.User&quot;)]<br>impl UserApi {<br>    fn register(&amp;self, username: &amp;str, password: &amp;str) -&gt; zbus::fdo::Result&lt;String&gt; {<br>        let mut database = self<br>            .database<br>            .lock()<br>            .map_err(|_| zbus::fdo::Error::Failed(&quot;Database is unavailable&quot;.to_string()))?;<br><br>        database<br>            .create_user(username, password, UserType::User)<br>            .map_err(|error| zbus::fdo::Error::Failed(error.to_string()))?;<br><br>        return Ok(&quot;User registered successfully&quot;.to_string());<br>    }<br>}</pre><p>So similar, we have our interface co.esloth.PasswordKeeper1.User and method Register, it accepts two parameters: username and password.</p><p>For database, there is a separation, when I build the project for development creats a memory database to say something, only uses vectors and stuff, and if compiles with release it uses postgres connection:</p><pre>#[cfg(not(feature = &quot;postgres&quot;))]<br>use crate::database::db_dummy::DBDummy;<br><br>#[cfg(feature = &quot;postgres&quot;)]<br>use crate::database::db_conn::DBConn;</pre><h4>Front-end</h4><p>As mentioned before, I used C++ to do the CLI to interact with the DBus API. Lets go by parts:</p><ul><li>The DBus communication is through its low level API, is a pain to use, I created something like a class and methods to interact, but is very limited, for example, for now it can work when the methods returns one value, because some methods return complex values like structures and arrays, but this one only can accept one return value, is enough thou since the replies are strings and JSONs so for that there is no problem.</li><li>I used my ConsoleIF framework as mentioned before, so lets see an example impleementation to create a command:</li></ul><pre><br>void greetings_command(const std::vector&lt;std::any&gt;&amp; args){<br>    auto res = consumer-&gt;call_method&lt;std::string&gt;(OBJ_PATH, &quot;co.esloth.PasswordKeeper1.Greeter&quot;,<br>                                                  &quot;Greeting&quot;);<br>    if (!res){<br>        spdlog::error(&quot;Error calling greeter: {}&quot;, res.Error());<br>        exit(1);<br>    }<br><br>    std::cout&lt;&lt;*res&lt;&lt;std::endl;<br>}<br><br>app.create_command(&quot;hello&quot;, greetings_command);</pre><p>This creates a command called “hello” and executes its callback associated to the create_command method. lets see it in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MnJnAuhlVZ8kcbh3AocNFw.png" /></figure><p>Also, to avoid just seing a JSON when returning value, I used another library called tabulate (<a href="https://github.com/p-ranav/tabulate">https://github.com/p-ranav/tabulate</a>) to show data in a prettier way as well with nlohmann json library (<a href="https://github.com/nlohmann/json">https://github.com/nlohmann/json</a>) to parse JSON.</p><p>Another command creation example with parameters would be get password:</p><pre>std::string get_password_cmd = &quot;get_password&lt;string&gt;&quot;;<br>app.create_command(get_password_cmd, get_password_command);</pre><p>This will create a command with a parameter IN password, so the command would be something like:</p><pre>&gt; get password mainYT<br>[password info]<br>&gt;</pre><p>Lets see a complete example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0rozwoJZ1dmOAie1Wul4tQ.png" /></figure><p>One last thing to mention about the front-end, is that the token is saved in memory while the software is running, you can logout or close the software to delete that session.</p><h4>Conclusions and future work</h4><ul><li>This app has some security issues, for example, can be susceptible to SQL injection attacks, not sure, not tested it, but since i don’t sanitize the input it may happen.</li><li>When asking for your password when logging in or creating the user, it shows the password in plain text in terminal, I will implement a way to hide that password</li><li>There is an admin/admin hard coded user, It needs an change password endpoint, but since the admin is only used to create platforms and don’t have access to the other users information, I can take my time.</li><li>Something interesting it could be that the API when building, a feature to select which protocol will accept, HTTP, TCP, DBus and so on, so it can satisfy every necesity.</li><li>I know it was more complicated to build this app like this, but at the end is for learning, and if you want to try out this API, or complete software, you can create your own interface, graphical or terminal to be used as you want.</li><li>I want to create a deploy server and be able to deploy in a custom APT repository, but for now, i am good with what I have</li></ul><h4>Repositories</h4><ul><li>PasswordKeeperAPI <a href="https://github.com/juamarCas/PasswordKeeperAPI">https://github.com/juamarCas/PasswordKeeperAPI</a></li><li>PasswordKeeperCLI <a href="https://github.com/juamarCas/PasswordKeeperCLI">https://github.com/juamarCas/PasswordKeeperCLI</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=926cabab47a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A little thoughts on math]]></title>
            <link>https://medium.com/@juanmartincas/a-little-thoughts-on-math-1d6f8d481967?source=rss-28c883f5974c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d6f8d481967</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[fourier-transform]]></category>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[signal-processing]]></category>
            <category><![CDATA[math]]></category>
            <dc:creator><![CDATA[Yiond]]></dc:creator>
            <pubDate>Fri, 22 May 2026 14:35:25 GMT</pubDate>
            <atom:updated>2026-05-22T14:35:48.068Z</atom:updated>
            <content:encoded><![CDATA[<p>Something I love about maths is how they are implicit in nature everywhere and we can’t see them that easily. Recently a friend of mine and I started to test a DSP library for microcontrollers to apply the Fourier transform (Fourier said that all periodic signals can be decomposed in a sum of sines and cosines, those trigonometric functions we see in High School) in a sound signal that was being captured with an audio codec. We did several tests and at the end, we tested with two cellphones generating two sound signals, one with 1 kHz and the other in 2.5 kHz, and the result of that experiment is shown in the following picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/0*GkIGOMtFN_Aqtan9" /><figcaption>Signal in time domain and frequency domain</figcaption></figure><p>Looking at the second graph, that is the Fourier transform, we can see two peaks, each in the frequency we were testing (1 kHz and 2.5 kHz), I thought, well, if Fourier is right, if I do a sum of two sine function each with the frequencies of the test, I should obtain a similar result, so I went to an online math function graph generator and following this formula:</p><p>sin(f*2*π*t) where f is the frequency I define and t the time variable I made the following equation:</p><p>f(t)=sen(1000*2 π t)*0.001+sen(2500 π*2 t)*0.001, the 0.001 is amplitude, to see better the graph. I got the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/0*D4UauDl3KlJkjwQI" /><figcaption>Math graph</figcaption></figure><p>There are some differences because of the noise, but is so interesting, something we tested in a real live application just shows up in something that simple we learned in High School such as trigonometric functions.</p><p>Hope you liked this little reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d6f8d481967" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic DBUS tutorial]]></title>
            <link>https://medium.com/@juanmartincas/basic-dbus-tutorial-d740dc790ce8?source=rss-28c883f5974c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d740dc790ce8</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dbus]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Yiond]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 00:19:53 GMT</pubDate>
            <atom:updated>2025-09-01T16:01:29.396Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>DBUS is an Inter Process Communication (IPC) system present in linux-based OSs. These are its base characteristics:</p><ul><li>Is peer-to-peer client-server architecture</li><li>According to its documentation, “It is easy to use.” Honestly, at first, is a pain to implement it, but once you understand its core concepts, it turns a little bit easier to use. A little bit</li><li>It is a way to create APIs to communicate processes in your Linux system.</li></ul><p>In this basic tutorial, we will create a simple program in C that calls a method in a DGBUS Go server.</p><h3>Scope</h3><p>Even though I will describe some technical and architectural topics for the DBUS protocol, I won’t go into any detail that does not serve the basic comprehension of this system. For more detailed information on the protocol, you can check the official documentation:</p><ul><li><a href="https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces">https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces</a></li></ul><h3>Assumptions</h3><p>In this article, it’s assumed that the reader has some experience in programming, not necessarily in both languages used in this example (C and Go), but knows some basic programming concepts, since everything that is programmed using these languages can be achieved with other languages. Also, some basic Linux knowledge would be wonderful.</p><p>The link to the GitHub with the complete code with both examples will be at the end of the article.</p><p>That said, we can start.</p><h3>DBUS</h3><p>As said in the introduction, DBUS is an IPC system, which means we can establish communication between our programs using this protocol, and since it is intrinsic to Linux, we don’t have to do any installation, so let’s start explaining the basic concepts of DBUS.</p><p>In the DBUS we have:</p><ul><li>Bus name: This is what DBUS uses to associate a connection with a bus. So when we export methods and signals, these are associated with the bus name. The standard bus names are written like: com.example, com.example.system being com.example a DNS, but it is not necessary to use a DNS to use DBUS, since it is just a formality to identify the owner of that DBUS API.</li><li>Methods: Is the action that is going to be performed. Methods have parameters and return values.</li><li>Signals: Are special functions that, when they are called, every subscribed process to that signal will receive that call. Like a pub sub system.</li><li>Interfaces: An interface is a collection of methods and signals: com. example (yes, you can have an interface called as your bus name, but you can have several interfaces) com. example.audio, com.example.power, and these interfaces have their methods and signals related to their system.</li><li>Object paths: Objects have the interfaces, and the object path is a logical path described as it would be a Linux file path: /com/example/</li><li>Services: a service is the executable that implements all objects in the system that call the DBUS daemon.</li></ul><p>So when we create our DBUS API, we export interfaces that contains methods and signals that can bring us information or not, like an API would do. How do we call these methods? We have to specify the bus name, object path, interface, and method name that we want to call. A method called Hello, in the interface com.example, would be seen like: com.example.Hello. Anyways, let’s see first the server-side implementation.</p><h3>Server side</h3><p>The server side was developed in the Go language, which will implement a service that will return a greeting message whose parameter is a name. for example: I call it with the parameter “Juan” from the client, and it will return “Hi! Juan”. Let’s get started.</p><p>First, let’s establish our method, which will return the greetings:</p><pre>type Server struct{}<br><br>func (g *Server) Hello(name string) (string, *dbus.Error) {<br> if name == &quot;&quot; {<br>  return &quot;&quot;, dbus.MakeFailedError(errors.New(&quot;empty name&quot;))<br> }<br> return fmt.Sprintf(&quot;Hi! %v&quot;, name), nil<br>}</pre><p>This creates a struct called Server, and Hello is one of its methods. As mentioned, it will accept a string as a parameter and return a string, but also a DBus error object (we will cover that on the client side)</p><p>Now, we have created our method, now we need to expose it with an interface. For that, I have created the Init() function that will expose this method. Let’s break it into pieces:</p><pre>conn, _err := dbus.SessionBus()<br>if _err != nil {<br> return _err<br>}</pre><p>First, we stablish a connection to the bus, with the SessionBus function. Something worth mentioning is that there are two types of “connections” to the bus:</p><ul><li>Session — Used with desktop environments</li><li>System — Core system (doesn’t have any GUI system like GNOME)</li></ul><p>To establish a system connection, just need to call the SystemBus() function, but for security reasons, the bus blocks these types of connections unless you configure the bus to accept this connection with a given name. For simplicity, we will tie to the Session bus.</p><p>Now, we will request a bus name, since this will help us to know which bus to request. If we do not specify the bus name, DBus will assign one randomly, but we want to know it at all times. (The problem with the system bus mentioned before has to do with the bus name.) In Go, we can do it like this:</p><pre>reply, _err := conn.RequestName(&quot;example.service&quot;,    dbus.NameFlagDoNotQueue)<br>	<br>if _err != nil {<br>	return _err<br>}<br><br>if reply != dbus.RequestNameReplyPrimaryOwner {<br> return fmt.Errorf(&quot;name already taken&quot;)<br>}<br>fmt.Println(&quot;Connected to session bus!&quot;)</pre><p>With this, we will request a name, and if it is taken, we will return an error. If everything is Ok, we will see the message “Connected to session bus!” in the console.</p><p>Lastly, it will export our interface and method:</p><pre>_err = conn.Export(&amp;Server{}, &quot;/example/service&quot;, &quot;example.service&quot;)<br>if _err != nil {<br> return _err<br>}<br>select {}</pre><p>We export our interface “example.service” in the object path “/example/service” and let the service run in the background. Now, let’s go with the client side.</p><h3>Client side</h3><p>This is the first thing someone can read on the main page of the DBus low-level C API: “If you use this low-level API directly, you’re signing up for some pain.” That said, it is not impossible to implement it and is kind of fun. It suggests using other languages, wrappers, or frameworks, but trying with this implementation allows us to see step by step the process of sending a message. So let’s see it.</p><pre>DBusConnection *conn = NULL;<br>DBusError err;<br>dbus_error_init(&amp;err);<br>conn = dbus_bus_get(DBUS_BUS_SESSION, &amp;err);<br><br>if (dbus_error_is_set(&amp;err)) { <br>      printf(&quot;Error: %s\n&quot;, err.message); <br>      dbus_error_free(&amp;err); <br>      exit(1);<br>}<br>dbus_bus_set_unique_name(conn, &quot;awesomeappiguess&quot;);</pre><p>The initial process is similar to the Go server example, but we add an “err” type of variable, which will receive any error that we can get in any call or configuration (for example, the error return type implemented in the method “Hello” in the Go server). As in the Go server, we request a session bus and establish our bus name “awesomeappiguess” (which is not necessary, since we don’t need to know at all times the bus name of this connection).</p><p>To check that the bus name was changed, we can ask with the <em>dbus_bus_get_unique_name</em>() function:</p><pre>const char * busname = dbus_bus_get_unique_name(conn);<br>printf(&quot;Bus name is %s\n&quot;, busname);</pre><p>Now, let’s make a call to the Method exposed in the Go server:</p><pre>char * name = &quot;juan&quot;;<br> DBusMessage * msg = dbus_message_new_method_call(&quot;example.service&quot;, &quot;/example/service&quot;, &quot;example.service&quot;, &quot;Hello&quot;);<br>    <br>dbus_bool_t res = dbus_message_append_args (msg, DBUS_TYPE_STRING, &amp;name, DBUS_TYPE_INVALID);<br><br>DBusMessage * reply_msg = dbus_connection_send_with_reply_and_block(conn, msg, DBUS_TIMEOUT_USE_DEFAULT, &amp;err);<br>if (dbus_error_is_set(&amp;err)) { <br>      printf(&quot;Error %s\n&quot;, err.message); <br>      dbus_error_free(&amp;err); <br>}<br>dbus_connection_flush(conn);<br>dbus_message_unref(msg);</pre><p>So, it will send “juan” to the method for the greetings! First, it creates a message, in that message it specifies the busname, object path, interface, and lastly the method it wants to call, in this case, Hello (Note that I am passing the name of the method in a string as it is typed in the Go server function). Also, the method expects a parameter, so for that, it has to append it to the message with the function <em>dbus_message_append_args</em></p><p>Since it is a function that returns a value, and it expects a reply from the method the function, calls the function <em>dbus_connection_send_with_reply_and_block,</em> which will block until we receive a reply message, stored in the <em>reply_msg</em> variable.</p><p><em>dbus_connection_flush</em> will wait until the message queue is empty when sending a message, and <em>dbus_message_unref</em> will clean the memory it used to store the message it sent.</p><p>Now, let’s get the reply message that the program is expecting.</p><pre>char * reply = NULL;<br>dbus_message_get_args(reply_msg, &amp;err, DBUS_TYPE_STRING, &amp;reply, DBUS_TYPE_INVALID);<br>// remember always check if some errors happened :)<br>printf(&quot;%s\n&quot;, reply);</pre><p>Since it is expecting a string, it creates a pointer to a char variable called reply and call the function dbus_message_get_args to extract the return value of the method.</p><p>Let’s test the implementation.</p><h3>Result</h3><p>Let’s run the server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*nOkAfl31z-UsqLqe" /></figure><p>and, to compile the C code, we use this command:</p><pre>gcc main.c -o main -I/usr/include/dbus-1.0 -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include -ldbus-1</pre><p>And execute the binary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/0*ESXAhfSYxuuFq4mS" /></figure><p>And as that, the program in C, made a call to a program in Go</p><p>Complete source code:</p><p><a href="https://github.com/juamarCas/DBUS_example">https://github.com/juamarCas/DBUS_example</a></p><h3>Acknowledgement</h3><p>This article and project were possible thanks to the people who dedicated some time to explaining these concepts. All the links to pages that I used to create this article are listed here:</p><ul><li>Matthew Jhonson: <a href="https://www.matthew.ath.cx/misc/dbus">https://www.matthew.ath.cx/misc/dbus</a></li><li>DBUS freedesktop specification: <a href="https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces">https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces</a></li><li>DBUS low-level API for C: <a href="https://dbus.freedesktop.org/doc/api/html/index.html">https://dbus.freedesktop.org/doc/api/html/index.html</a></li><li>Investigating DBUS for Linux/GNU: <a href="https://github.com/makercrew/dbus-sample">https://github.com/makercrew/dbus-sample</a></li><li>godbus: <a href="https://pkg.go.dev/github.com/godbus/dbus#NewConn">https://pkg.go.dev/github.com/godbus/dbus#NewConn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d740dc790ce8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IR control for air conditioner]]></title>
            <link>https://medium.com/@juanmartincas/ir-control-for-air-conditioner-7b5338d5c7d2?source=rss-28c883f5974c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b5338d5c7d2</guid>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[microcontrollers]]></category>
            <category><![CDATA[electronics]]></category>
            <dc:creator><![CDATA[Yiond]]></dc:creator>
            <pubDate>Thu, 15 Aug 2024 20:19:30 GMT</pubDate>
            <atom:updated>2024-08-15T21:32:22.156Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>IR stands for infrared and consists of an electromagnetic wave with a wavelength range of 780 nm to 1000 nm above the visible light as shown in the following picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/0*tX-Ud5c6emKu2Chg" /><figcaption>Electromagnetic spectrum</figcaption></figure><p>ref: <a href="https://www.icnirp.org/en/frequencies/infrared/index.html#:~:text=Infrared%20radiation%20(IR)%2C%20also,3%20%C2%B5m%2D1%20mm).">https://www.icnirp.org/en/frequencies/infrared/index.html#:~:text=Infrared%20radiation%20(IR)%2C%20also,3%20%C2%B5m%2D1%20mm).</a></p><p>this allows a safe and high data rate communication channel between devices to exchange information or in the case of this article, send commands to other devices. This type of communication can be seen in remote controls for TVs and air conditioners among other devices that use remote controllers.</p><p>This article will describe an IR communication protocol and the design of an IR controller for an air conditioner from scratch with a microcontroller that sends a command to turn it off, explaining the concepts, procedure, logic, and finally the specific implementation with an STM32F1 microcontroller. It is worth mentioning that the concepts shown in this article are valid for other microcontrollers.</p><h3>Infrared communication</h3><p>Infrared waves are just the medium of transmission, so a communication protocol is needed, these are the rules that each device has to follow to establish communication and exchange information, in most cases the protocol used to communicate with air conditioners is a protocol called NEC.</p><p>The following part will describe some rules and times for this protocol, it is worth mentioning that these depend on the manufacturer but are the same ideas.</p><p>These are the following rules for this protocol:</p><ul><li>A start condition: is a high pulse followed by a low pulse, the duration of both of these pulses varies depending on the manufacturer.</li><li>Address of the device.</li><li>Command, for example: turn off, turn on, set 25°C.</li><li>Checksum: to check if the command was received without any data corruption</li></ul><p>Now, what is a logic low and logic high to send data? is not just a pulse in high and a pulse in low to establish the logic level, the logic levels are defined like this:</p><ul><li>a logic “1” is a 560us pulse, followed by a 1,24ms space</li><li>a logic “0” is a 560us pulse, followed by a 560us space</li></ul><p>The following picture shows an example command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/0*IWfJBvsWb0s4lqGO" /><figcaption>Command example</figcaption></figure><p>ref: <a href="https://techdocs.altium.com/display/FPGA/NEC+Infrared+Transmission+Protocol">https://techdocs.altium.com/display/FPGA/NEC+Infrared+Transmission+Protocol</a></p><h3>Pre-development</h3><p>Before starting the development of the solution, it was necessary to see real commands by sending some from the controller to have an idea of how the system behaves. For this, a circuit was built with an IR receiver and an oscilloscope to see its response from an air conditioner controller, specifically the one from the model LG VM242C7:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/0*HlXFoHWyyzY9y2gX" /><figcaption>Target air conditioner</figcaption></figure><p>ref: <a href="https://www.qccolombia.com/shop/product/vm242c7-aire-acondicionado-tipo-mini-split-dualcool-plus-standard-lg-24-000-btu-h-no-wifi-compresor-dual-inverter-220v-19302?page=4&amp;order=name+asc#attr=">https://www.qccolombia.com/shop/product/vm242c7-aire-acondicionado-tipo-mini-split-dualcool-plus-standard-lg-24-000-btu-h-no-wifi-compresor-dual-inverter-220v-19302?page=4&amp;order=name+asc#attr=</a></p><p>For the receiver, a TSOP38238 circuit was used (more about it later), for reference, this is the component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*MAviEX6gSZeNMtno" /><figcaption>TSOP38238</figcaption></figure><p>ref: <a href="https://components101.com/diodes/tsop38238-ir-receiver">https://components101.com/diodes/tsop38238-ir-receiver</a></p><p>This component will simulate a receiver from the air conditioner, where power and ground are connected to their respective rails, and the out signal is connected to the oscilloscope to see the waveform.</p><p>After connecting everything, and pressing the turn-off button of the air conditioner controller pointing to the circuit, the oscilloscope showed the following waveform:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lc-KB1Kc-V-TYWV7" /></figure><p>Following the rules mentioned before, a binary code was extracted and proceeded to measure the times of each pulse (notice that is “inverse logic”, by default, it is in a high state, and a pulse is represented with a low state) getting the following results:</p><ul><li>The start condition is a 3,2ms pulse followed by a 10ms space.</li><li>logic “1” is (roughly) a 600us pulse followed by a 600us space</li><li>logic “0” is (roughly) a 600us pulse followed by a 1,24 ms space</li></ul><p>Side note: only the last bits changed when another command was sent, so this varies a lot.</p><h3>Development</h3><p>With the concepts clear, the solution to this problem seems to be pretty simple, anyone can connect an infrared LED to emit pulses following the specifications mentioned before with an infrared LED receptor to receive them, like the following picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*HGGATlvHCTC7y-6C" /><figcaption>Simple solution circuit</figcaption></figure><p>This should get the work done, but there is a little problem, things like the sun, fire, lightbulbs, etc. can emit infrared radiation so the infrared signal that the LED is emitting has to compete with the rest of the infrared emitters causing noise and data loss, denying the communication between both systems.</p><p>What happens if the LED is only pulses of the desired length? the IR receiver won’t be able to differentiate from the infrared waves sent by the controller from the environment. On the other hand, a simple receiver alone won’t work, so integrated circuits like the TSOP38238 shown before have all the control systems to filter and demodulate the data, this is the block diagram of the IC:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/0*53mgXOQGnYl0wSX6" /><figcaption>TSOP28238 block diagram</figcaption></figure><p>From the side of the transmitter, the system should have a modulation frequency such that it can be used to transmit data that can be later demodulated and filtered, normally, the carrying frequency for this modulation is 38kHz, so for example, the system won’t just send a high pulse for 560us, it should send a 38kHz PWM signal for 560us.</p><p>Having all the requirements, this is what the system needs to send IR commands:</p><ul><li>A timer that can generate a 38kHz PWM signal</li><li>A timer to create a delay function that can handle microseconds</li></ul><p>The following program shows the logic and is not the complete code, but the logic can be implemented in most microcontrollers.</p><pre>// this structure is just to save the binary code for the command<br>typedef union nec_command{<br> struct bits{<br>  uint8_t bit_0: 1;<br>  uint8_t bit_1: 1;<br>  uint8_t bit_2: 1;<br>  uint8_t bit_3: 1;<br>  uint8_t bit_4: 1;<br>  uint8_t bit_5: 1;<br>  uint8_t bit_6: 1;<br>  uint8_t bit_7: 1;<br>  uint8_t bit_8: 1;<br>  uint8_t bit_9: 1;<br>  uint8_t bit_10: 1;<br>  uint8_t bit_11: 1;<br>  uint8_t bit_12: 1;<br>  uint8_t bit_13: 1;<br>  uint8_t bit_14: 1;<br>  uint8_t bit_15: 1;<br>  uint8_t bit_16: 1;<br>  uint8_t bit_17: 1;<br>  uint8_t bit_18: 1;<br>  uint8_t bit_19: 1;<br>  uint8_t bit_20: 1;<br>  uint8_t bit_21: 1;<br>  uint8_t bit_22: 1;<br>  uint8_t bit_23: 1;<br>  uint8_t bit_24: 1;<br>  uint8_t bit_25: 1;<br>  uint8_t bit_26: 1;<br>  uint8_t bit_27: 1;<br>  uint8_t bit_28: 1;<br>  uint8_t bit_29: 1;<br>  uint8_t bit_30: 1;<br>  uint8_t bit_31: 1;<br> }bits_t;<br> uint32_t command;<br>}nec_command_u;<br><br>int main(){<br>  //this function just initializates the timer to generate a pwm signal<br>  //but it deactivate the pwm by default<br>  nec_controller_init();<br>  <br>  //sets the binary code extracted for the &quot;turn-off&quot; command<br>  shut_down_cmd.bits_t.bit_0 = 1;<br>  shut_down_cmd.bits_t.bit_1 = 0;<br>  shut_down_cmd.bits_t.bit_2 = 0;<br>  shut_down_cmd.bits_t.bit_3 = 0;<br>  shut_down_cmd.bits_t.bit_4 = 1;<br>  shut_down_cmd.bits_t.bit_5 = 0;<br>  shut_down_cmd.bits_t.bit_6 = 0;<br>  shut_down_cmd.bits_t.bit_7 = 0;<br>  shut_down_cmd.bits_t.bit_8 = 1;<br>  shut_down_cmd.bits_t.bit_9 = 1;<br>  shut_down_cmd.bits_t.bit_10 = 0;<br>  shut_down_cmd.bits_t.bit_11 = 0;<br>  shut_down_cmd.bits_t.bit_12 = 0;<br>  shut_down_cmd.bits_t.bit_13 = 0;<br>  shut_down_cmd.bits_t.bit_14 = 0;<br>  shut_down_cmd.bits_t.bit_15 = 0;<br>  shut_down_cmd.bits_t.bit_16 = 0;<br>  shut_down_cmd.bits_t.bit_17 = 0;<br>  shut_down_cmd.bits_t.bit_18 = 0;<br>  shut_down_cmd.bits_t.bit_19 = 0;<br>  shut_down_cmd.bits_t.bit_20 = 0;<br>  shut_down_cmd.bits_t.bit_21 = 1;<br>  shut_down_cmd.bits_t.bit_22 = 0;<br>  shut_down_cmd.bits_t.bit_23 = 1;<br>  shut_down_cmd.bits_t.bit_24 = 0;<br>  shut_down_cmd.bits_t.bit_25 = 0;<br>  shut_down_cmd.bits_t.bit_26 = 0;<br>  shut_down_cmd.bits_t.bit_27 = 1;<br>  shut_down_cmd.bits_t.bit_28 = 0;<br>  <br>  // function to send the command for 29 bits<br>  nec_controller_send_command(shut_down_cmd, 29);<br><br>  //just do nothing<br>  while(1){<br>  __asm volatile(&quot;NOP&quot;);<br>  }<br>}<br><br><br>// iterates over all the bits one by one turning on and off the PWM signal<br>void nec_controller_send_command(nec_command_u command, uint8_t size){<br> uint8_t i = 0;<br> uint32_t cmd = command.command;<br> nec_controller_init_communication();<br> while(i &lt; size){<br>  if(cmd &amp; 0x01){<br>   nec_controller_send_1();<br>  }else{<br>   nec_controller_send_0();<br>  }<br>  cmd = cmd &gt;&gt; 1;<br>  i++;<br><br> }<br><br> return;<br>}<br><br><br>/**<br> * @brief start condition ofnec communication. <br> * for test device:<br> * a 9ms high state and then a 3,2ms low state<br> */<br>static void nec_controller_init_communication(){<br> nec_driver_start_pwm();<br> delay_us(3200);<br> nec_driver_stop_pwm();<br> delay_us(10000);<br>}<br><br><br>static void nec_controller_send_1(){<br> nec_driver_start_pwm();<br> delay_us(600);<br> nec_driver_stop_pwm();<br> delay_us(1240);<br><br>}<br><br>static void nec_controller_send_0(){<br> nec_driver_start_pwm();<br> delay_us(600);<br> nec_driver_stop_pwm();<br> delay_us(600);<br>}<br><br><br><br></pre><p>After programming the microcontroller and test sending a command to the same IR receiver with the oscilloscope, it showed the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9JP3kveUH40loJ78ZKAog.jpeg" /></figure><p>As it can be seen, it achieved similar results, the following picture shows the simplified schematic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*zoU9UsUUU10wMcwtpJGxDg.png" /><figcaption>Simplified circuit</figcaption></figure><p>A video with the result:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWMgvLXdNafs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FWMgvLXdNafs%3Ffeature%3Dshare&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWMgvLXdNafs%2Fhq2.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/69b6bfbe4ea71471d6619ef7a3aaebba/href">https://medium.com/media/69b6bfbe4ea71471d6619ef7a3aaebba/href</a></iframe><h3>Conclusions</h3><ul><li>These solutions can be used for example (adding more features) the ability to turn off air conditioners when no one is in the room.</li><li>Adding internet features can make this system controlled from anywhere in the world.</li><li>This project is an interesting way to see and test how these systems like air conditioners work with infrared communication very helpful when trying to fix one of these devices.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b5338d5c7d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>