<?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 Kevin C. on Medium]]></title>
        <description><![CDATA[Stories by Kevin C. on Medium]]></description>
        <link>https://medium.com/@kevin.ceresa?source=rss-b3e3ca91381------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KNcUsde7FKum-6X56YmJkw.png</url>
            <title>Stories by Kevin C. on Medium</title>
            <link>https://medium.com/@kevin.ceresa?source=rss-b3e3ca91381------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:37:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kevin.ceresa/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[Exploring Yocto with Flutter — Part 3]]></title>
            <link>https://medium.com/@kevin.ceresa/exploring-yocto-with-flutter-part-3-e6edc8567faa?source=rss-b3e3ca91381------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6edc8567faa</guid>
            <dc:creator><![CDATA[Kevin C.]]></dc:creator>
            <pubDate>Sat, 15 Jun 2024 14:43:45 GMT</pubDate>
            <atom:updated>2024-06-15T14:55:25.003Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring Yocto with Flutter — Part 3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KLwtxADYMB58id7vu2wXdg.jpeg" /></figure><p>In this third and final part of this journey, I will dig deeper into the Yocto ecosystem by implementing an external custom hardware I2C kernel driver and using it in the previous Flutter example application.</p><blockquote>Note: The following code snippets/software implementations should not be taken as models; some corners were cut to simplify and/or speed up the development process, use only as general reference, and follow the original API documentation. The process is based on a Rpi Zero 2 with the Raspberry Pi kernel v6.1.</blockquote><h3>The custom device</h3><p>To be sure to use something not already implemented in the Linux kernel and easily acquirable, I went with the <a href="https://shop.m5stack.com/products/8-angle-unit-with-potentiometer">8-Angle Unit from M5 Stack</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*__z3C5SbhqPLovaA8NdvHw.jpeg" /><figcaption>M5 Stack 8-Angle Unit</figcaption></figure><p>This little “gadget” comes with 8 potentiometers, 8 RGB LEDs and one switch. It could serve as a nice absolute input for setting the volume level or the intensity of a remote light bulb (thinking of smart homes). Unfortunately, the device does not provide an interrupt line to notify the host/master of a value change, therefore we cannot leverage the advantages provided by working in kernel space, but still a nice “workout” nonetheless. This means that the input driver will have to poll the I2C device to be able to detect any change.</p><h4>In-tree kernel device: preparation</h4><p>First thing first, we need to prepare the Yocto environment to be able to add our driver and device tree overlay as patches to the original kernel.</p><p>In the Yocto directory, modify the Rpi kernel recipe with:</p><pre>devtool modify linux-raspberrypi</pre><p>This command will create/fetch the Linux Rpi kernel source in the folder <em>./workspace/sources/linux-raspberrypi</em>.</p><p>In the newly created directory, we need to add our custom kernel driver, and device tree overlay and modify the existing Makefile and Kconfig to include the new entry.</p><p>To simplify, since it is I2C based, the driver is created under <em>drivers/i2c/</em>:</p><pre>touch ./drivers/i2c/m5_8angle.c</pre><p>And the driver I2C driver starting structure:</p><pre>#include &quot;linux/delay.h&quot;<br>#include &quot;linux/dev_printk.h&quot;<br>#include &quot;linux/device.h&quot;<br>#include &quot;linux/input-event-codes.h&quot;<br>#include &lt;linux/i2c.h&gt;<br>#include &lt;linux/init.h&gt;<br>#include &lt;linux/module.h&gt;<br>#include &lt;linux/proc_fs.h&gt;<br>#include &lt;linux/mutex.h&gt;<br>#include &lt;linux/led-class-multicolor.h&gt;<br>#include &lt;linux/input.h&gt;<br><br>#define M5_8ANGLE_DRIVER &quot;m5stack_8angle&quot;<br><br>// Driver load function<br>static int rotary_probe(struct i2c_client *client,<br>   const struct i2c_device_id *device_id);<br><br>// Driver remove function<br>static void rotary_remove(struct i2c_client *client);<br><br>static struct of_device_id rotary_ids[] = { {<br>          // Strings used to identify the module <br>          // in device tree overlay<br>          .compatible =<br>           &quot;m5stack,8angle&quot;,<br>         },<br>         { /* sentinel */ } };<br>MODULE_DEVICE_TABLE(of, rotary_ids);<br><br>static struct i2c_device_id rotary[] = {<br> { &quot;angle8&quot;, 0 },<br> {},<br>};<br>MODULE_DEVICE_TABLE(i2c, rotary);<br><br>static struct i2c_driver rotary_driver = {<br>    .probe = rotary_probe,<br>    .remove = rotary_remove,<br>    .id_table = rotary,<br>    .driver =<br>        {<br>            .name = M5_8ANGLE_DRIVER,<br>            .of_match_table = rotary_ids,<br>        },<br>};<br><br>/* This will create the init and exit function automatically */<br>module_i2c_driver(rotary_driver);<br><br>/* Meta Information */<br>MODULE_LICENSE(&quot;GPL&quot;);<br>MODULE_AUTHOR(&quot;Kevin C.&quot;);<br>MODULE_DESCRIPTION(&quot;I2C driver for M5Stack 8Angle device&quot;);</pre><p>We include the new target in the I2C Makefile:</p><pre>....<br>....<br>obj-$(CONFIG_M5_8ANGLE) += m5_8angle.o<br>....</pre><p>And add the config in the Kconfig file (uses the multi-color kernel feature, which is disabled by default):</p><pre>....<br>config M5_8ANGLE <br>   tristate &quot;M5 Stack 8Angle device driver&quot;<br>   default y<br>   depends on I2C=y &amp;&amp; m &amp;&amp; LEDS_CLASS_MULTICOLOR<br>   help<br>       Say Y here if you have the m5 Stack 8angle.<br>....</pre><p>Now, for the device tree overlay (to load the kernel module at boot), we add a dts:</p><pre>touch ./arch/arm/boot/dts/overlays/m5-8angle-rpi-overlay.dts</pre><p>Where we target the <em>i2c1</em> interface which should load the m5_8angle device matching “m5stack,8angle” (IDs will be defined in the kernel driver later on). Here we also set the target I2C address, which for the M5 Stack 8angle is 0x43.</p><pre>/dts-v1/;<br>/plugin/;<br>/ {<br> compatible = &quot;brcm,bcm2835&quot;, &quot;brcm,bcm2710&quot;;<br> fragment@0 {<br>  target = &lt;&amp;i2c1&gt;;<br>  __overlay__ {<br>   #address-cells = &lt;1&gt;;<br>   #size-cells = &lt;0&gt;;<br><br>   m5_8angle: m5_8angle@43 {<br>    compatible = &quot;m5stack,8angle&quot;;<br>    reg = &lt;0x43&gt;;<br>    status = &quot;okay&quot;;<br>   };<br>  };<br> };<br>};</pre><p>This completes the kernel changes, although we still need to enable the overlay which can be done by adding to the <em>meta-raspberrypi/conf/machine/include/rpi-base.inc</em>:</p><pre>KERNEL_DEVICETREE:append = &quot; \<br>    overlays/m5-8angle-rpi.dtbo \<br>    &quot;<br>RPI_EXTRA_CONFIG = &quot;\ndtoverlay=m5-8angle-rpi\n&quot;</pre><p>This step can change depending on which boot-loader is being used. It would also be recommended to not change directly the include file, but to use the <em>local.conf</em> or another <em>bbappend</em>.</p><h4>In-tree kernel device: RGB LEDs</h4><p>Now that all the configuration is done, we can move on to write the kernel driver, starting from the LEDs. From the M5 Stack documentation, the first register bank is 0x30 for the first channel through register 0x53. Each channel has four 8-bit registers for each color + a master intensity factor.</p><p>Since the kernel already provides the multi-color class device, there is no need to assign each color a single LED device. To use this kernel “feature”, we need to add the <em>linux/led-class-multicolor.h</em> header and implement each registration with its driver data and callback.</p><pre>#define M5_8ANGLE_LED0_NAME &quot;m5_8angle_0:rgb:indicator&quot;<br>#define M5_8ANGLE_LED1_NAME &quot;m5_8angle_1:rgb:indicator&quot;<br>#define M5_8ANGLE_LED2_NAME &quot;m5_8angle_2:rgb:indicator&quot;<br>#define M5_8ANGLE_LED3_NAME &quot;m5_8angle_3:rgb:indicator&quot;<br>#define M5_8ANGLE_LED4_NAME &quot;m5_8angle_4:rgb:indicator&quot;<br>#define M5_8ANGLE_LED5_NAME &quot;m5_8angle_5:rgb:indicator&quot;<br>#define M5_8ANGLE_LED6_NAME &quot;m5_8angle_6:rgb:indicator&quot;<br>#define M5_8ANGLE_LED7_NAME &quot;m5_8angle_7:rgb:indicator&quot;<br>#define M5_8ANGLE_LED8_NAME &quot;m5_8angle_8:rgb:indicator&quot;<br><br>// Multicolor LED Driver Data<br>struct m5_8angle_led {<br> struct led_classdev_mc cdev;<br> struct m5_8angle_data *parent;<br> struct mc_subled subled_info[3];<br> u8 base_address;<br>};<br><br>// I2C Driver Data<br>struct m5_8angle_data {<br> struct i2c_client *client;<br><br> struct mutex lock;<br><br> struct m5_8angle_led cdev_led0;<br> struct m5_8angle_led cdev_led1;<br> struct m5_8angle_led cdev_led2;<br> struct m5_8angle_led cdev_led3;<br> struct m5_8angle_led cdev_led4;<br> struct m5_8angle_led cdev_led5;<br> struct m5_8angle_led cdev_led6;<br> struct m5_8angle_led cdev_led7;<br> struct m5_8angle_led cdev_led8;<br>};<br><br>// Multicolor callback for device write operation<br>static int m5_8angle_brightness_set_blocking(struct led_classdev *led_cdev,<br>          enum led_brightness brt_val);<br><br>// Helper function to initialize a single multicolor LED<br>static void init_m5_8angle_led(struct m5_8angle_led *led, const char *name,<br>          const u16 addr);<br><br>// Driver loading function<br>static int rotary_probe(struct i2c_client *client,<br>   const struct i2c_device_id *device_id)<br>{<br> struct m5_8angle_data *drvdata;<br> struct input_dev *idev_0;<br><br> printk(&quot;[M5Stack][Rotary] i2c - Probing address 0x43\n&quot;);<br><br> if (client-&gt;addr != 0x43) {<br>  printk(&quot;[M5Stack][Rotary] i2c - Wrong I2C address!\n&quot;);<br>  return -1;<br> }<br><br> drvdata = devm_kzalloc(&amp;client-&gt;dev, sizeof(struct m5_8angle_data),<br>          GFP_KERNEL);<br> if (drvdata == NULL) {<br>  printk(&quot;[M5Stack][Rotary] Failed to allocate driver data&quot;);<br>  return -ENOMEM;<br> }<br><br> mutex_init(&amp;drvdata-&gt;lock);<br><br> i2c_set_clientdata(client, drvdata);<br><br> drvdata-&gt;client = client;<br> drvdata-&gt;cdev_led0.parent = drvdata;<br> /*...<br>   ...  LED CH1 to CH7<br>   ... */<br> drvdata-&gt;cdev_led8.parent = drvdata;<br><br> init_m5_8angle_led(&amp;drvdata-&gt;cdev_led0, M5_8ANGLE_LED0_NAME,<br>      M5_8ANGLE_LED0_REG);<br>/*...<br>  ...  LED CH1 to CH7<br>  ... */<br> init_m5_8angle_led(&amp;drvdata-&gt;cdev_led8, M5_8ANGLE_LED8_NAME,<br>      M5_8ANGLE_LED8_REG);<br><br> if (devm_led_classdev_multicolor_register(&amp;client-&gt;dev,<br>        &amp;drvdata-&gt;cdev_led0.cdev))<br>  return -EINVAL;<br> printk(&quot;[M5Stack][Rotary] Registered LED 0 successfully&quot;);<br>/*...<br>  ...  LED CH1 to CH7<br>  ... */<br> if (devm_led_classdev_multicolor_register(&amp;client-&gt;dev,<br>        &amp;drvdata-&gt;cdev_led8.cdev))<br>  return -EINVAL;<br> printk(&quot;[M5Stack][Rotary] Registered LED 8 successfully&quot;);<br><br> return 0;<br>}<br><br>// Registered multicolor have to be de-registered on driver unload<br>static void rotary_remove(struct i2c_client *client)<br>{<br> struct m5_8angle_data *drvdata = i2c_get_clientdata(client);<br><br> printk(&quot;[M5Stack][Rotary] i2c - Removing driver\n&quot;);<br><br> devm_led_classdev_multicolor_unregister(&amp;client-&gt;dev,<br>      &amp;drvdata-&gt;cdev_led0.cdev);<br>/*...<br>  ...  LED CH1 to CH7<br>  ... */<br> devm_led_classdev_multicolor_unregister(&amp;client-&gt;dev,<br>      &amp;drvdata-&gt;cdev_led8.cdev);<br>}</pre><p>For each LED we create a multi-color class device, which in turn helps to handle the different colors:</p><pre>static void init_m5_8angle_led(struct m5_8angle_led *led, const char *name,<br>          const u16 addr)<br>{<br> const struct mc_subled def_subled_red = {<br>  .color_index = LED_COLOR_ID_RED,<br>  .brightness = 0,<br>  .intensity = 0,<br>  .channel = 0,<br> };<br> const struct mc_subled def_subled_green = {<br>  .color_index = LED_COLOR_ID_GREEN,<br>  .brightness = 0,<br>  .intensity = 0,<br>  .channel = 1,<br> };<br> const struct mc_subled def_subled_blue = {<br>  .color_index = LED_COLOR_ID_BLUE,<br>  .brightness = 0,<br>  .intensity = 0,<br>  .channel = 2,<br> };<br><br> led-&gt;cdev.led_cdev.name = name;<br> led-&gt;cdev.led_cdev.max_brightness = 255;<br> led-&gt;cdev.led_cdev.brightness_set_blocking =<br>  m5_8angle_brightness_set_blocking;<br> led-&gt;cdev.num_colors = 3;<br> led-&gt;subled_info[0] = def_subled_red;<br> led-&gt;subled_info[1] = def_subled_green;<br> led-&gt;subled_info[2] = def_subled_blue;<br> led-&gt;cdev.subled_info = led-&gt;subled_info;<br> led-&gt;base_address = addr;<br>}</pre><p>When we try to write to the multi-color device, the callback function is called, which sends the new values through the I2C client:</p><pre>static int m5_8angle_brightness_set_blocking(struct led_classdev *led_cdev,<br>          enum led_brightness brt_val)<br>{<br> int err;<br> // Fetches the device node pointer<br> struct led_classdev_mc *mccdev = lcdev_to_mccdev(led_cdev);<br> // Resolve the containing structure <br> struct m5_8angle_led *cled =<br>  container_of(mccdev, struct m5_8angle_led, cdev);<br> // Retrieve the I2C driver data<br> struct m5_8angle_data *drvdata = cled-&gt;parent;<br><br> int i;<br> mutex_lock(&amp;drvdata-&gt;lock);<br> for (i = 0; i &lt; mccdev-&gt;num_colors; i++) {<br>  err = i2c_smbus_write_byte_data(<br>   drvdata-&gt;client, cled-&gt;base_address + i,<br>   mccdev-&gt;subled_info[i].intensity);<br>  if (err)<br>   dev_err(&amp;drvdata-&gt;client-&gt;dev,<br>    &quot;Unable to set intensity to color idx %d: %d\n&quot;,<br>    i, err);<br> }<br> err = i2c_smbus_write_byte_data(drvdata-&gt;client, cled-&gt;base_address + 3,<br>     brt_val);<br><br> if (err)<br>  dev_err(&amp;drvdata-&gt;client-&gt;dev, &quot;Unable to set brightness: %d\n&quot;,<br>   err);<br><br> mutex_unlock(&amp;drvdata-&gt;lock);<br><br> return err;<br>}</pre><p>Each LED data structure helps in retrieving the necessary information about the LED that is being modified.</p><h4>In-tree kernel device: analog input</h4><p>To make use of the available potentiometers, we can implement a single input device that provides different absolute “axis”.</p><pre>// Starting address for 12-bit ADC VRx registers<br>#define M5_8ANGLE_VR0_REG_L 0x00<br><br>// Analog input driver data<br>struct m5_8angle_analog {<br>  struct input_dev *cdev;<br>  struct m5_8angle_data *parent;<br>  u8 base_address;<br>};<br><br>// Input polling callback<br>void poll_analog_input(struct input_dev *dev);<br><br>// Driver load callback<br>static int rotary_probe(struct i2c_client *client,<br>                        const struct i2c_device_id *device_id) {<br>  struct input_dev *idev_0;<br>  // Allocate an input struct<br>  idev_0 = devm_input_allocate_device(&amp;client-&gt;dev);<br>  if (idev_0 == NULL) {<br>    printk(&quot;[M5Stack][Rotary] Failed to allocate input device&quot;);<br>    return -ENOMEM;<br>  }<br>  // Assign the input driver data<br>  input_set_drvdata(idev_0, drvdata);<br>  drvdata-&gt;vr0.cdev = idev_0;<br>  // Populate the register base address<br>  drvdata-&gt;vr0.base_address = M5_8ANGLE_VR0_REG_L;<br>  idev_0-&gt;name = M5_8ANGLE_DRIVER;<br>  idev_0-&gt;phys = M5_8ANGLE_DRIVER &quot;/input0&quot;;<br>  idev_0-&gt;id.bustype = BUS_I2C;<br>  // Setup the input device to handle 8 ABS events<br>  input_set_abs_params(idev_0, ABS_X, 0, 4095, 4, 0);<br>  input_set_abs_params(idev_0, ABS_Y, 0, 4095, 4, 0);<br>  input_set_abs_params(idev_0, ABS_Z, 0, 4095, 4, 0);<br>  input_set_abs_params(idev_0, ABS_RX, 0, 4095, 4, 0);<br>  input_set_abs_params(idev_0, ABS_RY, 0, 4095, 4, 0);<br>  input_set_abs_params(idev_0, ABS_RZ, 0, 4095, 4, 0);<br>  input_set_abs_params(idev_0, ABS_GAS, 0, 4095, 4, 0);<br>  input_set_abs_params(idev_0, ABS_BRAKE, 0, 4095, 4, 0);<br>  <br>  drvdata-&gt;vr0.parent = drvdata;<br><br>  // We do not have interrupt, so we must poll the data<br>  if (input_setup_polling(drvdata-&gt;vr0.cdev, poll_analog_input)) {<br>    dev_err(&amp;client-&gt;dev, &quot;[M5Stack][Rotary] Failed to setup polling for VR0&quot;);<br>    return -EINVAL;<br>  }<br>  <br>  // To avoid completely blocking the I2C bus, a min of 50ms is set<br>  input_set_poll_interval(idev_0, 100);<br>  input_set_min_poll_interval(idev_0, 50);<br>  input_set_max_poll_interval(idev_0, 200);<br><br>  if (input_register_device(idev_0)) {<br>    dev_err(&amp;client-&gt;dev, &quot;[M5Stack][Rotary] Failed to register VR0&quot;);<br>    return -EINVAL;<br>  }<br>  printk(&quot;[M5Stack][Rotary] Registered VR0 successfully&quot;);<br>}</pre><p>With the input device set up, it is only needed to build the query callback that will be executed every ~100ms.</p><pre>void poll_analog_input(struct input_dev *dev)<br>{<br> struct m5_8angle_data *pDrv =<br>  input_get_drvdata(dev); // Retrieve the driver data<br> u16 value[8];<br><br> mutex_lock(&amp;pDrv-&gt;lock);<br><br> for (size_t i = 0; i &lt; 8; ++i) {<br>  s32 ret;<br>  u8 data[2];<br>  ret = i2c_smbus_write_byte(pDrv-&gt;client, i * 2);<br>  if (ret &lt; 0) {<br>   dev_err(&amp;pDrv-&gt;client-&gt;dev,<br>    &quot;[M5Stack][Rotary] I2C write error&quot;);<br>   mutex_unlock(&amp;pDrv-&gt;lock);<br>   return;<br>  }<br><br>  // Write and read was split due to required ADC timing<br>  ret = i2c_master_recv(pDrv-&gt;client, data, 2);<br>  if (ret != 2) {<br>   dev_err(&amp;pDrv-&gt;client-&gt;dev,<br>    &quot;[M5Stack][Rotary] I2C read error&quot;);<br>   mutex_unlock(&amp;pDrv-&gt;lock);<br>   return;<br>  }<br>  value[i] = (data[1] &lt;&lt; 8) | data[0];<br>  msleep(1);<br> }<br>  <br> // Notify the new values<br> input_event(dev, EV_ABS, ABS_X, value[0]);<br> input_event(dev, EV_ABS, ABS_Y, value[1]);<br> input_event(dev, EV_ABS, ABS_Z, value[2]);<br> input_event(dev, EV_ABS, ABS_RX, value[3]);<br> input_event(dev, EV_ABS, ABS_RY, value[4]);<br> input_event(dev, EV_ABS, ABS_RZ, value[5]);<br> input_event(dev, EV_ABS, ABS_GAS, value[6]);<br> input_event(dev, EV_ABS, ABS_BRAKE, value[7]);<br> // Sends an event type 0, used as a sync in userspace<br> input_sync(dev);<br><br> mutex_unlock(&amp;pDrv-&gt;lock);<br>}</pre><p>This concludes the device Kernel module and thus the changes can be saved either to the raspberry pi layer or to a new layer:</p><pre>devtool update-recipe linux-raspberrypi</pre><h4>In-tree kernel device: check</h4><p>To see if everything is working as planned, once the image is built and flashed, under the folder <em>/sys/class/leds/</em> there should be all the LEDs:</p><pre>m5_8angle_0:rgb:indicator<br>m5_8angle_1:rgb:indicator<br>m5_8angle_2:rgb:indicator<br>m5_8angle_3:rgb:indicator<br>m5_8angle_4:rgb:indicator<br>m5_8angle_5:rgb:indicator<br>m5_8angle_6:rgb:indicator<br>m5_8angle_7:rgb:indicator<br>m5_8angle_8:rgb:indicator</pre><p>Likewise, under /dev/input/:</p><pre>event0<br>by-path/platform-3f804000.i2c-event</pre><p>To test out one of the LEDs, we can echo the values directly:</p><pre>echo 100 0 0 &gt; /sys/class/leds/m5_8angle_0:rgb:indicator/multi-intensity</pre><p>Which should make the first LED bright red.</p><h3>The connector</h3><p>To simplify the acquisition of events from the absolute inputs; it is easier to write a small C script that listens to the <em>event0</em> and propagates the useful data through a socket. Another way, without using third-party libraries, would be to create a native plugin in Flutter/Dart, but it would take a bit more effort to do so.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;fcntl.h&gt;<br>#include &lt;unistd.h&gt;<br>#include &lt;linux/input.h&gt;<br>#include &lt;sys/socket.h&gt;<br>#include &lt;sys/un.h&gt;<br>#include &lt;string.h&gt;<br><br>#define SOCKET_PATH &quot;/tmp/absx_socket&quot;<br><br>// Function to read ABS_X from /dev/input/event0 and send through socket<br>void read_and_send_abs_x(int socket_fd) {<br>    int fd = open(&quot;/dev/input/event0&quot;, O_RDONLY);<br>    if (fd &lt; 0) {<br>        perror(&quot;Failed to open /dev/input/event0&quot;);<br>        return;<br>    }<br><br>    struct input_event ev;<br>    int abs_x;<br><br>    while (1) {<br>        if (read(fd, &amp;ev, sizeof(struct input_event)) == -1) {<br>            perror(&quot;Failed to read input event&quot;);<br>            close(fd);<br>            return;<br>        }<br><br>        if (ev.type == EV_ABS &amp;&amp; ev.code == ABS_X) {<br>            abs_x = 4095 - ev.value;<br>            write(socket_fd, &amp;abs_x, sizeof(abs_x));<br>        }<br>    }<br><br>    close(fd);<br>}<br><br>int main() {<br>    int socket_fd;<br>    struct sockaddr_un addr;<br><br>    // Create socket<br>    socket_fd = socket(AF_UNIX, SOCK_STREAM, 0);<br>    if (socket_fd &lt; 0) {<br>        perror(&quot;Failed to create socket&quot;);<br>        exit(EXIT_FAILURE);<br>    }<br><br>    memset(&amp;addr, 0, sizeof(struct sockaddr_un));<br>    addr.sun_family = AF_UNIX;<br>    strncpy(addr.sun_path, SOCKET_PATH, sizeof(addr.sun_path) - 1);<br><br>    // Bind socket<br>    unlink(SOCKET_PATH);<br>    if (bind(socket_fd, (struct sockaddr *)&amp;addr, sizeof(struct sockaddr_un)) == -1) {<br>        perror(&quot;Failed to bind socket&quot;);<br>        close(socket_fd);<br>        exit(EXIT_FAILURE);<br>    }<br><br>    // Listen for connections<br>    if (listen(socket_fd, 5) == -1) {<br>        perror(&quot;Failed to listen on socket&quot;);<br>        close(socket_fd);<br>        exit(EXIT_FAILURE);<br>    }<br><br>    printf(&quot;Waiting for a connection...\n&quot;);<br>    int client_fd = accept(socket_fd, NULL, NULL);<br>    if (client_fd == -1) {<br>        perror(&quot;Failed to accept connection&quot;);<br>        close(socket_fd);<br>        exit(EXIT_FAILURE);<br>    }<br><br>    printf(&quot;Client connected, starting to send ABS_X values...\n&quot;);<br>    read_and_send_abs_x(client_fd);<br><br>    close(client_fd);<br>    close(socket_fd);<br>    unlink(SOCKET_PATH);<br><br>    return 0;<br>}</pre><p>This connector is limited only to the <em>ABS_X</em> event code, but it can be easily extended to include all other events. The main advantage we have using C is that we can rely on the event struct defined in the <em>input.h</em> Linux header.</p><p>With the dependencies installed in the target machine:</p><pre>IMAGE_INSTALL:append = &quot; flutter-pi xdg-utils flutter-customapp connman kernel-devsrc kernel-modules kernel-dev dtc&quot;</pre><p>We can directly compile the C code above and run it:</p><pre>gcc connector.c -o connector<br>./connector &amp;; # &quot;&amp;;&quot; to run in background</pre><h3>The user application</h3><p>Everything is ready to be implemented in the user application. Taking the example from the previous article, I modified the code to listen to the socket from the connector and changed on newly received data the gauge. The value is also used to drive the corresponding LED.</p><pre>import &#39;dart:async&#39;;<br>import &#39;dart:io&#39;;<br>import &#39;dart:isolate&#39;;<br><br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:geekyants_flutter_gauges/geekyants_flutter_gauges.dart&#39;;<br><br>class MyHomePageState extends State&lt;MyHomePage&gt; {<br>  double value = 0;<br>  final AbsXListener _reader = AbsXListener();<br>  late Timer _timer;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Center(<br>        child: SizedBox(<br>          width: MediaQuery.of(context).size.height * 0.8,<br>          height: MediaQuery.of(context).size.height * 0.8,<br>          child: Stack(<br>            children: [<br>              RadialGauge(<br>                yCenterCoordinate: 0.6,<br>                track: RadialTrack(<br>                    start: 0,<br>                    end: 100,<br>                    thickness: 30,<br>                    trackStyle: TrackStyle(<br>                        labelStyle: Theme.of(context).textTheme.labelSmall)),<br>                shapePointer: const [],<br>                valueBar: [<br>                  RadialValueBar(<br>                    value: value * 100,<br>                    valueBarThickness: 30,<br>                  )<br>                ],<br>              ),<br>              const Align(<br>                alignment: Alignment.topCenter,<br>                child: Text(<br>                  &quot;CH1&quot;,<br>                  style: TextStyle(<br>                    fontSize: 26,<br>                    fontWeight: FontWeight.w500,<br>                  ),<br>                ),<br>              ),<br>              Align(<br>                alignment: const Alignment(0, 0.1),<br>                child: Text(<br>                  (value * 100).toStringAsFixed(1),<br>                  style: const TextStyle(<br>                    fontSize: 26,<br>                    fontWeight: FontWeight.w500,<br>                  ),<br>                ),<br>              )<br>            ],<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br><br>  @override<br>  void dispose() {<br>    _timer.cancel();<br>    _reader.stopListening();<br>    super.dispose();<br>  }<br><br>  @override<br>  void initState() {<br>    super.initState();<br><br>    _reader.absXStream.listen((val) {<br>      setState(() {<br>        value = val / 4095.0;<br>        _writeToLedDevice(value);<br>      });<br>    });<br>    _reader.startListening();<br>  }<br><br>  void _writeToLedDevice(double value) {<br>    const ledDeviceFile =<br>        &#39;/sys/class/leds/m5_8angle_0:rgb:indicator/multi_intensity&#39;;<br>    final intensityValue = (value * 255).round();<br>    final ledValue = &quot;0 $intensityValue 0&quot;;<br>    try {<br>      File(ledDeviceFile).writeAsStringSync(ledValue);<br>    } catch (e) {<br>      print(&#39;Error writing to LED device: $e&#39;);<br>    }<br>  }<br>}<br><br>const String socketPath = &#39;/tmp/absx_socket&#39;;<br><br>class AbsXListener {<br>  final ReceivePort _receivePort = ReceivePort();<br>  Isolate? _isolate;<br>  StreamSubscription? _subscription;<br><br>  Stream&lt;int&gt; get absXStream =&gt;<br>      _receivePort.asBroadcastStream().map((event) =&gt; event as int);<br><br>  Future&lt;void&gt; startListening() async {<br>    _isolate = await Isolate.spawn(_listenForAbsX, _receivePort.sendPort);<br>  }<br><br>  Future&lt;void&gt; stopListening() async {<br>    _isolate?.kill(priority: Isolate.immediate);<br>    _isolate = null;<br>    _subscription?.cancel();<br>    _subscription = null;<br>  }<br><br>  static Future&lt;void&gt; _listenForAbsX(SendPort sendPort) async {<br>    final socket = await Socket.connect(<br>        InternetAddress(socketPath, type: InternetAddressType.unix), 0);<br>    final receivePort = ReceivePort();<br>    sendPort.send(receivePort.sendPort);<br><br>    socket.listen((data) {<br>      final int absX = data.buffer.asInt32List().first;<br>      sendPort.send(absX);<br>    }, onDone: () {<br>      socket.destroy();<br>    }, onError: (error) {<br>      socket.destroy();<br>    });<br><br>    await for (var message in receivePort) {<br>      if (message == &#39;stop&#39;) {<br>        socket.close();<br>        break;<br>      }<br>    }<br>  }<br>}</pre><p>With a running isolate, a <em>ReceivePort</em> is used to send the received data from the stream to the main thread, which in turn runs the <em>setState</em> callback that updates the gauge value.</p><p>That’s it! By running the connector first and then the <em>customapp</em>, we have the example working!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*v0kxfC97UZtt79ZKpTQDlA.gif" /></figure><h3><strong>Conclusion</strong></h3><p>It was surely fun to experiment with merging low and high-level programming. However, at the end of the journey, I was a bit discouraged by the Dart FFI (<strong>F</strong>oreing <strong>F</strong>unction <strong>I</strong>nterface) which, compared to other programming languages, was a bit more intricate and in the end not worth delving into.</p><p>I would still consider using Flutter as an embedded framework for graphical user applications, even though it may be inconvenient at times when leveraging low-level hardware. A quick solution it is always possible by splitting up the main application into decoupled services.</p><p>Nowadays we are getting used to working at a high abstraction level, which allows us to ship products faster, but at a great cost; being performances, licensing, or flexibility. However, it is nice that we can still retain a great degree of freedom by mixing two worlds that are usually far distant from each other without compromising excessively the time-to-market required.</p><h3>References</h3><ul><li><a href="https://github.com/ch-vik/m5stack-8angle-driver">https://github.com/ch-vik/m5stack-8angle-driver</a> — Kernel driver src</li><li><a href="https://medium.com/@kevin.ceresa/exploring-yocto-with-flutter-part-1-f6c5e1caabf4">Exploring Yocto with Flutter — Part 1</a></li><li><a href="https://medium.com/@kevin.ceresa/exploring-yocto-with-flutter-part-2-eb91b7b1aad8">Exploring Yocto with Flutter — Part 2</a></li><li><a href="https://docs.kernel.org/input/input-programming.html">Linux input Kernel documentation</a></li><li><a href="https://docs.kernel.org/leds/leds-class-multicolor.html">Linux LEDs Kernel documentation</a> — multi-color</li><li><a href="https://docs.m5stack.com/en/unit/UNIT%208Angle">M5 Stack 8-Angle</a> — documentation</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6edc8567faa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Yocto with Flutter — Part 2]]></title>
            <link>https://medium.com/@kevin.ceresa/exploring-yocto-with-flutter-part-2-eb91b7b1aad8?source=rss-b3e3ca91381------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb91b7b1aad8</guid>
            <category><![CDATA[yoctoproject]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Kevin C.]]></dc:creator>
            <pubDate>Wed, 24 Jan 2024 07:12:30 GMT</pubDate>
            <atom:updated>2024-01-24T07:12:30.959Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring Yocto with Flutter — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KEcGr6dIH_g4K7CkiBUB3g.jpeg" /></figure><p>This part covers the steps to create and deploy a custom application in the Yocto ecosystem. While Yocto offers a plethora of options, navigating the process of adding packages can be tricky. However, this complexity is “intentional”, designed to provide flexibility without compromising reliability. In this part of the journey, I will only scrape the surface of building and deploying a custom Flutter app in Yocto.</p><h3>Flutter Project</h3><p>Create a new flutter project with the following:</p><pre>flutter create customapp</pre><p>You can run the generated app with:</p><pre>flutter run</pre><p>Now, this part aims to demonstrate how to integrate normal Flutter development into the Yocto project, enabling the app to be available on the target device. Therefore, only a small example is created here, serving as an interface for the future hardware that will be added.</p><p>The app is nothing more than a dial/gauge indicating a selected value from 0 to 100. This represents the % of a potentiometer or the user-overridden selected value. For this purpose, I will use the <a href="https://pub.dev/packages/geekyants_flutter_gauges">geekyants_flutter_gauges</a> for the gauge widget, which can be added with:</p><pre>flutter pub add geekyants_flutter_gauges</pre><p>And the main.dart entry point is changed to show a simple selectable gauge with the exact current value in its center.</p><pre>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  // This widget is the root of your application.<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Journey with the Yocto Project and Flutter&#39;,<br>      theme: ThemeData(<br>        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>        fontFamily: &quot;Roboto&quot;,<br>        useMaterial3: true,<br>      ),<br>      home: const MyHomePage(),<br>    );<br>  }<br>}<br><br>class MyHomePage extends StatefulWidget {<br>  const MyHomePage({super.key});<br><br>  @override<br>  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();<br>}<br><br>class _MyHomePageState extends State&lt;MyHomePage&gt; {<br>  double value = 0;<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Center(<br>          child: SizedBox(<br>        width: MediaQuery.of(context).size.height * 0.8,<br>        height: MediaQuery.of(context).size.height * 0.8,<br>        child: Stack(<br>          children: [<br>            RadialGauge(<br>              yCenterCoordinate: 0.6,<br>              track: RadialTrack(<br>                  start: 0,<br>                  end: 100,<br>                  thickness: 30,<br>                  trackStyle: TrackStyle(<br>                      labelStyle: Theme.of(context).textTheme.labelSmall)),<br>              shapePointer: [<br>                RadialShapePointer(<br>                  value: value,<br>                  isInteractive: true,<br>                  color: Colors.blue.shade800,<br>                  width: 22,<br>                  onChanged: (val) =&gt; setState(() {<br>                    value = val;<br>                  }),<br>                )<br>              ],<br>              valueBar: [<br>                RadialValueBar(<br>                  value: value,<br>                  valueBarThickness: 30,<br>                )<br>              ],<br>            ),<br>            const Align(<br>              alignment: Alignment.topCenter,<br>              child: Text(<br>                &quot;PWM&quot;,<br>                style: TextStyle(<br>                  fontSize: 26,<br>                  fontWeight: FontWeight.w500,<br>                ),<br>              ),<br>            ),<br>            Align(<br>              alignment: const Alignment(0, 0.1),<br>              child: Text(<br>                value.toStringAsFixed(1),<br>                style: const TextStyle(<br>                  fontSize: 26,<br>                  fontWeight: FontWeight.w500,<br>                ),<br>              ),<br>            )<br>          ],<br>        ),<br>      )),<br>    );<br>  }<br>}</pre><p>Since there are not many fonts available in the built image, I went with a custom font <em>“Roboto”</em> and embedded it into the app.</p><p>Finally the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Ch8BWbH8sTWXFLXVbqp1EQ.gif" /><figcaption>Custom Flutter application</figcaption></figure><p>With the custom app ready to be built for the embedded hardware, we can proceed with its integration within the Yocto build system. The process does not tamper with the original Flutter project, allowing us to easily revert and modify the application as needed. This flexibility ensures that the build process remains ready to deliver a new app version at any time.</p><p>Before proceeding further, it’s essential to track the project with Git (which will be required by the Yocto build system) and create a license file.</p><p>LICENSE file:</p><pre>Creative Commons Attribution-ShareAlike 4.0 International License (CC-BY-SA-4.0)<br><br>The full text of the license is available at:<br>https://creativecommons.org/licenses/by-sa/4.0/legalcode</pre><p>Git initialization:</p><pre>git init<br>git add *<br>git add .gitignore<br>git add .metadata<br>git commit -m &quot;first commit&quot;</pre><p>Later on we will also need the commit SHA, which can be retrieved with:</p><pre>git log<br><br>---------<br><br>commit 3a2a923eda0b247f8d1523ef8156c040813d4139 (HEAD -&gt; master)<br>Author: Kevin C.<br>Date:   Mon Jan 22 20:58:19 2024 +0100<br><br>    first commit</pre><h3>Yocto Project</h3><p>We can get started by creating a new recipe with the devtool utility.</p><pre>devtool add customapp /path/to/custom/app</pre><p>This will create a new workspace directory under the build folder, where the new recipe is temporarily stored and built. Working with devtool eases the process of creating a new recipe by allowing easy delivery of the package to a running image (though I will not be covering it here).</p><p>Inside build/workspace/recipes we can find the newly created recipe and we can proceed to overwrite it with something similar to what is found on a app recipe in the meta-flutter layer:</p><pre>S = &quot;${WORKDIR}/git&quot;<br>LICENSE = &quot;CC-BY-SA-4.0&quot;<br>LIC_FILES_CHKSUM = &quot;file://${S}/LICENSE;md5=ee1fad90478815ab9ccbf7cf41488c3b&quot;<br>PV = &quot;1.0&quot;<br><br><br><br># No information for SRC_URI yet (only an external source tree was specified)<br>SRC_URI =&quot;&quot; <br><br># This SRC_URI should be used once finished with the workspace<br>#SRC_URI = &quot;git:///absolute/path/to/customapp/;rev=3abe0ca2f14602898ccf82707632e7c891da30bf&quot;<br><br>SUMMARY = &quot;Custom User Application&quot;<br>DESCRIPTION = &quot;User build application&quot;<br>AUTHOR = &quot;Kevin C.&quot;<br>SECTION = &quot;graphics&quot;<br><br>PUBSPEC_APPNAME = &quot;customapp&quot;<br>FLUTTER_APPLICATION_INSTALL_PREFIX = &quot;/flutter&quot;<br><br>inherit flutter-app</pre><p>It is then possible to build the image with the workspace layer included with:</p><pre>devtool build-image core-image-base</pre><p>Once finished, we can flash the image to the SD card:</p><pre>$ bmaptool copy --bmap core-image-base-raspberrypi0-2w-64.wic.bmap core-image-base-rasp<br>berrypi0-2w-64.wic.bz2 /dev/sdc</pre><p>And run the app with:</p><pre>flutter-pi --release /usr/share/flutter/customapp/{version}/release/</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TX9ZHMRZexQK3hAEnQrt2A.jpeg" /><figcaption>App running on Raspberry Pi</figcaption></figure><p>Now that we are done with working on the package recipe, we can finish it up by adding it to the meta-flutter layer:</p><pre>devtool finish flutter-customapp meta-flutter/recipes-graphics/flutter-apps --initial-rev 3a2a923eda0b547f8d1553ef8126c040813d4139</pre><p>If everything worked out, the recipe should pop-up in the meta-layer/recipes-graphics/flutter-apps/ folder. Proceed by editing the .bb file by setting the correct SRC_URI with the correct git revision.</p><p>That’s it! We can now add the app to the IMAGE_INSTALL:append and run the normal build process:</p><pre>bitbake core-image-base</pre><h3><strong>Wrapping up</strong></h3><p>It is amazing how easy it was to work with the Yocto/bitbake ecosystem. The greatest advantage is the provided rootfs, which allows building for the target architecture — something that would have to be manually provided otherwise.</p><p>There is still a lot that has to be done to properly set up a versioned and production-ready application, but for now, it does the job and does it impressively.</p><p>In the next part, I will be exploring the integration of custom hardware, which will make the custom app a bit more useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb91b7b1aad8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Yocto with Flutter — Part 1]]></title>
            <link>https://medium.com/@kevin.ceresa/exploring-yocto-with-flutter-part-1-f6c5e1caabf4?source=rss-b3e3ca91381------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6c5e1caabf4</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[yoctoproject]]></category>
            <dc:creator><![CDATA[Kevin C.]]></dc:creator>
            <pubDate>Sun, 24 Dec 2023 12:23:41 GMT</pubDate>
            <atom:updated>2024-04-27T14:49:11.159Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring Yocto with Flutter — Part 1</h3><p>Join me on a journey through a series of articles as I delve into the integration of the Yocto Project and the Flutter framework. Together, we’ll navigate the process of porting high-level programming to embedded systems, uncovering the potential and possibilities this fusion brings to the world of embedded development.</p><h3>Intro</h3><p>The series will be composed of:</p><ul><li>Part 1 — Running an example application</li><li>Part 2 — Building and running a custom application</li><li>Part 3 — Custom hardware integration</li></ul><p>Currently, UI development in embedded systems heavily relies on the Qt framework, recognized as a reliable tool for creating robust systems with a good level of quality. This becomes especially crucial when dealing with hardware, which lacks the constant update accessibility found in devices like phones or PCs typically connected to the internet. However, as time progresses, it’s becoming more common for embedded systems to establish connections with the outside world, be it through a cellular network, WiFi, or even less conventional means like LoRaWAN. Allowing Over-The-Air (OTA) updates, developers can worry less about stringent quality standards and focus more on delivering a variety of features, a shift driven by the growing importance of staying competitive in the market. This is where a framework like Flutter could potentially become a new industry standard in the future, where its simplicity and structure could reduce significantly the time to market.</p><h4>Flutter</h4><p>Flutter is an open-source UI software development toolkit created by Google. It is used for building natively compiled applications for mobile, web, and desktop from a single codebase. It is becoming more and more popular and companies are starting to use it. It is still mainly used for mobile app development but web and desktop applications are supported.<br>What makes it awesome is not only the portability but also the capability of designing complex interfaces extremely fast. It comes with the downsides of high-level programming but it still delivers fast performances. Some of its main strengths are:</p><ul><li>huge widget library;</li><li>fast complex UI design;</li><li>portability.</li></ul><p>Flutter has the potential to elevate the development of UI in embedded systems to new heights, approaching a state-of-the-art standard comparable to that of a mobile app.<br>There is one major downside to Flutter for the embedded world, it cannot easily cross-compile; it can be done but some manual tinkering is required.</p><h4>The Yocto Project</h4><p>Yocto provides templates, tools, and methods to help developers create custom Linux-based systems for embedded products. Some of its main strengths are:</p><ul><li>extreme flexibility and customizability;</li><li>cross-compilation;</li><li>reproducibility.</li></ul><p>Tailoring an operating system for a target application/hardware can be crucial when developing embedded systems. Although I weigh the importance of portability; starting solely from a BSP can easily tie the software developed to a specific chip, board, or manufacturer. As seen in the recent lack of components “crisis”, companies are starting to give more importance to portability than ever before. <br>With Yocto, this is also possible thanks to its guaranteed reproducibility, where a system image can be recreated consistently.</p><h4>Hardware setup</h4><p>The whole system can be easily emulated with quemu, although since I already have one lying around, I will be using a Raspberry Pi Zero 2 with a small touch TFT display. To load the system, a microSD card is required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WO1Ouw0kP9yiHpVBuxxcFA.jpeg" /></figure><h3>Yocto dependencies</h3><p>First off we want to install the required host packages:</p><h4>Ubuntu</h4><pre>$ apt install gawk wget git diffstat unzip texinfo gcc build-essential \<br>chrpath socat cpio python3 python3-pip python3-pexpect xz-utils debianutils \<br>iputils-ping python3-git python3-jinja2 libegl1-mesa libsdl1.2-dev \<br>python3-subunit mesa-common-dev zstd liblz4-tool file locales libacl1</pre><h4>ArchLinux</h4><pre>$ pacman -S gawk wget git diffstat unzip texinfo base-devel chrpath socat \<br>cpio python python-pip python-pexpect xz debianutils iputils \<br>python-gitpython python-jinja libgl mesa sdl2 python-subunit mesa zstd \<br>lz4 file glibc</pre><h4>Generating locale</h4><p>This should be, in most cases, not necessary, since it is usually generated when the host operating system is installed.</p><pre>$ locale-gen en_US.UTF-8</pre><h3>Yocto base image</h3><p>We can then start with cloning the Yocto repository Poky:</p><pre>git clone git://git.yoctoproject.org/poky</pre><p>Next, we have to checkout a release branch, which in this case has to be the kirkstone one. This specific release is needed due to some compatibility of some of the layers that we will use further down the road.</p><pre>cd poky<br># git branch -a : get a list of all the available branches<br>git checkout -t origin/kirkstone -b my-kirkstone</pre><p>Now, to start working we need to export some env. variables, which is done by sourcing the oe-init-build-env .</p><pre>. ./oe-init-build-env</pre><p>If it worked, should result in printing out:</p><pre>You had no conf/bblayers.conf file. This configuration file has therefore been<br>created for you from poky/meta-poky/conf/bblayers.conf.sample<br>To add additional metadata layers into your configuration please add entries<br>to conf/bblayers.conf.<br><br>The Yocto Project has extensive documentation about OE including a reference<br>manual which can be found at:<br>    https://docs.yoctoproject.org<br>For more information about OpenEmbedded see the website:<br>    https://www.openembedded.org/<br><br>### Shell environment set up for builds. ###<br>You can now run &#39;bitbake &lt;target&gt;&#39;<br>Common targets are:<br>    core-image-minimal<br>    core-image-full-cmdline<br>    core-image-sato<br>    core-image-weston<br>    meta-toolchain<br>    meta-ide-support<br>You can also run generated qemu images with a command like &#39;runqemu qemux86&#39;<br>Other commonly useful commands are:<br> - &#39;devtool&#39; and &#39;recipetool&#39; handle common recipe tasks<br> - &#39;bitbake-layers&#39; handles common layer tasks<br> - &#39;oe-pkgdata-util&#39; handles common target package tasks</pre><p>The project tree now looks like this, with the conf folder populated with a local.conf file. Here is where the main configurations of the distro are located.</p><pre>├── bitbake<br>├── build<br>│   └── conf<br>│       ├── bblayers.conf<br>│       ├── local.conf<br>│       └── templateconf.cfg<br>├── contrib<br>├── documentation<br>├── meta<br>├── meta-poky<br>├── meta-selftest<br>├── meta-skeleton<br>├── meta-yocto-bsp<br>└── scripts</pre><p>The Yocto base image can now be built, although consider that the currently selected machine is quemux86-64.</p><h3>Adding the meta-raspberrypi layer</h3><p>To be able to build an image suitable for the Raspberry Pi, we need to add the meta layer that provides the necessary machine recipes. We first have to clone the meta-raspberrypi repository and checkout the branch matching our poky release one.</p><pre>git clone https://github.com/agherzan/meta-raspberrypi.git # in root poky folder<br>cd meta-raspberrypi<br># git branch -a : list of all branches<br>git checkout -t origin/kirkstone</pre><p>Now this layer provides the recipes for the following machines (rpi boards) and they can be found in the meta-raspberrypi folder:</p><pre>├── conf<br>│   ├── layer.conf<br>│   └── machine<br>│       ├── include<br>│       ├── raspberrypi0-2w-64.conf<br>│       ├── raspberrypi0-2w.conf<br>│       ├── raspberrypi0.conf<br>│       ├── raspberrypi0-wifi.conf<br>│       ├── raspberrypi2.conf<br>│       ├── raspberrypi3-64.conf<br>│       ├── raspberrypi3.conf<br>│       ├── raspberrypi4-64.conf<br>│       ├── raspberrypi4.conf<br>│       ├── raspberrypi-cm3.conf<br>│       ├── raspberrypi-cm.conf<br>│       └── raspberrypi.conf</pre><p>We can add this layer with the bitbake-layers add-layer command:</p><pre>cd poky/build<br>bitbake-layers add-layer ../meta-raspberrypi</pre><p>This will add the absolute path to the layer in the bblayers.conf file in the build/conf folder.</p><p>Since I am using a raspberry-pi Zero 2, I need to set the MACHINE in build/conf/local.conf to raspberrypi0-2w-64.</p><pre>MACHINE ??= &quot;raspberrypi0-2w-64&quot;</pre><p>We can now build the image by running:</p><pre>bitbake core-image-base</pre><p>Once the compilation has finished, an image ready to be loaded onto the SD card should be available in the folder build/tmp/deploy/images/&lt;machine-name&gt;/. In this case, the Raspberry Pi meta layer creates a *.wic.bz2 image file that can be written onto the SD card with the bmaptool utility.</p><p>To check where is the SD card node, you can use fdisk:</p><pre>$ fdisk -l</pre><p>Then write the image with the *.wiz.bmap and *.wiz.bz2 files:</p><pre>$ bmaptool copy --bmap core-image-base-raspberrypi0-2w-64.rootfs.wic.bmap \<br>core-image-base-raspberrypi0-2w-64.rootfs.wic.bz2 /dev/sdc</pre><p>By powering up the raspberry, you should be welcomed with a terminal prompt asking the login name, which defaults to root with no password.</p><h3>Adding the meta-flutter layer</h3><p>To execute a Flutter application, it’s essential to have the Flutter engine installed on the system. This is facilitated through the meta-flutter layer. As I&#39;m utilizing a Raspberry Pi, I&#39;ll depend on the flutter-pi command utility. This tool enables the execution of a Flutter application without the necessity of a display server like Wayland.</p><p>First, we want to clone the meta layer repository in our poky root alongside its meta-clang and meta-oe dependency:</p><pre>git clone https://github.com/meta-flutter/meta-flutter.git<br>git clone https://github.com/kraj/meta-clang<br>git clone git://git.openembedded.org/meta-openembedded</pre><p>meta-flutter should already be tracking the kirkstone branch, if not, checkout the branch (same for meta-clang):</p><pre>cd meta-flutter<br>#git branch -a : list of available branches<br>git checkout -t origin/kirkstone<br>cd meta-clang<br>git checkout -t origin/kirkstone<br>cd meta-openembedded<br>git checkout -t origin/kirkstone</pre><p>We need to add the layers to our local.conf file:</p><pre>cd poky/build<br>bitbake-layers add-layer ../meta-openembedded/meta-oe<br>bitbake-layers add-layer ../meta-flutter<br>bitbake-layers add-layer ../meta-flutter/meta-flutter-apps<br>bitbake-layers add-layer ../meta-clang</pre><p>Now we can add the packages to our distro by adding to our local.conf file:</p><pre>IMAGE_INSTALL:append = &quot;\<br>              flutter-pi \<br>              flutter-gallery \<br>              &quot;<br>DISTRO_FEATURES:append = &quot; systemd opengl&quot;</pre><p>To be able to run the example application and compile the flutter engine, we need to enable both opengl and systemd features.</p><p>We can thus run the building and flashing commands:</p><pre>bitbake core-image-base<br>---<br># $ fdisk -l : check what node is the SD card<br>$ bmaptool copy --bmap core-image-base-raspberrypi0-2w-64.rootfs.wic.bmap \<br>core-image-base-raspberrypi0-2w-64.rootfs.wic.bz2 /dev/sdc</pre><p>Once the system boots, from the welcome message, we can log in as root and run flutter-pi. The built example gallery package can be found under /usr/share/flutter/gallery/3.13.9/release/.</p><pre>Poky (Yocto Project Reference Distro) 4.0.15 raspberrypi0-2w-64 /dev/tty1<br><br>raspberrypo0-2w-64 login: root<br>root@raspberrypi0-2w-64:~# flutter-pi --release /usr/share/flutter/gallery/3.13.9/release/</pre><p>You can also set a temporary locale with:</p><pre>export LANG=en_GB.UTF-8</pre><p>And finally, here is the example app running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*IJGmC-C2o3JUZ2r5-ZJbuw.gif" /></figure><h3>Sum up</h3><p>The current process is quite straightforward, though I’ve only touched the basics. The real challenge awaits when integrating custom hardware, a task I aim to tackle in the third part of this journey. Flutter is impressively fast to work with and has the potential to make a significant impact in the embedded world. While it may not be as sturdy as Qt, it excels in quickly creating attractive interfaces.</p><h3>References</h3><ul><li><a href="https://github.com/meta-flutter/meta-flutter">meta-flutter</a></li><li><a href="https://github.com/kraj/meta-clang">meta-clang</a></li><li><a href="https://github.com/agherzan/meta-raspberrypi">meta-raspberrypi</a></li><li><a href="https://docs.yoctoproject.org/brief-yoctoprojectqs/index.html">Yocto Project Quick Build</a></li><li><a href="https://github.com/flutter/gallery">Flutter gallery example source</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6c5e1caabf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>