<?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 Oleg Tarasov on Medium]]></title>
        <description><![CDATA[Stories by Oleg Tarasov on Medium]]></description>
        <link>https://medium.com/@oleg.tarasov?source=rss-5b8648659d8c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Fc-fNWcWo-Soy2M6szX20A.jpeg</url>
            <title>Stories by Oleg Tarasov on Medium</title>
            <link>https://medium.com/@oleg.tarasov?source=rss-5b8648659d8c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 17:57:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oleg.tarasov/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[Testing SCD41, BME280, BME680, DS18B20, PT100 and SNZB-02P temperature sensors for DIY thermostat]]></title>
            <link>https://medium.com/@oleg.tarasov/testing-scd41-bme280-bme680-ds18b20-pt100-and-snzb-02p-temperature-sensors-for-diy-thermostat-0e1e6683f5ac?source=rss-5b8648659d8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e1e6683f5ac</guid>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[home-assistant]]></category>
            <category><![CDATA[diy]]></category>
            <category><![CDATA[smart-home]]></category>
            <dc:creator><![CDATA[Oleg Tarasov]]></dc:creator>
            <pubDate>Mon, 20 Jan 2025 19:17:07 GMT</pubDate>
            <atom:updated>2025-05-01T08:23:08.673Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WQ2OqWC56QKoS3eqeTvIJw.png" /></figure><p>A crucial step towards my goal of individual room temperature control is to be able to measure current room temperature with precision and minimum amount of lag. Unfortunately, off-the-shelf battery-powered devices like <strong>Sonoff SNZB-02P</strong> are not really suitable for such a task. They are quite good at measuring temperature and humidity, but their out-of-the-box reaction time is slow due to the need to conserve battery (more on changing update frequency below). For example, <strong>SNZB-02P</strong> reports temperature only once per hour, given there are no rapid temperature changes like an open window in the winter. Such update frequency will lead to a dramatic overshoot in room temperature, so I decided to make my own ambient temperature sensor. It will also be a mains-powered device because I want to minimize the amount of battery hassle in my smart home. I decided to test several sensors and choose one that is most suitable for this task.</p><p><strong>Important note</strong>: all of my sensors were sourced from China, and most of them from AliExpress. I did not get my sensors from official distributors, so there is a real possibility that all sensors I tested were unreliable knock-offs. This post is intended only for my fellow DIY enthusiasts who experiment with their own devices and in their own homes. Although I use a somewhat calibrated reference temperature sensor, my methodology is quite wonky overall. I urge you not to make any decision about commercial or industrial applications based on data presented in this post. I will not be responsible for any loss that you might incur by taking into account information from this post.</p><h3>Reference sensor (PT100)</h3><p>I made several attempts at testing these sensors, but earlier iterations had one flaw: I didn’t have a ground truth sensor, so I had no way of telling which sensor showed correct values. At some point I decided to stop goofing around and find a way to make precise measurements to compare all the other sensors to. Turns out, you don’t need a laboratory-grade device for that: <strong>PT100</strong> RTDs are relatively cheap and very precise. I got a 3-wire version from a local electronics supplier, along with a <strong>MAX31865</strong> board, which removes all the hassle of interpreting resistance values and just gives the final measurement over SPI. Be sure to read the original <a href="https://learn.adafruit.com/adafruit-max31865-rtd-pt100-amplifier?ref=olegtarasov.me">Adafruit tutorial</a>, because the board needs some tuning depending on what type of RTD you have. My board was definitely not the original Adafruit version (rather a Chinese knock-off really), but it still works nicely. I also removed screw terminals and sensor connectors, and soldered the wires directly to the board in order to minimize parasitic resistance from an accidental poor connection.</p><p>I then soldered a basic test board with a <a href="https://doc.riot-os.org/group__boards__esp32__mh-et-live-minikit.html?ref=olegtarasov.me">MH-ET LIVE MiniKit</a> and the following ESPHome configuration:</p><pre>esphome:<br>  name: sensor-tester<br>  friendly_name: Sensor Tester<br><br>esp32:<br>  board: mhetesp32minikit<br>  framework:<br>    type: esp-idf<br>    version: recommended<br><br>wifi:<br>  ssid: !secret wifi_ssid<br>  password: !secret wifi_password<br><br># Enable Home Assistant API<br>api:<br>  encryption:<br>    key: !secret api_key<br><br>ota:<br>  - platform: esphome<br>    password: !secret ota_password<br>    <br>logger:<br>  level: INFO<br>  <br># RTD Configuration<br>spi:<br>  clk_pin: GPIO18<br>  miso_pin: GPIO19<br>  mosi_pin: GPIO23<br>  <br>sensor:<br>  - platform: max31865<br>    name: &quot;RTD Temperature&quot;<br>    cs_pin: GPIO5<br>    update_interval: 10s<br>    reference_resistance: 430 Ω<br>    rtd_nominal_resistance: 100 Ω<br>    mains_filter: 50 Hz<br>    rtd_wires: 3<br>    filters:<br>      - offset: 3.10 # Calibrated by ice water test :)</pre><h3>Calibrating the sensor</h3><p><strong>PT100</strong> is a precise sensor, but I soon found that it steel needed calibrating. The easiest method I could find to calibrate at home was to submerge the sensor into ice water. The idea is that in order to calibrate a sensor, you need a known reference point, and it’s known that water turns to ice at 0° C. So we can assume that ice water is close to 0°C and calibrate the sensor accordingly. It’s not a precise method, but we are not running a lab here, and such precision will be more than enough for room temperature control. So here is the calibration process where I submerge the RTD into ice water along with a temperature probe from a multimeter to verify we are indeed in the vicinity of 0°C.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zw3JIYJlxn1prIUG.jpeg" /></figure><h3>Test setup</h3><p>Here is a photo of my testing rig with all the sensors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cnUgnI2F2rKIkpFC.jpeg" /></figure><p>Now, that’s A LOT of sensors 😄 Here is what’s going on:</p><ul><li>I’ve got a separate in-wall ESPHome device with SCD41 sensor in its own enclosure and a <strong>DS18B20</strong> sensor that just barely shows itself. The original idea was to have a single in-wall device that measures heated floor temperature with a separate <strong>DS18B20</strong> probe, and also measures room temperature (and hopefully humidity and CO2) through small cutouts in the decorative wall panel (test holes are not pretty; I was going to ultimately use laser engraving).</li><li>There is a <strong>PT100</strong> reference sensor.</li><li>Test board has <strong>SCD41</strong> and <strong>BME280</strong> sensor which are not enclosed.</li><li>The lower enclosure contains another <strong>SCD41</strong> and <strong>BME680</strong> sensors. The idea is to see whether adding an enclosure to the sensor hurts its performance. I also tested a configuration where <strong>BME680</strong> was replaced with a second <strong>BME280</strong>, so that enclosed version could be compared with the dangling one. The enclosed variant looks like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/0*pvvmzy3gx4kvntrr.jpeg" /></figure><p>I also made a dashboard in Home Assistant using awesome <a href="https://github.com/dbuezas/lovelace-plotly-graph-card?ref=olegtarasov.me">lovelace-plotly-graph-card</a> integration.</p><h3>DS18B20: the simplest and most responsive, but not when inside the wall</h3><p>It turns out that a good old <strong>DS18B20</strong> sensor follows my reference RTD with the most precision and responsiveness. But there is a caveat: it shouldn’t be placed very close to a wall, and not inside the wall socket like I originally wanted.</p><h3>In-wall sensor</h3><p>My in-wall <strong>DS18B20</strong> isn’t even really inside the wall, but still it doesn’t respond well to increases in temperature when radiators start heating the room. It follows RTD quite closely when there is no heating and room temperature is more or less the same, and it even detects when I open the window in the adjacent room, while no other sensors detect that (it’s 10–20 cm closer to the door, and that’s enough to catch a draft). But when radiators are turned on, this sensor doesn’t detect rising heat as rapidly as the dangling sensor. Unfortunately, such behavior will result in heavy overshoot and in-wall variant can’t be used for reliable temperature control.</p><h3>Dangling sensor</h3><p>The dangling <strong>DS18B20</strong> on the other hand followed the reference sensor precisely and with no lag. So if it’s acceptable to just leave an unenclosed <strong>DS18B20 </strong>in your setup, this is the cheapest and most hassle-free option to measure room temperature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vKTbnQc23CmhcUR-.png" /></figure><p>Here is a graph showing reference RTD in green, dangling <strong>DS18B20</strong> in red (needs to be offset just a little) and in-wall <strong>DS18B20</strong> in blue:</p><h3>BME280: unreliable temperature and humidity.</h3><p><strong>IMPORTANT!</strong> The first version of this post said that BME280 is a reliable temperature sensor. After experimenting with it a bit more, I found that this is not the case (at least, for my particular sensors). I’m changing my recommendation, which is now: <strong>don’t use BME280 to measure ambient temperature and humidity</strong>. I suggest using a much more reliable <strong>SHT40</strong> sensor.</p><p>First of all, it should be noted that <a href="https://www.bosch-sensortec.com/products/environmental-sensors/humidity-sensors-bme280/?ref=olegtarasov.me">BME280</a> is a <strong>humidity and pressure</strong> sensor. The datasheet clearly states that temperature sensor is primarily used to compensate readings for pressure and humidity, and ambient temperature can be at best <em>estimated</em>. Curiously, temperature readings proved to be quite good in both sensors I tested, while humidity readings were off by whopping 15 points comparing to all other sensors. I don’t have a reference humidity sensor, but given that literally all other sensors showed humidity around 40%, both <strong>BME280</strong> sensors were showing around 25–27%. The problem with temperature reading became apparent after I tried using this sensor for a couple of days. Unfortunately, my <strong>BME280</strong> sensors turned out to be susceptible to huge temperature drifts at the scale of 1–2° which renders them completely useless for fine-grained room temperature control. I am removing a remaining part of this post concerning the <strong>BME280</strong> sensor since it proved to be mostly inaccurate.</p><h3>BME680: great when not enclosed, decent when enclosed. Unreliable CO2 readings.</h3><p><a href="https://www.bosch-sensortec.com/products/environmental-sensors/gas-sensors/bme680/?ref=olegtarasov.me">BME680</a> is a gas sensor, which can also measure temperature and humidity. I was hoping that this sensor will allow me to monitor not only temperature, but also air quality in the room, so that alarm could be raised when CO2 climbs to dangerous levels. There is also a <a href="https://esphome.io/components/sensor/bme68x_bsec2.html?ref=olegtarasov.me">BSEC2</a> library from Bosch that allows to estimate a ton of different gas-related readings, as opposed to the simple mode when only temperature, pressure, humidity and gas resistance is supported. As was hoping to estimate CO2 levels, I opted for BSEC2 version in my tests.</p><p>Unfortunately, CO2 reading turned out to be completely unreliable for me. <strong>BME680</strong> has an elaborate self-calibrating procedure, which takes into account historical data from the environment the sensor is exposed to. In my earlier experiments this sensor showed some adequate CO2 readings after 1.5–2 days of continuous operation with windows being opened periodically and people present in the house. But then we left for a week, the sensor became uncalibrated, showing super high value when we came back. There is no way to alter this calibration procedure (you can only set the number of days that are taken into account), and self-reported calibration status from the sensor (“calibrating”, “uncertain”, “calibrated”) in practice doesn’t reflect the reliability of CO2 reading.</p><p>I had no means of checking all the other gas-related readings from this sensor, but pressure, temperature and humidity readings were great and dynamics was similar to <strong>BME280</strong> in both enclosed and unenclosed variants (additionally, humidity reading was correct unlike <strong>BME280</strong>). Enclosed version of <strong>BME680</strong> also didn’t show a drift when temperature dropped to 22 °C at night, and it followed reference RTD rather nicely. But then again, <strong>BME680</strong> is much more expensive than <strong>BME280</strong>, so I see no reason to use it in a simple home automation setting given the unreliable CO2 readings. Don’t get me wrong: <strong>BME680</strong> might be a great sensor in some industrial applications, but for me it’s definitely an overkill. Also, if you are living in your house continuously and open the windows from time to time, CO2 readings from this sensor might work great for you. There is also a chance that I got some sketchy knock-off sensor, since almost all my sensors were sourced from AliExpress (see the note above).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-hrV5pNWXqBkj1WG.png" /></figure><p>Here is a graph showing reference RTD in green, and enclosed version of <strong>BME680</strong> in purple:</p><h3>SCD41: good when not enclosed, decent when enclosed. Great CO2 readings.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KTQ9e-tr3UH0yTia.jpg" /></figure><p><a href="https://sensirion.com/products/catalog/SCD41?ref=olegtarasov.me">SCD41</a> was the original sensor that I considered using for my project. It is a CO2 sensor (notice how most of the fancy sensors make a point of not calling themselves temperature sensors) and it also has consistent humidity readings. One drawback that I noticed is inconsistency in temperature sensing response between two sensors working in the same conditions (both without enclosure). In the graph below you can see these sensors in purple and gray. One sensor follows reference RTD (in green) quite closely, while the other clearly lags behind:</p><p>Humidity and CO2 readings from these sensors follow each other very closely, so I have no explanation for such a difference in temperature sensing behavior. CO2 readings are very consistent, but unfortunately I don’t have a reference sensor to estimate their correctness.</p><h3>In-wall sensor</h3><p>As you might remember from the beginning of the post, my original idea was to hide the sensor in the wall socket behind a decorative panel with laser-engraved cutouts. I also made a separate isolated enclosure for the sensor inside the wall socket so that heat from the main device wouldn’t interfere with the readings. Sensirion has an excellent <a href="https://sensirion.com/media/documents/0D0C9129/623B1183/Sensirion_CO2_Sensors_SCD4x_design-in_guide.pdf?ref=olegtarasov.me">design-in guide</a> at their website, which I tried to follow as close as possible. Unfortunately, this idea didn’t pan out. My tests show that temperature sensing response from in-wall <strong>SCD41</strong> is <em>abysmal</em>, with sensor reacting very poorly to changes in room temperature. Humidity readings were also consistently higher than those from other sensors. The only reading that was not at all affected was CO2 level. It seems that these sensors are really good at measuring CO2 (which is their actual purpose), no matter what enclosure you place them in.</p><p><strong>Placing a temperature and humidity sensor inside the wall will likely not work as you expect. Adding more cutouts doesn’t seem to remedy the situation. In order to measure temperature and humidity with some degree of reliability, you should place your sensors in an area with active air exchange.</strong></p><h3>Enclosed sensor</h3><p>Enclosed version of <strong>SCD41</strong> performed very closely to <strong>BME680</strong> in its temperature measurements. I need to point out that I put a more laggy <strong>SCD41 </strong>into the enclosure, and while unenclosed <strong>BME680</strong> followed reference RTD very closely, when both laggy <strong>SCD41</strong> and <strong>BME680</strong> were placed inside the enclosure, their performance became almost the same. Temperature response from <strong>SCD41</strong> was not awesome when the heating was turned on, but it’s comparable with <strong>BME280</strong>. I also noticed a more prominent deviation from reference RTD during the night when temperature dropped to 22 °C, just as with <strong>BME280</strong>.</p><p>Humidity and CO2 readings were great, and seemed not to be affected by adding an enclosure at all.</p><h3>Dangling sensor</h3><p>Unenclosed version of <strong>SCD41</strong> did a very good job at following reference RTD. But then again, as I mentioned earlier, the identical unenclosed <strong>SCD41</strong> showed much poorer temperature response at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4eE-EimI5qYgk3M0.png" /></figure><p>The following graph is a bit overcrowded showing reference RTD in green, in-wall <strong>SCD41</strong> in orange, enclosed <strong>SCD41</strong> in gray and dangling <strong>SCD41</strong> in purple:</p><h3>Sensor calibration</h3><p>SCD41 can also be calibrated: either automatically or manually. The best option is to leave automatic calibration on (set automatic_self_calibration in ESPHome config to true), but that requires that you expose the sensor to outdoors level of CO2 from time to time (basically open a window really wide for a couple of minutes 😄 ).</p><p>You can also set automatic_self_calibration to false, but you should calibrate your sensor once:</p><ul><li>You can estimate current outdoors CO2 levels at <a href="https://www.co2.earth/daily-co2?ref=olegtarasov.me">https://www.co2.earth/daily-co2</a> and replace the value 419 from the example (yes, global CO2 levels are not 419 ppm anymore 😦 ).</li><li>Run your sensor for more than 5 minutes outdoors and activate the calibration action.</li></ul><pre>button:<br>  - platform: template<br>    entity_category: config<br>    name: &quot;Calibrate SCD&quot;<br>    on_press:<br>      then:<br>        - scd4x.perform_forced_calibration:<br>            value: 425<br>            id: scd_sensor # sensor id</pre><p>Beware that CO2 readings will drift with time, so you will need to either perform another manual calibration or enable automatic_self_calibration.</p><h3>Pressure compensation</h3><p>I tested <strong>SCD41</strong> with ambient_pressure_compensation_source enabled (from a <strong>BME280</strong> sensor), but it didn&#39;t seem to make a difference in my environment.</p><h3>Sensor-to-sensor variability</h3><p>I had several <strong>SCD41</strong> sensors on hand, and discovered that temperature and humidity sensing capability was not uniform across all sensors. Some units tracked temperature quite nicely, but others clearly had lower sensitivity to changes in temperature. Also, some sensors consistently report humidity values that are quite off from the rest of the bunch. CO2 readings, on the other hand, were good and consistent across all sensors.</p><p><strong>IMPORTANT! </strong>This leads me to not recommend using <strong>SCD41</strong> alone for temperature and humidity measurements. I suggest using a much more reliable <strong>SHT40</strong> sensor instead.</p><h3>SHT40: the best option for temperature and humidity</h3><p>After testing so many sensors, I finally stumbled on a relatively cheap and reliable option: <strong>SHT40</strong> from Sensirion. My tests showed that this sensor works reliably in an enclosure, and follows the good units from the <strong>SCD41</strong> bunch. When enclosed, it has less sensitivity to sudden temperature drops compared to the non-enclosed RTD probe, but that’s expected. Here is a graph showing RTD probe in blue, <strong>SCD41</strong> in orange and <strong>SHT40</strong> in green.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OXzDwwU0vRKZy6ic.png" /></figure><h4>The final design</h4><p>I’m quite happy with <strong>SHT40</strong>, as it allowed me to finally settle on a design for my room sensors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1HzYhOrFb605xp9Z.jpeg" /></figure><p>I used a generic <strong>LK-AC92</strong> sensor case from AliExpress and hand-drilled two meshes for <strong>SCD41</strong> and <strong>SHT40</strong> sensors. This is not the pinnacle of craftsmanship, but nobody will look close enough at a wall sensor 😄 I’m using <strong>SCD41</strong> for CO2 measurement only and <strong>SHT40</strong> for temperature and humidity.</p><h3>Sonoff SNZB-02P: as good as SCD41 whith increased update frequency</h3><p>Battery-powered sensors are always a compromise between battery life and update frequency. <strong>Sonoff SNZB-02P</strong> is a great sensor (it’s based on <strong>SHT40</strong> from Sensirion), but it provides very infrequent updates out of the box. It reports a value every hour or if temperature changes by 1 °C or more. Such a low sensitivity is not useful for controlling room temperature because of large overshoots that will inevitably happen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sy6kbQ-duzY_ysWD.png" /></figure><p>This is a graph of <strong>Sonoff SNZB-02P</strong> (in gold) versus enclosed <strong>SCD41</strong> (in gray) and reference RTD (in green).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hrdirj6VtGsfHtD6.png" /></figure><p>Fortunately, you can change reporting frequency and sensitivity for <strong>Sonoff SNZB-02P</strong>. I am using <a href="https://www.zigbee2mqtt.io/?ref=olegtarasov.me">Zigbee2MQTT</a>, and these settings can be found under the Reporting tab of your device.</p><ul><li>Min/Max rep interval are set in seconds and define minimum and maximum update frequency. Max interval is the frequency of mandatory updates, even if measured temperature doesn&#39;t change much. Here I set max interval for a <strong>Sonoff SNZB-02P</strong> sensor to 5 minutes (300 secs), but it doesn&#39;t respect this setting very well and still reports approximately once in 30 mins.</li><li>Min rep change is the delta with a previous value that is required to do an unscheduled report. For <strong>Sonoff SNZB-02P</strong> it was set to 1 °C, and I changed it to 0.1 °C. This actually works better than report interval, and sensor starts to report small deltas. Mapping is really not straightforward and is not universal for different measurements (temperature, humidity etc). For temperature the desired delta (0.1 in my case) must be multiplied by 100 to get the setting value (I set it to 10).</li></ul><p>These are the default settings. We are interested in Min/Max rep interval and Min rep change values for Temperature cluster (I&#39;m not an expert in Zigbee terminology, so bear with me).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*td8OBcoHuBTvZGLj.png" /></figure><p>After I changed these settings and ran some tests, I found that <strong>Sonoff SNZB-02P</strong> performed remarkably close to <strong>SCD41</strong> in enclosure. Here is <strong>Sonoff</strong> in gold, <strong>SCD41</strong> in gray and reference RTD in green:</p><p>Sonoff sensor needs a little offset, but other than that it is very close to what <strong>SCD41 </strong>measures.</p><p>I don’t know how dramatic will the effect of increased frequency on battery life be, but if you consider using this sensor in this mode, also consider <a href="https://www.reddit.com/r/homeautomation/comments/1aj2zjn/modified_sonoff_snzb02p_dc_battery_temperature/?ref=olegtarasov.me">providing a mains power source with a hack</a>.</p><h3>Conclusions</h3><p>When I started this project, I definitely didn’t expect to go this deep into the rabbit hole. I thought that I’ll just slap together a couple of random sensors, write some code and be done with my per-room thermostats project. Instead, I’m doing this on and off for almost half a year and get a occasional raised eyebrow from my wife while dipping weird-looking stuff in ice water 😄 But it’s actually fun and I learn a lot of stuff in the process, and isn’t it this the true goal? ;)</p><ol><li>If temperature reading is all you are after, and you can get away with sticking an uncovered sensor somewhere not close to a wall, just go with <strong>DS18B20</strong>. It’s the cheapest, easiest and most reliable option in my opinion.</li><li>If you want to measure humidity, go with <strong>Sonoff SNZB-02P</strong> (with mains power hack if you want more frequency) as a finished device or with <strong>SHT40</strong> if you want to integrate it into your own device.</li><li>If you’d like to estimate CO2 levels in the room, use <strong>SCD41</strong>. You can also try to use <strong>BME680</strong> for a more precise temperature reading, but be aware that CO2 readings from this sensor require people living in the house and opening windows on a regular basis. Also, be prepared for inaccurate temperature readings from <strong>SCD41</strong>. I recommend using it with <strong>SHT40</strong> to get the most reliable results.</li><li>If you want a laboratory-grade precision in measuring room temperature, roll the <strong>PT100</strong> setup, but don’t forget to calibrate!</li></ol><p><em>Originally published at </em><a href="https://olegtarasov.me/environmental-sensors/"><em>https://olegtarasov.me</em></a><em> on January 20, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e1e6683f5ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ESPHome packages and substitutions tutorial: managing complex configurations effectively]]></title>
            <link>https://medium.com/@oleg.tarasov/esphome-packages-and-substitutions-tutorial-managing-complex-configurations-effectively-db941bbe9d98?source=rss-5b8648659d8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/db941bbe9d98</guid>
            <category><![CDATA[esphome]]></category>
            <category><![CDATA[diy]]></category>
            <category><![CDATA[iot]]></category>
            <dc:creator><![CDATA[Oleg Tarasov]]></dc:creator>
            <pubDate>Fri, 13 Dec 2024 14:13:53 GMT</pubDate>
            <atom:updated>2024-12-13T17:56:35.528Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oTU9His65FPQwJHf.png" /></figure><p>Over the course of this year I’ve been getting closer to my goal of regulating temperature in each room of my house individually. I made small ESPHome devices to measure ambient and floor temperatures and placed them in every room. I also installed <a href="https://olegtarasov.me/opentherm-thermostat-esphome/">my smart thermostat</a> at my relatives’ house and flashed a couple of Shelly relays with ESPHome. Needless to say, my ESPHome configurations quickly got out of hand, so it was time to introduce some unification and refactor tons of copy-pasted yaml. In this blog post I will describe the system that I’m currently using. You can use my base configurations with your own devices by referencing them from my repo: <a href="https://github.com/olegtarasov/esphome-common?ref=olegtarasov.me">https://github.com/olegtarasov/esphome-common</a>.</p><h3>How packages and substitutions work</h3><p>ESPHome has two main tools for configuration composition: <a href="https://esphome.io/components/packages.html?ref=olegtarasov.me">packages</a> and <a href="https://esphome.io/components/substitutions?ref=olegtarasov.me">substitutions</a>. When I first read the documentation on these features, I struggled to understand how are they interconnected and what approach would be optimal for me. Here I will try to explain these features together and build a composition system on top.</p><h3>Substitutions</h3><p><a href="https://esphome.io/components/substitutions?ref=olegtarasov.me">Substitutions</a> are quite simple: they are just shell-style variables that can be overriden in config file hierarchy. Let’s consider the simplest compilable config file for ESPHome:</p><pre>substitutions:<br>  foo: This is default value from innermost substitutions section<br><br>esphome:<br>  name: substest<br>  friendly_name: ${foo}<br><br>esp32:<br>  board: lolin_s2_mini</pre><p>If you run esphome config inner.yaml, you will see that frinedly_name gets substituted with default value specified in substitutions section. This is already useful for cases when you need to use the same value in different places in your config file.</p><h3>Includes</h3><p>Substitutions become even more powerful when used with !include statement. In ESPHome you can include arbitrary config snippets almost anywhere, while specifying values for substitutions that are used in the file you are including. There is a <a href="https://esphome.io/components/substitutions?ref=olegtarasov.me#substitute-include-variables">good example in ESPHome documentation</a>, which I will not repeat here for brevity.</p><p>The important thing here is that you can omit substitutions section with all the default values if you are not going to compile this file directly. Just be sure to provide substitution values for each file you are including.</p><h3>Packages</h3><p>The most interesting feature that allows you to build flexible composition architecture is <a href="https://esphome.io/components/packages.html?ref=olegtarasov.me">Packges</a>. They are different from !include statement in their ability to intelligently <strong>merge</strong> configurations. Consider the following configuration:</p><pre># sensor1.yaml<br><br>sensor:<br>  - platform: template<br>    id: sensor1<br>    name: &quot;Sensor 1&quot;</pre><pre># sensor2.yaml<br><br>sensor:<br>  - platform: template<br>    id: sensor2<br>    name: &quot;Sensor 2&quot;</pre><pre># sensors.yaml<br><br>esphome:<br>  name: test<br><br>esp32:<br>  board: lolin_s2_mini<br><br>&lt;&lt;: !include sensor1.yaml<br>&lt;&lt;: !include sensor2.yaml</pre><p>If you run esphome config sensors.yaml, you will notice that while configuration is considered valid, contents from sensor2.yaml is silently dropped, because YAML doesn&#39;t allow the duplicate sensor: section. But what happens if we import sensor1.yaml and sensor2.yaml as packages?</p><pre># sensors.yaml<br><br>esphome:<br>  name: substest<br><br>esp32:<br>  board: lolin_s2_mini<br><br>packages:<br>  sensor1: !include sensor1.yaml<br>  sensor2: !include sensor2.yaml</pre><p>Now when you run esphome config sensors.yaml, you will see that both sensors were included! This happens because package component intelligently merges config sections based on node names and component ids.</p><h3>Substitutions in packages</h3><p>Now we can go even further and eliminate repetition by extracting a generic sensor package and substituting the number in our main file:</p><pre># sensor_generic.yaml<br><br>sensor:<br>  - platform: template<br>    id: sensor${number}<br>    name: &quot;Sensor ${number}&quot;</pre><pre># sensors.yaml<br><br>esphome:<br>  name: substest<br><br>esp32:<br>  board: lolin_s2_mini<br><br>packages:<br>  sensor1: !include<br>    file: sensor_generic.yaml<br>    vars:<br>      number: 1<br>  sensor2: !include<br>    file: sensor_generic.yaml<br>    vars:<br>      number: 2</pre><p>After checking the result with esphome config sensors.yaml, you will see that we achieved the same result as before, but reduced copy-pasted config even further. As you can see, package variables and substitutions are in fact the same thing, and this is what confused me a lot when I read the official docs. For a while I thought they are different, but as it turns out, you don&#39;t need to change anything about your inner config files, whether you include them with a simple !include or as a package.</p><h3>Package hierarchy and substitutions</h3><p>The last piece of the puzzle is the relation between packages, substitutions and defaults sections. Official docs say that a package can have a defaults section where default values for that package&#39;s substitutions can be specified. I&#39;m not clear why did ESPHome creators decided to use two separate ways of doing basically the same thing - maybe defaults section came first, and when substitutions section was introduced, they decided to keep backwards compatibility.</p><p>Let’s consider two levels of configuration:</p><pre># inner.yaml<br><br>substitutions:<br>  foo: This is default value from inner substitutions section<br><br>defaults:<br>  foo: This is default value from inner defaults section<br><br>esphome:<br>  name: substest<br>  friendly_name: ${foo}<br><br>esp32:<br>  board: lolin_s2_mini</pre><pre># top-level.yaml<br><br>substitutions:<br>  foo: This is default value from top-level substitutions section<br><br>packages:<br>  base: !include inner.yaml</pre><p>After running esphome config top-level.yaml you will see that frinedly_name got replaced with value from defaults: section in inner.yaml, ignoring substitutions section from both files. But if we comment out the defaults: section, things change.</p><pre># inner.yaml<br><br>substitutions:<br>  foo: This is default value from inner substitutions section<br><br># defaults:<br>#   foo: This is default value from inner defaults section<br><br>esphome:<br>  name: substest<br>  friendly_name: ${foo}<br><br>esp32:<br>  board: lolin_s2_mini</pre><p>Now friendly_name got its value from top-level.yaml substitutions: section. So we can deduce the following rule:</p><blockquote>When there is no explicit value specified in package → vars: section, substitution at <strong>any</strong> depth will take its value from the <strong>outermost</strong> substitutions: section where its value is specified.</blockquote><p>This still means that we can specify substitution value directly in package → vars: section and it will override values from substitutions at any depth. To prove this, let&#39;s test three layers of packages:</p><pre># inner.yaml<br><br>substitutions:<br>  foo: This is default value from inner substitutions section<br><br>esphome:<br>  name: substest<br>  friendly_name: ${foo}<br><br>esp32:<br>  board: lolin_s2_mini</pre><pre># middle.yaml<br><br>substitutions:<br>  foo: This is default value from middle substitutions section<br><br>packages:<br>  base: !include inner.yaml</pre><pre># top-level.yaml<br><br>substitutions:<br>  foo: This is default value from top-level substitutions section<br><br>packages:<br>  base: !include<br>    file: middle.yaml<br>    vars:<br>      foo: &quot;Overriden!&quot;</pre><p>No matter how deep in include hierarchy the substitution foo is used, it still receives the Overriden! value explicitly defined in top-level.yaml.</p><blockquote>These experiments suggest that the most flexible way of combining packages and substitutions is to use the hierarchy of substitutions: blocks, abandoning the use of defaults: completely. This is, of course, my opinion, which can be wrong 😄</blockquote><h3>How I manage my configuration</h3><p>I hope that my examples help you better understand how packages and substitutions work. There are still more cool package features that I didn’t cover here, like <a href="https://esphome.io/components/packages.html?ref=olegtarasov.me#extend">Extend</a> and <a href="https://esphome.io/components/packages.html?ref=olegtarasov.me#remove">Remove</a> directives, but my goal was to explain the main rules of package composition and not copy the official docs 😄 Now I will try to explain how I manage my own ESPHome configurations.</p><h3>Composition over inheritance</h3><p>My first stab at refactoring my configurations was an idea to use some sort of inheritance, where there is one main device template that can be configured in different ways to do different things. I quickly abandoned this idea because it proved difficult to create such a universal configuration.</p><p>Instead I opted for small, composable yaml snippets that can be included as packages so their contents is intelligently merged by ESPHome. Each package is focused on a single task. For example, specify device board and framework, configure Wi-Fi, logging, etc.</p><p>For each ESPHome device I then create a separate yaml file, most of which consists of package include statements and some configuration using substitutions. Let&#39;s look at some of the base files that I use.</p><h3>Wi-Fi, OTA, and Home Assistant API</h3><p>All of my devices that connect to Wi-Fi, should also connect to Home Assistant and have an OTA update capability. I decided to lump all these sections in a single file, but you may split them in different files depending on your requirements.</p><pre># .wifi.yaml<br><br>wifi:<br>  ssid: !secret wifi_ssid<br>  password: !secret wifi_password<br>  manual_ip:<br>    static_ip: ${wifi_ip}<br>    gateway: ${wifi_gateway}<br>    subnet: 255.255.255.0<br><br># Enable Home Assistant API<br>api:<br>  encryption:<br>    key: !secret api_key<br><br>ota:<br>  - platform: esphome<br>    password: !secret ota_password<br><br>sensor:<br>  - platform: wifi_signal<br>    name: &quot;RSSI&quot;<br>    id: sensor_rssi<br>    update_interval: 60s<br>    entity_category: &quot;diagnostic&quot;<br><br>text_sensor:<br>  - platform: wifi_info<br>    ip_address:<br>      id: wifi_ip_address<br>      name: &quot;IP Address&quot;<br>      icon: &quot;mdi:wan&quot;<br>      entity_category: &quot;diagnostic&quot;<br>    bssid:<br>      id: wifi_bssid<br>      name: &quot;BSSID&quot;<br>      icon: &quot;mdi:wan&quot;<br>      entity_category: &quot;diagnostic&quot;</pre><p>There are two substitutions, wifi_ip and wifi_gateway that are configured in top-level files. I configure wifi_gateway as a substitution because I have two homes that reside in different subnets with one main router in each subnet.</p><h3>Base device: Wi-Fi, logging and restart</h3><p>Then comes the base device package that combines previously defined Wi-Fi package with logging code that calls Home Assistant and a restart button:</p><pre># .base_device.yaml<br><br>packages:<br>  wifi: !include .wifi.yaml<br><br>esphome:<br>  name: ${device_name}<br>  friendly_name: ${device_friendly_name}<br><br># Enable logging<br>logger:<br>  level: INFO<br>  logs:<br>    component: ERROR<br>    sensor: WARN<br>  on_message:<br>    level: DEBUG<br>    then:<br>      - homeassistant.action:<br>          action: system_log.write<br>          data:<br>            level: !lambda |-<br>              switch (level) {<br>                case 0:<br>                  return &quot;notset&quot;;<br>                case 1:<br>                  return &quot;error&quot;;<br>                case 2:<br>                  return &quot;warning&quot;;<br>                case 3:<br>                  return &quot;info&quot;;<br>              }<br>              return &quot;debug&quot;;<br>            logger: !lambda |-<br>              return &quot;esphome.${site}.${device_name}&quot;;<br>            message: !lambda |-<br>              return message;<br><br>button:<br>  - platform: restart<br>    id: restart_device<br>    entity_category: config<br>    name: &quot;Restart&quot;</pre><p>I was looking for a solution that would allow me to continuously ship device logs to Loki. I decided against making an external HTTP call on each logging operation (my internet might be down), and opted to call a Home Assistant service that writes logs from all my devices to its system log, which is later shipped to Loki with Promtail add-on.</p><h3>Boards</h3><p>I use several boards in my projects, so I created a package for each combination of a board and target framework. Here are some of them:</p><pre># .board.mhet.yaml<br><br>esp32:<br>  board: mhetesp32minikit<br>  framework:<br>    type: esp-idf<br>    version: recommended<br><br>wifi:<br>  enable_btm: true<br>  enable_rrm: true</pre><pre># .board.s3_micro.yaml<br><br>esp32:<br>  board: esp32-s3-devkitc-1<br>  variant: ESP32S3<br>  framework:<br>    type: esp-idf<br>    version: 5.1.2<br>    platform_version: 6.5.0<br><br>wifi:<br>  enable_btm: true<br>  enable_rrm: true</pre><h3>Debugging</h3><p>There are also a couple of packages that can help debug devices. I don’t usually include them in device config, but sometimes they are useful. Here is a package that configures debug sensors:</p><pre># .debug_sensors.yaml<br><br>debug:<br>  update_interval: 5s<br><br>sensor:<br>  # Debug sensors<br>  - platform: debug<br>    free:<br>      id: debug_heap_free<br>      name: &quot;Heap Free&quot;<br>      entity_category: diagnostic<br>    block:<br>      id: debug_heam_max_block<br>      name: &quot;Heap Max Block&quot;<br>      entity_category: diagnostic<br>    loop_time:<br>      id: debug_loop_time<br>      name: &quot;Loop Time&quot;<br>      entity_category: diagnostic<br><br>text_sensor:<br>  - platform: wifi_info<br>    scan_results:<br>      id: wifi_scan_results<br>      name: &quot;Wi-Fi scan results&quot;<br>      icon: &quot;mdi:wan&quot;<br>      entity_category: &quot;diagnostic&quot;</pre><p>And debug logging package. There are a lot of entries that are commented out — I just tune them on the spot when there is a need to add debug logs to a device.</p><pre># .debug_log.yaml<br><br>logger:<br>  #level: INFO<br>  level: DEBUG<br>  #level: VERY_VERBOSE<br>  logs:<br>    component: ERROR<br>    ## Enable the following when base level is DEBUG<br>    #opentherm: WARN<br>    # sensor: WARN<br>    # opentherm.output: INFO<br>    ## Enable the following when base level is VERY_VERBOSE<br>    #esp32.preferences: WARN<br>    #dallas.sensor: WARN<br>    #scheduler: WARN<br>    #sensor.filter: WARN<br>    #api.service: WARN</pre><h3>Putting it all together</h3><p>Now let’s stitch all these files together. In each room in my house I have devices that measure room and heated floor temperatures. In order to manage them all, I first create a base configuration.</p><h3>Base device config</h3><pre># .sensotron.base.yaml<br><br>packages:<br>  base: !include common/.base_device.yaml<br>  board: !include common/.board.s3_micro.yaml<br><br>sensor:<br>  - platform: dallas_temp<br>    id: floor_temp<br>    address: ${temp_floor_address}<br>    name: &quot;Floor Temperature&quot;<br>    one_wire_id: dallas_floor<br>    accuracy_decimals: 2<br>    update_interval: 30s<br>    filters:<br>      - sliding_window_moving_average:<br>          window_size: 5<br>          send_every: 2<br>  - platform: dallas_temp<br>    id: room_temp<br>    address: ${temp_room_address}<br>    name: &quot;Temperature&quot;<br>    one_wire_id: dallas_room<br>    accuracy_decimals: 2<br>    update_interval: 30s<br>    filters:<br>      - sliding_window_moving_average:<br>          window_size: 5<br>          send_every: 2<br><br>one_wire:<br>  - platform: gpio<br>    pin: GPIO4<br>    id: dallas_floor<br>  - platform: gpio<br>    pin: GPIO2<br>    id: dallas_room<br><br># Turn off the on-board LED<br>light:<br>  - platform: esp32_rmt_led_strip<br>    id: status_light<br>    rgb_order: GRB<br>    pin: GPIO21<br>    num_leds: 1<br>    rmt_channel: 0<br>    chipset: ws2812<br>    name: &quot;Status light&quot;<br>    internal: True<br><br>esphome:<br>  on_boot:<br>    then:<br>      - light.turn_off:<br>          id: status_light<br>          transition_length: 0s</pre><p>As you can see, this package uses pre-configured .base_device.yaml and .board.s3_micro.yaml, as well as defines two substitutions of its own: temp_floor_address and temp_room_address. These are the addresses of <a href="https://esphome.io/components/sensor/dallas_temp.html?ref=olegtarasov.me">Dallas temperature sensors</a> that I will configure for each end device.</p><h3>End device config</h3><p>And finally let’s configure an example end device.</p><pre># sensotron-bedroom.yaml<br><br>substitutions:<br>  device_name: sensotron-bedroom<br>  device_friendly_name: Sensotron Bedroom<br>  wifi_ip: 192.168.3.242<br>  site: estate<br>  wifi_gateway: 192.168.3.1<br>  temp_room_address: 0xc4012273a0e2d528<br>  temp_floor_address: 0x13062391ca90d928<br><br>packages:<br>  base: !include common/.sensotron.base.yaml</pre><p>As you can see, there is not much that goes into end device config. I set all the substitutions that are scattered among files in this one place — it’s easier to track them this way. I also set device-specific sensor addresses and include one base device package. And we are done! 🎉</p><h3>Conclusion</h3><p>Here I describe a heavily opinionated approach to managing ESPHome configuration files. It’s still evolving and you shouldn’t adopt it blindly. Look at your requirements and make a system that works for you. I hope this tutorial is helpful for people who, like me, struggled to understand how both packages and substitutions work in tandem.</p><p><em>Originally published at </em><a href="https://olegtarasov.me/esphome-packages-substitutions-tutorial/"><em>https://olegtarasov.me</em></a><em> on December 13, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db941bbe9d98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Nextion display with ESPHome]]></title>
            <link>https://medium.com/@oleg.tarasov/using-nextion-display-with-esphome-eb612f606aab?source=rss-5b8648659d8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb612f606aab</guid>
            <category><![CDATA[esphome]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[diy]]></category>
            <dc:creator><![CDATA[Oleg Tarasov]]></dc:creator>
            <pubDate>Tue, 11 Jun 2024 17:31:27 GMT</pubDate>
            <atom:updated>2024-12-13T17:45:33.279Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2bD9upOSkCgtRPxwlSbC7w.jpeg" /></figure><p>After <a href="https://olegtarasov.me/opentherm-thermostat-esphome/">successfully connecting my gas boiler to Home Assistant</a> I decided to add a physical touchscreen display so that less technically inclined users could operate the system. We also had contractors living in the house throughout the whole winter while they made renovations (this is a typical arrangement in Russia; we were not living there at the same time). I wouldn’t expect them to install Home Assistant and get familiar with all my stuff — they just needed a simple interface with minimal amount of buttons.</p><h3>Choosing the technology</h3><p>I was always planning to add a display to my thermostat, but I never thought about it in detail. I had a lot of experience coding WPF apps for Windows and even dabbled in some React shenanigans, so UI development was always a pretty high-level abstraction for me. The worst thing I could remember was some hairy MFC/WTL business when I was learning C++ in high school.</p><p>But then it dawned on me that making UI for a hardware device might be a little bit more complicated than that. There is no graphical OS, no window subsystem, no button primitives. In best case scenario you can draw lines or rectangles or paint individual pixels. Of course I suspected that some frameworks and higher-level solutions are out there, and they would help me avoid drawing at the lowest level.</p><p>After some initial googling and consulting with ESPHome docs, I arrived at two options:</p><ol><li>Use a cheaper general-purpose LCD display like <a href="https://esphome.io/components/display/ili9xxx?ref=olegtarasov.me">ILI9341</a> along with some UI framework. This seemed rather problematic since not many of these displays have an integrated touchscreen and bringing a UI framework to ESPHome also seemed non-trivial.</li><li>Use a more expensive touchscreen LCD from <a href="https://nextion.tech/?ref=olegtarasov.me">Nextion</a>, which is advertised to have an on-board CPU with built-in UI framework, so all you need to do is communicate with it using UART.</li></ol><p>As you might’ve guessed, I chose the second option. I never thought this would be a walk in a park, but frankly I was a little taken aback by problems cropping up on <em>every</em>. <em>Freaking</em>. <em>Step</em> of the way.</p><h3>Nextion displays</h3><p>Before I dive into all the details, let’s talk about concepts behind Nextion displays. As I mentioned earlier, creating hardware UIs using low-level primitives like lines and pixels is very time-consuming. If a company produces devices for which UI is not a defining feature (like industrial machinery), they don’t need to pour money into developing a unique interface. They can make a more generic and a bit clunkier UI and their customers won’t mind. And this is exactly the value proposition of Nextion displays. They have a CPU and memory on board and communicate over most common interface — UART. They come preinstalled with a proprietary operating system and a UI framework. You draw your UI in a graphical editor (much like in good old VB6 days), compile a package and upload it to the display. You can use a simple scripting language and incapsulate a lot of UI logic in the display itself. All that is left is to connect the display to your main device through UART and use high-level commands to change UI elements. It’s kind of like MVC pattern for hardware.</p><p>All this looks great on paper, but don’t rush buying a display for your next project just yet. Here are some drawbacks that I found while integrating a Nextion display into my project:</p><ol><li>Nextion scripting language is not really straightforward. It’s quite simple, yes, but there were a couple of times when I needed to dive into documentation, which is not always helpful.</li><li>Documentation exists, but it’s more of a command reference, rather than a set of tutorials and explanations. Be ready to watch some YouTube videos and spend time reading the reference, especially if you want to do something non-trivial.</li><li>The only way you can create firmware packages for the display is with Nextion Editor which only runs on Windows. There are no open-source projects, just this opaque vendor IDE. If it works for your use case — great, because this IDE is really not that terrible. But if it doesn’t work for you, then then there is no other option, but to choose a different technology. I use MacBook as my daily driver and had no problems running Nextion editor <a href="https://olegtarasov.me/alternatives-to-parallels-desktop-on-apple-silicon/">under Windows 11 in UTM</a>.</li><li>Integrating Nextion display with ESPHome is no walk in the park either. All those fancy <a href="https://esphome.io/components/display/nextion.html?highlight=nextion&amp;ref=olegtarasov.me#see-also">sensors</a> worked most of the time, but when they didn’t, they randomly corrupted their states which completely jumbled the whole logic of the thermostat.</li></ol><p>If all those caveats are acceptable for you use case, then by all means try those displays in your project.</p><h3>Drawing the UI</h3><p>It’s easy to be blown away by all the slick demos that exist on the net for Nextion displays. When I first saw them, I thought that all those translucent buttons and futuristic gauges are part of Nextion framework, and all I need is to install Nextion Editor and start creating some crazy-ass thermostat UIs. Well, nope 😃</p><p>All those fancy UI elements are in fact just pre-rendered images that you need to supply yourself. Nextion UI framework is much simpler that one would suspect by just looking at demos. Basically, each element can be either this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/0*f_fmq0AJhNMHvCwJ.png" /></figure><p>Or it can be any image you define. UI elements have some additional mechanics. For example, you can specify two button images for its normal and pressed states. So if you don’t want your UI to look like the image above, be prepared to spend some quality time with image editor before you can actually start doing anything with the display.</p><p>For my thermostat project I decided to use an excellent <a href="https://github.com/basnijholt/lovelace-ios-themes?ref=olegtarasov.me">collection of iOS themes for Home Assistant</a> as a starting point. I carefully crafted my UI mockup and finally settled on this version:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*DDJbfqi6KM3Gkv_2.png" /></figure><p>To everyone who contemplates embarking on a similar adventure I strongly suggest using image editor with layer support. Draw each element on its own layer; that way you can easily switch layers to bring your mockup to a desired state and then crop individual UI elements. If you have non-uniform background, you will have to crop each element along with its background, since Nextion doesn’t support PNG transparency, and you will end up with several versions of basically same UI element:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/0*UDjgcYkS9aKXkQAk.png" /></figure><h3>Compiling display firmware</h3><p>After I had my images ready, it was time to start building the actual UI for the display. Since I am using macOS, I had to jump through some hoops in order to use Nextion Editor, which runs on Windows only. I chose the option of running arm64 version of Windows 11 <a href="https://olegtarasov.me/alternatives-to-parallels-desktop-on-apple-silicon/">in UTM</a>, and didn’t encounter any problems with Nextion Editor so far.</p><p>First thing I did after creating a new project was generating some fonts. Nextion displays don’t come with any preinstalled fonts, so that you can import any font you like. The process is pretty straightforward: select the desired font and codepage in Tools→ Font Generator, save the resulting file and import generated font in Fonts tool window.</p><p>Next, I imported all my images using Picture tool window. Each image gets assigned a numeric id which we will use later.</p><p>I decided that I want my display to show initialization message while ESPHome boots and establishes proper connection with the display. So I renamed default page to init , set its sta property to image and specified the id of my full-screen initialization image. It&#39;s very important to visit the Event tool window and add the following script in a Preinitialize Event tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/0*sSC_fijWr0810XOU.png" /></figure><p>This will allow ESPHome to intercept page load event and use the on_page event. It&#39;s not mentioned anywhere in ESPHome docs, so be careful not to miss this if you want to handle such events.</p><p>Then I created a new page called main, activated it, set a different background and added the following controls (adding the sendme script as well):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/0*s3_eaKv8bxKgRINr.png" /></figure><ul><li>For all temperature values I used XFloat elements. They are really not straightforward, since Nextion doesn’t actually support floating-point numbers. It emulates them by using integer numbers and inserting a separator at the specified position, which is defined by properties ws0 and ws1. It took me a couple of YouTube videos to get to the bottom of this, but if you want to use fixed-point numbers with exactly 1 number after the separator, just set ws0 to 0 and ws1 to 1 as I did. It&#39;s also worth noting that Nextion doesn&#39;t support UI element transparency in a way that you would expect. I got around this issue with buttons by cropping my images along with their backgrounds, but another kind of workaround is needed for text elements. You need to emulate transparency by setting sta property to crop image and setting picc property to your background image. Nextion takes your background image, crops an area corresponding to the coordinates of the text element and sets this cropped image to be text element&#39;s background. It&#39;s super convoluted and hard to understand, but you will get the desired outcome in the end.</li><li>For “Up” and “Down” buttons I used simple Buttons with pic and pic2 properties set to images of normal and pressed states respectively. Don&#39;t forget to check the &quot;Send component ID&quot; checkbox for all buttons you plan on handling in ESPHome.</li><li>And finally for “Flame Active” icons I just used Picture components.</li></ul><p>It’s a good idea to give a meaningful objname to each component you plan to update or handle from ESPHome.</p><p>Finally, I switched to Program.s tab in the editor and changed baud value in default script generated by the editor.</p><pre>int sys0=0,sys1=0,sys2=0 <br>baud=115200 <br>dim=100 <br>recmod=0 <br>printh 00 00 00 ff ff ff 88 ff ff ff <br>page 0</pre><p>Most of this code is generated by default, but I increased baud rate to 115200 to be able to upload new firmware version by UART and not grow old in the process.</p><p>After all this was done, I compiled my firmware. Alas, the resulting TFT file wasn’t placed in my project directory, and it took some googling to figure out why. It turns out, compiled firmware files are placed in some obscure directory in your AppData folder, and you can get them out by selecting File → TFT File output, choosing a different directory and pressing the Output button.</p><p>Finally I was able to copy my firmware to a FAT32-formatted SD card, place it into the display and connect it to power. Firmware installation is fully automatic and if all goes well, you can just disconnect your display from power, take out the SD card and get working firmware on the next power-on.</p><h3>Integrating the display with ESPHome</h3><p>Before starting out on this journey I combed through ESPHome documentation and discovered a <a href="https://esphome.io/components/display/nextion.html?ref=olegtarasov.me">built-in integration for Nextion displays</a>. “Well, at least I won’t have any problems on ESPHome side of things” — or so I thought. Unfortunately, the original author of Nextion component seems no longer interested in supporting it. So when something goes wrong you have the choice of either delving into ESPHome source code and fixing the bug yourself, or reporting the bug on Github, and — let’s be honest — watching it grow old like a fine Italian <em>parmigiano</em> 🤌. And go wrong things did. But let’s not get ahead of ourselves and start with the the basics.</p><h3>Setting up UART</h3><p>As I mentioned earlier, Nextion displays talk to the main device over UART using plain text commands. So the first thing we do is define a UART component:</p><pre>## Nextion Display<br>uart:<br>  id: uart_2<br>  rx_pin: GPIO16<br>  tx_pin: GPIO17<br>  baud_rate: 115200</pre><p>Here I declare a UART component that uses pins 16 and 17. Actually, you can use almost any GPIO pin for UART, but those particular pins were the most comfortable to wire on my prototype, so I went with them. These pins are default for UART2, hence the id. But you should know that ESPHome juggles hardware UARTs dynamically based on particular chip model and whether logger is enabled, so depending on the chip I actually end up with UART0 or UART1 on those pins. This is completely irrelevant in case of ESP32 as long as your chip has more hardware UARTs than you need.</p><p>The problem would be using software UART either on ESP8266 or when you run out of hardware UARTs on ESP32. Software UART doesn’t work well on high speeds, so you will have to sacrifice the ability to update display firmware over UART instead of using the microSD card. But, as I will explain momentarily, even hardware UART will not save you from data corruption 😦</p><h3>Declaring the dsiplay</h3><p>Now we can declare our display component:</p><pre># Display<br>display:<br>  - platform: nextion<br>    id: boilotron_display<br>    uart_id: uart_2<br>    # touch_sleep_timeout: 60<br>    # auto_wake_on_touch: True</pre><p>Basic setup is pretty straightforward. We give our display an explicit id and tell it which UART to use. You can also uncomment two lines that enable auto sleep and wake up on touch.</p><h3>Moving data to and from display</h3><p>ESPHome has a nice collection of specialised sensors for Nextion displays: <a href="https://esphome.io/components/sensor/nextion?ref=olegtarasov.me">numeric</a>, <a href="https://esphome.io/components/binary_sensor/nextion?ref=olegtarasov.me">binary</a>, <a href="https://esphome.io/components/switch/nextion?ref=olegtarasov.me">switch</a> and <a href="https://esphome.io/components/text_sensor/nextion?ref=olegtarasov.me">text</a>. The idea is that you declare one sensor per button or number that you want to control on your display, and things magically work in both directions: when you change a sensor in ESPHome, its value is sent to Nextion, and if value is changed on Nextion side, it gets updated in ESPHome.</p><p>My idea was to setup a sensor for each numeric value in Nextion display and let buttons change only the values on the display side. Then those values would be propagated to ESPHome like in a textbook MVC pattern. I would also be able to change ESPHome values from Home Assistant, and they would be propagated back to the display.</p><p>It’s a nice and clean concept, and it almost worked. Unfortunately, sometimes data from display would get corrupted and I would receive weird values on ESPHome side. Since some values like CH setpoint get propagated directly to climate component, my whole thermostat would stop functioning. This would happen at random, even if no values were actually changed. I would have to add some hairy C++ code to each sensor to check every value that comes from the display, and even then it was unclear how to decide which values I should trust and which to discard.</p><p>It’s a classic architectural problem, when you have two sources of truth and you need to constantly keep them in sync. If your sync mechanism fails, you are in trouble. The best solution in such cases is to eliminate all sources of truth except one. In my case that meant abandoning all those fancy sensors and adopting a different paradigm. I would only intercept events like button presses, process them on ESPHome side and then send updated values to Nextion unidirectionally. This approach adds a noticeable lag when seeing a result of a button press, but no data would be ever corrupted since we are not receiving actual values from the display.</p><ul><li>It can be set from Climate component in Home Assistant</li><li>It can be set with buttons from display</li><li>It should be displayed in chsetpoint component on Nextion display.</li><li>It should be propagated to climate component in ESPHome.</li></ul><h3>Setting CH setpoint with buttons</h3><p>I will demonstrate this approach on a single value, CH setpoint. It’s deeply embedded into thermostat logic, so it’s the most interesting to dissect:</p><p>In order to intercept button presses from Nextion, I used specialized binary sensor components for nextion platform:</p><pre>binary_sensor:<br>  # Display buttons<br>  - platform: nextion<br>    page_id: 1<br>    component_id: 3<br>    id: display_chup<br>    internal: true<br>    on_press:<br>      then:<br>        - lambda: |-<br>            auto pid = id(boiler_pid);<br><br>            if (pid-&gt;target_temperature &gt;= 30) {<br>              ESP_LOGD(&quot;nextion&quot;, &quot;Reached maximum temperature&quot;);<br>            } else {<br>              auto call = pid-&gt;make_call();<br>              call.set_target_temperature(pid-&gt;target_temperature + 0.5);<br>              call.perform();<br>            }<br>  - platform: nextion<br>    page_id: 1<br>    component_id: 4<br>    id: display_chdown<br>    internal: true<br>    on_press:<br>      then:<br>        - lambda: |-<br>            auto pid = id(boiler_pid);<br><br>            if (pid-&gt;target_temperature &lt;= 15) {<br>              ESP_LOGD(&quot;nextion&quot;, &quot;Reached minimum temperature&quot;);<br>            } else {<br>              auto call = pid-&gt;make_call();<br>              call.set_target_temperature(pid-&gt;target_temperature - 0.5);<br>              call.perform();<br>            }</pre><p>Here I define sensors for Up and Down buttons that control CH setpoint. Note that for this sensor you must use numeric component and page ids that you can look up in Nextion Editor. As you might remember, we enabled “Send component ID” checkbox in Nextion Editor for button press and release events, and this is how these binary sensors work. When Nextion event is received, ESPHome fires on_press event for a specific sensor. Both event handlers find the PID component, check for boundaries and update PID target temperature as described in <a href="https://esphome.io/components/climate/?ref=olegtarasov.me#lambda-calls">ESPHome docs</a>.</p><p>As you might’ve guessed, I chose PID component to be the single point of truth for CH setpoint. I just showed how its value can be changed with buttons from display. The same value can be changed from Home Assistant, so we get that requirement fulfilled for free. What is left for us to do is to just update the resulting value on display. We do that using on_control handler in PID component. It gets fired when target mode is changed, and that includes target temperature.</p><pre># PID<br>climate:<br>  - platform: pid<br>    id: boiler_pid<br>    <br>    # More PID configuration...<br>    <br>    on_control:<br>      - lambda: |-<br>          auto target = x.get_target_temperature();<br>          if (!target.has_value()) {<br>            ESP_LOGD(&quot;pid&quot;, &quot;No value for PID target temperature&quot;);<br>          } else {<br>            ESP_LOGD(&quot;pid&quot;, &quot;PID setpoint: %f&quot;, *target);<br>            id(boilotron_display).set_component_value(&quot;main.chsetpoint&quot;, (int)(round(*target * 10)));<br>          }</pre><ol><li>Display a “Loading…” page on Nextion display while ESPHome boots up and initializes.</li><li>Send current values for various temperatures and other stuff to display.</li><li>Display the main page with all values present.</li></ol><p>Here we get target temperature from PID component, check if it has any value and send that value to Nextion. Note that we get a float value from PID component, but Nextion doesn&#39;t support floats - it just emulates them using integers and some floating point shenanigans. So first I am multiplying my value by 10 (since I decided to use one digit after decimal point) and then round it and cast it to int. In this case I address my chsetpoint component by its fully qualified name, including page name main.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*9zyDkGYd2EZdvp4_.png" /></figure><p>Now let’s add some missing bells and whistles to this system. I would like my device to behave in a following way:</p><p>As you might remember, I added two pages in Nextion Editor, and all controls are placed on the second page, main. The page with index 0, which is activated when the display is turned on, contains just one fullscreen image:</p><p>In order to do things on boot, I used on_setup handler on display component:</p><pre># Display<br>display:<br>  - platform: nextion<br>    id: boilotron_display<br>    uart_id: uart_2<br>    # touch_sleep_timeout: 60<br>    # auto_wake_on_touch: True<br>    on_setup:<br>      then:<br>        lambda: |-<br>          id(boilotron_display).set_component_value(&quot;main.chsetpoint&quot;, (int)(round(id(boiler_pid)-&gt;target_temperature * 10)));<br><br>          // Other initialization<br><br>          id(boilotron_display).goto_page(1);</pre><p>As you can see, I simply copy-pasted the code that gets CH setpoint from PID component and sends it to the display. When all initialization is done, I switch the page to main using goto_page method.</p><h3>Conclusion</h3><p>There are several other things that I would like to cover regarding Nextion displays in ESPHome, but this post is once again growing beyond any measure.</p><p>I hope that my experience with Nextion and ESPHome will help other people to save some time and avoid things that don’t work. For me it was definitely a fun journey, which allowed me to refresh my C++ skills and contribute two bugfixes to ESPHome codebase 😄</p><p><em>Originally published at </em><a href="https://olegtarasov.me/nextion-display-esphome/"><em>https://olegtarasov.me</em></a><em> on June 11, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb612f606aab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenTherm thermostat with ESPHome and Home Assistant]]></title>
            <link>https://medium.com/@oleg.tarasov/opentherm-thermostat-with-esphome-and-home-assistant-e9ce1aeb4c06?source=rss-5b8648659d8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9ce1aeb4c06</guid>
            <category><![CDATA[home-assistant]]></category>
            <category><![CDATA[smart-home]]></category>
            <category><![CDATA[iot]]></category>
            <dc:creator><![CDATA[Oleg Tarasov]]></dc:creator>
            <pubDate>Fri, 12 Apr 2024 19:58:02 GMT</pubDate>
            <atom:updated>2024-10-29T08:26:00.672Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jrO3NCYWPdsag6tH_kNPwQ.png" /></figure><p>In this series of posts I describe my journey of automating a heating system in my suburban home. This particular post is about a simple, but fully functional thermostat that uses a PID controller to maintain a target room temperature. I use this thermostat with an OpenTherm gas boiler, but most of the ESPHome configuration is universal and can be reused with other boilers, if they have a ESPHome component.</p><p>In the <a href="https://olegtarasov.me/opentherm-thermostat-esphome-prototype1/">previous post</a> I left off with a prototype interface board for an OpenTherm boiler, which was loosely connected to a ESP32 dev board by a bunch of jumper wires. In this post I am going to build a first useful device using ESPHome and Home Assistant.</p><h3>The water heating system</h3><p>It’s always good to plan in advance and gather requirements before you heat up the soldering iron. First of all, let’s take a look at the system I am dealing with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lMDok5pM8bRZqm6o.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uaCfVlXmVt1cZt-I.jpeg" /></figure><p>At first glance it looks really intimidating, and it took me a good portion of a week to figure out how it works. I had no prior experience with heating systems, so I had to read up quite a lot theory before I could make heads or tails of it. It really helps to remember that it’s all just water, flowing in the direction of lower pressure 😄</p><p>Anyway, here I have 3 subsystems:</p><ol><li>Wall-mounted radiators that do the bulk of heating.</li><li>Heated floor, with one or two individual loops in each room.</li><li>Indirect water heater that prepares domestic hot water for use in showers and faucets.</li></ol><p>Radiators and heated floors are merged into one branch, and water heater uses a separate branch. Natural gas boiler can operate only one branch at a time, switching between them when necessary. Hot water for showers and faucets has priority (it’s hardwired), so when it becomes colder, the boiler stops heating the house and starts heating the water tank. These two heating branches are closed loops which contain water under pressure of 1.5 atm. So a gas boiler heats up the water in these branches and moves it around the loop with electric pumps. When heated water passes radiators, heated floor pipes or water heater, it transfers its heat, gets colder, and then comes back to the boiler to be heated again. Whew, easy!</p><p>Another branch goes to the indirect water heater that transfers heat from boiler to cold water stored in the tank. This way, faucet water never enters the boiler itself, so that boiler heating loop maintains its own pressure at all times. Here is a simple schematic of how indirect water heater operates:</p><h3>Boiler control signals</h3><p>Controlling such a system would seem like a great challenge, but luckily a lot of low-level logic is hidden inside the boiler itself. It turns out, thermostat needs to provide only two control signals to the boiler:</p><ol><li>Central Heating setpoint, which is the temperature of heated water coming out of the boiler in a central heating loop. For example, I can tell the boiler that I want water to be 60° C at all times, and it will control its burning intensity and on-off cycles to match this temperature to the best of its ability. So I would always get water entering my heating system at 60°.</li><li>Domestic Hot Water (DHW) setpoint, which is the temperature of hot water coming out of the water heater to showers and faucets. Since domestic hot water never enters the boiler and heat transfer is happening inside the storage tank, the boiler needs an additional temperature sensor that needs to be placed in a special slot in the water heater. That way boiler knows when hot water stored in the tank becomes cooler and it’s time to switch to DHW loop from central heating.</li></ol><p>In theory, I could tell the boiler to always support each setpoint temperature constant, and it’s usually OK with DHW. But this approach is suboptimal for central heating, especially when weather is not that cold yet. Wall-mounted radiators would run for a short period of time at full capacity, overshoot target room temperature by 1–2 degrees and then turn off for a long time to wait for temperature to drop. This leads to unnecessary temperature fluctuations, which can easily be avoided. In order to control target room temperature more smoothly, I can vary Central Heating setpoint so that radiators and heated floors don’t blast with full power, but rather stay just warm enough to support a comfortable room temperature.</p><h3>Monitoring</h3><p>It’s always a good idea to monitor production systems, and water heating is no exception. There is not much variety in what I can monitor:</p><ol><li><strong>Temperature</strong>. Placing temperature sensors strategically can help „debug” heating systems and tune some hard to guess parameters like water pump power.</li><li><strong>Pressure</strong>. Maintaining near-constant pressure is critical for a heating system. It’s usually achieved by installing expansion tanks, but it’s always a good idea to be able to monitor system pressure remotely.</li><li><strong>Various boiler parameters</strong>, like whether it’s currently burning, or what heating loop is active.</li></ol><p>In this prototype I decided to limit monitoring to temperature and boiler parameters, since I wasn’t able to find an affordable and reliable digital pressure sensor. In order to monitor temperature, I decided to use widely popular <a href="https://www.analog.com/media/en/technical-documentation/data-sheets/ds18b20.pdf?ref=olegtarasov.me">DS18B20</a> temperature sensor. I like its simplicity and ability to daisy-chain several sensors on a single 1-Wire bus.</p><h3>Schematics and soldering</h3><p>It’s time to design a schematic for my thermostat. I am using a variation of <a href="https://www.reddit.com/r/esp8266/comments/a93raj/wemos_ttgo_mini_d1_esp32/?ref=olegtarasov.me">Wemos D1 Mini ESP32</a> development boards in this design. You can use any ESP32 dev board that is <a href="https://esphome.io/components/esp32?ref=olegtarasov.me">supported by ESPHome</a>, or even roll with a bare bones ESP32 SoC. I find dev boards exceptionally handy during prototyping phase. I even contemplate using dev boards in my final designs due to their small footprint and ease of soldering. Another perk of using a dev board is on-board USB and voltage conversion support. You can power your whole device with any 5V USB power supply and easily debug it if something goes wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MT8uq1Ac-Y0CLzkT.png" /></figure><p>As you can see here, most of the schematic is an implementation of <a href="https://ihormelnyk.com/opentherm_adapter?ref=olegtarasov.me">Ihor Melnik’s OpenTherm adapter</a>. I also added one 4-pin connector for a Nextion Display (will be covered in one of the next posts) and 10 3-pin connectors for various temperature sensors I plan to install into my system.</p><p>Long story short, this is the final prototype PCB:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c0zh3gLGfPdbVP1h.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6JExS7_gE92MCq_d.jpeg" /></figure><p>It’s definitely not a pinnacle of soldering mastery, but it works 😄 You can notice that there is a second screw terminal that is absent from the schematics. This an additional 5V power terminal that can be used to power the PCB instead of ESP32 board USB connector. I’m not sure whether it will be used in the final design, so I omitted it from the schematics. Here’s how it looks in a temporary enclosure with boiler and one temperature sensor connected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RjqEU0vHKZ5ISMVE.jpeg" /></figure><p>I also made 8 or 9 screw-in temperature sensors to monitor temperature in various point in my system. I bought super cheap analogue gauge thermometers, threw out the thermometers and glued a bunch of <a href="https://www.analog.com/media/en/technical-documentation/data-sheets/ds18b20.pdf?ref=olegtarasov.me">DS18B20</a> sensors into screw-in enclosures. I used a thermal glue which is also used to glue CPU heat sinks, and later filled it all with heat-resistant resin. Here is an individual temperature sensor and the whole rat’s nest of wires when they are all connected:</p><h3>Configuring ESPHome</h3><p>The final step in this little adventure is configuring and uploading ESPHome firmware to the device. But first we need to install ESPHome.</p><h3>Installing ESPHome in Home Assistant</h3><p>The great advantage of ESPHome is its tight integration with Home Assistant. While you can install ESPHome on your machine and don’t use HA at all, it’s much easier to start with HA integration, if using your device in HA is ultimately your goal.</p><p>To install ESPHome in HA, I went to Settings → Add-ons → Add-on store. I found ESPHome in the add-on list and installed it. It&#39;s also a good idea to turn on the &quot;Show in sidebar&quot; checkbox in order to find ESPHome dashboard more easily. I am running Home Assistant in its Operating System form, so I&#39;m able to install and maintain add-ons easily. If you are not using HA OS, then you probably can&#39;t install ESPHome add-on from the store. Your other option might be installing ESPHome on your machine by following <a href="https://esphome.io/guides/installing_esphome?ref=olegtarasov.me">the docs</a>.</p><h3>Creating a new configuration</h3><p>Creating a new device in ESPHome dashboard is really easy. I followed the wizard and after a little while ended up with a basic firmware uploaded to my prototype device. After that first upload updating the device is usually performed over the Wi-Fi. If you are not sure about this step, be sure to consult the <a href="https://esphome.io/guides/getting_started_hassio?ref=olegtarasov.me">official docs</a> for the most up-to-date instructions.</p><p>In the next few sections I will gradually build up ESPHome configuration to get a minimally functioning thermostat with PID control.</p><h3>Basic setup</h3><p>First of all, I declare some basic stuff: dev board configuration, wi-fi credentials and API keys:</p><pre>esphome:<br>  name: boilotron<br>  friendly_name: Boilotron<br><br>esp32:<br>  board: mhetesp32minikit<br>  framework:<br>    type: arduino<br><br>external_components:<br>  - source: github://olegtarasov/esphome-opentherm<br><br># Enable logging<br>logger:<br>  level: INFO<br>  logs:<br>    component: ERROR<br>    sensor: WARN<br>    opentherm.output: INFO<br><br># Enable Home Assistant API<br>api:<br>  encryption:<br>    key: &quot;&lt;your key&gt;&quot;<br><br>ota:<br>  password: &quot;&lt;your password&gt;&quot;<br><br>wifi:<br>  ssid: !secret wifi_ssid<br>  password: !secret wifi_password</pre><p>Note the external_components section. Since there is no built-in support for OpenTherm in ESPHome, I need to reference an external component. I will be using <a href="https://github.com/olegtarasov/esphome-opentherm/tree/new_lib?ref=olegtarasov.me">my fork</a> of the esphome-opentherm component. As I&#39;ve mentioned in a previous post, the upstream component seems to be abandoned and doesn&#39;t even compile with latest versions of ESPHome. Nevertheless, this component seems to be the most mature, so I decided to fork it, integrate several outstanding pull requests and replace the underlying OpenTherm protocol library. More on this in one of the next posts 😃 Here we just reference the external component.</p><h3>OpenTherm configuration</h3><p>Next I declare OpenTherm configuration with its controls and sensors:</p><pre># Declare the phisical pins that OpenTherm adapter is connected to<br>opentherm:<br>  in_pin: 21<br>  out_pin: 26<br><br># Outputs are controlled by some other components, not manually<br>output:<br>  - platform: opentherm<br>    t_set:<br>      id: boilotron_ch_setpoint<br>      min_value: 40<br>      max_value: 60<br>      zero_means_zero: true<br><br># Values that can be set maually from HA interface<br>number:<br>  - platform: opentherm<br>    t_dhw_set:<br>      id: boilotron_dhw_setpoint<br>      name: &quot;Hot Water target temperature&quot;<br>      min_value: 20<br>      max_value: 60<br>      restore_value: true<br>      initial_value: 60<br><br># Switches that can be operated manually from HA interface<br>switch:<br>  - platform: opentherm<br>    ch_enable:<br>      id: boilotron_ch_enable<br>      name: &quot;Central Heating enabled&quot;<br>      restore_mode: RESTORE_DEFAULT_OFF<br>    dhw_enable:<br>      id: boilotron_dhw_enable<br>      name: &quot;Hot Water enabled&quot;<br>      restore_mode: RESTORE_DEFAULT_OFF<br><br># Boiler numeric sensors<br>sensor:<br>  - platform: opentherm<br>    rel_mod_level:<br>      id: boilotron_rel_mod_level<br>      name: &quot;Boiler Relative modulation level&quot;<br>    t_boiler:<br>      id: boilotron_temperature_ch<br>      name: &quot;Boiler Feed Temperature&quot;<br><br># Boiler binary (True/False) sensors<br>binary_sensor:<br>  - platform: opentherm<br>    ch_active:<br>      id: boilotron_ch_active<br>      name: &quot;Boiler Central Heating active&quot;<br>    dhw_active:<br>      id: boilotron_dhw_active<br>      name: &quot;Boiler Hot Water active&quot;<br>    flame_on:<br>      id: boilotron_boiler_flame_on<br>      name: &quot;Boiler Flame on&quot;<br>    fault_indication:<br>      id: boilotron_boiler_fault<br>      name: &quot;Boiler Fault&quot;<br>      entity_category: diagnostic<br>    diagnostic_indication:<br>      id: boilotron_boiler_diagnostic<br>      name: &quot;Boiler Diagnostic&quot;<br>      entity_category: diagnostic</pre><p>There is a lot to process here, but let’s dissect this config step-by-step. First of all, on the top level you can see components: outputs, numbers, switches etc. These are sometimes confusing, because a component can live on the top level, like opentherm here, but in other cases top-level statements represent component „classes&quot;, with components nested underneath, like switches and sensors. There is no apparent system to this, you just need to consult <a href="https://esphome.io/?ref=olegtarasov.me">ESPHome documentation</a> a lot 😃</p><p>First of all I’m configuring base OpenTherm hub component to let ESPHome know which pins my adapter is connected to.</p><p>Next I declare several components that let me control the boiler and read its state. The most important is t_set component of class output. It corresponds to central heating setpoint, and declaring it as output means that I will not set its value manually, but rather through some other component. In a couple of moments I will connect a software PID controller to this output. There are some additional properties like min and max values. Recommended maximum temperature for heating system with wall-mounted radiators is usually 60° C and minimum temperature needs to be discovered empirically. I found that 40° is the minimum temperature that my boiler can sustain on its lowest burn intensity without turning off and on again.</p><p>Note that esphome-opentherm allows to declare any non-sensor component as a number - that way you will be able to set its value manually using Home Assistant UI. This is exactly what happens with t_dhw_set component - as noted earlier, we usually want faucet water to be roughly the same temperature, so I just need to set this temperature once and let boiler handle the rest.</p><p>I also declare two switches that allow me turn central heating and DHW on or off completely: ch_enable and dhw_enable. The state of these switches can be restored by ESPHome after reboot and I also prefer to set them to „off&quot; in case no saved value is present. RESTORE_DEFAULT_OFF allows me to do just that.</p><p>After that I declare a bunch of sensors that can be read from the boiler. rel_mod_level shows current burn intensity and t_boiler shows the temperature of the water coming out of the boiler (this is the temperature that we set with t_set). There is also a bunch of binary flags that indicate current state of the boiler.</p><p>OpenTherm is a common standard with many vendors and boilers implementing it to a different degree. My boiler is one of the simpler ones, and this is all the info that I can get out of it. Other boilers support more sensors, and you can find the whole list in the <a href="https://github.com/olegtarasov/esphome-opentherm/blob/new_lib/README.md?ref=olegtarasov.me">library readme</a> on GitHub.</p><h3>Adding room temperature sensor</h3><p>My goal is to maintain a fixed room temperature with minimum variation. In order to do that, I need to get this temperature from somewhere. In my target design I will place climate sensors in every room and connect them all to Home Assistant. It will be a complex control system which will have an ability to control temperature in each room individually with TRVs placed on radiators. But I should also plan for failure and make sure that my heating system can operate on a basic level when Home Assistant and even Wi-Fi are down. It’s also impractical to try and build a complex system right off the bat. I better start with something simple, and then iterate to add complexity.</p><p>The most self-contained way to measure room temperature that will be resilient to network failure is to connect a temperature sensor to the thermostat itself. So it’s time to connect a sensor to one of the temperature connectors that I left on the board and add some more ESPHome configuration (I omitted all the screw-in temperature sensors for the sake of simplicity):</p><pre># Temperature sensor hub<br>dallas:<br>  - pin: GPIO18<br>    update_interval: 30s<br><br>sensor:<br>  # [.. boiler sensors omitted ..]<br>  <br>  # Temperature sensors<br>  - platform: dallas<br>    address: 0x2001229265635128<br>    name: &quot;Room Temperature&quot;<br>    id: boilotron_temp_room<br>    accuracy_decimals: 2<br>    filters:<br>      - sliding_window_moving_average:<br>          window_size: 5 # Average over this number of last measurements<br>          send_every: 2 # When sensor update interval is 30s, new value will be pushed every minute <br>      # PID controller updates its parameters only on sensor signal, so we push the last value every second<br>      # We don&#39;t want to actually read the sensor temperature every second, since it would hurt performance.<br>      - heartbeat: 1s</pre><p>First of all, I declared a dallas component, which contains pin number for all the temperature sensors that are daisy-chained on a single 1-Wire bus. I also set update_interval so that all sensors on that bus will be polled once every 30 seconds. I wouldn&#39;t recommend decreasing this interval by much, since 1-Wire communication seems to hurt performance and even interfere with OpenTherm protocol (more on this in a separate post).</p><p>Next I setup individual temperature sensors. It’s important to note that this configuration goes into the existing sensor section, where I placed some OpenTherm sensors earlier. The most important here is sensor address. You can find out your sensor addresses by temporarily setting logger level to DEBUG and rebooting your device. ESPHome will print out addresses of all found sensors, so in order to determine an individual address you need to connect your sensors one by one and reboot after each new sensor is connected.</p><p>I also want to add several filters to this particular sensor. I’m going to use a PID controller to calculate target t_set temperature based on boilotron_temp_room temperature and there is a couple of considerations here:</p><ol><li>Digital temperature sensors can be rather noisy. For example, you can observe random small changes from one measurement to the next. These are OK when you just print your temperature reading to a dashboard, but for a PID controller every input change is a trigger to adjust the control signal. Such noise doesn’t reflect well on the resulting signal, so you typically want to make your temperature readings smoother. That’s why I added a sliding_window_moving_average filter which does just that: it takes last 5 measurements, averages them, and reports every other one to ESPHome. So if my update_interval is 30 seconds, every minute I will get a new measurement averaged over last 2.5 minutes. These values are eyeballed empirically and you might need different values based on how your particular sensors behave.</li><li>PID controller output is adjusted only when new input value is received. PID controller works is by making small changes to current output value, so pushing a new input each minute will be ineffective: we would wait for a very long time for t_set to change even a little bit. To combat that I apply a heartbeat filter to my temperature sensor. It remembers last known temperature reading and pushes it out every second. So effectively I will drive my PID controller every second with the same input, and each minute that input has a chance of updating if room temperature actually changes enough to go through the sliding average filter.</li></ol><p>I know, all these settings seem a bit arbitrary — that’s because they are. Finding the right combination of filters and coefficients took me some time of just running this system and staring at Home Assistant dashboard. If you try to reproduce this design, you might get lucky and these numbers work for you too. If they don’t — don’t despair, you can probably tune it to your environment in a couple of hours 😃</p><h3>Adding PID control</h3><p>OK, this is a super long post already, but bear with me — we are almost there. It’s time to put all these things together by adding a PID controller. It will take room temperature as an input and output a single number in range of [0..1], which is then scaled to fit the range of [min_value..max_value] in our t_set component.</p><p>The most useful example to help you understand a PID controller is cruise control in a car. You tell the car its desired speed and an onboard computer slowly tunes fuel intake and other parameters to reach that speed over a period of time. It’s important to understand that no control system reaches its target instantaneously (you can’t accelerate from 0 to 100 in 0 seconds) and it’s usually not desirable to change control signals by large amount (you can shift from first to fourth gear, but you car won’t thank you).</p><p>PID controller is a vital part of large and complex fields of control theory and industrial automation. People actually get degrees in this stuff, and that’s exactly what I did more than a decade ago 😀 But the truth is that most of this theoretical apparatus is very rarely used and people are just eyeballing the coefficients, even at serious establishments like oil refineries and nuclear plants. If you want to dive deeper into the theory, I suggest starting at <a href="https://esphome.io/components/climate/pid?ref=olegtarasov.me">ESPHome documentation for PID controller</a>. It’s a good idea to understand how it works in detail, but it’s not required right away. You can try my values and see if they make sense in your environment.</p><p>Here is how I configure a PID controller:</p><pre>climate:<br>  - platform: pid<br>    id: boilotron_boiler_pid<br>    name: &quot;Central heating&quot;<br>    heat_output: boilotron_ch_setpoint<br>    default_target_temperature: 23<br>    sensor: boilotron_temp_room<br>    visual:<br>      min_temperature: 15<br>      max_temperature: 30<br>      temperature_step:<br>        target_temperature: 0.5<br>        current_temperature: 0.1<br>    control_parameters: <br>      kp: 0.76394<br>      ki: 0.00050<br>      kd: 0 # Derivative term reacts too much to small changes in temperature, effectively turning off the boiler while target temperature is still far<br>      output_averaging_samples: 10<br>    deadband_parameters:<br>      threshold_high: 0.5<br>      threshold_low: -0.5<br>      # Will try to turn off any control signal inside the deadband in order to minimize flame jerking<br>      kp_multiplier: 0   # Added proportional gain since integral alone doesn&#39;t seem to fall fast enough when target is reached (but removed again after changing min feed temperature to 40 deg)<br>      ki_multiplier: 0.15  # integral accumulates at only 20% of normal ki<br>      kd_multiplier: 0.0   # derviative is turned off inside deadband<br>      deadband_output_averaging_samples: 15   # average the output over 15 samples within the deadband</pre><p>The most important settings are these:</p><ul><li>sensor - this is the input that is used to calculate the control signal. I put boilotron_temp_room there to point to my temperature sensor.</li><li>heat_output - the component that I want to control. I put boilotron_ch_setpoint there to control t_set value.</li><li>default_target_temperature - default temperature that I would like to have in my room. This is a starting point, and I can change target temperature in home Assistant UI later.</li></ul><p>There is a visual section that configures how the component will render in Home Assistant UI. I put some sensible boundaries on target temperature and adjust step size.</p><p>control_parameters and deadband_parameters sections contain the actual coefficients that are used for PID control algorithm. In ideal world of control theory you would use complicated methods to measure you particular system&#39;s response to various control signals, maybe solve a couple of partial differential equations and arrive at perfect values that work for you flawlessly. But in the real world these methods are seldomly used and you can try to reuse my values as they are.</p><p>The main idea here is that PID regulator outputs lower temperature when room temperature is close to target, and higher temperature if it’s further from target. For example, if my target is 23° and current room temperature is 22.7°, PID controller might output 40°, which is the lower bound in t_set component, heating my radiators just a little bit so that target temperature is reached slowly without little overshoot. But if my current temperature is 19°, the controller will likely output 60° in order to make radiators go full blast and heat the room faster.</p><p>After all this was done I compiled and uploaded new firmware to my device wirelessly using the „Install” button in ESPHome dashboard. After a couple of seconds, my device showed up in Home Assistant device list and this is roughly what I see if I open it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HAxPz1xp9v77QI9B.png" /></figure><p>If I click on „Central Heating”, I get a nice Home Assistant thermostat UI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/0*hAWMWMxfstU-gnQn.png" /></figure><p>Now I can add some of these items to my dashboard and control my heating system from my phone!</p><h3>Conclusion</h3><p>This turned out to be a much larger post than I anticipated. I didn’t cover a lot of topics like adding an LCD display or rewriting half of the OpenTherm library. Stay tuned for more posts with hairy details 😃</p><p><em>Originally published at </em><a href="https://olegtarasov.me/opentherm-thermostat-esphome/"><em>https://olegtarasov.me</em></a><em> on April 12, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9ce1aeb4c06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making a prototype DIY OpenTherm thermostat]]></title>
            <link>https://medium.com/@oleg.tarasov/creating-opentherm-thermostat-with-esphome-first-prototype-d86609b44e84?source=rss-5b8648659d8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d86609b44e84</guid>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[smart-home]]></category>
            <category><![CDATA[home-assistant]]></category>
            <dc:creator><![CDATA[Oleg Tarasov]]></dc:creator>
            <pubDate>Mon, 08 Apr 2024 14:37:10 GMT</pubDate>
            <atom:updated>2024-04-10T12:10:57.633Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXfFG0h0bTDJFHADCi0QHw.png" /></figure><h3>Introduction</h3><p>Recently me and wife became proud owners of a suburban home. We were both born and raised in a big city, so owning a house where you are responsible for your own heating system is a new challenge for both of us. I’ve dabbled in the field of IoT and smart home in the past, but it was mostly using Shelly smart relays and dimmers to control lights and electric outlets. But here in our new home we have an assortment of heating systems and devices:</p><ol><li>A Buderus Logamax U072 boiler running on natural gas, which can alternate between central heating and indirect water heater.</li><li>A Stout indirect water heater that heats up and stores domestic hot water.</li><li>A system of wall-mounted radiators in each room.</li><li>A system of heated floors throughout the entire house.</li></ol><p>Gas boilers such as ours are very popular in Russia, but most of them don’t come equipped with any smart or remote control features. For example, the most sophisticated thermostat from Buderus that you can use with our boiler is this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GGwWvcmHcOhCo0dG.jpg" /></figure><p>It’s a bit underwhelming, to say the least. Granted, you can even „program” it for different temperatures based on time of day and day of week, but this is not what I was looking for in 2023.</p><p>There are also more sophisticated systems from other vendors on the market, and they promise all the good stuff, at least on paper: mobile apps, cloud access, reporting, alerts and so on. But these are all cloud based services which are vendor-locked and closed-source, so I’m a bit reluctant to build critical and generally hard to replace infrastructure with a service that can be breached or simply go out of business. You can argue that a DIY solution is even less reliable in this regard, but at least I will know exactly how my infrastructure is built and what points of failure it has.</p><h3>Collecting the requirements</h3><p>So, as you might’ve guessed, I decided to roll my own thing 😄 First of all, I collected some requirements of what my future system might look like:</p><ol><li>I want to run everything through Home Assistant. In my opinion, this is a great project and not much else can compete with HA on features and device support right now.</li><li>I’d like to have a traditional thermostat device with basic functions, like setting target temperatures for central heating and domestic hot water. It’s important that this device retains basic functionality even if all other infrastructure fails: it should be able to work without Home Assistant, and even without Wi-Fi. But when HA is functioning, thermostat should enable fine-grained temperature control and other features.</li><li>Ideally, I would like to control the temperature in every room separately by using smart TRVs on each wall-mounted heater.</li><li>The same goes for heated floors: I would like to set target temperatures room-by-room. For example, during summer I would like to keep most floors cool, but still be able to enjoy warm floors in the bathroom.</li><li>I would like to digitise and monitor as many system parameters as possible: temperatures, pressures and so on.</li><li>I should be able to build this system incrementally. I started planning this project in August 2023, and by October I needed heating to work in its most basic form, so that the house wouldn’t freeze.</li></ol><h3>Choosing the hardware and libraries</h3><p>Quick googling around showed that our boiler supports OpenTherm protocol. This is good in a way that this standard is documented and there are several open-source libraries available. The not so great part is that a hardware bridge is required, since boiler operates in a 0–18 V range, and you can’t just plop a microcontroller on top of it.</p><p>So I googled some more and settled on the following setup:</p><ol><li><a href="https://esphome.io/?ref=olegtarasov.me">ESPHome</a> as a framework for thermostat firmware. It is actively maintained and has super tight integration with Home Assistant, so for me it was the most logical choice.</li><li>Some variation of ESP32 SoC. Partly because it’s a requirement from ESPHome, and partly because having Wi-Fi, Bluetooth and a ton of computing power in such a tiny package is just mind-blowing for a guy whose last encounter with electronics was tinkering with ATMega chips in 2009.</li><li><a href="https://github.com/arthurrump/esphome-opentherm?ref=olegtarasov.me">OpenTherm component</a> for ESPHome. This is the most complicated part which led me to a series of deep rabbit holes 😄 There are several OpenTherm libraries for ESPHome, but none of them were of release quality (at least at the time of writing). This is one looked like most mature, but unfortunately, it doesn’t seem to be actively maintained. I chose this library knowing full well that I might end up supporting my own fork until the end of times.</li><li><a href="https://ihormelnyk.com/opentherm_adapter?ref=olegtarasov.me">Ihor Melnik’s</a> OpenTherm adapter schematics. There are several other schematics and readily available adapters, but I decided to go with this one, because it seemed the easiest to prototype and then extend to support additional features.</li></ol><h3>Soldering the first prototype</h3><p>Without further ado, I ordered an assortment of components and got to soldering. Considering the fact that I did any soldering almost 15 years ago and I wasn’t a virtuoso even back then, I was pretty satisfied with the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*58NPr-gD-KDI2Bi0.jpeg" /></figure><p>In order to constrain the scope of the prototype, and test this on the real hardware as soon as possible, I decided to postpone the ESPHome part and flashed this project to a ESP32 dev board using Arduino IDE:</p><p>I rigged it all up with my boiler and a test Wi-Fi router, and it worked!</p><p><a href="https://youtube.com/shorts/8eBPa90fQ38?feature=share">Boilotron first prototype</a></p><p>It’s hard to describe the satisfaction of controlling some form of machinery in a physical world, since most of my projects are pure software 😄 Satisfied with this success, I set out to create a second version of this prototype, this time with ESPHome support. Stay tuned for more posts!</p><p><em>Originally published at </em><a href="https://olegtarasov.me/opentherm-thermostat-esphome-prototype1/"><em>https://olegtarasov.me</em></a><em> on April 8, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d86609b44e84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Export anaconda environment with conda export]]></title>
            <link>https://medium.com/@oleg.tarasov/export-anaconda-environment-with-conda-export-ee898ec9dc73?source=rss-5b8648659d8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee898ec9dc73</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[virtual-environment]]></category>
            <category><![CDATA[anaconda]]></category>
            <dc:creator><![CDATA[Oleg Tarasov]]></dc:creator>
            <pubDate>Wed, 21 Feb 2024 10:56:36 GMT</pubDate>
            <atom:updated>2024-02-25T11:36:15.557Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*51l7vWWMh1xJ68OG.png" /></figure><p>Managing projects with virtual environments is one of the core practices of modern Python development. There are several tools for managing virtual environments, such as venv, pipenv, poetry and conda. Some of these tools also provide dependency and project management capabilities, and there is no universally acknowledged favorite. The important thing to understand is that the exact tool you use is much less important than a clear and consistent development process that you and your team use.</p><p>In this blog post we will discuss one specific problem with managing conda environment specifications. I would like to keep this post focused, so we will not dive into reasons for choosing conda over other tools, neither will we discuss the full Python development pipeline.</p><h3>Why version environment specifications</h3><p>Saving and versioning your environment spec is always a good idea, even when you work alone on a pet project. A specification stored along with your code will help you recreate your environment on a different machine or when you take a break from you project and get back to it half a year later.</p><p>Having an environment spec is even more important when you work with a team: all of your teammates should be able to spin up a new environment quickly and reliably.</p><p>As mentioned in this <a href="https://pythonspeed.com/articles/conda-dependency-management/?ref=olegtarasov.me">great blog post</a>, we need to accomplish two distinct and sometimes conflicting objectives:</p><ol><li><strong>Reproducibility</strong>. You should be able to reproduce your environment with as much precision as possible. It’s really important that you deploy your code to the same environment that you develop and test it in. You can achieve great reproducibility with conda-lock tool, but such environment specs are really hard to read, reason about and maintain.</li><li><strong>Upgradability</strong>. You should be able to manage your environment specification by hand in a text editor. Ideally, you would start your project with an empty environment and gradually install packages with conda install or even pip install. After some initial fiddling you settle on an environment that works, and you would like to save its configuration for your team to use. You would like everyone to have the exact same environment, so you use conda-lock to generate locked specifications for each platform. But to generate a lockfile, you first need a less strict version of a specification - one that contains only those packages and their versions that you really care about, and not all the transitive dependencies. This file you can edit by hand and be sure that the packaging system will do its best to resolve all the dependencies. Right now you would either author this file completely by hand, or use conda env export and then edit the output by hand, since the resulting specifications are not portable, unfortunately.</li></ol><h3>Automating environment specifications with conda export</h3><p>Since it’s quite burdensome to manually track all the packages you install, I decided to find a way to do this automatically. I quickly found that conda env export doesn&#39;t help much, since:</p><ol><li>It exports all the transient dependencies too. This is problematic, since on different platforms transient dependencies might differ.</li><li>It adds a fixed version component, which prevents cross-platform portability and generally defeats the idea of upgradability that we discussed previously.</li><li>It includes environment prefix, which should also be deleted for specification to be portable.</li></ol><p>As you can see, conda env export doesn&#39;t help much with our task, and one might argue that it&#39;s more effective to write the specification by hand.</p><p>To tackle this problem I’ve created <a href="https://github.com/olegtarasov/conda-export?ref=olegtarasov.me">conda-export</a> - a tool that generates portable environment specifications, which contain only top-level packages that you installed over the lifetime of your environment.</p><h3>The solution</h3><p>You can install <a href="https://github.com/olegtarasov/conda-export?ref=olegtarasov.me">conda-export</a> into your root environment (so that your other environments are not cluttered by tools not relevant to the projects):</p><pre>conda install conda-export -n base</pre><p>And then you can export you portable environment specification with a command like this:</p><pre>conda export -n [environment name] -f environment.yml</pre><p>And that’s it! You will find that conda export tries to minimize total number of packages in a specification by taking into account only those packages that you explicitly installed. It includes specific versions only if you specified them, and also handles pip packages separately and correctly.</p><h3>Suggested workflow</h3><p>So what would be the complete workflow for having both reproducible and upgradable environment specifications? I would suggest the following:</p><ol><li>Start with an empty environment by using conda create.</li><li>Install packages as you normally would with conda install or pip install. You can even use specific versions, like conda install numpy=1.26.</li><li>When you are satisfied with your environment, use conda export to create a portable and upgradable environment.yml file.</li><li>Use conda lock to generate conda-lock.yml with all dependencies fully locked.</li><li>Use conda-lock.yml to deploy your code to production, build containers and spin up new environments on development machines.</li><li>When it’s time to upgrade packages, just regenerate conda-lock.yml from environment.yml possibly updating versions for only those packages that need to have fixed versions.</li></ol><p><em>Originally published at </em><a href="https://olegtarasov.me/export-anaconda-environment/"><em>https://olegtarasov.me</em></a><em> on February 21, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee898ec9dc73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Alternatives to Parallels Desktop on M1, M2 and M3 Macs]]></title>
            <link>https://medium.com/@oleg.tarasov/alternatives-to-parallels-desktop-on-m1-m2-and-m3-macs-85b5a3822fe2?source=rss-5b8648659d8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/85b5a3822fe2</guid>
            <category><![CDATA[apple-silicon]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[virtual-machine]]></category>
            <category><![CDATA[mac]]></category>
            <dc:creator><![CDATA[Oleg Tarasov]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 17:07:28 GMT</pubDate>
            <atom:updated>2024-02-20T17:24:48.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Q6EfY7B2Q7k1r2Os-gO_A.png" /><figcaption>Ah, yes, another AI-generated image :)</figcaption></figure><p>When it comes to running virtual machines on macOS, people often default to using Parallels Desktop. It’s a great piece of software, and it does its job very well, but it also has some limitations, especially when used with ARM-based Apple Silicon Macs.</p><h3>Parallels Desktop limitations and strengths on Apple Silicon</h3><p>It’s not widely known, but Apple created its own system for running virtual machines on Apple Silicon. It’s free and it’s installed by default with every version starting from macOS Monterey. You can’t use it directly as an app, but it’s there and it supports running any ARM-based guest operating system. When Apple announced its transition to Apple Silicon, Parallels already had a great solution for running virtual machines on Intel-based Macs. Unfortunately, ARM-based Apple Silicon Macs required a totally different technology. So there is no surprise that Parallels chose to reuse an already existing technology from Apple.</p><p>So you might ask yourself a question: “Is Parallel Desktop for Apple Silicon is just a fancy wrapper on top of free virtualization engine from Apple?” Well, it kind of is. Sure, Parallels tries to add lots of nice cosmetic features, but unfortunately, they are not in control of the most core part of their product: the virtualization engine.</p><p><strong>What exactly are the limitations of Parallels Desktop?</strong></p><ul><li><strong>It’s a paid app</strong>. This is quite subjective, but you also can’t get around the fact that the cheapest version of Parallels Desktop costs $99 a year.</li><li><strong>It can virtualize only ARM-based versions of operating systems</strong>. While Linux and macOS support for ARM architecture is great, Windows seems to be lagging behind. ARM is supported well enough in Windows 11, but it’s still in beta. Windows has a translation layer of its own, which allows you to run x86 apps on ARM architecture, but it may not work in some situations.</li><li><strong>You can’t connect USB devices to a macOS VM</strong>. Although you can do it in Windows VMs.</li><li><strong>Snapshots are not supported on macOS VMs</strong>. This seems to be another limitation of the core Apple virtualization component.</li><li><strong>There is no UI to change settings for macOS VMs</strong>. This seems to be a shortcoming on Parallels’ side.</li><li><strong>Nested virtualization is not supported for Windows 11 VMs</strong>. This means that you wouldn’t be able to use WSL2 on Windows.</li></ul><p><strong>What are the strengths of Parallel Desktop?</strong></p><p>Well, this is simple: Coherence mode. If you want to run virtual machines based on Windows, this is the top feature you might want to shell out $99 for. While all other virtualization apps can either run guest operating systems in a window or in full screen mode, Parallels can merge windows from your VM straight onto your macOS desktop. This feature is really cool and it works exceptionally well.</p><h3>UTM — a free and open-source alternative to Parallels Desktop</h3><p><a href="https://mac.getutm.app/?ref=olegtarasov.me">UTM</a> is a relatively new project, but in my opinion it is the best solution for general-purpose virtualization on macOS that you can get for free. It has two modes of operation: virtualization and emulation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nOP0sL8hwt2LA76u.png" /></figure><h4>Virtualization</h4><p>This mode allows you to create virtual machines with ARM operating systems. This mode utilizes built-in macOS virtualization engine, so you will get roughly the same high speed and core features as you would get with Parallels. UTM gives you a nice UI to customize VM options and a one-click helper to download the latest Windows for ARM installer (otherwise not a trivial task, since it’s still in beta).</p><p>There is a special case for Debian Linux, which can use Apple’s Rosetta component in order to run Intel-based binaries, just like you would on a macOS itself. This is certainly not for the faint of heart, as most things with Linux are, but it’s nice to have such an option out of the box.</p><p>There is not much else to be said about this mode overall, since it leverages the same core virtualization technology. In my experience, virtual machines created in this mode run smooth and fast. Virtualized macOS runs close to bare metal performance, as advertised (with an exception of some caveats like writing to a virtual volume).</p><h4>Emulation</h4><p>This mode is what makes UTM so useful among other virtualization solutions. There are cases when you want to run x86 versions of operating systems — for example, there is simply no ARM-compatible version of Windows XP. UTM allows you to do just that by bundling a well established full-system emulator called QEMU. It can emulate lots of system architectures, not just x86. It is almost infinitely configurable, and this makes working with QEMU quite challenging: there are a lot of intricacies to learn and a lot of experimentation to do. UTM greatly simplifies this process by providing a user-friendly UI over QEMU, which allows you to create new VMs almost as easily as in virtualization mode. To make things even easier, UTM has a <a href="https://mac.getutm.app/gallery/?ref=olegtarasov.me">gallery</a> with preconfigured virtual machines for different operating systems. You can just download a template, open it in UTM and provide installation media for the selected OS.</p><p>Here is a screenshot of Windows XP running with decent performance on my M2 MacBook Pro:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qzQt3z3bxFrWKIxW.png" /></figure><p>How crazy is that!</p><h3>Other options</h3><p>Of course, UTM isn’t the only solution you can use for running unusual things on Apple Silicon.</p><h4>Whisky</h4><p>If you want a way to run Windows software on a Mac, there is another possibility besides creating a full-blown virtual machine. You can try <a href="https://github.com/Whisky-App/Whisky?ref=olegtarasov.me">Whisky</a>, which is a free and open-source frontend for Wine and Apple’s Game Porting Toolkit. Wine is a whole different rabbit hole, but in short, it aims to create a <em>compatibility layer</em> for Windows, which allows you to run Windows apps directly on macOS or Linux. There is a different project called CrossOver, which is built on top of Wine in order to improve compatibility and make it more user-friendly. And finally, Apple created a Game Porting Toolkit, which in turn is based on CrossOver, and aims to enable running big titles directly on macOS. This is something that Steam has done successfully with Proton and Steam Deck, so Apple decided to try and join the party.</p><p>Anyway, if you want to run modern game titles on macOS, you can try Whisky. It can also be used to run any other Windows app, not just games. Many people report great results, but beware that all this stuff is still highly experimental, and you should expect spending hours on various forums and wikis.</p><h4>VMware Fusion Player</h4><p>Another alternative to Parallels Desktop and UTM is Fusion Player from VMWare. You can obtain a personal license and use it for free if you do non-commercial work. Personally, I don’t see a point in using it, since you need to register and jump through some hoops to get a license, and there is no additional value that Fusion Player can offer on top of free and open-source UTM. It can only virtualize ARM-based operating systems, and it also lacks Parallels’ bells and whistles such as Coherence.</p><h4>VirtualBox — not an option</h4><p>Unfortunately, another popular virtualization software — VirtualBox — doesn’t support Apple Silicon Macs at the moment of writing.</p><h3>Conclusion</h3><p>If you are looking for an alternative to Parallels Desktop, consider trying <a href="https://mac.getutm.app/?ref=olegtarasov.me">UTM</a>. It doesn’t have more advanced features like Coherence mode, but it’s free and open-source. And if you require running non-ARM operating systems, UTM is much more user-friendly than using QEMU directly.</p><p><em>Originally published at </em><a href="https://olegtarasov.me/alternatives-to-parallels-desktop-on-apple-silicon/"><em>https://olegtarasov.me</em></a><em> on February 20, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85b5a3822fe2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to fix “The provided certificate file is not a valid PFX file” with dotnet dev-certs https…]]></title>
            <link>https://medium.com/@oleg.tarasov/the-provided-certificate-file-is-not-a-valid-pfx-on-macos-2f1f60a9b916?source=rss-5b8648659d8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f1f60a9b916</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Oleg Tarasov]]></dc:creator>
            <pubDate>Thu, 26 May 2022 14:17:36 GMT</pubDate>
            <atom:updated>2022-06-17T08:39:28.264Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to fix “The provided certificate file is not a valid PFX file” with dotnet dev-certs https import on macOS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fK1C_eJx_rckP0Pv.png" /></figure><p>This is a relly short post that addresses an error with dotnet dev-certs https --import on macOS.</p><p>You would typically use dotnet dev-certs https --trust to generate your ASP.NET development certificates and be done with it. But sometimes you need to generate your own certificate or share a certificate between several environments. Normally, you would import an external certificate with dotnet dev-certs https --clean --import, but unfortunately you get an error executing this command on macOS (at least at the time of writing on .NET SDK 6.0.202).</p><p>Assuming, you have your certificate exported to PFX format, you can import it manually with (replacing &lt;CERT&gt; with cert file name and &lt;CERT_PASSWORD&gt; with exported certificate password):</p><pre>security import &lt;CERT&gt;.pfx \<br>  -k ${HOME}/Library/Keychains/login.keychain-db \<br>  -t cert -f pkcs12 -P &lt;CERT_PASSWORD&gt; -A</pre><p>This is the exact command that dotnet dev-certs tries to perform, but fails.</p><p>Beware, that at this point your certificate is imported, but still not trusted. You can use standard dotnet dev-certs command to trust it:</p><pre>dotnet dev-certs https --trust</pre><p>If you want to dig deeper into ASP.NET development certificates, visit an excellent <a href="https://www.fearofoblivion.com/setting-up-asp-net-dev-certs-for-both-wsl-and-windows">post</a> by Chris Klug.</p><p><em>Originally published at </em><a href="https://olegtarasov.me/dotnet-dev-certs-import-macos/"><em>https://olegtarasov.me</em></a><em> on May 26, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f1f60a9b916" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mamba: a robust alternative to Anaconda package manager]]></title>
            <link>https://medium.com/@oleg.tarasov/mamba-a-robust-alternative-to-anaconda-package-manager-890dbb03368?source=rss-5b8648659d8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/890dbb03368</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Oleg Tarasov]]></dc:creator>
            <pubDate>Sun, 20 Jun 2021 10:13:43 GMT</pubDate>
            <atom:updated>2022-06-17T08:00:35.466Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*3grWphMwvzGgw-3k.png" /></figure><p>Did you ever try to install a complicated mix of conda packages only to find yourself in an infinite &quot;Solving environment&quot; and &quot;Retrying with flexible solve&quot; loop? Or maybe your installation succeeded, but later you found out that some package versions are out of date? As good as Anaconda ecosystem is, and as much as I advocate using conda at all times, sometimes the default dependency resolver just doesn&#39;t cut it.</p><p>The other day I was yet again struggling with conda not being able to install the packages I needed. But this time instead of just giving up and using pip, I decided to do a little research. Imagine my surprise when I found a great drop-in replacement for conda while digging in the bowels of some obscure GitHub issue.</p><h3>What’s mamba?</h3><p><a href="https://mamba.readthedocs.io/en/latest/index.html">Mamba</a> is an alternative package manager for conda ecosystem. It has a much better dependency resolver and it supports almost all the commands conda does. You can do your ususal routines, but just type mamba instead of conda:</p><pre>mamba create -n test python numpy <br>conda activate test <br>mamba install notebook</pre><p>The minor inconvenience is that you still need to use conda activate and conda deactivate to switch active environments and conda config to manage configuration from command line. For all other things use mamba!</p><h3>Installing mamba</h3><p>Since mamba is just a binary that relies on conda ecosystem, you can simply add it to your existing Anaconda or Miniconda installation:</p><pre>conda install mamba -n base -c conda-forge</pre><p>It’s important to install mamba into base environment. After that you can start using it!</p><h3>New installation with mambaforge</h3><p>When you are bootstrapping a new machine, you can install <a href="https://github.com/conda-forge/miniforge#mambaforge">mambaforge</a> instead of Miniconda or full Anaconda distribution. Mambaforge is similar to Miniconda in size, but comes with preconfigured conda-forge channel and preinstalled mamba binary.</p><p>As per GitHub documentation, install for Unix-like systems:</p><pre>wget https://github.com/conda-forge/miniforge/releases/latest/download/Mambaforge-$(uname)-$(uname -m).sh <br>bash Mambaforge-$(uname)-$(uname -m).sh</pre><p>And for Windows just download and run the installer.</p><p>I also strongly suggest to turn on strict channel priority:</p><pre>conda config --set channel_priority strict</pre><h3>Do I need it, or should I just stick with conda?</h3><p>If you are not convinced that mamba resolves dependencies better than conda, let&#39;s do a little experiment.</p><p><em>Warning! The following experiment is valid at the time of writing, but things may change in the future, when packages evolve or </em><em>conda dependency resolver is improved.</em></p><p>So let’s do something really simple: create a new environment with pytorch and mlflow. We will use pytorch and conda-forge channels. First, let&#39;s try to create a new environment with channel_priority option set to strict (a recommended way of doing things with conda-forge). Here is my .condarc:</p><pre>channels:<br>  - pytorch<br>  - conda-forge<br>  - defaults<br>channel_priority: strict</pre><p>Let’s try creating a new environment with plain old conda:</p><pre>conda create -n test pytorch mlflow</pre><p>It would seem like we are getting a sensible install plan: pytorch is v. 1.9.0 and mlflow is 1.18.0 which are the latest versions at the time of writing. But let&#39;s look more closely at Python version that&#39;s going to be installed:</p><pre>The following NEW packages will be INSTALLED:</pre><pre>alembic            conda-forge/osx-64::alembic-0.9.5-py36_0<br>mlflow             conda-forge/osx-64::mlflow-1.18.0-py36h6d49074_0<br>python             conda-forge/osx-64::python-3.6.13-h7728216_0_cpython<br>pytorch            pytorch/osx-64::pytorch-1.9.0-py3.6_0<br>  <br># Other packages omitted</pre><p>Yes, we are getting Python 3.6.13, while Python 3.9.5 is available and compatible with Pytorch and MLFlow! I will omit some cumbersome dependency analysis, but it looks like alembic dependency is the culprit. Despite the fact that MLFlow lists alembic &lt;=1.4.1 as its dependency, we are getting some ancient version 0.9.5, which seems to force Python to downgrade to 3.6.13.</p><p>Fine, but maybe the problem is with strict channel priority? Let’s try removing this option from .condarc.</p><pre>channels:<br>  - pytorch<br>  - conda-forge<br>  - defaults</pre><pre>conda create -n test pytorch mlflow</pre><p>OK, this time it’s a little better: we are getting Python 3.7.10. Oh, come on!</p><pre>The following NEW packages will be INSTALLED:</pre><pre>  alembic            pkgs/main/osx-64::alembic-1.0.9-py37_0<br>  mlflow             conda-forge/osx-64::mlflow-1.18.0-py37h712bc25_0<br>  python             conda-forge/osx-64::python-3.7.10-h7728216_100_cpython<br>  pytorch            pytorch/osx-64::pytorch-1.9.0-py3.7_0</pre><pre># Other packages omitted</pre><h3>Trying it with mamba</h3><p>Let’s turn strict priority back on and try the same thing with mamba.</p><pre>channels:<br>  - pytorch<br>  - conda-forge<br>  - defaults<br>channel_priority: strict</pre><pre>mamba create -n test pytorch mlflow</pre><pre>  alembic        1.4.1  py_0                conda-forge/noarch     Cached<br>  mlflow         1.18.0  py39h8ac9d56_0      conda-forge/osx-64     Cached<br>  python         3.9.5  hd187cdc_0_cpython  conda-forge/osx-64     Cached<br>  pytorch        1.9.0  py3.9_0             pytorch/osx-64         Cached</pre><p>We are finally getting up-to-date versions for all packages! And a nice poisonous kill-you-in-a-blink-of-an-eye snake in your console! Can this day get any better?</p><h3>Yes, you need it.</h3><p>So if you are using conda ecosystem there is absolutely no reason not to install mamba and use it for all of your package management.</p><p><em>Originally published at </em><a href="https://olegtarasov.me/mamba-alternative-to-conda/"><em>https://olegtarasov.me</em></a><em> on June 20, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=890dbb03368" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Calling a cross-platform C++ library from .NET Core]]></title>
            <link>https://medium.com/@oleg.tarasov/calling-a-cross-platform-c-library-from-net-core-befd3f1ee646?source=rss-5b8648659d8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/befd3f1ee646</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cross-platform]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Oleg Tarasov]]></dc:creator>
            <pubDate>Sun, 09 Jun 2019 07:20:56 GMT</pubDate>
            <atom:updated>2019-06-09T07:29:40.175Z</atom:updated>
            <content:encoded><![CDATA[<h3>Calling a cross-platform C++ library from .NET Core</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ANw8jyGraVm8Et2pnu2e0w.png" /></figure><p>This is the second post in a series of posts where we will learn how to build a cross-platform C++ library which can be seamlessly called from .NET Core applications using P/Invoke on all supported platforms. In the <a href="https://www.olegtarasov.me/cross-platform-net-core-1">previous post</a> we created a C++ library which exports a simple function. We then compiled this library under Windows, Linux and MacOs. In this post we will create a .NET Core console application which will bundle all native binaries and seamlessly call our exported function in a uniform way.</p><p>All source code is available at my GitHub repo: <a href="https://github.com/olegtarasov/CrossplatformNativeTest">https://github.com/olegtarasov/CrossplatformNativeTest</a>. You can easily inspect the code for each post using tags. For this post the tag is 2_hello_world.</p><h3>Creating a .NET Core project</h3><p>Since we are using .NET Core, the workflow to create and compile a project will be identical for all three platforms. Assume we want to create our project in a CoreNativeTest directory. Let&#39;s use dotnet command:</p><pre>mkdir CoreNativeTest &amp;&amp; cd CoreNativeTest <br>dotnet new console</pre><p>And just like that you have a brand new cross-platform console app! Let’s build and test it:</p><pre>dotnet build dotnet run</pre><p>It should output a standard “Hello world!” message.</p><h3>Bundling native dependencies</h3><p>As we discussed in the <a href="https://www.olegtarasov.me/cross-platform-net-core-1">previous post</a>, we could just place our native binaries in the same directory as our new console app, and it would work. But I suggest we give it a little more effort and embed native binaries into our app as resources. With this approach we will have less files to distribute and we will circumvent potential problems with native dependencies if we decide to reference our assembly in some other .NET project.</p><p>First of all, let’s place native binaries in our project directory. If you are following the tutorials closely, these will be TestLib.dll, libTestLib.so and libTestLib.dylib. Now we need to tell the compiler to embed these files into CoreNativeTest.dll assembly as resources. To do so, we open the project file CoreNativeTest.csproj in text editor and change it as follows:</p><pre>&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt;<br><br>    &lt;PropertyGroup&gt;<br>        &lt;OutputType&gt;Exe&lt;/OutputType&gt;<br>        &lt;TargetFramework&gt;netcoreapp2.2&lt;/TargetFramework&gt;<br>    &lt;/PropertyGroup&gt;<br><br>    &lt;ItemGroup&gt;<br>      &lt;EmbeddedResource Include=&quot;libTestLib.dylib&quot; /&gt;<br>      &lt;EmbeddedResource Include=&quot;libTestLib.so&quot; /&gt;<br>      &lt;EmbeddedResource Include=&quot;TestLib.dll&quot; /&gt;<br>    &lt;/ItemGroup&gt;<br>&lt;/Project&gt;</pre><p>If you are using Visual Studio, you can just select these files in Project Explorer and set their type to “Embedded Resource”.</p><p>Now when we build the project, native binaries will be embedded into the assembly. But how do we get them out and call our exported function? We can write some code to do it by hand, or we can use <a href="https://github.com/olegtarasov/NativeLibraryManager">NativeLibraryManager</a> that I made specifically for this purpose. This library lets you define which binary to use under which platform, and it will handle all the work of detecting the target platform and extracting the binary.</p><p>Let’s add NativeLibraryManager to our project with dotnet add package command.</p><pre>dotnet add package NativeLibraryManager</pre><h3>Extracting and calling the native library</h3><p>Now let’s open Program.cs in text editor and change it as follows:</p><pre>using System;<br>using System.Reflection;<br>using System.Runtime.InteropServices;<br>using NativeLibraryManager;</pre><pre>namespace CoreNativeTest<br>{<br>    internal class Program<br>    {<br>        [DllImport(&quot;TestLib&quot;)]<br>        private static extern void hello();<br>    <br>        private static void Main(string[] args)<br>        {<br>            var accessor = new ResourceAccessor(Assembly.GetExecutingAssembly());<br>            var libManager = new LibraryManager(<br>                Assembly.GetExecutingAssembly(),<br>                new LibraryItem(Platform.MacOs, Bitness.x64,<br>                    new LibraryFile(&quot;libTestLib.dylib&quot;, accessor.Binary(&quot;libTestLib.dylib&quot;))),<br>                new LibraryItem(Platform.Windows, Bitness.x64, <br>                    new LibraryFile(&quot;TestLib.dll&quot;, accessor.Binary(&quot;TestLib.dll&quot;))),<br>                new LibraryItem(Platform.Linux, Bitness.x64,<br>                    new LibraryFile(&quot;libTestLib.so&quot;, accessor.Binary(&quot;libTestLib.so&quot;))));<br>            <br>            libManager.LoadNativeLibrary();<br>            <br>            hello();<br>            Console.WriteLine(&quot;Hello from C#!&quot;);<br>        }<br>    }<br>}</pre><p>First of all, we use standard P/Invoke declaration to import hello() function from the native library. We don&#39;t need to use any cross-platform specifics, since all shared library loaders will find our native library as long as it&#39;s placed in a well-known directory. The easiest well-known directory is the directory in which our .NET assembly is located. What we need to do is to extract a corresponding binary from assembly resources depending on current platform.</p><p>To do this, we create an instance of ResourceAccessor. This is a simple helper that reads embedded resources as arrays of bytes. We use Assembly.GetExecutingAssembly() to tell ResourceAccessor in which assembly to look for resources.</p><p>After that we create an instance of LibraryManager. This is the main class that detects target platform and extracts the appropriate binary. It receives an assembly reference as well, along with any number of LibraryItem object. Each LibraryItem specifies a bundle of files that should be extracted for a specific platform. It this case we create 3 instances to support Windows, Linux and MacOs - all 64-bit. LibraryItem takes any number of LibraryFile objects. With these objects you specify the extracted file name and an actual binary file in the form of byte array. This is where ResourceAccessor comes in handy.</p><p>We should note that resource name you pass to ResourceAccessor is just a path to original file relative to project root with slashes \ replaced with dots .. So, for example, if we place some file in Foo\Bar\lib.dll project folder, we would adderss it as:</p><pre>accessor.Binary(&quot;Foo.Bar.lib.dll&quot;)</pre><p>So back to native library management. After we define binaries for all platforms that we want to support, we just call libManager.LoadNativeLibrary() to extract the appropriate native binary and optionally call LoadLibrary() on it under Windows. File extractor is smart: first it checks if target binary already exists on disk and then it computes its hash to make sure there is a newer version that needs to be extracted. With this approach there is no unnecessary writes to file system and library updates are handled gracefully.</p><p>After we are done extracting the binary, we just call our hello() exported function with standard P/Invoke.</p><h3>Building and running the project</h3><p>Now that we took care of our dependencies and put in some P/Invoke code, we can just build and run our project.</p><pre>dotnet build <br>dotnet run</pre><p>If everything went fine, you will see two lines printed to standard output. For example, under MacOs:</p><pre>Hello from MacOS! <br>Hello from C#!</pre><p>Hooray! We finally made a cross-platform .NET Core app that calls into native library! In the next post we will discuss more advanced topics of native interop like string, class and structure manipulations. Stay tuned!</p><p><em>Originally published at </em><a href="https://www.olegtarasov.me/call-native-lib-from-net-core/"><em>https://www.olegtarasov.me</em></a><em> on June 9, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=befd3f1ee646" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>