<?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 Alejandro Corredor on Medium]]></title>
        <description><![CDATA[Stories by Alejandro Corredor on Medium]]></description>
        <link>https://medium.com/@aecorredor?source=rss-5cb12838004d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cySc1jX6HnX3Z0zGl1Txww.png</url>
            <title>Stories by Alejandro Corredor on Medium</title>
            <link>https://medium.com/@aecorredor?source=rss-5cb12838004d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 22:16:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aecorredor/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[Medical Device Data Ingestion and File Upload in the LifeOmic Platform]]></title>
            <link>https://medium.com/lifeomic/medical-device-data-ingestion-and-file-upload-in-the-lifeomic-platform-e5e18e29b91?source=rss-5cb12838004d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5e18e29b91</guid>
            <category><![CDATA[iot-platform]]></category>
            <category><![CDATA[medical-devices]]></category>
            <dc:creator><![CDATA[Alejandro Corredor]]></dc:creator>
            <pubDate>Fri, 11 Aug 2023 16:32:37 GMT</pubDate>
            <atom:updated>2023-08-11T16:32:37.591Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7t4SWWiiJL8sp26AEPZLPA.png" /><figcaption>Midjourney depiction of data ingestion for medical devices</figcaption></figure><h3>Introduction</h3><p>In the rapidly evolving landscape of healthcare technology, medical platforms have become integral for collecting and analyzing data from various devices. A critical aspect of these platforms is the seamless ingestion of data and efficient upload of files. In this article, we will delve into the intricacies of the code responsible for enabling data ingestion and file upload in the LifeOmic Platform. By gaining a comprehensive understanding of the underlying mechanisms, we can appreciate how this code streamlines the flow of information, ensuring accurate diagnostics and efficient data management.</p><p>We will go through an example project that demonstrates the ability to handle button events on a medical device, simulating real-world scenarios while recording relevant results. We will discuss how these observations are structured, published to specific topics using MQTT, and seamlessly transmitted to the LifeOmic Platform for further analysis.</p><p>Another critical aspect we will cover is the code’s capability to facilitate efficient file upload. We will examine how the code requests upload URLs via MQTT in the event of error detection, allowing diagnostic log files to be securely transmitted to the server. We will explore the process of establishing an HTTP connection, performing PUT requests, and ensuring successful file uploads.</p><p>We’ll also go over what can be accomplished within our Platform’s web application once device data is available, from creating a table that lets us visualize all observations recorded on a device, to creating a graph that plots device data over time.</p><p>By delving into the code implementation, you’ll have a comprehensive understanding of the data ingestion and file upload processes within the LifeOmic Platform. Armed with this knowledge, we hope that you can optimize your own solutions, ensuring accurate data capture, efficient diagnostics, and enhanced patient care, all within a single secure and easy-to-use service.</p><h3>Prerequisites</h3><p>In order for devices to be able to communicate with the LifeOmic Platform, they must be correctly provisioned. The process for provisioning devices is explained in detailed in this <a href="https://medium.com/lifeomic/how-to-integrate-your-medical-device-with-the-lifeomic-platform-c40b9241a1a3">publication</a>. For the purposes of this article, we’ll assume that our device has already been successfully provisioned. Ultimately, this means that the device has access to its device certificate, which is used to securely communicate with the LifeOmic Platform.</p><h3>Overview</h3><p>Before diving into the implementation code, let’s look at a high-level overview of the data ingestion and file upload flow. The sequence diagram below illustrates the interactions between the device, the LifeOmic MQTT broker, and the LifeOmic API.</p><figure><img alt="Sequence Diagram for the data ingestion and file upload flow." src="https://cdn-images-1.medium.com/max/1024/1*4tuERg8OlngzDErecCAEnA.png" /><figcaption>Sequence Diagram for the data ingestion and file upload flow</figcaption></figure><p>At the start, the device establishes a connection with the LifeOmic MQTT broker, enabling communication between the device and the platform. Once connected, the device subscribes to its unique FHIR ingest and File Upload topics, ensuring it receives relevant messages from the broker. Both the FHIR ingest and File Upload topics have /accepted and /rejected sub-topics so devices can listen for success and error responses as messages are published to them.</p><p>As in our past articles, we’ll be using the <a href="https://docs.m5stack.com/en/core/core2">M5Stack Core 2</a>. The device is equipped with hardware buttons that we’ll use to trigger events. One button triggers ingesting data and the other will simulate an error for uploading device diagnostics.</p><p>In the case of data ingestion, the device publishes the calculated results to the FHIRIngest topic. The LifeOmic MQTT broker receives the result and acknowledges its successful delivery by publishing to the ${DEVICE_ID}/FHIRIngest/accepted topic.</p><p>However, if an error is simulated by pressing on the error button, the device requests diagnostics upload by publishing a message to the CreateFileUploadLinktopic. The LifeOmic MQTT broker responds by publishing a signed file upload URL to the ${DEVICE_ID}/CreateFileUploadLink/accepted topic.</p><p>With the upload URL in hand, the device initiates an HTTP PUT request to the LifeOmic API, transmitting the diagnostic log file for upload. The LifeOmic API processes the request and returns a result indicating the success or failure of the file upload.</p><p>This overview provides a high-level understanding of the data ingestion and file upload flow within the medical device platform. In the subsequent sections, we will explore the code implementation that enables these functionalities, examining the steps involved in establishing connections, publishing messages, and handling file uploads.</p><h3>Code Overview</h3><p>Without further ado, let’s take a look at the code. For brevity, we’ll only show the most relevant parts of the code, and use // ... to indicate where code was omitted. A repository with all of the code can be found <a href="https://github.com/lifeomic/device-samples/tree/master/samples/data-ingestion">here</a>.</p><h4>Establishing Connectivity</h4><p>At its core, the code focuses on establishing connectivity, ensuring seamless communication between the medical device and the LifeOmic Platform. It begins by initializing an authenticated WiFi connection by using the device certificate and device private key.</p><pre>// ...<br><br>void setupWifi();<br><br>// ...<br><br><br>void setup()<br>{<br>  // ...<br>  setupWifi();<br>  // ...<br>}<br><br>void loop()<br>{<br>  // ...<br><br>  if (WiFi.status() != WL_CONNECTED)<br>  {<br>    M5.Lcd.println(&quot;error, wifi not connected&quot;);<br>  }<br><br>  // ...<br>}<br><br>void setupWifi()<br>{<br>  M5.Lcd.print(&quot;Connecting to WiFi&quot;);<br>  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);<br>  while (WiFi.status() != WL_CONNECTED)<br>  {<br>    delay(500);<br>    M5.Lcd.print(&quot;.&quot;);<br>  }<br>  M5.Lcd.println(&quot;&quot;);<br>  M5.Lcd.println(&quot;Wifi Connected&quot;);<br><br>  wifiClient.setCACert(AWS_CERT_CA);<br>  wifiClient.setCertificate(LO_DEVICE_CERTIFICATE);<br>  wifiClient.setPrivateKey(LO_DEVICE_PRIVATE_KEY);<br>  mqttConnect();<br>  delay(2000);<br><br>  // ...<br>}</pre><p>Additionally, the code configures the MQTT connection by subscribing to the device topic and adding a handler for dealing with “file upload” messages that the broker publishes to the device.</p><pre>// in &quot;Config.h&quot;<br><br>std::string LO_IOT_ENDPOINT = &quot;data.iot.us.lifeomic.com&quot;;<br>std::string AWS_RULES_TOPIC = &quot;$aws/rules&quot;;<br>std::string LO_FHIR_INGEST_TOPIC_NAME = &quot;FHIRIngest&quot;;<br>std::string LO_FILE_UPLOAD_TOPIC_NAME = &quot;CreateFileUploadLink&quot;;<br>std::string LO_FHIR_INGEST_RULES_TOPIC = AWS_RULES_TOPIC + &quot;/&quot; + LO_FHIR_INGEST_TOPIC_NAME;<br>std::string LO_FILE_UPLOAD_RULES_TOPIC = AWS_RULES_TOPIC + &quot;/&quot; + LO_FILE_UPLOAD_TOPIC_NAME;<br><br>// ...<br><br>// in &quot;main.cpp&quot;<br><br>// ...<br><br>std::string fhirIngestAcceptedTopic = DEVICE_ID + &quot;/&quot; + LO_FHIR_INGEST_TOPIC_NAME + &quot;/accepted&quot;;<br>std::string fhirIngestRejectedTopic = DEVICE_ID + &quot;/&quot; + LO_FHIR_INGEST_TOPIC_NAME + &quot;/rejected&quot;;<br>std::string fileUploadAcceptedTopic = DEVICE_ID + &quot;/&quot; + LO_FILE_UPLOAD_TOPIC_NAME + &quot;/accepted&quot;;<br>std::string fileUploadRejectedTopic = DEVICE_ID + &quot;/&quot; + LO_FILE_UPLOAD_TOPIC_NAME + &quot;/rejected&quot;;<br><br>// ...<br><br>void setupWifi();<br>void mqttConnect();<br><br>// ...<br><br>void handleMessage(String &amp;topic, String &amp;payload);<br><br>// ...<br><br>void setup()<br>{<br>  // ...<br>  setupWifi();<br>  // ...<br>}<br><br>void loop()<br>{<br>  mqttConnect();<br>  mqttClient.loop();<br><br>  // ...<br><br>  if (WiFi.status() != WL_CONNECTED)<br>  {<br>    M5.Lcd.println(&quot;error, wifi not connected&quot;);<br>  }<br><br>  // ...<br>}<br><br>void setupWifi()<br>{<br>  M5.Lcd.print(&quot;Connecting to WiFi&quot;);<br>  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);<br>  while (WiFi.status() != WL_CONNECTED)<br>  {<br>    delay(500);<br>    M5.Lcd.print(&quot;.&quot;);<br>  }<br>  M5.Lcd.println(&quot;&quot;);<br>  M5.Lcd.println(&quot;Wifi Connected&quot;);<br><br>  wifiClient.setCACert(AWS_CERT_CA);<br>  wifiClient.setCertificate(LO_DEVICE_CERTIFICATE);<br>  wifiClient.setPrivateKey(LO_DEVICE_PRIVATE_KEY);<br>  mqttConnect();<br>  delay(2000);<br>}<br><br>void mqttConnect()<br>{<br>  if (mqttClient.connected())<br>  {<br>    return;<br>  }<br><br>  Serial.print(&quot;Last MQTT Error: &quot;);<br>  Serial.println(mqttClient.lastError());<br><br>  Serial.println(&quot;Connecting to MQTT broker&quot;);<br>  mqttClient.begin(LO_IOT_ENDPOINT.c_str(), 8883, wifiClient);<br>  mqttClient.setCleanSession(false);<br><br>  while (!mqttClient.connect(DEVICE_ID))<br>  {<br>    Serial.print(&quot;.&quot;);<br>    delay(100);<br>  }<br><br>  if (!mqttClient.connected())<br>  {<br>    Serial.println(&quot;&quot;);<br>    Serial.println(&quot;Broker timeout!&quot;);<br>  }<br>  else<br>  {<br>    Serial.println(&quot;Connected to MQTT broker&quot;);<br><br>    Serial.printf(&quot;Subscribing to topic %s\n&quot;, fhirIngestAcceptedTopic.c_str());<br>    mqttClient.subscribe(fhirIngestAcceptedTopic.c_str());<br><br>    Serial.printf(&quot;Subscribing to topic %s\n&quot;, fhirIngestRejectedTopic.c_str());<br>    mqttClient.subscribe(fhirIngestRejectedTopic.c_str());<br><br>    Serial.printf(&quot;Subscribing to topic %s\n&quot;, fileUploadAcceptedTopic.c_str());<br>    mqttClient.subscribe(fileUploadAcceptedTopic.c_str());<br><br>    Serial.printf(&quot;Subscribing to topic %s\n&quot;, fileUploadRejectedTopic.c_str());<br>    mqttClient.subscribe(fileUploadRejectedTopic.c_str());<br><br>    // We&#39;ll take a look at the implementation of &quot;handleMessage&quot; in the<br>    // following sections.<br>    mqttClient.onMessage(handleMessage);<br>  }<br>}<br><br>// ...</pre><h4>Button Event Handling</h4><p>The code is set up to publish data when either of the two side buttons on the device are pressed. The code that gets triggered when pressing those buttons simulates result calculations and publishes them to the data ingestion topic. At the same time, the device diagnostics also get updated by recording the last triggered action.</p><pre>// ...<br><br>String diagFileBuffer = &quot;&quot;;<br><br>// ...<br><br>void handleButton(Button btn);<br>void recordObservation(String val, String code, String system, String display);<br>void updateDiagnostic(String val);<br><br>// ...<br><br>void loop()<br>{<br>  // ...<br><br>  handleButton(m5.BtnA);<br>  handleButton(m5.BtnC);<br><br>  // ...<br>}<br><br>// ...<br><br>void handleButton(Button btn)<br>{<br>  if (btn.wasReleased() || btn.pressedFor(1000, 200))<br>  {<br>    M5.Lcd.print(&quot;Calculating Results...&quot;);<br>    delay(500);<br><br>    String result = &quot;success&quot;;<br>    // LO_RESULT_CODE and LO_CODE_SYSTEM are arbitrary here, and <br>    // can either match the FHIR spec or your own ingestion<br>    // structure. See more in the FHIR docs:<br>    // http://hl7.org/fhir/STU3/terminologies-systems.html<br>    recordObservation(result, LO_RESULT_CODE, LO_CODE_SYSTEM, &quot;&quot;);<br>    M5.Lcd.printf(&quot;%s: %s\n&quot;, btn.label(), result);<br>    updateDiagnostic(&quot;Btn=&quot; + String(btn.label()) + &quot;;result=&quot; + result);<br>  }<br>}<br><br>// ...<br><br>void recordObservation(String val, String code, String system, String display)<br>{<br>  StaticJsonDocument&lt;200&gt; doc;<br>  doc[&quot;value&quot;] = val;<br>  doc[&quot;unit&quot;] = &quot;status&quot;;<br>  StaticJsonDocument&lt;200&gt; codeObj;<br>  codeObj[&quot;code&quot;] = code;<br>  codeObj[&quot;system&quot;] = system;<br>  // fn argument display variable results in null.<br>  codeObj[&quot;display&quot;] = &quot;btn_press_event&quot;;<br>  JsonArray coding = doc.createNestedArray(&quot;coding&quot;);<br>  coding.add(codeObj);<br>  char jsonBuffer[1024];<br>  serializeJson(doc, jsonBuffer);<br>  // retained and qos are required.<br>  bool pubResp = mqttClient.publish(LO_FHIR_INGEST, jsonBuffer, false, 1);<br>  Serial.print(&quot;pub response &quot;);<br>  Serial.println(pubResp);<br>}<br><br>void updateDiagnostic(String val)<br>{<br>  diagFileBuffer += val + &quot;\n&quot;;<br>}<br><br>// ...</pre><p>The data that gets published to the ingestion topic is a JSON buffer that has a specific structure. First, it includes the value and the unit of the data point being ingested. It also includes a coding property, which is itself another JSON object which includes code, system, and display properties.</p><p>In the FHIR specification, a code represents a concept or a value that has a defined meaning within a particular code system. It serves as a standardized representation of clinical or administrative data. A code system, on the other hand, is a collection of codes and their associated definitions. It provides a controlled vocabulary or terminology that facilitates the consistent and interoperable exchange of healthcare information.</p><p><a href="http://hl7.org/fhir/STU3/terminologies-systems.html">FHIR</a> supports the use of various existing code systems to ensure consistency and interoperability across different healthcare systems. Some common systems include LOINC, SNOMED CT, and ICD-10. When ingesting data with the LifeOmic Platform, you can choose an existing code system or decide to roll your own.</p><h4>File Upload</h4><p>In addition to data ingestion, the code facilitates efficient file upload for diagnostic logs. An error is simulated when the middle button on the device is pressed. The press event triggers a function that initiates the file upload process by requesting an upload URL via the file upload MQTT topic. Upon receiving the request, the broker generates a unique signed file upload URL and sends it back via the device topic. Since the device is listening for messages on the device topic, it receives the event with the new upload URL. It then performs a PUT request to the upload URL, transferring the diagnostic log file securely to the LifeOmic API.</p><pre>// ...<br><br>void handleErrorButton(Button btn);<br>void requestDeviceDiagnosticUpload();<br>void uploadDeviceDiagnostic(String &amp;topic, String &amp;payload);<br><br>// ...<br><br>void loop()<br>{<br>  // ...<br><br>  handleErrorButton(m5.BtnB);<br><br>  // ...<br>}<br><br>// ...<br><br>void handleErrorButton(Button btn)<br>{<br>  if (btn.wasReleased() || btn.pressedFor(1000, 200))<br>  {<br>    M5.Lcd.print(&quot;Calculating Results...&quot;);<br>    delay(500);<br><br>    String result = &quot;fail&quot;;<br>    M5.Lcd.println(&quot;error detected. Uploading diagnostic log file&quot;);<br>    startFileUpload();<br>    recordObservation(result, LO_RESULT_CODE, LO_CODE_SYSTEM, &quot;&quot;);<br>    updateDiagnostic(&quot;Btn=&quot; + String(btn.label()) + &quot;;result=&quot; + result);<br>  }<br>}<br><br>// ...<br><br>void startFileUpload()<br>{<br>  StaticJsonDocument&lt;200&gt; doc;<br>  doc[&quot;fileName&quot;] = String(DEVICE_ID) + &quot;_&quot; + String(millis()) + &quot;_device_diagnostic.txt&quot;;<br>  doc[&quot;contentType&quot;] = &quot;text/plain&quot;;<br>  char jsonBuffer[1024];<br>  serializeJson(doc, jsonBuffer);<br>  Serial.println(jsonBuffer);<br>  bool pubResp = mqttClient.publish(LO_FILE_UPLOAD_RULES_TOPIC.c_str(), jsonBuffer, false, 1);<br>  Serial.print(&quot;pub response &quot;);<br>  Serial.println(pubResp);<br>}<br><br>// We previously registered this function to the &quot;onMessage&quot; MQTT handler<br>// on the device. <br>void handleMessage(String &amp;topic, String &amp;payload)<br>{<br>  Serial.print(&quot;Message received on topic: &quot;);<br>  // In a production environment, we&#39;d use the topic to know which type of <br>  // payload we&#39;re getting:<br>  // - success if the topic ends with &quot;CreateFileUploadLink/accepted&quot;<br>  // - error if the topic ends with &quot;CreateFileUploadLink/rejected&quot;<br>  Serial.println(topic);<br>  Serial.print(&quot;Payload: &quot;);<br>  Serial.println(payload);<br><br>  // unmarshall payload, extract uploadUrl<br>  DynamicJsonDocument doc(2048);<br>  DeserializationError err = deserializeJson(doc, payload);<br>  if (err)<br>  {<br>    Serial.print(&quot;Deserialization Error: &quot;);<br>    Serial.println(err.c_str());<br>  }<br><br>  if (!doc[&quot;uploadUrl&quot;].isNull())<br>  {<br>    HTTPClient http;<br>    http.begin(wifiClient, doc[&quot;uploadUrl&quot;]);<br>    http.addHeader(&quot;Content-Type&quot;, &quot;text/plain&quot;);<br>    http.addHeader(&quot;Content-Length&quot;, String(diagFileBuffer.length()));<br>    int response = http.PUT(diagFileBuffer);<br>    if (response &gt;= 200 &amp;&amp; response &lt; 300)<br>    {<br>      diagFileBuffer = &quot;&quot;;<br>    }<br>    else<br>    {<br>      Serial.printf(&quot;Error uploading diagnostic file: %d\n&quot;, response);<br>    }<br>  }<br>}</pre><h4>Keep in Mind</h4><p>As you implement and adapt this code to your specific medical device platform, consider incorporating additional features such as robust error handling, <a href="https://github.com/lifeomic/device-samples/tree/master/samples/storage-encryption">data encryption</a>, and optimization techniques.</p><h3>Data Analysis Inside the LifeOmic Platform</h3><p>Now that we have taken a closer look at the data ingestion and file upload process, let’s dive into how we can leverage our device data once it has made its way to the LifeOmic Platform.</p><p>Let’s start with checking out some of the button event data that we’ve been sending so far. Once we are in the LifeOmic Platform, we can navigate to the Medical Devices tab on the left menu. Once there, we can search for the device we’d like to inspect. In this scenario, we’ve chosen one of our test devices, which has been sending the events shown in the previous code.</p><p>We have selected a time range to get an overview of all the events that were recorded during a certain time period.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B56cgYRo-DhH1FylMd-pcA.png" /><figcaption>Table view showing device button events</figcaption></figure><p>We’ve configured our table to show the event type, the event value, and the time when it was recorded. Tables are configurable and can adapt to many different types of values, as seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iX6066ffchrHqwhgNsy5Tw.png" /><figcaption>Table settings in the right panel</figcaption></figure><p>The other type of visualization we can reach for is a graph of data points over time. In our example, we have configured a graph to display the different button event values over time as dots on the graph. When hovering over each dot, we can see all of the event’s details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UcpJqRfk8cXcysnuUk5VfA.png" /><figcaption>Graph view showing button events over time</figcaption></figure><p>As with the table visualization, the graph is also configurable. Most importantly, we can choose which type of FHIR data we want to plot, and then filter the data by specific codes. In our example, we have chosen to trace Observations matching codes with the btn_press_event value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EFzK5obE2UIrRppb1OkdMQ.png" /><figcaption>Graph settings in the right panel</figcaption></figure><p>On top of the specific data events we ingested, we were also able to upload a device diagnostics file when we simulated an error on the device. The LifeOmic Platform lets us inspect that file by navigating to the Files tab on the left navigation menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Ow-ffVRicciCxGqnJd58g.png" /><figcaption>Navigating to the files tab on the left menu</figcaption></figure><p>We can use the search bar to find and open our diagnostics file. In our example, once we open it, we’ll be able to see a timeline of all the actions the device recorded before it encountered the error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*imWs_1xJmIqNyyZwfj61Nw.png" /><figcaption>Device Diagnostics file opened in the LifeOmic Platform file browser</figcaption></figure><h3>Closing Thoughts</h3><p>The capabilities offered by the LifeOmic Platform provide us with powerful tools to gain valuable insights into the behavior of a fleet of devices. The visualizations and data analytics within the Platform allow us to unlock a deeper understanding of device performance and utilization. Armed with this knowledge, we are empowered to make data-driven decisions that have the potential to enhance the overall experience for practitioners and patients alike.</p><p>The ability to monitor and analyze device data within the LifeOmic Platform not only improves operational efficiency but also enables us to proactively identify patterns, detect anomalies, and optimize device performance. This proactive approach translates into better outcomes, reduced downtime, and improved patient care.</p><p>Additionally, the LifeOmic Platform ensures the secure storage and management of all the essential data required for these insights. With a robust and reliable infrastructure in place, we can trust that our sensitive data is protected, maintaining the highest standards of privacy and security.</p><p>To find out more about our medical device solutions, check out our <a href="https://lifeomic.com/solutions/medical-devices/">website</a>. We’ve also published another <a href="https://medium.com/lifeomic/medical-device-failure-analysis-with-the-lifeomic-platform-668e166cd2fa">article</a> that goes deeper into device failure analysis, which pairs well with the topics we have just discussed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5e18e29b91" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lifeomic/medical-device-data-ingestion-and-file-upload-in-the-lifeomic-platform-e5e18e29b91">Medical Device Data Ingestion and File Upload in the LifeOmic Platform</a> was originally published in <a href="https://medium.com/lifeomic">Life and Tech @ LifeOmic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure ESP32 Device Provisioning with Hardware Security]]></title>
            <link>https://medium.com/lifeomic/secure-esp32-device-provisioning-with-hardware-security-ccb72ea5c326?source=rss-5cb12838004d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccb72ea5c326</guid>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[healthcare-technology]]></category>
            <category><![CDATA[medical-devices]]></category>
            <category><![CDATA[medtech]]></category>
            <category><![CDATA[healthtech]]></category>
            <dc:creator><![CDATA[Alejandro Corredor]]></dc:creator>
            <pubDate>Thu, 22 Jun 2023 18:34:53 GMT</pubDate>
            <atom:updated>2023-06-22T18:34:53.531Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u694wuibJGK__0OSSUuKPQ.png" /><figcaption>Midjourney Generated Microchip</figcaption></figure><p><strong><em>DISCLAIMER</em></strong><em>: The examples shown in this article deal with sensitive data like claim certificates, private keys, and encryption keys. None of this data should be exposed. DO NOT commit any file containing sensitive information to version control (e.g. via .gitignore for git). If this type of file is committed, a bad actor could obtain a claim certificate and private key for a fleet of devices. This would allow the bad actor to potentially deploy an infinite number of unauthorized machines.</em></p><h3>Intro</h3><p>In <a href="https://medium.com/lifeomic/how-to-integrate-your-medical-device-with-the-lifeomic-platform-c40b9241a1a3">one of our previous articles</a>, we explained how to provision a medical device for use with the LifeOmic Platform. The process consists of obtaining a claim certificate and a private key for a fleet of devices, getting those into the device, and exchanging them for a device certificate on the first boot-up. However, there is one important aspect that we left out of the initial article — securely storing the claim certificates and private keys in the device. The secure storage process is complicated, so we left it out of the first article for simplicity’s sake. This article addresses securely storing the claim certificates and private key in the device.</p><p>In the first article, we stored the claim certificate and private key in plain text inside the application code. Plain text is a clear security vulnerability. An attacker with access to the device could read the claim certificate and private key from the binary. That means that the attacker could provision an infinite number of unauthorized devices. We don’t want that.</p><p>We still need to get that claim certificate and private key into the device during the manufacturing process. So, how do we securely do that? Enter Flash Encryption. Devices with the ESP32 architecture support Flash Encryption through the use of the ESP-IDF framework. In basic terms, Flash Encryption works by doing a one-time encryption activation on the device through a series of commands. After that, the contents of the flash memory are fully encrypted. But, for our provisioning use case, the story does not end there. The claim certificate and private key will not be stored in flash memory, since they would be erased as soon as the device is turned off. We’ll be storing them in something durable: Non-Volatile Storage (NVS). NVS is the type of storage that does not get wiped when the device is turned off — Exactly what we need.</p><p>But wait, NVS is not encrypted, so that would defeat the whole purpose of this story. Well, the truth is that Flash Encryption is just the first step towards NVS Encryption. We actually encrypt the claim certificate and private key with another set of encryption keys. After that happens, we’ll store the encryption keys in a new partition on the device. That partition is indeed protected by Flash Encryption and is what makes everything work together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D4Zvhq1USgjFLr0iWnxn5g.png" /><figcaption>Overview of the NVS encryption flow</figcaption></figure><p>Our first step was to load our initial encrypted data (the claim certificate and private key) and their corresponding encryption keys into the device. NVS Encryption is then activated. Any subsequent read/writes made to or from the device are fully protected. For those interested in the fine-grained details, check out the <a href="https://docs.espressif.com/projects/esp-idf/en/latest/esp32/security/flash-encryption.html#flash-encryption">Flash Encryption documentation</a>. We’ve also published the final repository of the example to GitHub; find it <a href="https://github.com/lifeomic/device-samples/tree/master/samples/storage-encryption">here</a>.</p><p>Here are the steps to securely provision our claim certificate and private key into the device hardware:</p><ol><li>Set up a custom partition table for our device with a CSV file. It will include a partition for NVS and a partition for securely storing NVS Encryption keys (more on this in a bit).</li><li>Specify how we’ll load our claim certificate and private key binaries into NVS with a CSV file. The file will specify where our data is and in what NVS namespace it will live.</li><li>Generate encrypted binaries of our claim certificate and private key. This step will also output the binary of the keys used to encrypt the data.</li><li>Flash the encrypted binaries of the claim certificate and the private key into the NVS partition.</li><li>Flash the binary of the keys used to encrypt the data from step 4 into the NVS keys partition. The NVS keys partition is encrypted through Flash Encryption.</li><li>Flash the device for the first time. This enables Flash Encryption on the initial boot.</li><li>Confirm that everything worked by inspecting the output of the application code. The code should print the decrypted claim certificate and private key.</li></ol><p>We now have a general understanding of the encryption process. Let’s begin the step-by-step guide.</p><h3>Prerequisites</h3><p>Before we get into the actual setup, we need to install a few things on our local machine:</p><ol><li>Python 3</li><li>The ESP-IDF Framework. To follow along, we recommend you install and use it via their VSCode plugin: <a href="https://github.com/espressif/vscode-esp-idf-extension/blob/master/docs/tutorial/install.md">https://github.com/espressif/vscode-esp-idf-extension/blob/master/docs/tutorial/install.md</a></li><li>After installing ESP-IDF, set the $IDF_PATH in your bash/zsh profile. When installing ESP-IDF with the VSCode plugin, the path should end up looking something like this:</li></ol><pre># Inside your bash/zsh profile file.<br><br>export IDF_PATH=$HOME/esp/esp-idf</pre><h3>Securely Storing the Claim Certificate and Private Key</h3><p>After having access to a claim certificate and a private key, the next step is to locate where they were saved. For this article, we store them in a certs folder under the main project code. Keep in mind that we do not commit that folder to version control. We now have to configure the partition table for our device. Importantly, it specifies our NVS partition and a partition for securely storing our NVS encryption keys. The custom partition table is specified by creating a CSV file:</p><pre>custom_partitions.csv<br><br># Name,     Type,    SubType,  Offset,  Size,     Flags<br>nvs,        data,    nvs,      ,        0x6000,<br>storage,    data,    0xff,     ,        0x1000,<br>factory,    app,     factory,  ,        1M,<br>nvs_key,    data,    nvs_keys, ,        0x1000,   encrypted,</pre><p>The two important rows here are the first and last one. The first one specifies our NVS partition with its given size. The last one specifies an extra partition for storing our NVS encryption keys. Note that it’s marked with an encrypted flag. This is what tells ESP-IDF to protect the encryption keys using Flash Protection. It’s also worth noting that we do not specify offsets. This allows the offsets to be automatically calculated during the build process.</p><p>We can now specify the content that our NVS partition initially loads (the claim certificate and private key). This is also done by leveraging a CSV file:</p><pre>main/nvs.csv<br><br>key,type,encoding,value<br>certs,namespace,,<br>claim_cert,file,string,main/certs/claim-cert.pem<br>private_key,file,string,main/certs/private.key</pre><p>We first declare a new namespace called certs. Namespaces are a concept in NVS for dividing stored data. This single CSV file essentially defines a key/value store. The first row specifies the namespace, and the remaining rows specify the values. Our last two rows specify where our claim certificate and private key are located, as well as the name of the key we’ll use to access them.</p><p>We’re now ready to generate the encrypted data that will be flashed into the NVS storage. We can do this with the NVS partition generator tool. The tool is included with the ESP-IDF installation:</p><pre>$IDF_PATH/components/nvs_flash/nvs_partition_generator/nvs_partition_gen.py \<br>  encrypt main/nvs.csv encrypted_nvs.bin 0x6000 --keygen --keyfile nvs_keys.bin</pre><p>The command takes an input file, an output file, the size of the NVS partition, and a set of options. The NVS partition size corresponds to the size specified in the partition table. The options specify the encryption of the data and the output of the encryption keys binary.</p><p>After running the above command, our ESP-IDF project tree should look like this:</p><pre>├── build<br>│   └── (...)<br>├── keys<br>│   ├── nvs_keys.bin        &lt;---- DO NOT COMMIT TO VERSION CONTROL<br>├── components<br>│   └── (...)               &lt;---- No components for our example<br>├── main<br>│   ├── CMakeLists.txt<br>│   ├── certs               &lt;---- Contains claim certificate and private key<br>│   │   ├── claim-cert.pem        DO NOT COMMIT TO VERSION CONTROL<br>│   │   ├── private.key<br>│   ├── main.c<br>│   └── nvs.csv             &lt;---- CSV with NVS key/value data<br>├── CMakeLists.txt<br>├── encrypted_nvs.bin       &lt;---- Encrypted claim cert + private key to be<br>│                                 Flashed to NVS storage<br>├── custom_partitions.csv   &lt;---- CSV with device partition table<br>└── sdkconfig.defaults      &lt;---- More on this in a bit</pre><p>For the final step of this section, we’ll flash the two generated binaries into the device. The encrypted NVS data is flashed to the nvs partition, and the NVS encryption keys are flashed to the nvs_key partition. Before we can do that, we need to locate the offset of each partition.</p><p>First, we make sure that our sdkconfig.defaults file has the correct configuration:</p><pre># Tells the build we have a custom partition table<br>CONFIG_PARTITION_TABLE_CUSTOM=y <br><br># Tells the build where our custom partition table is defined<br>CONFIG_PARTITION_TABLE_CUSTOM_FILENAME=&quot;custom_partitions.csv&quot;<br>CONFIG_PARTITION_TABLE_FILENAME=&quot;custom_partitions.csv&quot;<br><br># Specifies where the partition table is stored. The default location<br># is 0x8000, but when Flash Encryption is enabled, the size of the <br># Bootloader increases, which requires us to move this to a higher offset.<br># The size of the binary also has an impact on the end value of this <br># location, so it may change depending on the size of the application.<br>CONFIG_PARTITION_TABLE_OFFSET=0x10000<br><br># Tells the build that the device will use Flash Encrytpion and<br># NVS Encryption.<br># These values are the key to making things work.<br>CONFIG_NVS_ENCRYPTION=y<br>CONFIG_SECURE_FLASH_ENC_ENABLED=y<br># This last option would only be enabled while developing. For <br># a final production release, it would be off. See the <br># reference links for more info about what the option does.<br>CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT=y</pre><p>Then, we build our project. Open it with VSCode and run the command palette with ESP-IDF: Build your project. This generates a binary file for the partition table under the build folder. We can now inspect that partition by running the following command:</p><pre>$IDF_PATH/components/partition_table/gen_esp32part.py \ <br>  build/partition_table/partition-table.bin</pre><p>The output should look like this:</p><pre>Parsing binary partition input...<br>Verifying table...<br># ESP-IDF Partition Table<br># Name, Type, SubType, Offset, Size, Flags<br>nvs,data,nvs,0x11000,24K,<br>storage,data,255,0x17000,4K,<br>factory,app,factory,0x20000,1M,<br>nvs_key,data,nvs_keys,0x120000,4K,encrypted</pre><p>We’ll remember the Offset for the nvs and nvs_key.</p><p>We can now flash the encrypted binary of the claim certificate and the private key to the NVS partition:</p><pre>python $IDF_PATH/components/esptool_py/esptool/esptool.py \<br>  -p $PORT \<br>  --before default_reset \<br>  --after no_reset \<br>  write_flash $OFFSET encrypted_nvs.bin</pre><p>$OFFSET<strong> </strong>corresponds to the value obtained from the previous step for the nvs row. $PORT corresponds to the port that connects to the device.</p><p>We do the same for the NVS encryption keys, but this time passing the --encrypt option. If we don’t include it, we’ll encounter errors when flashing the device and encryption won’t end up working.</p><pre>python $IDF_PATH/components/esptool_py/esptool/esptool.py \<br>  -p $PORT \<br>  --before default_reset \<br>  --after no_reset \<br>  write_flash --encrypt $OFFSET keys/nvs_keys.bin</pre><p>$OFFSET<strong> </strong>corresponds to the value obtained from the previous step for the nvs_key row. Again, do not forget the --encrypt option when flashing the encryption keys.</p><h3>Enabling Flash Encryption</h3><p>At this point, the data required for securely provisioning the device is loaded. The only thing left to do is to flash the device for the first time. This step will actually enable Flash Encryption. In simple terms, the device flashes, the encryption fuse turns on, and the device resets. All flash memory is subsequently encrypted.</p><p>To do this we first open an ESP-IDF terminal within VSCode with ESP-IDF: Open ESP-IDF and then run the following command inside it:</p><pre>idf.py -p $PORT flash monitor</pre><p>At this point everything should be good to go. The application code within main/main.c should have printed out the chip information and chip encryption status. The chip encryption status should be ON. The code should also have printed the decrypted claim certificate and the private key. That proves that NVS encryption is working correctly. Let’s take a look at what we should see in the console:</p><pre>Loaded app from partition at offset ${OFFSET}<br>Checking flash encryption...<br>Generating new flash encryption key...<br>flash_encrypt: Read &amp; write protecting new key...<br>flash_encrypt: Setting CRYPT_CONFIG efuse to 0xF<br>flash_encrypt: Not disabling UART bootloader encryption<br>flash_encrypt: Disable UART bootloader decryption...<br>flash_encrypt: Disable UART bootloader MMU cache...<br>flash_encrypt: Disable JTAG...<br>flash_encrypt: Disable ROM BASIC interpreter fallback...<br>flash_encrypt: Flash encryption completed<br>boot: Resetting with flash encryption enabled...<br>Checking Flash Encryption Status<br>FLASH_CRYPT_CNT eFuse value is 1<br>Flash encryption feature is enabled in DEVELOPMENT mode<br>storage-encryption: Loading private key &amp; certificate<br>storage-encryption: Loaded private key &amp; certificate successfully!<br>Private Key:<br>------BEGIN RSA PRIVATE KEY------<br>...<br>...<br>...<br>------END RSA PRIVATE KEY------<br><br>Claim Certificate:<br>------BEGIN CERTIFICATE------<br>...<br>...<br>...<br>------END CERTIFICATE------</pre><p>Next, let’s look at the application code more closely.</p><h3>Application Code</h3><p>For our example, there’s not much to it. It’s a single C file. We first have a couple of helper functions. These just print out some information about the chip and its encryption status.</p><p>The important part is where we securely initialize NVS to access the encrypted claim certificate and private key. nvs_secure_initialize finds the nvs_key partition, reads the encrypted encryption keys (yeap, encryptception) and initializes NVS. It does this by passing them along when calling nvs_flash_secure_init.</p><p>The code then just accesses the certs namespace by using the native NVS library. It retrieves the claim certificate and private key by using the nvs_load_value_if_exist helper.</p><p>Let’s look at the code:</p><pre>// Inside main/main.c<br><br>#include &lt;stdio.h&gt;<br>#include &lt;inttypes.h&gt;<br>#include &quot;freertos/FreeRTOS.h&quot;<br>#include &quot;freertos/task.h&quot;<br>#include &quot;soc/efuse_reg.h&quot;<br>#include &quot;esp_efuse.h&quot;<br>#include &quot;esp_chip_info.h&quot;<br>#include &quot;esp_flash.h&quot;<br>#include &quot;esp_partition.h&quot;<br>#include &quot;esp_flash_encrypt.h&quot;<br>#include &quot;esp_efuse_table.h&quot;<br>#include &quot;nvs.h&quot;<br>#include &quot;nvs_flash.h&quot;<br><br>static void print_chip_info(void);<br>static void print_flash_encryption_status(void);<br><br>static const char *TAG = &quot;storage-encryption&quot;;<br><br>#if CONFIG_IDF_TARGET_ESP32<br>#define TARGET_CRYPT_CNT_EFUSE ESP_EFUSE_FLASH_CRYPT_CNT<br>#define TARGET_CRYPT_CNT_WIDTH 7<br>#else<br>#define TARGET_CRYPT_CNT_EFUSE ESP_EFUSE_SPI_BOOT_CRYPT_CNT<br>#define TARGET_CRYPT_CNT_WIDTH 3<br>#endif<br><br>static void print_chip_info(void)<br>{<br>    esp_chip_info_t chip_info;<br>    uint32_t flash_size;<br>    esp_chip_info(&amp;chip_info);<br><br>    printf(&quot;This is %s chip with %d CPU core(s), WiFi%s%s, &quot;,<br>           CONFIG_IDF_TARGET,<br>           chip_info.cores,<br>           (chip_info.features &amp; CHIP_FEATURE_BT) ? &quot;/BT&quot; : &quot;&quot;,<br>           (chip_info.features &amp; CHIP_FEATURE_BLE) ? &quot;/BLE&quot; : &quot;&quot;);<br><br>    unsigned major_rev = chip_info.revision / 100;<br>    unsigned minor_rev = chip_info.revision % 100;<br><br>    printf(&quot;silicon revision v%d.%d, &quot;, major_rev, minor_rev);<br><br>    if (esp_flash_get_size(NULL, &amp;flash_size) != ESP_OK)<br>    {<br>        printf(&quot;Get flash size failed&quot;);<br>        return;<br>    }<br><br>    printf(&quot;%&quot; PRIu32 &quot;MB %s flash\n&quot;, flash_size / (1024 * 1024),<br>           (chip_info.features &amp; CHIP_FEATURE_EMB_FLASH) ? &quot;embedded&quot; : &quot;external&quot;);<br>}<br><br>static void print_flash_encryption_status(void)<br>{<br>    printf(&quot;\nChecking Flash Encryption Status\n&quot;);<br><br>    uint32_t flash_crypt_cnt = 0;<br>    esp_efuse_read_field_blob(TARGET_CRYPT_CNT_EFUSE, &amp;flash_crypt_cnt, TARGET_CRYPT_CNT_WIDTH);<br>    printf(&quot;FLASH_CRYPT_CNT eFuse value is %&quot; PRIu32 &quot;\n&quot;, flash_crypt_cnt);<br><br>    esp_flash_enc_mode_t mode = esp_get_flash_encryption_mode();<br>    if (mode == ESP_FLASH_ENC_MODE_DISABLED)<br>    {<br>        printf(&quot;Flash encryption feature is disabled\n&quot;);<br>    }<br>    else<br>    {<br>        printf(&quot;Flash encryption feature is enabled in %s mode\n&quot;,<br>               mode == ESP_FLASH_ENC_MODE_DEVELOPMENT ? &quot;DEVELOPMENT&quot; : &quot;RELEASE&quot;);<br>    }<br>}<br><br>/**<br> * Helper function that loads a value from NVS.<br> * It returns NULL when the value doesn&#39;t exist.<br> */<br>char *nvs_load_value_if_exist(nvs_handle handle, const char *key)<br>{<br>    // Try to get the size of the item<br>    size_t value_size;<br>    if (nvs_get_str(handle, key, NULL, &amp;value_size) != ESP_OK)<br>    {<br>        ESP_LOGE(TAG, &quot;Failed to get size of key: %s&quot;, key);<br>        return NULL;<br>    }<br><br>    char *value = malloc(value_size);<br>    if (nvs_get_str(handle, key, value, &amp;value_size) != ESP_OK)<br>    {<br>        ESP_LOGE(TAG, &quot;Failed to load key: %s&quot;, key);<br>        return NULL;<br>    }<br><br>    return value;<br>}<br><br>esp_err_t nvs_secure_initialize()<br>{<br>    static const char *NVS_TAG = &quot;nvs&quot;;<br>    esp_err_t err = ESP_OK;<br><br>    // 1. Find partition with NVS encryption keys<br>    const esp_partition_t *partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA,<br>                                                                ESP_PARTITION_SUBTYPE_DATA_NVS_KEYS,<br>                                                                &quot;nvs_key&quot;);<br>    if (partition == NULL)<br>    {<br>        ESP_LOGE(NVS_TAG, &quot;Could not locate nvs_key partition. Aborting.&quot;);<br>        return ESP_FAIL;<br>    }<br><br>    // 2. Read NVS encryptions from key partition<br>    nvs_sec_cfg_t cfg;<br>    if (ESP_OK != (err = nvs_flash_read_security_cfg(partition, &amp;cfg)))<br>    {<br>        ESP_LOGE(NVS_TAG, &quot;Failed to read nvs keys (rc=0x%x)&quot;, err);<br>        return err;<br>    }<br><br>    // 3. Securely initialize NVS partition<br>    if (ESP_OK != (err = nvs_flash_secure_init(&amp;cfg)))<br>    {<br>        ESP_LOGE(NVS_TAG, &quot;failed to initialize nvs partition (err=0x%x). Aborting.&quot;, err);<br>        return err;<br>    };<br><br>    return err;<br>}<br><br>void app_main(void)<br>{<br>    print_chip_info();<br>    print_flash_encryption_status();<br><br>    esp_err_t err = nvs_secure_initialize();<br>    if (err != ESP_OK)<br>    {<br>        ESP_LOGE(&quot;main&quot;, &quot;Failed to initialize nvs (rc=0x%x). Halting.&quot;, err);<br>        while (1)<br>        {<br>            vTaskDelay(100);<br>        }<br>    }<br><br>    // Open the &quot;certs&quot; namespace in read-only mode<br>    nvs_handle handle;<br>    ESP_ERROR_CHECK(nvs_open(&quot;certs&quot;, NVS_READONLY, &amp;handle) != ESP_OK);<br><br>    // Load the private key &amp; certificate<br>    ESP_LOGI(TAG, &quot;Loading private key &amp; certificate&quot;);<br>    char *private_key = nvs_load_value_if_exist(handle, &quot;private_key&quot;);<br>    char *certificate = nvs_load_value_if_exist(handle, &quot;claim_cert&quot;);<br><br>    // We&#39;re done with NVS<br>    nvs_close(handle);<br><br>    // Check if both items have been correctly retrieved<br>    if (private_key == NULL || certificate == NULL)<br>    {<br>        ESP_LOGE(TAG, &quot;Private key or cert could not be loaded&quot;);<br>        return; // You might want to handle this in a better way<br>    }<br>    else<br>    {<br>        // We&#39;re printing the keys to the console for demonstration<br>        // purposes. This shows that NVS Encryption is actually working.<br>        // Don&#39;t do this in production code, obviously!<br>        ESP_LOGI(TAG, &quot;Loaded private key &amp; certificate successfully!&quot;);<br>        printf(&quot;Private Key:\n %s\n&quot;, private_key);<br>        printf(&quot;Claim Certificate:\n %s\n&quot;, certificate);<br>    }<br><br>    // At this point the private_key and claim_cert have been loaded.<br>    // Use them to exchange them for a claim certificate and proceed to<br>    // communicate with the LifeOmic Platform via MQTT.<br><br>    // Once we&#39;ve exchanged the claim certificate for a device certificate,<br>    // we would also proceed to securely storing the device certificate to<br>    // NVS storage. Since NVS Encryption is already enabled at this point, <br>    // we do not have to worry about exposing it to bad actors.<br>}</pre><p>At this point, we can do anything we want with our retrieved data. For our example, we want to be able to authenticate against the LifeOmic Platform. To do that we would follow the same steps as in our previous article. We would use the claim certificate and private key to start the <a href="https://en.wikipedia.org/wiki/MQTT">MQTT</a> exchange process for obtaining a device certificate. Once we obtain the certificate, we can securely store it in NVS, since NVS Encryption is already enabled.</p><p>Voila!</p><h3>Closing Thoughts</h3><p>We have seen how to securely provision an ESP32 chip with any preloaded data that we wish to include. Provisioning occurs before we ship off our device. By enabling Flash Encryption along with NVS Encryption, we also guarantee that our runtime code can securely store future data. This improves our security posture when provisioning a fleet of devices.</p><p>This is only one way of achieving secure device provisioning. Depending on the specific architecture of the chip, the process may vary. This article is based on the ESP32 architecture, which is the architecture we are using throughout our device series. Some ESP32 chips even include a separate secure hardware element, which can provide similar security capabilities. It is important to keep in mind the type of data being dealt with. You need to come up with a battle-tested strategy for securing sensitive information before letting your devices out into the wild.</p><h3>Troubleshooting</h3><p>When flashing the device for the first time with encryption enabled, certain eFuses are burned. This changes the eFuse values from 0 to 1 and turns on encryption. If things go wrong and encryption is not enabled, it’s possible to check the eFuse values. Run the following command:</p><pre>python $IDF_PATH/components/esptool_py/esptool/espefuse.py <br>  --port $PORT summary</pre><p>See the links in the references for more details on how the flash encryption process works.</p><h3>References</h3><ul><li><a href="https://medium.com/lifeomic/how-to-integrate-your-medical-device-with-the-lifeomic-platform-c40b9241a1a3">How to integrate your medical device with the LifeOmic Platform</a></li><li><a href="https://github.com/lifeomic/device-samples">Repository with Full Example Code</a></li><li><a href="https://dev.to/kkentzo/how-to-encrypt-the-nvs-volume-on-the-esp32-4n9k">How to encrypt the NVS volume on the ESP32</a></li><li><a href="https://savjee.be/blog/esp-idf-store-aws-iot-certificates-in-nvs-partition/">ESP-IDF: Storing AWS IoT certificates in the NVS partition (for OTA)</a></li><li><a href="https://docs.espressif.com/projects/esp-idf/en/latest/esp32/security/flash-encryption.html#flash-encryption">ESP-IDF Flash Encryption</a></li><li><a href="https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/storage/nvs_flash.html#nvs-encryption">ESP-IDF NVS Encryption</a></li><li><a href="https://github.com/espressif/esp-idf/tree/efe919275e8f4516ffd5f99f9a59e9d3efbae281/examples/security/flash_encryption">ESP-IDF Example</a></li><li><a href="https://en.wikipedia.org/wiki/MQTT">MQTT Wikipedia Page</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccb72ea5c326" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lifeomic/secure-esp32-device-provisioning-with-hardware-security-ccb72ea5c326">Secure ESP32 Device Provisioning with Hardware Security</a> was originally published in <a href="https://medium.com/lifeomic">Life and Tech @ LifeOmic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>