<?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[The Toit Take - Medium]]></title>
        <description><![CDATA[Continuously update the code on your microcontrollers even over cellular connections. Monitor and securely service your devices in production; all through the Toit API. - Medium]]></description>
        <link>https://medium.com/the-toit-take?source=rss----ac7619cafdf1---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>The Toit Take - Medium</title>
            <link>https://medium.com/the-toit-take?source=rss----ac7619cafdf1---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 00:59:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/the-toit-take" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Get insight into memory use on your ESP32 running Toit]]></title>
            <link>https://medium.com/the-toit-take/get-insight-into-memory-use-on-your-esp32-running-toit-65c62e5b65fd?source=rss----ac7619cafdf1---4</link>
            <guid isPermaLink="false">https://medium.com/p/65c62e5b65fd</guid>
            <dc:creator><![CDATA[Erik Corry]]></dc:creator>
            <pubDate>Fri, 26 Apr 2024 08:11:50 GMT</pubDate>
            <atom:updated>2024-04-26T08:11:50.106Z</atom:updated>
            <content:encoded><![CDATA[<p>One advantage of running a virtual machine on an ESP32 is that the VM can provide ways to inspect the state of the system. For example, the <a href="https://libs.toit.io/core/utils/class-Profiler">profiler</a> can tell you where your program is spending time, and exceptions produce stack traces with method names and source line numbers.</p><p>There are four ways to get insights into memory use on your ESP32 running Toit. Here we will show some sample output from each of them, and discuss what information they provide.</p><p>These four methods all produce output on the ESP32’s serial port, which can be connected to your workstation using a USB connection. For most of them, the output is produced in a compact, encoded, form which must be decoded on your workstation. Therefore you will only see these reports on the serial line if you are decoding messages using the jag monitor command from <a href="https://github.com/toitlang/jaguar">Jaguar</a>.</p><h3>Serial-print-heap-report</h3><p>The serial-print-heap-report function produces the same output on the serial port that you get when you have an out-of-memory error. This shows the amount of memory used by each allocation type, but does not provide much information on layout and relative placement.</p><pre>import system<br><br>main:<br>  system.serial-print-heap-report</pre><pre>Heap report:<br>  ┌───────────┬──────────┬─────────────────────────────────────────────────────┐<br>  │   Bytes   │  Count   │  Type                                               │<br>  ├───────────┼──────────┼─────────────────────────────────────────────────────┤<br>  │    2648   │      7   │  external byte array                                │<br>  │   45056   │     13   │  toit processes                                     │<br>  │     16384 │        4 │    system    0 2f5cc0cb-d843-503e-9d5c-ba92a0652eda │<br>  │     24576 │        6 │    other     1 93a90cd2-30b6-c513-326a-66c5310785ae │<br>  │      4096 │        1 │    current   2 474e8bcb-2db1-d561-49d0-f82651ae198a │<br>  │   16384   │      1   │  heap metadata                                      │<br>  │    4096   │      1   │  spare new-space                                    │<br>  │    7800   │     27   │  lwip                                               │<br>  │    6488   │    507   │  heap overhead                                      │<br>  │    1944   │     28   │  event source                                       │<br>  │    5544   │     90   │  thread/other                                       │<br>  │   26400   │     21   │  thread/spawn                                       │<br>  │   49152   │    225   │  untagged                                           │<br>  │   12224   │     59   │  wifi                                               │<br>  └───────────┴──────────┴─────────────────────────────────────────────────────┘<br>  Total: 177736 bytes in 470 allocations (73%), largest free 60k, total free 66k</pre><p>The Toit processes each have a garbage collected heap. This heap is always made up of a whole number of 4k pages. In this case the processes occupy 4, 6, and 1 page. Toit heaps can only expand 4k at a time, so they will fail to expand if the largest free space is not at least 4k.</p><p>Often you have 3 Toit processes running:</p><p><strong>System</strong>: This is the system process that takes care of RPC discovery and other kernel-like tasks.</p><p><strong>Other</strong>: This will normally be either <a href="https://github.com/toitlang/jaguar">Jaguar</a> or <a href="https://docs.toit.io/getstarted/fleet">Artemis</a>. They take care of installing and uninstalling programs, and installing OTA updates of the system. Usually, Jaguar is used for local development on your own Wifi, while Artemis takes care of deployed devices in the field, perhaps with a cellular network connection.</p><p><strong>Current</strong>: This is your program that provoked the heap report or ran out of memory. For example you may have started it with jag run .</p><p>Toit’s garbage collection uses some memory, shared between all processes. There is one 4k page used for new-space Toit garbage collection, and there is a static heap <strong>metadata</strong> area that is also there to support GC. This is sized as a fixed percentage of the memory size, so if you have 4Mbytes of PSRAM it will be proportionally bigger.</p><p>The <a href="https://github.com/toitlang/toit/tree/master/src/third_party/dartino">Toit garbage collector</a> can perform a garbage collection with no allocation. Thus, even when the malloc and Toit heaps are 100% full, we can run a GC and free up memory. This is done by using the reserved heap metadata memory.</p><p>The rest of the memory is accounted for by Toit’s c<a href="https://github.com/toitware/esp-idf/blob/master/components/heap/third_party/dartino/cmpctmalloc.c">ustom malloc implementation</a>. Not all calls to malloc are instrumented with information on the use, so these categories can be rather vague.</p><p>The category of <strong>external byte array</strong> is Toit ByteArrays that have their storage in the malloc’ed area. These will normally be larger than about 4000 bytes, otherwise their payload would be on the Toit heap.</p><p>For some of the malloc allocations, they come from some other component of esp-idf, and we don’t know the reason. These memory allocations are marked untagged. (See the conclusion for a way to reduce the amount of untagged memory if you don’t need BlueTooth.)</p><p>The final line gives a rough indication of how fragmented your memory is. If you have many small free areas, you may see something like “largest free 2k, total free 17k”. This would mean that there is not a single 4k page that is completely free, even if there are lots of smaller free areas within the 4k pages, adding up to 17k of free bytes.</p><h3>Print-objects</h3><p>print-objectprints a summary of the objects on the Toit heap of the current process. With the --gc flag it first does a garbage collection, so that only live objects are counted. This function will only tell you about one process, but it is the only function that tells you what is taking up space within the garbage-collected Toit heap. The Toit heap is sliding and compacting, so you should not see fragmentation issues here.</p><pre>import system<br><br>main:<br>  system.print-objects --gc</pre><pre>Objects:<br>  ┌─────────┬──────────────┬──────────────────────────────────────────────┐<br>  │   Count │        Bytes │ Class                                        │<br>  ├─────────┼──────────────┼──────────────────────────────────────────────┤<br>  │     100 │      2k  752 │ ByteArray_                                   │<br>  │     100 │      1k  576 │ Bar                                          │<br>  │       1 │      1k    8 │ SmallArray_                                  │<br>  │     100 │          800 │ Foo                                          │<br>  │       1 │          424 │ Stack_                                       │<br>  │       1 │           56 │ Task_                                        │<br>  │       1 │           12 │ List_                                        │<br>  ╞═════════╪══════════════╪══════════════════════════════════════════════╡<br>  │         │      6k  580 │ Total                                        │<br>  └─────────┴──────────────┴──────────────────────────────────────────────┘</pre><p>For each class we can see how many instances exist, and the size in bytes. In this case, ByteArray objects take up 2k plus 752 bytes, or 2800 bytes in all. The `List_` and `SmallArray_` classes are used to implement <a href="https://libs.toit.io/core/collections/library-summary">lists, maps and sets</a>. Internally, the lists are split up into parts, called SmallArray_, that are at most 500 elements (2000 bytes) long.</p><p>On 32 bit platforms like the ESP32, Toit objects have a 4-byte header, and each field takes up 4 bytes, so a class with one field takes up 8 bytes per instance.</p><p>The names of the classes are not stored on the device for space reasons, but the jag monitor command transparently looks them up in the snapshot file when decoding this message.</p><h3>Memory-page-report</h3><p>memory-page-report produces a concise per-page report on all the memory on the device, both malloc heap and Toit heap. For each 4k page, there is a colored rectangle indicating how much of it is allocated. If the color is black then the page is completely allocated. If it is light gray, then most of the page is free.</p><pre>import esp32<br><br>main:<br>  esp32.memory-page-report</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JXjyomZfD3foRKdklBg_wg.png" /><figcaption>The output of memory-page-report on the terminal.</figcaption></figure><p>The red rectangles are 4k pages that are in use for Toit’s garbage collected heap. These may not actually be completely full — that information is not available in this tool. On the left in this example we can see the 16k allocation that is called heap metadata (see above). Because this is a single large allocation, it is shown within one wide white box. Within the white box, each shaded rectangle represents a 4k page.</p><p>On the right we can see the free pages. In this case there are 6 completely empty pages, which means that a 24k allocation would succeed. Usually, the heap heuristics mean that the free pages are located on the right (high addresses), which means allocations of more than 4k are possible.</p><p>Multiple letters in a rectangle indicate that allocations of memory for different purposes are active on the same 4k page.</p><p>If you see many pale gray pages, and the free pages are not adjacent, then your heap is suffering from fragmentation. The Toit heap is able to defragment itself fairly well, but the malloc heap cannot move objects, and fragmentation can become an issue on long-running devices.</p><h3>Dump-heap</h3><p>dump-heap provides the most detailed and low level view of the memory use of your ESP32. In this view you can see a color-coded view of each 8-byte memory area, represented by a half-character-wide ASCII graphics block.</p><p>Large malloc allocations are headerless, so that a 4k page can be 100% used by an aligned 4k allocation. Each smaller malloc’ed memory allocation has a gray 8-byte header, followed by a number of bytes that is divisible by 8. Memory areas that are big enough are identified by a capital letter that shows a crude indication of the usage. Very small allocations, where a letter will not fit, are merely color coded.</p><pre>import esp32<br><br>main:<br>  esp32.dump-heap</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*B6JZilpRNEeI5xYJ2RImhw.png" /><figcaption>An extract of the terminal output of esp32.dump-heap.</figcaption></figure><p>At the end of the per-page output is a color key:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*5lQRXJskp-_iNBC2Kfurqw.png" /></figure><h3>Conclusion</h3><p>A basic ESP32 with no PSRAM doesn’t have a huge amount of memory, and some of it is taken by the system before your program even runs. These four functions should help you find out what is happening to your memory.</p><p>One thing to be aware of on the ESP32: The Bluetooth stack takes quite a lot of memory even if you don’t use it. However, it can be compiled out. If you don’t need Bluetooth support, see <a href="https://gist.github.com/erikcorry/6b913de8cc77ae3275d4d096f2d008eb">here</a> for a way to reduce memory usage.</p><p>Often, the largest memory allocation your system will encounter is the packet of certificates that your system receives when making a TLS (HTTPS) connection to a server. Since the size of this packet is out of your control it can cause issues. One way to handle this is to make the TLS connection just after boot time, when the memory is not fragmented. Once the connection has been made, subsequent connections can reuse the session data, making the handshake faster and avoiding the certificate data. The session data reuse happens automatically if you reuse the same <a href="https://pkg.toit.io/github.com/toitlang/pkg-http@2.7.2/docs/http/client/class-Client">HTTP Client</a> object.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65c62e5b65fd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-toit-take/get-insight-into-memory-use-on-your-esp32-running-toit-65c62e5b65fd">Get insight into memory use on your ESP32 running Toit</a> was originally published in <a href="https://medium.com/the-toit-take">The Toit Take</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Toit executables]]></title>
            <link>https://medium.com/the-toit-take/exploring-toit-executables-bff1f28dc9ef?source=rss----ac7619cafdf1---4</link>
            <guid isPermaLink="false">https://medium.com/p/bff1f28dc9ef</guid>
            <category><![CDATA[disassembly]]></category>
            <category><![CDATA[toit]]></category>
            <dc:creator><![CDATA[Florian Loitsch]]></dc:creator>
            <pubDate>Wed, 20 Mar 2024 12:10:09 GMT</pubDate>
            <atom:updated>2024-03-20T12:10:09.429Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently developed a small command-line tool called ai, utilizing OpenAI on the command line. Although there are many similar tools available, I wanted to create my own. Toit already includes an OpenAI package, and the remaining code is just a handful of lines. This also lets me tailor the tool’s API to suit my requirements. Those interested in the code can access it <a href="https://github.com/floitsch/ai-projects/tree/main/cli">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nPx0aIudhJwWYsjZXgLzAA.jpeg" /><figcaption>Vessel with tiger decoration.</figcaption></figure><p>The program’s concept was to use GPT-3.5 when called with ai and GPT-4 when called with ai4. At startup, the program just has to examine its name to determine the appropriate model to use.</p><p>Once written, I shared the executable with my brother, who immediately noticed that it wasn’t working correctly for him:</p><pre>% echo &quot;What gpt version are you?&quot; | ~/local/bin/ai4<br>I am based on the GPT-3 model.</pre><p>For fun he attempted to inspect the internals using ghidra, but his efforts were not successful. This prompted my curiosity about the complexity of inspecting Toit executables.</p><p>The Toit SDK provides a compiler capable of generating executables for various platforms. Rather than generating machine code, the compiler produces bytecode for the virtual machine, which is then loaded into prebuilt “vessels” designed to accommodate the bytecodes. The sdk/vessels directory contains prebuilt vessels for the host platform and optionally for different platforms/architectures. When downloading the Toit SDK from GitHub’s release page, a selection of vessels is already packaged with the SDK. When building locally, these vessels can also be downloaded separately.</p><p>Although Toit lacks a tool specifically for inspecting executables, it includes a program named toitp in the tools directory, which can be used to examine snapshots (bytecodes). By extracting the bytecodes from the executables, we can analyze them using toitp. The challenge lies in identifying where within the executables the bytecodes are stored. Interestingly, the simplest method to determine the offset is to compare two distinct executables (or the empty vessel and the executable). The first altered offset will indicate the offset of the snapshot-size, which is located just before the snapshot data itself (refer to the <a href="https://github.com/toitlang/toit/blob/76016975ca587d3f2cc22f5fb0045c45c86a88d7/src/vessel.cc#L57">code</a>):</p><pre>  int snapshot_size = reinterpret_cast&lt;uint32*&gt;(vessel_snapshot_data)[0];<br>  uint8* snapshot = &amp;vessel_snapshot_data[4];</pre><p>One minor hurdle remains: identifying the correct vessel to compare with the executable. For convenience, the SDK includes prebuilt vessels of various sizes capable of holding different bytecodes. The smallest vessel is named vessel128, and the largest is vessel8192, with vessels for snapshots of size 256, 512, and 1024 in between. Given the vessels’ distinct sizes, we can compare them with the executable sizes to find a match.</p><pre>ᐅ ls -l ~/local/bin/ai /opt/toit-sdk/vessels<br>-rwxr-xr-x 1 flo  flo  1624104 Mar 17 16:46 /home/flo/local/bin/ai<br><br>/opt/toit-sdk/vessels:<br>total 15492<br>-rwxr-xr-x 1 root root 2148496 Mar  9 16:13 vessel1024<br>-rwxr-xr-x 1 root root 1230992 Mar  9 16:13 vessel128<br>-rwxr-xr-x 1 root root 1361960 Mar  9 16:13 vessel256<br>-rwxr-xr-x 1 root root 1624104 Mar  9 16:13 vessel512<br>-rwxr-xr-x 1 root root 9488528 Mar  9 16:13 vessel8192</pre><p>As per the comparison, vessel512 seems to be the appropriate choice. Let’s compare the executables with this vessel:</p><pre>ᐅ cmp ~/local/bin/ai /opt/toit-sdk/vessels/vessel512<br>/home/flo/local/bin/ai /opt/toit-sdk/vessels/vessel512 differ: byte 1096898, line 6611</pre><p>It appears that the executables differ at byte position 1096898, which should thus be the snapshot size. Consequently, we can extract everything following the snapshot size:</p><pre>ᐅ dd if=$HOME/local/bin/ai bs=1 skip=1096900 of=/tmp/ai.snapshot<br>527204+0 records in<br>527204+0 records out<br>527204 bytes (527 kB, 515 KiB) copied, 1.03678 s, 508 kB/s</pre><p>The /tmp/ai.snapshot file now contains the bytecodes, along with some extraneous content at the end. Fortunately, toitp ignores trailing garbage, allowing us to inspect the snapshot without further manipulations:</p><pre>ᐅ /opt/toit-sdk/tools/toitp /tmp/ai.snapshot<br>snapshot: 527204 bytes (/tmp/ai.snapshot)<br> - program: 93965 bytes<br> - method_table: #1674, 62970 bytes<br> - class_table: #141, 2461 bytes<br> - primitives: #42, 1258 bytes<br> - selector_names_table: #276, 1094 bytes</pre><p>We can now disassemble the bytecodes:</p><pre>ᐅ /opt/toit-sdk/tools/toitp -bc /tmp/ai.snapshot main<br>Bytecodes for methods[4]: (only printing elements matching: &quot;main&quot;)<br><br>1414: main cli-secret.toit:3:1<br>  0/1418 [016] - load local 2<br>  1/1419 [020] - load literal sk-FB0EA...&lt;MY OPENAI-TOKEN&gt;<br>  3/1421 [053] - invoke static main cli.toit:16:1<br>  6/1424 [089] - return null S1 1<br><br>1427: main cli.toit:16:1<br>  0/1431 [052] - load local, as class, pop 3 - List_(112 - 116)<br>  2/1433 [052] - load local, as class, pop 2 - StringSlice_(84 - 86)<br>  4/1435 [020] - load literal gpt-3.5-turbo<br>  6/1437 [053] - invoke static program-name &lt;sdk&gt;/system/system.toit:222:1<br>  9/1440 [020] - load literal ai4<br> 11/1442 [062] - invoke eq<br> 12/1443 [082] - branch if false T18<br> 15/1446 [041] - pop 1<br> 16/1447 [020] - load literal gpt-4-turbo-preview<br> 18/1449 [022] - load null<br> 19/1450 [019] - load local 5<br> 20/1451 [053] - invoke static CollectionBase.is-empty &lt;sdk&gt;/core/collections.toit:116:3<br> ...</pre><p>And these few lines of disassembly already reveal the bug in my code: the comparison invoke eq at offset 11/1442 compares the result of calling program-name with “ai4”. However, <a href="https://libs.toit.io/system/library-summary#program-name(0%2C0%2C0%2C)">program-name</a> returns the path of how the program was invoked (similar to argv[0]) and not just the name of the executable. The fix is as simple as calling <a href="https://pkg.toit.io/github.com/toitlang/pkg-fs@2.2.0/docs/fs/library-summary#basename(1%2C0%2C0%2C)">basename</a> on the result of program-name first. This also explains why I hadn’t noticed the bug earlier: I always called the program with ai4 and not with ~/local/bin/ai4.</p><p>It’s important to note that not every Toit executable has disassembly output that is that easy to understand. If we had compiled the executable with the --strip flag all debug information would have been removed. Given that the program is open-source and I only shared it with my siblings there was no need to use that flag, and keeping debug-information yields nicer stack traces in case of issues.</p><h4>Conclusion</h4><p>Toit executables are just small virtual machines with a snapshot bolted onto them. By knowing a bit of how snapshots are stored in vessels we can easily extract these snapshots again. We can then use all the standard tools, like toitp to inspect the extracted snapshots.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bff1f28dc9ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-toit-take/exploring-toit-executables-bff1f28dc9ef">Exploring Toit executables</a> was originally published in <a href="https://medium.com/the-toit-take">The Toit Take</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Artemis]]></title>
            <link>https://medium.com/the-toit-take/artemis-1f7f1390927b?source=rss----ac7619cafdf1---4</link>
            <guid isPermaLink="false">https://medium.com/p/1f7f1390927b</guid>
            <category><![CDATA[artemis]]></category>
            <category><![CDATA[toit]]></category>
            <category><![CDATA[fleet-management]]></category>
            <dc:creator><![CDATA[Florian Loitsch]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 08:56:39 GMT</pubDate>
            <atom:updated>2024-02-23T08:56:39.326Z</atom:updated>
            <content:encoded><![CDATA[<h4>Fleet management for ESP32 devices</h4><p>For the last months, we have been working on the second version of our fleet management system. Using the lessons learned from the first version, we have designed a new system that is more modular, more flexible, and more powerful.</p><h3>Artemis</h3><p>Artemis is our new fleet management system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*Zqrc_36oKWkKHBVqJfrv-Q.png" /></figure><p>It builds on top of the Toit platform, allowing applications to be nicely containerized. In fact, the Artemis service running on the device is itself a container. Using containers with Toit means that a misbehaving application won’t bring down the whole system, and won’t affect other containers.</p><p>From the user’s point of view, Artemis is primarily a command-line interface (CLI), that manipulates local files, and applies the local configuration to all devices by pushing it to a broker server.</p><p>The current design was born out of frustration with many other cloud services, where state is stored in the cloud, and a simple click can have significant consequences. We wanted a system where the state is stored locally, and where the user can review and understand the changes before they are applied.</p><h3>Unix philosophy</h3><p>Artemis is designed to be a small, simple, and modular system. It is built on the Unix philosophy of doing one thing and doing it well. Artemis should be one tool among many, and won’t try to do everything. If there exists a program that does a great job at a specific task, Artemis should use it, rather than reinvent the wheel.</p><p>For example, instead of implementing another version control system (VCS), Artemis uses Git, or any other VCS you prefer. The communication between the devices and Artemis is done through a simple REST API, of which a reference implementation, using edge functions on Supabase, is provided. This doesn’t mean that our users need to run their own brokers, but they can!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*um61L5qn2Jralv4SRpc9jQ.png" /><figcaption>A terminal with invocations of Artemis.</figcaption></figure><p>For the same reasons, Artemis does not come with any fancy UI. Instead, it has an output mode that emits JSON. This way, other programs can take the output and visualize it in a way that suits the user’s needs.</p><p>Artemis isn’t a health-monitoring system either. While it is possible to query Artemis to know which version each device is running, and when they last checked for updates, Artemis can’t tell whether the device is actually behaving as expected. For that reason, we recommend that Artemis is used in conjunction with a health-monitoring system that is tailored to the specific needs of the devices.</p><h3>Architecture</h3><p>A fleet manager must coordinate with devices that are not directly<br>reachable. This requires multiple parts, running on different machines,<br>to work together. We think of Artemis as the combination of four<br>main components:</p><ul><li>The billing and user management server</li><li>The broker server</li><li>The CLI</li><li>The service that runs on provisioned devices</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*_KBOqhD3zgMN0DIQTUTBZw.png" /><figcaption>Diagram showing the Artemis’ architecture.</figcaption></figure><h4>Billing and user management</h4><p>We run a billing and user management server. Devices ping this server about once a day, so we know how much to charge for the service. The same server is also used for user management, used to determine who is allowed to add and remove devices from a fleet.</p><h4>Broker</h4><p>The broker is a server that devices and the CLI connect to. It’s best thought of as an asynchronous channel for the CLI to communicate with the devices. When new configurations are pushed to the devices, these are stored on the broker, so that devices can pick them up when they go online.</p><p>We provide a public broker server (secured with the same credentials as for the billing and user management server), but users can also run their own broker server.</p><p>As can be seen in the diagram, the broker server itself can often be implemented in two parts: a config database, and a file server. This distinction isn’t necessary or important, but highlights again that we try to use existing protocols and systems where possible.</p><h4>CLI</h4><p>The CLI is the main interface for the user. It is also, where most of the magic happens.</p><p>The CLI can be used to:</p><ul><li>Add and remove devices from a fleet, updating the local `devices.json` file.</li><li>Build pods, a firmware image containing the Toit and Artemis runtime and the user’s containers.</li><li>Upload pods to the broker server. There is also a way to download pods.</li><li>Update the configuration of devices, including which pod they should run.</li><li>Modify the configuration of a specific device. This is typically a temporary change, as a fleet roll-out resets devices to the configuration the device should have.</li></ul><p>When the CLI is used to update the configuration of a device, the CLI creates a patch to migrate from the current pod to the new pod. This binary patch allows efficient updates to the devices, often being only a few kilobytes in size.</p><pre>ᐅ artemis help<br>A fleet management system for Toit devices.<br><br>Usage:<br>  artemis &lt;command&gt; [&lt;options&gt;]<br><br>Commands:<br>  auth     Authenticate against the Artemis server.<br>  config   Configure Artemis tool.<br>  device   Manage devices.<br>  doc      Documentation.<br>  fleet    Manage multiple devices at the same time.<br>  help     Show help for a command.<br>  org      Manage organizations.<br>  pod      Create and manage pods.<br>  profile  Manage the user profile.<br>  sdk      Information about supported SDKs.<br>  serial   Serial port commands.<br>  version  Show the version of the Artemis tool.<br><br>Options:<br>      --fleet-root directory                             Specify the fleet root. Can also be set with the ARTEMIS_FLEET_ROOT environment variable.<br>  -h, --help                                             Show help for this command.<br>      --output-format text|json                          Specify the format used when printing to the console. (default: text)<br>      --verbose                                          Enable verbose output. Shorthand for --verbosity-level=verbose.<br>      --verbosity-level debug|info|verbose|quiet|silent  Specify the verbosity level. (default: info)<br><br>Examples:<br>  # Log in to the Artemis server using GitHub:<br>  artemis auth login<br><br>  # Create a new organization called &#39;in-the-sea&#39;, and make it the default:<br>  artemis org create in-the-sea<br><br>  # Initialize a fleet root in the current directory with the default organization:<br>  artemis fleet init<br><br>  # Build a pod from specification &#39;my-pod.yaml&#39; and upload it with just<br>  # the automatic &#39;latest&#39; tag:<br>  artemis pod upload my-pod.yaml<br><br>  # Flash the device on port /dev/ttyUSB0 with the pod for the default<br>  # group and add the new identity to the devices file:<br>  artemis serial flash --port /dev/ttyUSB0<br><br>  # Show the status of the fleet:<br>  artemis fleet status<br><br>  # Upload the pod file &#39;my-pod.pod&#39; with the tag &#39;v1.0.0&#39;, and the automatic<br>  # &#39;latest&#39; tag:<br>  artemis pod upload --tag=v1.0.0 my-pod.pod<br><br>  # Update group &#39;default&#39; to use pod &#39;my-podv1.0.0&#39;:<br>  artemis fleet group update --pod=my-pod@v1.0.0 default<br><br>  # Roll out the fleet configuration to all devices:<br>  artemis fleet roll-out</pre><h4>Service</h4><p>Provisioned devices run an Artemis service that is responsible for checking in with the broker, and updating the device’s firmware and configurations. The service can handle the incremental patches that the CLI produces. This means that firmware updates are typically small and fast.</p><p>As long as a device can be updated, software defects can be fixed, or new features can be added. As such, having a robust and reliable update mechanism is crucial. We have spent significant effort to make the update mechanism reliable and efficient.</p><p><strong>Features</strong></p><p>The Artemis service also provides a few features that are commonly useful for embedded devices. For example, it has a “channel” implementation that allows programs to reliably write sensor data (or other data) to the device’s flash.</p><p>With the help of channels it’s easy to periodically take sensor readings and<br>store them on the device. At specific intervals, or when the space runs low<br>the user can then upload the data to a server. Since wireless communication is often the most power-hungry part of a device, this can save a lot of power.</p><h3>Fleet management</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*z9ONoNG9I2vVJYdrEaESTA.png" /></figure><p>This section describes how Artemis can be used in a production setting. Smaller projects can use Artemis in a more simplified way, but the following might still be useful to understand the design choices.</p><h4>Pods</h4><p>A pod is a firmware image that contains the Toit and Artemis runtime, and the user’s containers. Using a <a href="https://docs.toit.io/getstarted/fleet/pods/#specifications">pod-specification</a> file, Artemis builds the bytecode for user’s containers and assembles them together with the chosen SDK, and Artemis service. The resulting pod can either be directly uploaded to the broker or can be saved as a file.</p><p>Pods are developed independently of the fleet. They should be seen as an image that can be deployed to any compatible device. Pods are not tied to a specific fleet or device. For that reason, pod development can be done in a separate repository, and can be versioned independently of fleet management changes.</p><p>Since Artemis always needs <em>some</em> fleet, a typical setup consists of a<br>development fleet in the development/pod repository, and a production fleet in the production repository. Since testing requires devices anyway, having a development fleet does not add any real overhead.</p><h4>Fleets</h4><p>A production fleet is normally stored in a separate repository. This repository contains (at least) the following two files:</p><p>- devices.json — A list of devices in the fleet, including their device ID,<br> and the group they belong to.<br>- fleet.json — The configuration of the fleet, including its ID (fleet and organization), and the pod-IDs for each group.</p><p>These files can be manipulated by hand, but most of the time the CLI is used instead. For example, to update the group ‘louvre’ to use pod ‘noise@v1.2.5’ one could write:</p><pre>artemis fleet group update --pod=noise@v1.2.5 louvre</pre><p>This updates the fleet.json file, but doesn’t yet change any devices. To<br>actually update the devices, the user would run:</p><pre>artemis fleet roll-out</pre><p>This command applies the state of the fleet.json/devices.json files to the broker, so that the devices can pick up the new configuration. During the roll-out, Artemis will also create patches for the devices, so that the<br>devices can update themselves efficiently.</p><h4>CI/CD integration</h4><p>While Artemis can be used manually, it is most powerful when integrated into a CI/CD pipeline. For example, devices of the development fleet can be updated automatically at each push to the development repository. Similarly, the pipeline can upload a pod of the development repository to the production fleet when a new release is tagged. Note that uploading the pod only makes the pod available to the production fleet. The actual deployment is still done in the development repository with the appropriate tools (like peer review, testing, etc.).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*MDENar2P8HnX-Au-O-3zWQ.png" /><figcaption>A step in the GitHub action workflow.</figcaption></figure><p>Feel free to get inspired by the GitHub actions in our demo repositories <a href="https://github.com/toitware/demo-artemis-pods">demo-artemis-pods</a> and <a href="https://github.com/toitware/demo-artemis-fleet">demo-artemis-fleet</a>.</p><h3>Conclusions</h3><p>Artemis is a small, simple, and modular system for fleet management. It is<br>designed to be used in a professional setting, and can be integrated into a CI/CD pipeline. Artemis is built on the Unix philosophy of doing one thing and doing it well, and tries to use existing protocols and systems where possible.</p><p>If you are interested in using Artemis, please reach out to us at <a href="/service/mailto:contact@toit.io">contact@toit.io</a> or hop into our Discord server at <a href="https://chat.toit.io/">chat.toit.io</a>. We are looking forward to hearing from you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f7f1390927b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-toit-take/artemis-1f7f1390927b">Artemis</a> was originally published in <a href="https://medium.com/the-toit-take">The Toit Take</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Syntax highlighting for Toit]]></title>
            <link>https://medium.com/the-toit-take/syntax-highlighting-for-toit-52b2f0fe71cd?source=rss----ac7619cafdf1---4</link>
            <guid isPermaLink="false">https://medium.com/p/52b2f0fe71cd</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[syntax-highlighting]]></category>
            <category><![CDATA[toit]]></category>
            <dc:creator><![CDATA[Florian Loitsch]]></dc:creator>
            <pubDate>Sat, 16 Dec 2023 05:54:51 GMT</pubDate>
            <atom:updated>2023-12-16T05:54:51.753Z</atom:updated>
            <content:encoded><![CDATA[<p>Syntax highlighting is one of these things one doesn’t really notice until it’s missing. And we have been missing it a lot …</p><p>Until recently, GitHub didn’t have Toit syntax support, and we did our code reviews in “black and white”. Horrible. With release v7.28.0 (released on December 12, 2023) of <a href="https://github.com/github-linguist/linguist/">linguist</a>, GitHub now knows about Toit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*nSdV6ZVAvmE7a_cqzegFvA.png" /><figcaption>Screenshot of the ‘add-all’ function with syntax highlighting.</figcaption></figure><p>Not only do we now get syntax highlighting of Toit code, but GitHub also recognizes the language when providing statistics for repositories. It turns out that roughly half of the <a href="https://github.com/toitlang/toit/">toit</a> repository is written in Toit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*4s0M0jEG9GaCfL2jMX--vg.png" /><figcaption>Screenshot of the language distribution in the toit repository.</figcaption></figure><p>Linguist’s support for Toit actually builds on top of our IDE support: it uses the same <a href="https://github.com/toitware/ide-tools/tree/master/vscode/syntaxes">“TextMate” grammar files</a> as are used for VS Code.</p><p>The <a href="https://github.com/toitware/ide-tools">ide-tools</a> repository that holds those grammar files is also the place where users can find a <a href="https://github.com/toitware/ide-tools/tree/master/start/vim">plugin for VIM</a>, and a <a href="https://github.com/toitware/ide-tools/tree/master/code_mirror">CodeMirror mode</a>. The latter is also used in the Google Docs and Slides extension <a href="https://workspace.google.com/marketplace/app/code_syntax/827674971433">Code Syntax</a>, which allows users to write nicely highlighted code in their documents and slides.</p><p>Creating all these different syntax highlighting rules for different editors and tools is a lot of work, but we hope to create (or receive) more of them in the future.</p><p>Also, we plan to add syntax-highlighting support to our language server — in the <a href="https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/">LSP specification</a> these are called “semantic tokens”. While this wouldn’t eliminate the need for highlighting rules for all the different editors, it would make them simpler as they wouldn’t need to handle all corner cases.</p><p>Thanks to the GitHub team for accepting our pull request!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52b2f0fe71cd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-toit-take/syntax-highlighting-for-toit-52b2f0fe71cd">Syntax highlighting for Toit</a> was originally published in <a href="https://medium.com/the-toit-take">The Toit Take</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Changing an ESP32 partition table over the air]]></title>
            <link>https://medium.com/the-toit-take/changing-an-esp32-partition-table-over-the-air-276c86feeba8?source=rss----ac7619cafdf1---4</link>
            <guid isPermaLink="false">https://medium.com/p/276c86feeba8</guid>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[toit]]></category>
            <category><![CDATA[over-the-air-update]]></category>
            <dc:creator><![CDATA[Florian Loitsch]]></dc:creator>
            <pubDate>Fri, 08 Dec 2023 17:32:57 GMT</pubDate>
            <atom:updated>2023-12-08T17:32:57.764Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the last years, the main commercial product of Toit.io has been our fleet-management system for ESP32-based IoT devices. Our first implementation, now called “v1”, worked well, but it had some undesirable properties:</p><ol><li>It ran on our own proprietary cloud.</li><li>Programs were installed in a program partition, and were versioned against the firmware version that was installed. This meant that upgrading the firmware invalidated all installed programs and required reinstalling programs again.</li><li>It didn’t allow custom firmwares, with user-provided compilation flags.</li></ol><p>Over the last year we wrote a new fleet-management system, called <a href="https://docs.toit.io/getstarted/fleet">Artemis</a>:</p><ol><li>the server (also called “broker”) is now <a href="https://github.com/toitware/artemis-releases/tree/main/broker">open-source</a>, and our users can run their own version of it. We developed it on top of <a href="https://supabase.com/">Supabase</a>, but fundamentally, any http-based server could handle the requests.</li><li>Firmware updates contain everything the device needs: the system code, packaged with the user’s programs. An efficient binary patching mechanism (which already existed in v1), makes sure that updating small parts of the firmware doesn’t require the device to download too much.</li><li>Customers can run their own firmware images, with custom compilation flags and partition tables. The only restriction is that these images must be built with a released Toit SDK that is supported by Artemis, so that the Artemis service container can run on the device. We even run a <a href="https://github.com/toitlang/envelopes">building service</a> for some important variants.</li></ol><h3>Migration</h3><p>The easiest way to migrate a device running with v1 to Artemis, is, of course, to just flash the device with the new system. However, some devices are hard to access (one of our customers has some devices offshore), or simply don’t expose any connectors.</p><p>The following image is a line-drawing from our Toitbox. This was a device we built several years ago that doesn’t expose any USB/UART port. This makes the device watertight, but it also means that the device can only be updated over the air.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8_Y2-hvtfaEPqJTzlrobxw.png" /><figcaption>Toitbox — line drawing</figcaption></figure><p>As mentioned before, Artemis now bundles user programs together with the system firmware. However, this also means that these images are significantly bigger than they used to be in v1. When we set up the partition table for our Toitboxes (or any other device that is running Toit v1), we didn’t allocate a lot of space for the OTA partitions ota_0 and ota_1. This is now coming back to haunt us: we can’t use the existing partition table for Artemis.</p><h3>Changing the partition table</h3><p>What we need to do, is change the partition table over the air. This is something that isn’t really supported by the esp-idf. On the contrary, if that process goes wrong the device might not be able to boot anymore.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fl2rC0EMQeS0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dl2rC0EMQeS0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fl2rC0EMQeS0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6cf2ed8d6c03f32107843491ff72196/href">https://medium.com/media/b6cf2ed8d6c03f32107843491ff72196/href</a></iframe><p>After a bit of tinkering, we came up with the following plan:</p><ol><li>Create a partition table that increases the OTA partition sizes, but keeps the starting location of partition ota_0 where it was.</li><li>Modify the firmware so that it checks whether it is running from ota_0 or ota_1.</li><li>If we are running from ota_1 and the partition offset is still the old one, immediately write the new partition table, and then roll back.</li><li>Otherwise, boot up normally.</li></ol><p>The crucial part in step 2 is the rollback. Once we have written the partition table, the offset of ota_1 is modified, and it’s not safe to read any data from the partition anymore. By rolling back we fake a bad OTA update and boot back into the existing ota_0 partition, which, crucially, hasn’t moved position.</p><p>Here is the original partition table we used to have on v1 devices:</p><pre># Name,   Type, SubType, Offset,   Size<br># bootloader,,  ,        0x1000,   0x7000<br># partitions,,  ,        0x8000,   0xc00<br>secure,   0x42, 0x00,    0x9000,   0x4000,<br>otadata,  data, ota,     0xd000,   0x2000,<br>ota_0,    app,  ota_0,   0x10000,  0x150000,<br>ota_1,    app,  ota_1,   0x160000, 0x150000,<br>ota_0_cfg,0x41, 0x00,    0x2B0000, 0x4000,<br>ota_1_cfg,0x41, 0x01,    0x2B4000, 0x4000,<br>nvs,      data, nvs,     0x2B8000, 0x4000,<br>coredump, data, coredump,0x2BC000, 0x10000,<br>data,     0x40, 0x00,    0x2CC000, 0x134000, encrypted</pre><p>And here is the new partition table where the OTA partition sizes have been increased:</p><pre># Name,   Type, SubType, Offset,   Size<br># bootloader,,  ,        0x1000,   0x7000<br># partitions,,  ,        0x8000,   0xc00<br>secure,   0x42, 0x00,    0x9000,   0x4000,<br>otadata,  data, ota,     0xd000,   0x2000,<br>ota_0,    app,  ota_0,   0x10000,  0x1D0000,<br>ota_1,    app,  ota_1,   0x1E0000, 0x1D0000,<br>ota_0_cfg,0x41, 0x00,    0x3B0000, 0x4000,<br>ota_1_cfg,0x41, 0x01,    0x3B4000, 0x4000,<br>nvs,      data, nvs,     0x3B8000, 0x4000,<br>coredump, data, coredump,0x3BC000, 0x10000,<br>data,     0x40, 0x00,    0x3CC000, 0x34000, encrypted</pre><p>Note that ota_0 and ota_1 are now significantly bigger (at the cost of the data partition).</p><p>Once we have a satisfactory partition table layout we can build the binary representation of the table using the ESP-IDF tools:</p><pre>python $(IDF_PATH)/components/partition_table/gen_esp32part.py \<br>    new_partition.bin new_partitions.csv</pre><p>This generates a new_partition.bin binary that we now need write into the partitions table partition. To do this, we convert that binary to C code with xxd or <a href="https://github.com/toitware/xxxd">xxxd</a>:</p><pre>xxd -C -n NEW_PARTITION -i new_partition.h new_partition.bin<br>sed -i &#39;s/unsigned char/cons unsigned char/&#39; new_partition.h</pre><p>Now we can #include the new_partition.h file and use the NEW_PARTITION_LEN and NEW_PARTITION globals to get the data.</p><h3>Prelude</h3><p>Before booting the system, our v1 firmware now needs to check whether it needs to grow the partition. Our main.c file got two new lines:</p><pre>extern void toit_start();<br>extern void grow_partition();<br><br>void app_main() {<br>  grow_partition();<br>  toit_start();<br>}</pre><p>Nice when such a big change is so minimally invasive.</p><h3>Writing the partition table</h3><p>Now the important, and risky part: writing the partition table.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FtwJ1fzE_La4&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DtwJ1fzE_La4&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FtwJ1fzE_La4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b250976d8d6bb58e3f64953c9599f390/href">https://medium.com/media/b250976d8d6bb58e3f64953c9599f390/href</a></iframe><p>We have created a <a href="https://gist.github.com/floitsch/ed2530caa613581057d8998dee0a911f">gist of the </a><a href="https://gist.github.com/floitsch/ed2530caa613581057d8998dee0a911f">grow_partition.cc</a> file, but here are the relevant parts:</p><p>We first need to check whether we still need to write the partition, and whether we are booting from ota_1. If either is false, then we just return and boot up normally.</p><pre>void grow_partition(void) {<br>  printf(&quot;Running from partition %s\n&quot;, esp_ota_get_running_partition()-&gt;label);<br>  if (invalid_or_already_written()) {<br>    printf(&quot;Partition is already grown.\n&quot;);<br>    return;<br>  }<br>  if (!running_from_ota1()) {<br>    printf(&quot;Can&#39;t update: running partition needs to be ota_1.\n&quot;);<br>    return;<br>  }<br><br>  // Update the partition table and restart to roll back to OTA_0.<br>  replace_partition_table();<br>  printf(&quot;Rebooting to roll-back.\n&quot;);<br>  esp_ota_mark_app_invalid_rollback_and_reboot();<br>  esp_restart();<br>}</pre><p>The code to check whether the partition offset is invalid or whether we have already written the partition table is here:</p><pre>static bool invalid_or_already_written() {<br>  // Check if the partition table has already been written.<br>  uint8_t buffer[256];<br>  for (int offset = 0; offset &lt; PARTITION_TABLE_SIZE; offset += 256) {<br>    esp_err_t err =<br>        spi_flash_read(PARTITION_TABLE_ADDRESS + offset, buffer, 256);<br>    if (err != ESP_OK) {<br>      printf(&quot;Failed to read partition table: 0x%x\n&quot;, err);<br>      return false;<br>    }<br>    if (offset == 0 &amp;&amp; (buffer[0] != 0xAA || buffer[1] != 0x50)) {<br>      printf(&quot;Invalid existing partition table. Maybe bad offset.\n&quot;);<br>      return false;<br>    }<br>    for (int i = 0; i &lt; 256; i++) {<br>      if (buffer[i] != NEW_PARTITION[offset + i]) {<br>        printf(&quot;Partition table differs at %d\n&quot;, offset + i);<br>        return false;<br>      }<br>    }<br>  }<br>  return true;<br>}</pre><p>It simply reads the partition table and compares it to the new partition table. If it is the same, then we have already written the table.</p><p>In our setup the partition table is always at 0x8000:</p><pre>const size_t PARTITION_TABLE_ADDRESS = 0x8000;<br>const size_t PARTITION_TABLE_SIZE = 0xC00;<br>const size_t PARTITION_TABLE_ALIGNED_SIZE = 0x1000;  // Must be divisible by 4k.</pre><p>It’s also pretty straightforward to check whether we are running from ota_1:</p><pre>static bool running_from_ota1() {<br>  const esp_partition_t* running_partition = esp_ota_get_running_partition();<br>  return strcmp(running_partition-&gt;label, &quot;ota_1&quot;) == 0;<br>}</pre><p>The only part left is now the code that writes the table to flash. For simplicity, I have removed some error checks and a retry-loop, but the gist link at the top of the section contains the whole code.</p><pre>static esp_err_t replace_partition_table() {<br>  // Copy the partition table to DRAM. This is a requirement of spi_flash_write.<br>  uint8_t* new_partition_table = (uint8_t*)malloc(NEW_PARTITION_LEN);<br>  if (new_partition_table == NULL) {<br>    printf(&quot;Failed to allocate memory for partition table.\n&quot;);<br>    return ESP_FAIL;<br>  }<br>  memcpy(new_partition_table, NEW_PARTITION, NEW_PARTITION_LEN);<br><br>  esp_err_t err = spi_flash_erase_range(PARTITION_TABLE_ADDRESS, PARTITION_TABLE_ALIGNED_SIZE);<br>  if (err != ESP_OK) {<br>    printf(&quot;Failed to erase partition table: 0x%x\n&quot;, err);<br>  }<br><br>  err = spi_flash_write(PARTITION_TABLE_ADDRESS, new_partition_table, PARTITION_TABLE_ALIGNED_SIZE);<br>  if (err != ESP_OK) {<br>    printf(&quot;Failed to write partition table: 0x%x\n&quot;, err);<br>  }<br><br>  free(new_partition_table);<br>  printf(&quot;Wrote new partition table.\n&quot;);<br>  return err;<br>}</pre><p>We first copy the new partition table to DRAM, then erase the old flash, and finally write the new partition table. If we ever manage to (partially) erase the partition table and then not (fully) write the new partition table the device will be bricked. Fortunately there isn’t much happening between these two calls, and no other program is running in parallel. So we should be pretty safe.</p><h3>Partitions tool</h3><p>While developing this update mechanism we also <a href="https://github.com/toitware/toit-partition-table-esp32">implemented a small tool</a> that lets us inspect OTA partitions and look at the current state of the OTA data partition (which defines which partition the device is currently booting from and in which state the OTA partitions are). Here is its help output:</p><pre><br>A tool to manage OTA partitions on the ESP32.<br><br>Usage:<br>  partitions &lt;command&gt; [&lt;options&gt;]<br><br>Commands:<br>  help              Show help for a command.<br>  print-otadata     Print the otadata partition.<br>  print-partitions  Print the partition table.<br>  read              Reads a partition from the flash.<br>  set-ota-state     Sets the partition&#39;s state.<br>  write             Writes a partition to the flash.<br><br>Options:<br>      --esptool string                 Path to esptool.py.<br>  -h, --help                           Show help for this command.<br>      --partition-table-offset string  Offset of the partition table. (default: 0x8000)<br>      --partition-table-size string    Size of the partition table. (default: 0xc00)<br>  -p, --port string                    Serial port to use.<br><br>Examples:<br>  # Print the partition table:<br>  partitions print-partitions<br><br>  # Print the otadata partition:<br>  partitions print-otadata<br><br>  # Read the partition &#39;ota_0&#39; to &#39;ota_0.bin&#39;:<br>  partitions read -o ota_0.bin ota_0<br><br>  # Write the partition &#39;ota_0&#39; from &#39;ota_0.bin&#39;:<br>  partitions write -i ota_0.bin ota_0<br><br>  # Set the state of &#39;ota_0&#39; to &#39;pending-verify&#39;:<br>  partitions set-ota-state --state=pending-verify ota_0</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=276c86feeba8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-toit-take/changing-an-esp32-partition-table-over-the-air-276c86feeba8">Changing an ESP32 partition table over the air</a> was originally published in <a href="https://medium.com/the-toit-take">The Toit Take</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Yet another tutorial]]></title>
            <link>https://medium.com/the-toit-take/yet-another-tutorial-7eba49b045b9?source=rss----ac7619cafdf1---4</link>
            <guid isPermaLink="false">https://medium.com/p/7eba49b045b9</guid>
            <category><![CDATA[toit]]></category>
            <category><![CDATA[documentation]]></category>
            <dc:creator><![CDATA[Florian Loitsch]]></dc:creator>
            <pubDate>Thu, 23 Nov 2023 13:57:29 GMT</pubDate>
            <atom:updated>2023-11-23T14:05:00.587Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the last months we have dramatically improved the <a href="https://docs.toit.io/tutorials">tutorial section</a> of our documentation page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*21YgrcuAZzh9Mk4sRcCokQ.png" /><figcaption>Screenshot of the tutorial page.</figcaption></figure><p>With a wide variety of topics, there is probably a tutorial for everyone there. For example, you can find:</p><ul><li>Beginners guides with <a href="https://docs.toit.io/tutorials/#setup">setup tutorials</a>.</li><li>Lots of <a href="https://docs.toit.io/tutorials/#hardware">hardware tutorials</a> that show users how to communicate with common hardware, like LEDs, servos, neopixels (LED strips), or i2c devices like the BME280.</li><li>A section on common <a href="https://docs.toit.io/tutorials/#network">network tasks</a>, like doing HTTP requests, or running an HTTP server. This part also includes tutorials for other protocols like MQTT, Supabase, or Telegram.</li><li>A <a href="https://docs.toit.io/tutorials/misc/ota">tutorial</a> on how to do over-the-air updates in Toit.</li></ul><p>Today, with a new <a href="https://docs.toit.io/tutorials/misc/watchdog">tutorial on watchdog timers</a>, we bring the number of tutorials to 47; hopefully hitting the 50 soon.</p><p>Enjoy, and let us know which tutorials you are missing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7eba49b045b9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-toit-take/yet-another-tutorial-7eba49b045b9">Yet another tutorial</a> was originally published in <a href="https://medium.com/the-toit-take">The Toit Take</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Toit’s GitHub actions]]></title>
            <link>https://medium.com/the-toit-take/toits-github-actions-0c01223ba154?source=rss----ac7619cafdf1---4</link>
            <guid isPermaLink="false">https://medium.com/p/0c01223ba154</guid>
            <category><![CDATA[toit]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Florian Loitsch]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 16:36:05 GMT</pubDate>
            <atom:updated>2023-11-17T16:36:04.931Z</atom:updated>
            <content:encoded><![CDATA[<p>We, at Toit.io, use GitHub for development. All our code changes go through peer-reviews there, and run through a continuous integration pipeline to make sure we don’t accidentally break things.</p><p>Fortunately for us, GitHub doesn’t charge open-source projects for running GitHub actions, because we use that service a lot! Every pushed Toit commit runs more than 1200 tests on different platforms (Windows, Linux and macOS), and sometimes even different configurations (debug, x86 vs x64). Shoutout to GitHub for that!</p><p>Similarly, we make an effort to add tests to Toit packages we write. While the scale of these is nowhere near the ones in the <a href="https://github.com/toitlang/toit">github.com/toitlang/toit </a>repository, we do end up with a lot of smaller repositories that do similar things in their continuous integration pipeline.</p><p>Over time we have developed a few reusable GitHub actions, two of which are probably useful to developers outside of Toitware as well.</p><p>The first one toitlang/action-publish can be used to automatically notify the Toit registry server whenever a new version of the package is available.</p><p>Typically we add the following workflow file to our packages:</p><pre>name: Publish package<br><br>on:<br>  push:<br>    tags:<br>    - &#39;v[0-9]+.[0-9]+.[0-9]+&#39;<br>    - &#39;v[0-9]+.[0-9]+.[0-9]+-*&#39;<br><br>jobs:<br>  create-release:<br>    name: Create new release<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Publish<br>        uses: toitlang/action-publish@v1.4.0</pre><p>Publishing a new package version is then as simple as creating a new release or just tagging with the new version.</p><p>The second action can be used to setup Toit for subsequent steps. If I wanted to use Toit version v2.0.0-alpha.121 to run my tests I could just add the following step to my job:</p><pre>- uses: toitlang/action-setup<br>  with:<br>    toit-version: v2.0.0-alpha.121<br><br>- run: make test</pre><p>This setup step downloads the SDK version v2.0.0-alpha.121, installs it, and updates the PATH variable so that the following steps can just execute toit.run, toit.pkg, or toit.compile. If I wanted the latest version I could also just omit the with section, or explicitly mark the toit-version entry as latest.</p><p>We hope other developers can benefit from these actions as much as we do.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c01223ba154" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-toit-take/toits-github-actions-0c01223ba154">Toit’s GitHub actions</a> was originally published in <a href="https://medium.com/the-toit-take">The Toit Take</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Toit package server open-sourced]]></title>
            <link>https://medium.com/the-toit-take/toit-package-server-open-sourced-6932dd383070?source=rss----ac7619cafdf1---4</link>
            <guid isPermaLink="false">https://medium.com/p/6932dd383070</guid>
            <category><![CDATA[short]]></category>
            <category><![CDATA[toit]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[package-management]]></category>
            <dc:creator><![CDATA[Florian Loitsch]]></dc:creator>
            <pubDate>Wed, 08 Nov 2023 14:40:56 GMT</pubDate>
            <atom:updated>2023-11-08T14:40:56.701Z</atom:updated>
            <content:encoded><![CDATA[<p>Today, we open-sourced the code that runs behind <a href="https://pkg.toit.io./">https://pkg.toit.io</a>. The code for it is split into two: <a href="https://github.com/toitware/web-tpkg">the web code</a>, written in React, that is visible on the page, and <a href="https://github.com/toitware/tpkg">the server code</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*Y69ONw-GdvzbuGE2C1sKew.png" /></figure><p>The server code is responsible for accepting new package contributions (through <a href="https://pkg.toit.io/publish,">https://pkg.toit.io/publish,</a> or through the publish <a href="https://github.com/toitlang/action-publish">action</a>). It also generates Toitdocs on demand.</p><p>Toit’s package management system was designed to allow multiple package registries. Similar to Linux package managers, different users are free to run their own registries. By open-sourcing these two repositories it’s now easier to also provide a front-end to them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6932dd383070" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-toit-take/toit-package-server-open-sourced-6932dd383070">Toit package server open-sourced</a> was originally published in <a href="https://medium.com/the-toit-take">The Toit Take</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Toit language is now open source]]></title>
            <link>https://medium.com/the-toit-take/the-toit-language-is-now-open-source-14bdcb1604d9?source=rss----ac7619cafdf1---4</link>
            <guid isPermaLink="false">https://medium.com/p/14bdcb1604d9</guid>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[micropython]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kasper Lund]]></dc:creator>
            <pubDate>Mon, 22 Nov 2021 08:05:52 GMT</pubDate>
            <atom:updated>2021-11-22T08:42:45.405Z</atom:updated>
            <content:encoded><![CDATA[<p>A few years ago, a bunch of software engineers got really frustrated with the state of the Internet of Things (IoT). Armed with plenty of experience from having built the <a href="https://v8.dev/">V8 JavaScript engine</a> and the <a href="https://dart.dev/">Dart language</a> for <a href="https://flutter.dev/">Flutter</a> at Google, we <a href="https://blog.toit.io/building-for-billions-bcb48814d864">set out</a> to invent the best platform to build, deploy, and maintain software for embedded devices connected to the internet. We had to solve some hard technical problems, but at the beginning of 2021 we had a working platform, and we started enabling developers to build high-quality functionality for their microcontrollers. Today, we’ve got customers all over the world building their products on the <a href="https://toit.io/">Toit platform</a>.</p><p>Back when we started building the platform, we quickly realized that we needed an efficient, high-level programming language specifically designed to meet the needs of IoT. It didn’t exist. We looked at Python and JavaScript, but on a microcontroller the two languages were just impossible to make fast enough and we were not willing to be hindered by poor performance or lack of robustness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eq00ImO4GlovlQLsY3x0qA.png" /><figcaption>In the immortal words of Johan van der Smut: Toit like a tiger</figcaption></figure><p>We went into crunch mode and some months later, we had the first results. We were executing code more than 30x faster than MicroPython on an ESP32 with a high-level language that abstracts away memory allocation and that can be learned in a few hours by a Python developer: <a href="https://docs.toit.io/language">the Toit language</a>.</p><p>We knew from the beginning that the Toit language had to be open source at some point. All major programming languages are open source, and the vibrant ecosystem you can get from open source is required to get large-scale adoption of a language. At the same time, we wanted to make sure that the fundamentals were in place before opening up. The way we chose to do that was to initially focus on making the paying customers of the Toit platform succeed.</p><p>After several iterations and lots of experience in using Toit in real-world settings, we now <strong>know</strong> that the Toit language is an immensely useful building block for writing robust software for microcontrollers and we’d like more developers to be able to benefit from this. We have been waiting for this day for quite a while, but we are excited to share that we have open-sourced the Toit language and our implementation and made it <a href="https://github.com/toitlang/toit">available through GitHub</a>.</p><p>Let the games begin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PHzarclCAek96ho7WL3RDg.png" /><figcaption>Hello, World!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14bdcb1604d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-toit-take/the-toit-language-is-now-open-source-14bdcb1604d9">The Toit language is now open source</a> was originally published in <a href="https://medium.com/the-toit-take">The Toit Take</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A really Toit GLAMP server]]></title>
            <link>https://medium.com/the-toit-take/a-really-toit-glamp-server-d8edd4897f42?source=rss----ac7619cafdf1---4</link>
            <guid isPermaLink="false">https://medium.com/p/d8edd4897f42</guid>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[esp32-programming]]></category>
            <category><![CDATA[lamp-stack]]></category>
            <dc:creator><![CDATA[Nils Westerlund]]></dc:creator>
            <pubDate>Mon, 08 Nov 2021 14:59:16 GMT</pubDate>
            <atom:updated>2021-12-01T22:39:39.401Z</atom:updated>
            <content:encoded><![CDATA[<p>In this project, we will use Toit to push data to a classic LAMP stack. We will also add Grafana to the stack. In other words, we are building a Toit-powered GLAMP stack! Data will flow from a BME280 sensor connected to an ESP32 running Toit, and this will forward the data via HTTP to a Linux computer running the GLAMP stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3DklNxIL6C1mx3NHjh3qKg.png" /></figure><p>The original LAMP stack is a classic web server setup. The acronym stands for “Linux, Apache, MySQL, and PHP” and this setup has been used by numerous well-known internet companies throughout the years. There are many tutorials available online (try <a href="https://randomnerdtutorials.com/raspberry-pi-apache-mysql-php-lamp-server/">this one</a>, for example) covering how to set up such a system, so that part will not be covered in this post: I will assume you have an online computer running a LAMP stack. The same goes for <a href="https://grafana.com/grafana/download">Grafana</a>: Downloading and installing Grafana on your computer is very straightforward and we’ll assume this step is also finished before starting.</p><h3><strong>Parts needed</strong></h3><ul><li>An ESP32 development kit (you can buy one <a href="https://www.banggood.com/Keyes-ESP32-WROOM-32-Module-Core-Board-ESP32-ESP-32-bluetooth-and-WIFI-MCU-p-1756083.html?cur_warehouse=CN&amp;rmmds=search">here</a>).</li><li>The BME280 sensor module, e.g. from <a href="https://www.sparkfun.com/products/15440">Sparkfun</a>.</li><li>A 1602 LCD. Check <a href="https://www.sparkfun.com/products/255">this one</a> out.</li><li>A Potentiometer, around 0–5 kOhm. <a href="https://www.digikey.se/product-detail/en/bourns-inc/PV36W502C01B00/490-2888-ND/666515">This</a> will do the trick.</li></ul><h3>On the sending side</h3><p>On the data generation side (i.e. the ESP32 with peripherals) we need to set up our hardware, i.e. connect the ESP32 to the LCD and the BME280 sensors. We will also create a free account at <a href="http://toit.io/">toit.io</a> to initialize (or “provision”) the ESP32 with Toit. Finally, we’ll download the required files from GitHub so that we can install the Toit application on the ESP32.</p><h4>Hooking up the hardware</h4><p>The BME280 sensor will be connected to the EPS32 using I²C, so we only need two wires for that: SDA and SCL. The LCD requires a few more wires since we talk to it in nibbles, i.e. chunks of four bits. It also requires a potentiometer for adjusting the LCD contrast, and two signal pins for RS (Register Select) and E (Enable). We will use the following GPIOs on the ESP32:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETzXjkzapFA2gCLnvqaMjQ.png" /></figure><p>Below is a Fritzing diagram of the setup. Note that we need 5V for the LCD, and 3.3V for the BME280. Do not mix these wires up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rQAKhn5bc7Ddn6U4" /></figure><h4>Setting up Toit</h4><p>Getting Toit up and running on your ESP32 is done in a few minutes:</p><ul><li>Connect your ESP32 dev kit to your computer.</li><li>Go to <a href="http://toit.io/">toit.io</a> and set up your free Toit account. Once logged in, you will be guided through the Toit setup process.</li><li>When the installation is complete after about a minute, the ESP32 will go online and show up in your list of devices in your Toit console.</li><li>You can now interact with your ESP32 without having it connected to your computer. All communication goes via the Toit console.</li><li>Install the Toit CLI and VSCode by following these <a href="https://docs.toit.io/getstarted/installation/linux">instructions</a>.</li></ul><h4>The Toit code</h4><p>First of all, you need to install the Toit driver for the BME280 sensor, using the following command:</p><pre>$toit pkg install github.com/toitware/bme280-driver</pre><p>The Toit package registry contains a suitable driver for the LCD. Install it with</p><pre>$toit pkg install github.com/nilwes/HD44780</pre><p>The code for reading the BME280 sensor, writing to the LCD, and publishing data via HTTP can be downloaded from <a href="https://github.com/nilwes/toitglamp">GitHub</a>. The code should be pretty much self-explanatory. Just download it and save the repository to a folder of your choice. Open VSCode and open the folder where you saved the GitHub files.</p><p>In VSCode, if you have installed the Toit extension, you should have a Toit logo in the left menu. If you click this logo, your Toit devices will show up in the list next to the left-hand menu. You can run your code by pressing the “Play” symbol that appears next to the device name (in my case “Huzzah1”) if you hover your mouse over it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GYoYtxqODKuhYG7K" /><figcaption>The Toit extension in VSCode lets you see and control your Toit devices.</figcaption></figure><p>When the code is executed, it should print temperature, humidity, and barometric pressure on the LCD:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aANosKuSEEb8sGww" /></figure><blockquote>Pro Tip: You can also run your code from your command line by typing:</blockquote><blockquote>&gt;&gt;toit device -d MyDeviceName run glamp.toit</blockquote><p>In order to get repeated sensor readings, we will use the yaml-file glamp.yaml(also included in the GitHub repository you downloaded) that will trigger the program to run at certain intervals. If we look in the yaml-file we’ll see that it is set up so that the Toit application will run (1) when the ESP32 reboots, (2) when we initially install the application, and (3) subsequently it will run every five minutes.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528255%252C255%252C255%252C1%2529%26t%3Dmaterial%26wt%3Dnone%26l%3Dauto%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D18px%26lh%3D132%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dname%25253A%252520%2527ToitGlamp%2527%25250Aentrypoint%25253A%252520glamp.toit%25250Atriggers%25253A%252520on_boot%25253A%252520true%25250Aon_install%25253A%252520true%25250Aon_interval%25253A%2525205m%25250A&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528255%25252C255%25252C255%25252C1%252529%26t%3Dmaterial%26wt%3Dnone%26l%3Dauto%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D18px%26lh%3D132%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dname%2525253A%25252520%252527ToitGlamp%252527%2525250Aentrypoint%2525253A%25252520glamp.toit%2525250Atriggers%2525253A%25252520on_boot%2525253A%25252520true%2525250Aon_install%2525253A%25252520true%2525250Aon_interval%2525253A%252525205m%2525250A&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7aff5fa31cf6416a5fd7765882f544c7/href">https://medium.com/media/7aff5fa31cf6416a5fd7765882f544c7/href</a></iframe><p>To deploy your application using your yaml-file, press the symbol with multiple “Play” symbols next to your Toit device:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*ot5iQNfmj2ijAfdnCNrB1w.png" /></figure><blockquote>Pro Tip: You can also deploy your app from your terminal by typing:</blockquote><blockquote>&gt;&gt;toit device -d MyDeviceName deploy glamp.yaml</blockquote><p>You can leave this app running on your ESP32. In the next step we’ll set up your database that will catch all data it generates!</p><h3>On the receiving side</h3><p>On the server-side we need to set up the PHP script that will <em>receive</em> the data from the ESP32, the MySQL database that will <em>store</em> our data, and Grafana that will <em>display</em> our data. Let us start with the MySQL setup.</p><h4>MySQL database setup</h4><p>Log in to MySQL in a terminal. Then use the following MySQL commands to create a database called THPDatabasethat contains a table called THPData:</p><pre>MariaDB [(none)]&gt; create database THPDatabase;</pre><pre>MariaDB [(none)]&gt; use THPDatabase;</pre><pre>MariaDB [THPDatabase2]&gt; CREATE TABLE THPData (Time TIMESTAMP, Temp VARCHAR(20), Hum VARCHAR(20), Press VARCHAR(20));</pre><p>You now have an empty table with four columns: Time , Temp , Hum , and Press</p><p>Now it is time to write the PHP script that will receive the data from your Toit ESP32 via HTTP, and insert it into this database table.</p><h4>PHP script</h4><p>Grab the file insert.php that you fetched from GitHub, and move it into your HTML root folder (probably /var/www/html). <strong>NOTE: You need to enter your MySQL database credentials into the PHP script</strong>:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528255%252C255%252C255%252C1%2529%26t%3Dmaterial%26wt%3Dnone%26l%3Dauto%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D18px%26lh%3D132%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%252524servername%252520%25253D%252520%252522localhost%252522%25253B%25250A%252524username%252520%25253D%252520%252522mySqlUsername%252522%25253B%25250A%252524password%252520%25253D%252520%252522mySqlPassword%252522%25253B%25250A%252524dbname%252520%25253D%252520%252522THPDatabase%252522%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528255%25252C255%25252C255%25252C1%252529%26t%3Dmaterial%26wt%3Dnone%26l%3Dauto%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D18px%26lh%3D132%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%25252524servername%25252520%2525253D%25252520%25252522localhost%25252522%2525253B%2525250A%25252524username%25252520%2525253D%25252520%25252522mySqlUsername%25252522%2525253B%2525250A%25252524password%25252520%2525253D%25252520%25252522mySqlPassword%25252522%2525253B%2525250A%25252524dbname%25252520%2525253D%25252520%25252522THPDatabase%25252522%2525253B&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cabc1f9196c26884ee612e3b08d0936e/href">https://medium.com/media/cabc1f9196c26884ee612e3b08d0936e/href</a></iframe><p>Go back to your MySQL command prompt, make sure your database is selected, and print all rows in the table THPData:</p><pre>MariaDB [THPDatabase]&gt; SELECT * FROM THPData;</pre><p>This should present a few lines with data that has been sent from your Toit application on your ESP32 since you deployed it earlier in this tutorial:</p><pre>+ — — — — — — — — — — -+ — — — + — — — + — — — — — +</pre><pre>| Time | Temp | Hum | Press |</pre><pre>+ — — — — — — — — — — -+ — — — + — — — + — — — — — +</pre><pre>| 2021–10–28 19:11:28 | 26.4 | 36.6 | 101556.2 |</pre><pre>| 2021–10–28 19:11:58 | 26.4 | 36.6 | 101561.6 |</pre><pre>| 2021–10–28 19:12:29 | 26.4 | 36.6 | 101554.6 |</pre><pre>| 2021–10–28 19:12:59 | 26.3 | 36.6 | 101559.0 |</pre><pre>+ — — — — — — — — — — -+ — — — + — — — + — — — — — +</pre><pre>4 rows in set (0.001 sec)</pre><p>Now it is time for the last step in the process. Displaying your data in a fancy way in Grafana!</p><h4>Set up Grafana</h4><p>Open Grafana in your browser by entering the IP to your computer followed by the port 3000, like so:</p><pre><a href="http://x.x.x.x:3000/">http://x.x.x.x:3000/</a></pre><p>Log in and go to “Data Sources” under “Configuration”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mLF0MNLbcyjU-IrY" /></figure><p>Click “Add data source” and search for MySQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lS-k1c-CPpeV8whw" /></figure><p>Click “Select” and enter the name of your database and your MySQL credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lLMap2JOAzAgthpS" /></figure><p>Finally, at the bottom of the page, press “Save &amp; Test”. Grafana now tries to connect to your database and gives an OK message if everything works fine. Your Grafana setup should now be complete.</p><p>To create a new dashboard, click the plus-sign in Grafana and click “Add an empty panel”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qJL1iQJl7QNviTTg" /></figure><p>In order to pull data from your database into Grafana you can enter MySQL queries by pressing the pencil button to the right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v6T3_CTpnBzr9-hY" /></figure><p>In the SQL text field, paste the following MySQL query:</p><pre>SELECT</pre><pre>  UNIX_TIMESTAMP(Time) as “time”,</pre><pre>  CONVERT(Temp, FLOAT) as Temperature</pre><pre>from THPData</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CB-dX-NVLlAS544j" /></figure><p>When you click outside the SQL text field, the data should be immediately pulled from your database and presented in a graph. <strong>NOTE: You might have to change the time span (x-axis) of the graph to see your data:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X71S19wP0PNkILsW" /></figure><p>Click apply and voilà, you have your first graph showing temperature readings from your ESP32 running Toit. To create graphs for humidity and barometric pressure you simply have to add two new panels and paste the following MySQL queries, just like you did before:</p><p>For humidity:</p><pre>SELECT</pre><pre>  UNIX_TIMESTAMP(Time) as “time”,</pre><pre>  CONVERT(Hum, FLOAT)</pre><pre>from THPData</pre><p>For barometric pressure:</p><pre>SELECT</pre><pre>  UNIX_TIMESTAMP(Time) as “time”,</pre><pre>  CONVERT(Press/100, FLOAT)</pre><pre>from THPData</pre><p>The result could look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GfOhy3gqThGdWFggSf9aHg.png" /><figcaption>It is easy to create beautiful dashboards in Grafana!</figcaption></figure><h3>Fine-tuning your Toit device</h3><p>Currently, the device is set to be online all the time and send data every five minutes. But going online consumes lots of power! If you are powering your ESP32 from a battery, you can increase battery life dramatically by changing how often your ESP32 should go online. This is easily done from your Toit console by going to the “Configuration” tab of your Toit device, and changing the “Max offline” parameter from 0s to, say, 30 minutes, i.e. 30m . Your application will still collect sensor data every five minutes, but the ESP32 will only go online every 30 minutes to offload this data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWxxq9LTC6VOE6YjfG9siQ.png" /><figcaption>Configuration tab in the Toit console</figcaption></figure><blockquote>Pro Tip: Under the device Configuration tab you can also sett logging levels to further tweak the amount of data your device produces.</blockquote><p>Being able to configure how often — or rather how seldom — a device should be online is one of the key strengths of the Toit platform, enabling devices to run on batteries for years. Instead of having to include connectivity as one task of many in a single program, it is handled by the platform, and configured with just a click in the console. The apps you develop focus only on the task at hand: Measuring data, triggering an actuator, or maybe sending an MQTT message.</p><h3>Summary</h3><p>The LAMP stack has been around for years, and with the combination of Toit and Grafana it becomes a fantastic system for easy set-up of an IoT application.</p><p>Want to keep going? Got an idea for an IoT project? Why not check the list of drivers that are included in our <a href="https://pkg.toit.io/">package registry</a>, or reach out to our team directly at <a href="/service/mailto:contact@toit.io">contact@toit.io</a> to get help writing your own. We’re also always open for a chat at <a href="https://toit-chat.slack.com/join/shared_invite/zt-t27ohk3m-UZyxtKz7kIp2TRth5P3jeg#/shared-invite/email">chat.toit.io</a>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ceea3VlJlJyBceHLntDkgA.jpeg" /><figcaption>ESP32 running Toit with a 1602 LCD and BME280 sensor.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8edd4897f42" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-toit-take/a-really-toit-glamp-server-d8edd4897f42">A really Toit GLAMP server</a> was originally published in <a href="https://medium.com/the-toit-take">The Toit Take</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>