<?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 vinsce on Medium]]></title>
        <description><![CDATA[Stories by vinsce on Medium]]></description>
        <link>https://medium.com/@vinsce?source=rss-5c0637053069------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by vinsce on Medium</title>
            <link>https://medium.com/@vinsce?source=rss-5c0637053069------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 22:51:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vinsce/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[Create an ESPHome external component (Part 2): expose functionality to HomeAssistant with Sensors]]></title>
            <link>https://medium.com/@vinsce/create-an-esphome-external-component-part-2-expose-functionality-to-homeassistant-with-sensors-675bd3a987b4?source=rss-5c0637053069------2</link>
            <guid isPermaLink="false">https://medium.com/p/675bd3a987b4</guid>
            <category><![CDATA[esphome]]></category>
            <category><![CDATA[diy]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[sensors]]></category>
            <category><![CDATA[home-assistant]]></category>
            <dc:creator><![CDATA[vinsce]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 22:27:12 GMT</pubDate>
            <atom:updated>2025-03-28T17:05:29.563Z</atom:updated>
            <content:encoded><![CDATA[<p>In this second post of the series we will explore how to extend the functionalities of our ESPHome external component and expose it to Home Assistant. We will see the different ways we can add a <strong>sensor </strong>and other entities, still keeping it as simple as possible to capture the main concepts.</p><p>Prerequisites to follow the post is a basic understanding of ESPHome components, which is presented in the <a href="https://medium.com/@vinsce/create-an-esphome-external-component-part-1-introduction-config-validation-and-code-generation-e0389e674bd6">Part 1</a>.</p><blockquote>To read this post without a Medium subscription click <a href="https://medium.com/@vinsce/create-an-esphome-external-component-part-2-expose-functionality-to-homeassistant-with-sensors-675bd3a987b4?sk=613ee60f1d16a965c6f5de42a53f8c93">here</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KeEo-TKMCvXnAimE5epmrQ.jpeg" /></figure><h3>Sensors</h3><p>There are multiple ways to add sensor capabilities to your custom ESPHome component. If your component inherently represents a single sensor, the simplest approach is to directly extend the sensor::Sensor class and have the sensor configuration at the root level of your component.<br>Let’s see how it looks like:</p><pre>#pragma once<br><br>#include &quot;esphome/core/component.h&quot;<br>#include &quot;esphome/components/sensor/sensor.h&quot;<br><br>namespace esphome {<br>namespace demo {<br><br>class DemoSensor : public sensor::Sensor, public PollingComponent {<br> protected:<br>  float get_sensor_value() {<br>    return random_float() * 50;<br>  }<br><br> public:<br>  void update() override {<br>    this-&gt;publish_state(get_sensor_value());<br>  }<br>};<br><br>}<br>}</pre><p>Here the DemoSensor class, which contains the actual logic of our component, extends from the <a href="https://esphome.io/api/classesphome_1_1sensor_1_1_sensor">sensor::Sensor</a> and <a href="https://esphome.io/api/classesphome_1_1_polling_component">PollingComponent</a>.</p><p>The <strong>PollingComponent </strong>is an extension of the base Component class, which allows to easily implement components that periodically check/update their state. Instead of the loop method, for a PollingComponent we implement the update method, which is called at regular intervals defined by its update_interval (in ms) after the startup.</p><p>The <strong>Sensor</strong> class is the base class to use for implementing a custom sensor. Using this class, our component inherits a lot of powerful features like support for filters, automation on value change, etc. You can read more about the Sensor component capabilities in the <a href="https://esphome.io/components/sensor/">official documentation</a>.<br>In the example above, the publish_state method from the Sensor class is used to emit a new value for the sensor. This value will go through the filters (if configured) and then published (e.g. to Home Assistant).</p><p>For simplicity, this example uses random values to simulate sensor data, in the get_sensor_value function. In a real-world scenario, you would replace this with code that reads data from your connected hardware.</p><p>Let’s see now how to configure our sensor:</p><pre>import esphome.codegen as cg<br>import esphome.config_validation as cv<br>from esphome.components import sensor<br>from esphome.const import (<br>    DEVICE_CLASS_TEMPERATURE, STATE_CLASS_MEASUREMENT, UNIT_CELSIUS, ICON_THERMOMETER<br>)<br><br>demo_ns = cg.esphome_ns.namespace(&quot;demo&quot;)<br>DemoSensor = demo_ns.class_(&quot;DemoSensor&quot;, sensor.Sensor, cg.PollingComponent)<br><br>CONFIG_SCHEMA = sensor.sensor_schema(<br>    DemoSensor,<br>    unit_of_measurement=UNIT_CELSIUS,<br>    icon=ICON_THERMOMETER,<br>    accuracy_decimals=1,<br>    state_class=STATE_CLASS_MEASUREMENT,<br>    device_class=DEVICE_CLASS_TEMPERATURE,<br>).extend(cv.polling_component_schema(&quot;30s&quot;))<br><br>async def to_code(config):<br>    var = await sensor.new_sensor(config)<br>    await cg.register_component(var, config)</pre><p>To define the sensor schema, we use the schema provided by the <a href="https://github.com/esphome/esphome/blob/48a7927a608627b8f904825ce61a74a26c0fab26/esphome/components/sensor/__init__.py#L308">sensor component</a> with sensor.sensor_schema(). Here we can configure behavior (e.g. accuracy) and appearance of the component. The values put here act as defaults and can be overridden in the YAML file. The schema is then extended with polling_component_schema where we can define the refresh interval (i.e. how often the update method should be called to fetch a new sensor value).</p><p>In YAML configuration, you can define the sensor as you normally would:</p><pre>demo:<br>   name: &quot;Demo Sensor&quot;</pre><p>This registers the sensor, and you can see the result in Home Assistant:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*Ag5ZaKyLHfAaRfOWRVS9hQ.png" /></figure><p>For more complex scenarios, such as components with multiple sensors, you can use composition instead of inheritance. This involves including sensor objects as member variables within your component:</p><pre>#pragma once<br><br>#include &quot;esphome/core/component.h&quot;<br>#include &quot;esphome/components/sensor/sensor.h&quot;<br><br>namespace esphome {<br>namespace demo {<br><br>static const char *const TAG = &quot;DemoSensor&quot;;<br><br>class DemoSensor : public PollingComponent {<br> protected:<br>  sensor::Sensor *temperature_sensor_{nullptr};<br>  sensor::Sensor *humidity_sensor_{nullptr};<br><br>  float get_temperature_value() {<br>    return random_float() * 50;<br>  }<br><br>  float get_humidity_value() {<br>    return random_float() * 100;<br>  }<br><br> public:<br>  void set_temperature_sensor(sensor::Sensor *temperature_sensor) { temperature_sensor_ = temperature_sensor; }<br>  void set_humidity_sensor(sensor::Sensor *humidity_sensor) { humidity_sensor_ = humidity_sensor; }<br><br>  void update() override {<br>    this-&gt;temperature_sensor_-&gt;publish_state(this-&gt;get_temperature_value());<br>    this-&gt;humidity_sensor_-&gt;publish_state(this-&gt;get_humidity_value());<br>  }<br>  <br>  void dump_config() override {<br>    ESP_LOGCONFIG(TAG, &quot;DemoSensor:&quot;);<br>    LOG_SENSOR(&quot;  &quot;, &quot;Temperature&quot;, this-&gt;temperature_sensor_);<br>    LOG_SENSOR(&quot;  &quot;, &quot;Humidity&quot;, this-&gt;humidity_sensor_);<br>  }<br>  <br>};<br><br>}<br>}</pre><p>The difference is that now we have two sensors as field of our component class, and we call the publish_state of the individual sensor we want to update.</p><p>The corresponding python code:</p><pre>import esphome.codegen as cg<br>import esphome.config_validation as cv<br>from esphome.components import (<br>    sensor,<br>)<br>from esphome.const import (<br>    CONF_ID, CONF_NAME, UNIT_CELSIUS, UNIT_PERCENT, DEVICE_CLASS_TEMPERATURE, DEVICE_CLASS_HUMIDITY, STATE_CLASS_MEASUREMENT, ICON_THERMOMETER, ICON_WATER_PERCENT<br>)<br><br>AUTO_LOAD = [<br>    &quot;sensor&quot;,<br>]<br><br>demo_ns = cg.esphome_ns.namespace(&quot;demo&quot;)<br>DemoSensor = demo_ns.class_(&quot;DemoSensor&quot;, cg.PollingComponent)<br><br>CONF_TEMPERATURE_SENSOR = &quot;temperature_sensor&quot;<br>CONF_HUMIDITY_SENSOR = &quot;humidity_sensor&quot;<br><br>CONFIG_SCHEMA = cv.Schema(<br>    {<br>        cv.GenerateID(): cv.declare_id(DemoSensor),<br>        cv.Optional(<br>            CONF_TEMPERATURE_SENSOR,<br>            default={ CONF_NAME: &quot;Demo Temperature Sensor&quot;,}<br>        ): sensor.sensor_schema(<br>            unit_of_measurement=UNIT_CELSIUS,<br>            icon=ICON_THERMOMETER,<br>            accuracy_decimals=1,<br>            state_class=STATE_CLASS_MEASUREMENT,<br>            device_class=DEVICE_CLASS_TEMPERATURE,<br>        ),<br>        cv.Optional(<br>            CONF_HUMIDITY_SENSOR,<br>            default={ CONF_NAME: &quot;Demo Humidity Sensor&quot;,}<br>        ): sensor.sensor_schema(<br>            unit_of_measurement=UNIT_PERCENT,<br>            icon=ICON_WATER_PERCENT,<br>            accuracy_decimals=1,<br>            device_class=DEVICE_CLASS_HUMIDITY,<br>            state_class=STATE_CLASS_MEASUREMENT,<br>        ),       <br>    }<br>).extend(cv.polling_component_schema(&quot;30s&quot;))<br><br>async def to_code(config):<br>    var = cg.new_Pvariable(config[CONF_ID])<br>    await cg.register_component(var, config)<br><br>    temperature_sensor = await sensor.new_sensor(config.get(CONF_TEMPERATURE_SENSOR))<br>    cg.add(var.set_temperature_sensor(temperature_sensor))<br><br>    humidity_sensor = await sensor.new_sensor(config.get(CONF_HUMIDITY_SENSOR))<br>    cg.add(var.set_humidity_sensor(humidity_sensor))</pre><p>In the configuration schema, we now have two sections where we can configure the two sensors, and a root-level configuration for the PollingComponent.</p><p>In the code generation part, we register our generic component, then we create the sensors variables and we call the <em>setters</em> methods to configure the sensors instances in the component.</p><pre>demo:<br>  temperature_sensor:<br>    name: &quot;Demo Temperature sensor&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*oKqFhQHXqlv_KD50gdZzJw.png" /></figure><p>What we have seen for sensors also applies to the other type of entities. We can also use binary_sensor::BinarySensor to expose boolean values. In the <a href="https://github.com/esphome/esphome/blob/48a7927a608627b8f904825ce61a74a26c0fab26/esphome/components/demo/__init__.py#L299">demo component</a> that is available in the ESPHome repository you can find different examples for sensors and more.</p><h3>LightOutput</h3><p>In the previous section we have seen how to expose values from our ESPHome component.<br>Let’s see now an example of a component that can be controlled from Home Assistant, like a <strong>light</strong>.</p><p>To create a light component, we use the light::LightOutput, which in the <a href="https://esphome.io/api/classesphome_1_1light_1_1_light_output#details">documentation</a> is defined as the <em>interface to write LightStates to hardware</em>:</p><pre>#pragma once<br><br>#include &quot;esphome/core/component.h&quot;<br>#include &quot;esphome/components/light/light_output.h&quot;<br><br>namespace esphome {<br>namespace demo {<br><br>class DemoLight : public light::LightOutput, public Component {<br>  public:<br>   // Return the LightTraits of this LightOutput.<br>   light::LightTraits get_traits() override {<br>     auto traits = light::LightTraits();<br>     traits.set_supported_color_modes({light::ColorMode::RGB});<br>     return traits;<br>   }<br>   <br>   // Called every time the light state has changed, and should<br>   // should write the new state to hardware.<br>   void write_state(light::LightState *state) override {<br>     // TODO write new state to hardware<br>   }<br> };<br> <br> }  // namespace demo<br> }  // namespace esphome</pre><p>An implementation of LightOutput should overrides at least the get_traits and write_state methods.<br>get_traits is supposed to describe the capabilities of the light, and this will reflect in Home Assistant how we can interact with the light entity. In this example we have declared our light to support the RGB color mode (see the <a href="https://esphome.io/api/namespaceesphome_1_1light#ae15e8fc701ad0efd46c3dfeefa408c7a">docs</a> for the available modes).<br>The write_state is where the actual <a href="https://esphome.io/api/classesphome_1_1light_1_1_light_state">LightState</a> should be written to the hardware.</p><p>The corresponding python file:</p><pre>import esphome.codegen as cg<br>import esphome.config_validation as cv<br>from esphome.components import light<br>from esphome.const import CONF_OUTPUT_ID<br><br>AUTO_LOAD = [<br>    &quot;light&quot;,<br>]<br><br>demo_ns = cg.esphome_ns.namespace(&quot;demo&quot;)<br>DemoLight = demo_ns.class_(&quot;DemoLight&quot;, light.LightOutput, cg.Component)<br><br><br>CONFIG_SCHEMA = light.RGB_LIGHT_SCHEMA.extend(cv.COMPONENT_SCHEMA).extend(<br>                {<br>                    cv.GenerateID(CONF_OUTPUT_ID): cv.declare_id(DemoLight),<br>                }<br>            )<br><br>async def to_code(config):<br>    var = cg.new_Pvariable(config[CONF_OUTPUT_ID])<br>    await cg.register_component(var, config)<br>    await light.register_light(var, config)</pre><pre>demo:<br>  name: &quot;Demo Light&quot;</pre><p>This will expose an RGB light which can be controlled from Home Assistant.</p><h3>Domain-based configuration</h3><p>In the examples we’ve covered so far, we’ve defined all entities within a single __init__.py and a corresponding C++ file.<br>This approach works well for simpler components. However, for more complex components, organizing entities by their respective domains (e.g., sensor, light, climate) into separate files offers advantages (code clarity, simpler maintenance, and better-defined scopes for each entity type). It also changes how the component is configured in the YAML files.</p><p>To use this approach, the component’s file structure will look like:</p><pre>├── my_external_component<br>│   ├── __init__.py<br>│   ├── my_external_component.cpp<br>│   ├── my_external_component.h<br>│   ├── sensor.py<br>│   ├── ...<br>│   ├── light.py</pre><p>Here, __init__.py at the root level handles component-wide configuration, while domain-specific files (e.g., sensor.py, light.py) manage the configuration and code generation for their respective entities. And this is how the component can be used now in YAML:</p><pre># Optional component configuration<br>my_external_component:<br> conf1: val1<br><br>sensor:<br> - platform: my_external_component<br><br>light:<br> - platform: my_external_component</pre><p>The platform: my_external_component line tells ESPHome to look for the code for the specified domain (e.g. sensor) within your custom component. ESPHome will then look for the sensor.py (or sensor/__init__.py, see later) file to find the specific configuration and code generation.<br>You can find <a href="https://github.com/search?q=path%3Aesphome%2Fcomponents%2F*%2Fsensor.py+repo%3Aesphome%2Fesphome&amp;type=code&amp;ref=advsearch">numerous components</a> using this approach in the ESPHome repository.</p><p>For even more complex components with multiple domains, each with its own configuration and C++ implementation, you can further organize your project by creating subdirectories for each domain:</p><pre>├── my_external_component<br>│   ├── __init__.py<br>│   ├── my_external_component.cpp<br>│   ├── my_external_component.h<br>│   ├── sensor<br>│   │   ├── __init__.py<br>│   │   ├── my_external_component_sensor.cpp<br>│   │   ├── my_external_component_sensor.h<br>│   ├── light<br>│   │   ├── __init__.py<br>│   │   ├── my_external_component_light.cpp<br>│   │   ├── my_external_component_light.h<br>│   ├── ...</pre><p>In this structure, the __init__.py files within each domain subdirectory (e.g., sensor/__init__.py, light/__init__.py) serve as the entry points for their respective domains. They define the configuration schemas and to_code functions for the entities within those domains.<br>And again you can find <a href="https://github.com/search?q=path%3Aesphome%2Fcomponents%2F*%2Fsensor%2F__init__.py+repo%3Aesphome%2Fesphome&amp;type=code&amp;ref=advsearch">multiple examples</a> in the ESPHome repository.</p><h3>Conclusion</h3><p>In this second part, we explored how to add sensors to an ESPHome external component and how to organize complex components using domain-based configurations. At this point, being able to navigate the <a href="https://github.com/esphome/esphome/">ESPHome repository</a> is an important tool. There, you can find a wealth of <a href="https://github.com/esphome/esphome/tree/dev/esphome/components">components</a> and examples of <a href="https://github.com/esphome/esphome/tree/dev/tests/components">how they are used</a>, which can provide inspiration. I hope this series of posts is providing the necessary foundation to start building your own custom ESPHome component.</p><p>References:</p><ul><li><a href="https://esphome.io/guides/contributing.html">https://esphome.io/guides/contributing.html</a></li><li><a href="https://github.com/esphome/esphome/tree/dev/esphome/components/demo">https://github.com/esphome/esphome/tree/dev/esphome/components/demo</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=675bd3a987b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create an ESPHome external component (Part 1): introduction, config validation and code generation]]></title>
            <link>https://medium.com/@vinsce/create-an-esphome-external-component-part-1-introduction-config-validation-and-code-generation-e0389e674bd6?source=rss-5c0637053069------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0389e674bd6</guid>
            <category><![CDATA[esp]]></category>
            <category><![CDATA[esphome]]></category>
            <category><![CDATA[home-assistant]]></category>
            <category><![CDATA[diy]]></category>
            <dc:creator><![CDATA[vinsce]]></dc:creator>
            <pubDate>Tue, 25 Feb 2025 22:45:39 GMT</pubDate>
            <atom:updated>2025-03-28T17:20:21.426Z</atom:updated>
            <content:encoded><![CDATA[<p>ESPHome is incredibly versatile, but sometimes you need to integrate a sensor or device that isn’t officially supported. That’s where external components come in. They allow you to extend ESPHome’s functionality and add support for your specific hardware. In ESPHome, a component is a self-contained piece of code that handles a specific function, like reading data from a sensor or controlling a motor.</p><p>With the <a href="https://esphome.io/changelog/2025.2.0.html#removal-of-custom-components">recent removal</a> of custom components, I needed to convert my existing component to an external component. While there are plenty of components to get inspiration from, as a beginner with ESPHome there may be difficulty in finding a quick start guide to create a simple component. This is why I decided to share my experience in this series of posts, which will guide you (and me) through the basic concepts of an ESPHome component.</p><blockquote>To read this post without a Medium subscription click <a href="https://medium.com/@vinsce/create-an-esphome-external-component-part-1-introduction-config-validation-and-code-generation-e0389e674bd6?sk=2662c54ab32439ffd85d5c71c9da939d">here</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FRGi4jFT3eTUl2zRPbH4cg.jpeg" /></figure><p>In this series of posts, we’ll create an external component to work with a CC1101 transceiver to capture RF signals.<br>Prerequisites to follow the posts are a working ESPHome installation, and familiarity with ESPHome configuration and installation.</p><h3>An overview</h3><p>External components are a way to extend ESPHome functionalities with community or personal projects. This is often necessary when working with hardware that isn’t officially supported by ESPHome, or when you want to create custom logic that’s specific to your needs.</p><p>A component consists of two main parts: some Python code responsible for the validation of the YAML configuration and for code generation, and some C++ code (.h and .cpp) that handles the actual runtime logic.</p><p>The C++ code is what runs on your ESP. Its job is to talk to your sensor or device and then send that data to ESPHome. It does this using special tools that ESPHome provides, like the Sensor, BinarySensor, and Switch.</p><p>A basic directory structure for a component is showed here:</p><pre>├── my_external_component<br>│ ├── __init__.py<br>│ ├── my_external_component.cpp<br>│ ├── my_external_component.h</pre><p>Your component’s code can technically be stored anywhere, as long as it is accessible during the installation process and it is specified correctly in the YAML configuration file, as we’ll see later.<br>We’ll store the components under /esphome/components/, so the whole directory tree will be:</p><pre>esphome<br>├── components<br>│ ├── __init__.py<br>│ ├── my_external_component<br>│ │ ├── __init__.py<br>│ │ ├── my_external_component.cpp<br>│ │ ├── my_external_component.h</pre><p>Now that we understand the basic structure, let’s dive into the implementation.</p><h3>C++ Code</h3><p>Let’s begin by writing our runtime logic, which will serve as the foundation for defining our component’s configuration and how it’s used during code generation. The C++ code consists of a header file (.h) and an implementation file (.cpp).</p><h4>Header File</h4><p>The basic structure for a component’s header file looks like this:</p><pre>#pragma once<br><br>#include &quot;esphome/core/component.h&quot;<br><br># Namespace definition<br>namespace esphome {<br>namespace my_external_component {<br><br>class MyExternalComponent : public Component {<br><br> public:<br>     // Constructor<br>     MyExternalComponent();<br>    <br>     // Configuration function<br>     void set_conf_x(float conf_x);<br>    <br>     // Standard component functions to override<br>     void setup() override;<br>     void dump_config() override;<br>    <br>    protected:<br>    # Internal fields definition<br>    float conf_x_;<br>};<br><br>}  // namespace cc1101<br>}  // namespace esphome</pre><p>Here, we define our component’s class, MyExternalComponent, which inherits from the ESPHome Component class. Depending on your component’s nature, you might inherit from other base classes like PollingComponent or sensor::Sensor.</p><p>The class definition is enclosed within two namespaces: esphome, the core ESPHome namespace, and my_external_component, our component’s namespace.</p><p>Inside the class, we define the public interface and internal fields/methods.<br>The public interface consists of all the methods you’d like to call from outside the class (e.g. during code generation) or that are called directly by ESPHome. Internal fields should be defined as protected and terminating with an _. For more on code convention, check the official <a href="https://esphome.io/guides/contributing.html#codebase-standards">contribution guide</a>.</p><p>Two essential methods, setup and dump_config, are overridden from the Component class:</p><ul><li>setup(): this method should be used to initialize the component’s hardware and verify communication. If communication fails, it should call mark_failed() to indicate an error. It’s invoked automatically after the calls defined in the Python codegen, so you can expect the fields to be already initialized.</li><li>dump_config(): this method should be used to log the component’s configuration using ESP_LOGCONFIG.</li></ul><p>Depending on the type of component and the specific needs, there might be other methods to be defined, like loop or update (for PollingComponent).</p><p>Let’s examine the header file for our CC1101 component:</p><pre>#pragma once<br><br>#include &lt;ELECHOUSE_CC1101_SRC_DRV.h&gt;<br><br>#include &quot;esphome/core/component.h&quot;<br>#include &lt;esphome/core/hal.h&gt;<br><br>namespace esphome {<br>namespace cc1101 {<br><br>class CC1101 : public Component {<br><br>  public:<br>      CC1101(InternalGPIOPin *sck_pin, InternalGPIOPin *miso_pin, InternalGPIOPin *mosi_pin, InternalGPIOPin *csn_pin, InternalGPIOPin *gdo0_pin);<br>      <br>      void set_bandwidth(float bandwidth);<br>      void set_frequency(float frequency);<br>      <br>      void setup() override;<br>      void dump_config() override;<br>  <br>  protected:<br>      InternalGPIOPin *SCK_;<br>      InternalGPIOPin *MISO_;<br>      InternalGPIOPin *MOSI_;<br>      InternalGPIOPin *CSN_;<br>      InternalGPIOPin *GDO0_;<br>      <br>      float bandwidth_;<br>      float frequency_;<br>      <br>      float moduleNumber_;<br>};<br><br>}  // namespace cc1101<br>}  // namespace esphome</pre><p>Here, the constructor accepts the CC1101’s pin configurations. We also have setters for bandwidth and frequency, and the standard setup and dump_config methods.</p><h4>Implementation File</h4><p>The implementation file (.cpp) provides the actual runtime logic, following the header file’s definitions. A basic structure looks like this:</p><pre>#include &quot;esphome/core/log.h&quot;<br>#include &quot;my_external_component.h&quot;<br><br>namespace esphome {<br>namespace my_external_component {<br><br>static const char *const TAG = &quot;MyExternalComponent&quot;;<br><br>MyExternalComponent::MyExternalComponent() {<br>    // Constructor<br>}<br><br>void MyExternalComponent::set_conf_x(float conf_x) { conf_x_ = conf_x; }<br><br>void MyExternalComponent::setup() {<br>    // Setup code<br>}<br><br>void CC1101::dump_config() {<br>    ESP_LOGCONFIG(TAG, &quot;MyExternalComponent:&quot;);<br>    LOG_PIN(&quot;  Conf X:  &quot;, this-&gt;conf_x_);<br>}<br><br>}  // namespace my_external_component<br>}  // namespace esphome</pre><p>The actual implementation depends on the component’s functionality that you want to add.<br>In our CC1101 example, we configure the module using the <a href="https://github.com/LSatan/SmartRC-CC1101-Driver-Lib">SmartRC-CC1101-Driver-Lib</a> library, taking inspiration from the custom component I was using before the deprecation (<a href="https://github.com/dbuezas/esphome-cc1101">esphome-cc1101</a>).<br>The component itself just configures the CC1101 module, so that we’ll be able to use it with remote_receiver in the YAML file later.</p><pre>#include &quot;esphome/core/log.h&quot;<br>#include &quot;cc1101.h&quot;<br><br>namespace esphome {<br>namespace cc1101 {<br><br>static const char *const TAG = &quot;cc1101&quot;;<br><br>CC1101::CC1101(InternalGPIOPin *sck_pin, InternalGPIOPin *miso_pin, InternalGPIOPin *mosi_pin, InternalGPIOPin *csn_pin, InternalGPIOPin *gdo0_pin) {<br>    this-&gt;SCK_ = sck_pin;<br>    this-&gt;MISO_ = miso_pin;<br>    this-&gt;MOSI_ = mosi_pin;<br>    this-&gt;CSN_ = csn_pin;<br>    this-&gt;GDO0_ = gdo0_pin;<br>    <br>    this-&gt;moduleNumber_ = 1;<br>}<br><br>void CC1101::set_bandwidth(float bandwidth) { bandwidth_ = bandwidth; }<br><br>void CC1101::set_frequency(float frequency) { frequency_ = frequency; }<br><br>void CC1101::setup() {<br>    ESP_LOGI(TAG, &quot;CC1101 initialized.&quot;);<br>    <br>    pinMode(GDO0_-&gt;get_pin(), INPUT);<br>    <br>    ELECHOUSE_cc1101.addSpiPin(SCK_-&gt;get_pin(), MISO_-&gt;get_pin(), MOSI_-&gt;get_pin(), CSN_-&gt;get_pin(), _moduleNumber);<br>    ELECHOUSE_cc1101.setModul(_moduleNumber);<br>    ELECHOUSE_cc1101.Init();<br>    ELECHOUSE_cc1101.setRxBW(bandwidth_);<br>    ELECHOUSE_cc1101.setMHZ(frequency_);<br>    ELECHOUSE_cc1101.SetRx();<br>}<br><br><br>void CC1101::dump_config() {<br>    ESP_LOGCONFIG(TAG, &quot;CC1101:&quot;);<br>    LOG_PIN(&quot;  GDO0 Pin:  &quot;, this-&gt;GDO0_);<br>    LOG_PIN(&quot;  SCK  Pin:  &quot;, this-&gt;SCK_);<br>    LOG_PIN(&quot;  MISO Pin:  &quot;, this-&gt;MISO_);<br>    LOG_PIN(&quot;  MOSI Pin:  &quot;, this-&gt;MOSI_);<br>    LOG_PIN(&quot;  CSN  Pin:  &quot;, this-&gt;CSN_);<br>    ESP_LOGCONFIG(TAG, &quot;  Bandwith:  %.2f KHz&quot;, this-&gt;bandwidth_);<br>    ESP_LOGCONFIG(TAG, &quot;  Frequency: %.2f MHz&quot;, this-&gt;frequency_);<br>}<br><br>}  // namespace cc1101<br>}  // namespace esphome</pre><p>Key aspects demonstrated here:</p><ul><li>Constructor Initialization: pin configurations and other fields are initialized.</li><li>Method implementation: setup and dump_config are implemented.</li><li>Hardware Initialization: the setup method initializes the CC1101 using the library.</li><li>Logging: ESP_LOGCONFIG and LOG_PIN are used to log the configuration.</li></ul><h3>Python code</h3><p>The __init__.py file tells ESPHome how to validate the configuration for your component and how to generate the final C++ code.</p><pre>import esphome.config_validation as cv<br>import esphome.codegen as cg<br><br>CODEOWNERS = [&quot;@vinsce&quot;]<br>DEPENDENCIES = [ ]<br>AUTO_LOAD = [ ]<br>MULTI_CONF = True<br><br># C++ namespace<br>ns = cg.esphome_ns.namespace(&quot;my_external_component&quot;)<br>MyExternalComponent = ns.class_(&quot;MyExternalComponent&quot;, cg.Component)<br><br>CONFIG_SCHEMA = cv.Schema({<br>    cv.GenerateID(): cv.declare_id(MyExternalComponent),<br>    # Schema definition, containing the options available for the component<br>}).extend(cv.COMPONENT_SCHEMA)<br><br>async def to_code(config):<br>    # Code generation<br>    pass</pre><p>The basic structure for a __init__.py file:</p><ul><li>Import helpers for config validation: <a href="https://github.com/esphome/esphome/blob/dev/esphome/config_validation.py">esphome.config_validation</a></li><li>Import helpers for code generation: <a href="https://github.com/esphome/esphome/blob/dev/esphome/codegen.py">esphome.codegen</a></li><li>Special variables: ESPHome uses special variable to define dependencies and other metadata (see <a href="https://esphome.io/guides/contributing.html#extras">here</a>)</li><li>Load C++ component class: <a href="https://github.com/esphome/esphome/blob/54cea6c41e3d43f94494c801f9e3c4ef8210fe18/esphome/cpp_generator.py#L790">loads </a>a mocked class which is used internally for code generation</li><li>Config validation: definition of the CONFIG_SCHEMA variable</li><li>Code generation: implementation of the to_code function</li></ul><p>Let’s now see in details the config generation and code generation parts.</p><h4>Configuration validation</h4><p>One of the roles of the Python file is configuration validation. ESPHome uses a system to make sure the user’s YAML configuration is correct. It will check if the user’s YAML configuration for your component matches the schema you define. If it doesn’t, ESPHome will provide helpful error messages, making it easier to debug configuration issues.</p><p>In order to define the validation, we create the CONFIG_SCHEMA variable which is a Python dictionary-like structure that defines the expected configuration options for your ESPHome component. Think of it as the contract between your component’s code and the user’s desired setup.</p><p>Under the hood, the <a href="https://github.com/alecthomas/voluptuous">voluptuous</a> library is used for the schema validation.<br>The keys in the dictionary are the names of the configuration options, usally wrapped using the markers cv.Required or cv.Optional. It’s a good practice to define constants for these keys. E.g., a good constant would be CONF_SCK_PIN = “sck_pin”.</p><p>The values in the dictionary are <strong>validators</strong>. They tell ESPHome the data type (e.g. cv.float_) but can also define further constraints like the allowed values range (cv.int_range) or the type of GPIO pin (pins.gpio_output_pin_schema).</p><p>A configuration schema can be created from scratch using the cv.Schema() constructor, which accepts a <a href="https://github.com/esphome/esphome/blob/b7b2f3e61cabfcd71dbe891e8affdbd2e5128e9e/esphome/voluptuous_schema.py#L26">dictionary</a> as input. Another way to create a configuration is starting from one of the provided schema (e.g. cv.COMPONENT_SCHEMA) and extend using another schema (a dictionary or another provided schema).</p><p>Example of provided schema are:</p><ul><li><a href="https://github.com/esphome/esphome/blob/b7b2f3e61cabfcd71dbe891e8affdbd2e5128e9e/esphome/config_validation.py#L1976">cv.COMPONENT_SCHEMA</a></li><li><a href="https://github.com/esphome/esphome/blob/b7b2f3e61cabfcd71dbe891e8affdbd2e5128e9e/esphome/config_validation.py#L1979">cv.polling_component_schema()</a></li><li><a href="https://github.com/esphome/esphome/blob/b7b2f3e61cabfcd71dbe891e8affdbd2e5128e9e/esphome/components/sensor/__init__.py#L308">sensor.sensor_schema()</a></li></ul><p>Here’s how we the configuration validation for our component looks like:</p><pre>import esphome.config_validation as cv<br>from esphome import pins<br>from esphome.const import (<br>    CONF_ID,<br>    CONF_FREQUENCY,<br>)<br><br># Define constants for configuration keys<br>CONF_SCK_PIN = &quot;sck_pin&quot;<br>CONF_MISO_PIN = &quot;miso_pin&quot;<br>CONF_MOSI_PIN = &quot;mosi_pin&quot;<br>CONF_CSN_PIN = &quot;csn_pin&quot;<br>CONF_GDO0_PIN = &quot;gdo0_pin&quot;<br>CONF_BANDWIDTH = &quot;bandwidth&quot;<br><br># C++ namespace<br>ns = cg.esphome_ns.namespace(&quot;cc1101&quot;)<br>CC1101 = ns.class_(&quot;CC1101&quot;, cg.Component)<br><br># The configuration schema to validate the user config against<br>CONFIG_SCHEMA = cv.COMPONENT_SCHEMA.extend(<br>    {<br>        cv.GenerateID(): cv.declare_id(CC1101),<br>        cv.Required(CONF_SCK_PIN): pins.gpio_output_pin_schema,<br>        cv.Required(CONF_MISO_PIN): pins.gpio_output_pin_schema,<br>        cv.Required(CONF_MOSI_PIN): pins.gpio_output_pin_schema,<br>        cv.Required(CONF_CSN_PIN): pins.gpio_output_pin_schema,<br>        cv.Required(CONF_GDO0_PIN): pins.gpio_input_pin_schema,<br>        cv.Optional(CONF_BANDWIDTH, default=200.0): cv.float_,<br>        cv.Optional(CONF_FREQUENCY, default=868.65): cv.float_,<br>    }<br>)</pre><p>This code defines the CONFIG_SCHEMA for our component. It specifies that the SCK, MISO, MOSI, CSN, and GDO0 pins are required, and that the bandwidth and frequency are optional. It also specifies the data types for each option.</p><p>First, we have defined the constants for our configuration options. Some of the constants have been imported directly from `esphome.const`.<br>Then, we created the schema:</p><ul><li>cv.GenerateID() will create create configuration field with key esphome.const.CONF_ID marked to be auto-generated</li><li>For pins, we have used validators from esphome.pins</li></ul><h4>Code generation</h4><p>Once ESPHome has validated the user’s YAML configuration, it calls the to_code function to generate the C++ code that will run on the ESP. Here you basically want to configure the runtime for your component, creating the necessary variables, applying the configuration and registering the components/sensors. In this section you will use the functions defined in the C++ code above.</p><p>Here’s what the to_code function looks like for our example component:</p><pre>async def to_code(config):<br>    sck_pin = await cg.gpio_pin_expression(config[CONF_SCK_PIN])<br>    miso_pin = await cg.gpio_pin_expression(config[CONF_MISO_PIN])<br>    mosi_pin = await cg.gpio_pin_expression(config[CONF_MOSI_PIN])<br>    csn_pin = await cg.gpio_pin_expression(config[CONF_CSN_PIN])<br>    gd0_pin = await cg.gpio_pin_expression(config[CONF_GDO0_PIN])<br>    <br>    # Declare new component<br>    var = cg.new_Pvariable(config[CONF_ID], sck_pin, miso_pin, mosi_pin, csn_pin, gd0_pin)<br>    await cg.register_component(var, config)<br>    <br>    # Configure the component<br>    cg.add(var.set_bandwidth(config[CONF_BANDWIDTH]))<br>    cg.add(var.set_frequency(config[CONF_FREQUENCY]))</pre><p>The input arguments of the to_code function is the validated configuration.</p><p>The <a href="https://github.com/esphome/esphome/blob/b7b2f3e61cabfcd71dbe891e8affdbd2e5128e9e/esphome/core/__init__.py#L321">cg.new_Pvariable</a> function is used to declare a new pointer variable in the code generation by calling it’s constructor with the given arguments. The first argument is an <a href="https://github.com/esphome/esphome/blob/b7b2f3e61cabfcd71dbe891e8affdbd2e5128e9e/esphome/core/__init__.py#L321">ID</a> which also contains the type information (as defined in the config validation phase) and returns a mocked object that we can reference later</p><p>The cg.add function adds a line of C++ code to the generated code. In this case, we’re using it to configure the bandwidth and frequency of our component.<br>See <a href="https://github.com/esphome/esphome/blob/dev/esphome/cpp_generator.py">cpp_generator.py</a> for more details.</p><h3>Usage of the component</h3><p>Now that we’ve implemented our first external component, it’s time to see it in action! To use it in your ESPHome configuration, you’ll need to update your YAML file with the following:</p><ol><li><strong>The location of the external component:</strong> ESPHome needs to know where to find the component’s source code.</li><li><strong>Any required libraries:</strong> If your component relies on external libraries (like our CC1101 component does), you need to specify them.</li><li><strong>The component’s configuration:</strong> You’ll configure the component using the options we defined in the configuration validation section. Here’s an example YAML configuration that uses our cc1101 component:</li></ol><pre>esphome:<br>  # ...<br>  libraries:<br>    - SPI<br>    - &quot;SmartRC-CC1101-Driver-Lib&quot;<br>  # For debugging, store generated code in an accessible location:<br>  # build_path: &quot;../config/esphome/component_build&quot;<br><br># ...<br><br>external_components:<br>  - source: <br>      type: local<br>      path: components<br><br>cc1101:<br>  id: transceiver<br>  bandwidth: 200<br>  frequency: 868.65<br>  sck_pin: GPIO18<br>  miso_pin: GPIO19<br>  mosi_pin: GPIO23<br>  csn_pin: GPIO5<br>  gdo0_pin:<br>    number: 32<br>    allow_other_uses: true<br><br>remote_receiver:<br>  - id: receiver<br>    pin:<br>      number: 32<br>      allow_other_uses: true<br>    dump: all</pre><p>For more details on how to use external components in the YAML file, check out the <a href="https://esphome.io/components/external_components">official documentation</a>.</p><p>In <a href="https://medium.com/@vinsce/create-an-esphome-external-component-part-2-expose-functionality-to-homeassistant-with-sensors-675bd3a987b4">Part 2</a>, we’ll extend our component to expose measures using a sensor.</p><p>References:</p><ul><li><a href="https://esphome.io/guides/contributing.html">https://esphome.io/guides/contributing.html</a></li><li><a href="https://esphome.io/components/external_components">https://esphome.io/components/external_components</a></li></ul><p>The code can be found on <a href="https://gist.github.com/vinsce/556183c7b0e7084341216ef5a2ecd65c">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0389e674bd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recovering Lost Bike Ride from Google Timeline]]></title>
            <link>https://medium.com/@vinsce/recovering-lost-bike-ride-from-google-timeline-820618cc5c29?source=rss-5c0637053069------2</link>
            <guid isPermaLink="false">https://medium.com/p/820618cc5c29</guid>
            <category><![CDATA[google-timeline]]></category>
            <category><![CDATA[google-location-history]]></category>
            <category><![CDATA[gps]]></category>
            <category><![CDATA[cycling]]></category>
            <category><![CDATA[strava]]></category>
            <dc:creator><![CDATA[vinsce]]></dc:creator>
            <pubDate>Fri, 07 Feb 2025 22:03:52 GMT</pubDate>
            <atom:updated>2025-02-07T22:06:00.898Z</atom:updated>
            <content:encoded><![CDATA[<p>Sunny weekend after a long winter, first bike ride of the year, ready to share the glory on Strava. and… your smartwatch didn’t record it. <br>We know that feeling. You may be tempted to go back record it again. But wait! There might be another solution.</p><figure><img alt="Disappointed cyclist looking at her smartwatch" src="https://cdn-images-1.medium.com/max/1024/1*t-6rReDGK592YsPprYdF3w.png" /></figure><p>In this post I’ll show you how I used Google Location History (Timeline) from my Android phone to (partially) recover my lost ride.</p><h3>Exporting Your Google Timeline Data</h3><p>For this method to work, your Android phone needs to have been recording your location data:</p><ul><li><strong>Location History (or Timeline) was </strong><a href="https://support.google.com/maps/answer/6258979">enabled</a> on your Android phone before the ride</li><li><strong>GPS was active</strong> during the ride</li><li>Ideally, <strong>Google Maps was used</strong> during the ride</li></ul><p>Google recently <a href="https://support.google.com/maps/answer/14169818?visit_id=638745594489592634-1158066043">updated</a> Location History. Unlike the old Location History, Timeline data is stored locally on your phone and can no longer be exported using <a href="https://takeout.google.com/">Takeout</a>.</p><p>To export it:</p><ul><li>Go to your Android phone’s <strong>Settings</strong></li><li>Select <strong>Location</strong> (or similar)</li><li>Select <strong>Location Services</strong></li><li>Select <strong>Timeline</strong></li><li>Choose <strong>Export Timeline data</strong></li><li>This will create a Timeline.json file. Choose where to save it</li><li>Copy the Timeline.json file to your computer</li></ul><pre>{<br>  &quot;semanticSegments&quot;: [],<br>  &quot;rawSignals&quot;: [<br>    {<br>      &quot;position&quot;: {<br>        &quot;LatLng&quot;: &quot;52.2006633°, 4.3908864°&quot;,<br>        &quot;accuracyMeters&quot;: 3,<br>        &quot;altitudeMeters&quot;: 56.18,<br>        &quot;source&quot;: &quot;UNKNOWN&quot;,<br>        &quot;timestamp&quot;: &quot;2025-02-01T12:35:15.000+01:00&quot;,<br>        &quot;speedMetersPerSecond&quot;: 6.9<br>      }<br>    }<br>  ]<br>}</pre><h3>Converting Timeline Data to GPX</h3><p>Now that you have your Timeline.json file, you need to convert it into a GPX file, one of the format supported by <strong>Strava</strong> for ride uploads.</p><p>While the extraction and conversion process might not be complex, there are already several tools available. I personally used the <a href="https://github.com/Scarygami/location-history-json-converter">location-history-json-converter</a> project.<br>While the original version only supports the old Location History format and I had to adapt it, now <a href="https://github.com/Scarygami/location-history-json-converter/pulls?q=is%3Apr+timeline">forks</a> that support the new Timeline format are available.</p><p>These tools has helpful features like filtering by time and accuracy and support for multiple output formats. For Strava, use the gpxtracks output format.</p><pre>git clone https://github.com/Scarygami/location-history-json-converter # or one of the forks<br>cd location-history-json-converter<br>pip install -r requirements.txt<br>python ./location_history_json_converter.py -s 2025-02-01 -e 2025-02-01 -f gpxtracks ./Timeline.json out.gpx</pre><h3>Upload to Strava</h3><p>You now have your GPX file ready!<br>Go to the <a href="https://www.strava.com/upload/select">Strava Upload page</a> and upload it. Your ride is now ready for those well-deserved kudos!</p><blockquote>This post shares my personal experience recovering a lost ride using Google Timeline. It’s not a comprehensive guide and may not work for everyone. I was using Google Maps on my phone for navigation, while my smartwatch failed. Using Google Timeline I was able to recover and upload more than half the track.<br>Hopefully, it will save you some time if you’re in a similar situation.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=820618cc5c29" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>