<?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 Christian Hollinger on Medium]]></title>
        <description><![CDATA[Stories by Christian Hollinger on Medium]]></description>
        <link>https://medium.com/@christian.hollinger?source=rss-7af40a2161c7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XtawwTq-jIlnHOhGVAHIZg.jpeg</url>
            <title>Stories by Christian Hollinger on Medium</title>
            <link>https://medium.com/@christian.hollinger?source=rss-7af40a2161c7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 11:53:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@christian.hollinger/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[Raspberry Pi Gardening: Monitoring a Vegetable Garden using a Raspberry Pi — Part 2: 3D Printing]]></title>
            <link>https://medium.com/data-science/raspberry-pi-gardening-monitoring-a-vegetable-garden-using-a-raspberry-pi-part-2-3d-printing-40471bd061dc?source=rss-7af40a2161c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/40471bd061dc</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[gardening]]></category>
            <category><![CDATA[3d-printing]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Christian Hollinger]]></dc:creator>
            <pubDate>Sat, 03 Jul 2021 00:00:00 GMT</pubDate>
            <atom:updated>2021-08-25T18:42:25.989Z</atom:updated>
            <content:encoded><![CDATA[<h3>Raspberry Pi Gardening: Monitoring a Vegetable Garden using a Raspberry Pi — Part 2: 3D Printing</h3><h4>Part 2 of throwing Raspberry Pis at the pepper plants in my garden: On the topics of 3D printing, more bad solder jobs, I2C, SPI, Python, go, SQL, and failures in CAD</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SZQRTcL6ObWBmkr7.jpg" /><figcaption>A journey through the project (by author)</figcaption></figure><h3>Introduction</h3><p>In the <a href="https://chollinger.com/blog/2021/04/raspberry-pi-gardening-monitoring-a-vegetable-garden-using-a-raspberry-pi-part-1">last iteration</a> of this project, I walked you through my journey of throwing a Raspberry Pi into my garden beds to monitor sun and water exposure. In this article, we’ll improve the prototype into something that can feasibly used both indoors and outdoors.</p><p>Just as the previous article, this here part 2 will go over all the steps I went through and documents some of the learning experiences I’ve had.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*dEd1R7pfoZPpDUOJ.jpg" /><figcaption>What secrets are you hiding? (by author)</figcaption></figure><h3>Version 1’s Issues</h3><p>Version 1 was fun — and it worked! But it wasn’t without its problems. Let’s do a quick retrospective as to what all needs to improve here.</p><h3>Cost</h3><p>One fairly prohibitive thing was cost — as a prototype, it used a beefy Raspberry Pi 4 (4GB), a machine that retails for a solid <a href="https://www.adafruit.com/product/4296">$55</a>. Realistically, however, we’d want to build the same box for maybe $30 all in (at consumer prices!), so we can deploy multiple of them inside and out.</p><p>This is an easy fix — <a href="https://www.raspberrypi.org/products/raspberry-pi-zero-w/">Raspberry Pi Zero W</a> comes with WiFi (which will be cheaper and more ubiquitous than [PoE] Ethernet <em>[0]</em>) and can be had for $10 (if you can find one for that price). Cheap micro-SD cards retail for $3, and so do cheap micro-usb cables and power bricks, but I assume everyone has multiple piles of cables and adapters anyways. We’ll be using small breadboards, but you can also just solder copper together if you’re down for a fun ride of short circuits. Add about $2 for a solderable breadboard — and continue reading to see why that might be a good idea.</p><p>Back to the Zero W: It&#39;s a magical little stick: 1Ghz, one core, 512MB memory, 40 PIN GPIO headers, camera connector, BLE / Bluetooth 4.1 and 802.11 b/g/n WiFi. For $10. $5 without WiFi. That&#39;s about ~7.7x the CPU capabilities of my first PC, in about 1/1,000 the volume!</p><p>It’s fair to say that it’s tiny, about half the size of a spacebar (if that’s a unit of measurement?):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bJTv3Si2w2Ll1f9b.jpg" /><figcaption>Raspberry Zero W on a Ducky Spacebar, on a bed of Cherry MX Blues (by author)</figcaption></figure><p>Sure — some ESP32’s might come cheaper — but Raspberries also have the distinct advantage of not being a microcontroller, but rather a fully-fledged computer. And for somebody who isn’t exactly an Embedded Engineer, the learning curve is a lot less steep. The little RasPis also support USB, which is neat!</p><p><em>[0]</em> <a href="https://buzzert.net/posts/2021-05-09-doorbell">This here</a> is a fun read that relies on PoE and can use a simpler design because of it.</p><h3>Power Consumption</h3><p>Using a Raspberry vs. an ESP32 does have its disadvantages, though - power consumption being one of them. Assuming we&#39;d want to collect data wireless for 48 hrs:</p><p>The previously used Raspberry Pi 4 will consume around <em>500 - 600mA</em> at idle. On a 5V power supply, we&#39;re looking at ~3W or ~144Wh for 48hrs.</p><p>Reminder:</p><blockquote><em>Power (as </em><strong><em>W</em></strong><em>att </em><strong><em>h</em></strong><em>our) = Voltage (as </em><strong><em>V</em></strong><em>olts) / Current (as </em><strong><em>A</em></strong><em>mps)</em></blockquote><blockquote><em>W = Voltage * Amps * Hours</em></blockquote><p>A Raspberry Pi Zero W on WiFi should be around <em>150 - 180 mA</em> on 3.3V, with a voltage regulator on-board to support 5V PSUs - so about 0.55W or 26.64Wh for 48hrs (about <em>18.5% the power consumption</em> of a Pi 4!).</p><p>However, an <a href="https://www.espressif.com/sites/default/files/documentation/esp32-wroom-32_datasheet_en.pdf">ESP32-WROOM-32</a>, on the other hand, would range around <em>100 mA</em> at 2.2 to 3.6V (as little as 10.5Wh for 48hrs) when actively sending data, and barely nothing when idle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*WrLPBnd-vvR12x2s.png" /><figcaption><a href="https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf">https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf</a></figcaption></figure><p>To put it into perspective, a single AA Lithium battery clocks in at about <em>~3,000mA</em>, albeit at 3.7V. Powerbanks, of course, come with power converters — with Pi Zero W&#39;s estimated consumption and a minimum runtime of 48hrs, a tiny powerbank at 10,000mAh (10A) and 3.7V (which would be typical for lithium) could power a Pi, in an ideal world without conversion loss and inefficiencies, for about <strong>67hrs</strong> (37Wh/0.55Wh). Assuming 50% efficiency, 10Ah would get us to about 1 1/2 days, which isn&#39;t amazing.</p><p>Cost is also a prohibitive factor — even cheap(ish) power bank or straight up lithium batteries would almost double the cost of one unit, for ultimately little benefit. The <a href="https://www.pisugar.com/">PiSugar</a> project, for instance, clocks in at $39.99 for a 1,200mAh battery, with an estimated runtime of 5–6hrs — which is in line with the calculations above ( 1.2A*3.7V=4.44Wh, 4.44/0.55Wh*.5=4.3hrs, with 50% efficiency).</p><p>So, despite this being not ideal, we’ll take the efficiency gain, but forego the battery topic for now.</p><h3>Sensors &amp; New Parts List</h3><p>The last project also used a lot of different sensors to figure out which ones work best — this time around, we already know the ones we need.</p><p>So, here’s an updated part list:</p><ul><li><strong>Board</strong>: <a href="https://www.raspberrypi.org/products/raspberry-pi-zero-w/">Raspberry Pi Zero W</a> — $10</li><li><strong>SD Card</strong>: Any cheap, 8–16GB card will do — $3</li><li><strong>Moisture</strong>: <a href="https://smile.amazon.com/gp/product/B076DDWDJK/ref=ppx_yo_dt_b_asin_image_o01_s00?ie=UTF8&amp;psc=1">Any resistive humidity sensor</a> — $5</li><li><strong>Temperature</strong>: <a href="https://www.adafruit.com/product/1782">MCP9808 High Accuracy I2C Temperature Sensor</a> — $4.95</li><li><strong>Light</strong>: <a href="https://smile.amazon.com/NOYITO-MAX44009-Intensity-Interface-Development/dp/B07HFRS8XX">NOYITO MAX44009</a> (up to 188k lux) — $4.95 (<em>price increased at time of writing</em>)</li><li><strong>ADC</strong>: <a href="https://www.adafruit.com/product/856">MCP3008 8-Channel 10bit ADC With SPI Interface</a> — $3.75</li></ul><p>Which brings our total from almost $100 for a development board to about <strong>$31.60</strong>. Add ~$2 for a solderable breadboard and maybe $0.10 for some jumper wires, if you want a more sturdy design.</p><p>I’ll call this a win, simply because I’d be able to get all parts (sans the Pi) from Aliexpress for about half the price, like a MCP3008 for $1.50. But even domestically, from places like Adafruit, Microcenter, and Amazon, the total cost per unit seems reasonable.</p><h3>Size, Enclosure, and Layout</h3><p>The bigger and more obvious limitation of the previous iteration, however, was size: Due to my genius plan of using a Dremel to drill holes into a massive (albeit flimsy) box from Ikea, the resulting box was both huge <em>and</em> impractical. A classic lose-lose situation, just how I like it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/0*rmfFs385Mb4gY66h.jpg" /><figcaption>Original case (by author)</figcaption></figure><p>It also relied on a breadboard, lots of dupont cables, and was generally not very well thought out — everything in it should have fit onto a much smaller footprint.</p><p>Improving the layout should be a relatively simple task: Since we know the sensors we need, we can optimize for space. We’ll do that further <a href="https://chollinger.com/blog/2021/07/raspberry-pi-gardening-monitoring-a-vegetable-garden-using-a-raspberry-pi-part-2-3d-printing/#a-new-component-layout">down</a>.</p><p>The enclosure for that, however… that is a different topic. We’ll get to that now.</p><h3>Introducing: The 3D Printer</h3><p>I’ve mentioned it last time, I’m using this as an opportunity to buy a 3D printer. I chose the <a href="https://www.creality.com/goods-detail/ender-3-v2-3d-printer">Creality Ender 3 V2</a>, which is probably the most recommended budget 3D printer for PLA and ABS at around $250.</p><p>This being my first 3D printer, it was an interesting learning experience to say the least.</p><p><em>You will find the background of all photos changing quite the bit, as we moved this ~19x19&quot; thing around the house a lot — I wound up buying a ~22x22&quot; IKEA Lack table for it, in case you were curious.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JpxSL8FDfwtwWgc8.jpg" /><figcaption>The part of the house formerly known as ‘the nice part’ (by author)</figcaption></figure><h3>Building a 3D Printer</h3><p>Creality’s own website (!) offers the following advice:</p><blockquote><em>Sure, it’s far from perfect.</em></blockquote><blockquote><em>But at this lower price, it offers a decent print volume, is easy to assemble and improve, and can produce high-quality prints.</em></blockquote><blockquote><em>( </em><a href="https://www.creality.com/goods-detail/ender-3-v2-3d-printer"><em>https://www.creality.com/goods-detail/ender-3-v2-3d-printer</em></a><em>)</em></blockquote><p>So, reading up online, it was clear to my that a “standard” Ender 3 v2 won’t cut it — too many reports of people struggling with basic functionality. So, I installed some updates before starting my first print. That wasn’t an overly smart move — I should have started with a test-print first.</p><h4>Aluminum extruder, 0.4mm Nozzle, and Capricorn PTFE Bowden Tubing</h4><p>The first number of updates fell under “preventative maintenance”, i.e. things I probably wouldn’t notice until I used the printer a bunch, but it seemed like a good thing to replace, since the printer doesn’t come assembled anyways. I soon learned that that was a mistake.</p><p>The first upgrade was an aluminum extruder: A simply sturdier version to move filament into the hot end (the part melting the filament), compared to the plastic default, with a stronger spring to keep better tension during the extruding process. This ensures that filament will always flow evenly. It’s also simply much less likely to break.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lVYSVthxTjSvEvJ1.jpg" /><figcaption>Upgraded extruder (by author)</figcaption></figure><p>What I didn’t realize, however, was that this process might mess up the calibration of the printer, where the length of filament requested and the length of filament extruded are out of sync, causing pooling on the hotbed and misshapen prints:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LbNPsUJFe3tMn-Js.jpg" /><figcaption>Misprint #1 (by author)</figcaption></figure><p>Thanks to a friend who actually knows stuff about 3D printing (for I am but a humble novice), we were able to follow the steps on <a href="https://teachingtechyt.github.io/calibration.html#esteps">this wonderful website</a> to re-calibrate it. This happened after many a failed print, though — even though it wasn’t the only root cause. In any case, heed his advice and bookmark <a href="https://teachingtechyt.github.io/">this</a> website — it’ll save you a lot of time.</p><p>I also installed updated tubing, nozzles, and connectors the same reasons — don’t believe I’d run into issues any time soon, but those upgrades were easiest to do while everything else was taken apart already.</p><h4>Auto-Leveling</h4><p>One of the most important things about 3D printing is leveling — one of the main problems with messed-up prints like the one above — and leveling something manually, especially in a house from 1949 (level floors weren’t invented until 1972, fun fact) was bound to be a pain, if not outright impossible.</p><p>So, the <a href="https://smile.amazon.com/Creality-BLTouch-Upgraded-Leveling-Mainboard/dp/B08L9DHP5R">Creality BLTouch V3.1</a> for about $40 is a terrific little invention: Instead of relying on a human to manually move the Z-Axis every on practically inch of the printing bed, it probes the surface for you.</p><p>Installing it was relatively straightforward: You replace the regular Z-Limiter’s cable with the BLTouch (which requires you to remove the mainboard cover), route the cable alongside the tubing, and bolt it to the print head.</p><p>At this point, it is advised to note down the mainboard version, as we’ll need that for the firmware upgrade in the next step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*z4RcqlXiZ7cVDJ8G.jpg" /><figcaption>v 4.2.2 (by author)</figcaption></figure><p>Once installed, it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9WjoR2aTIYZil85A.jpg" /><figcaption>BLTouch (by author)</figcaption></figure><p>The other thing I installed was a set of <a href="https://smile.amazon.com/Marketty-Printer-Compression-Actually-Perfectly/dp/B07MTGXYLW">updated springs</a>, so the bed stays level once it is leveled once.</p><h4>New Firmware</h4><p>After those updates were installed, the next journey was to get firmware installed — otherwise, the BLTouch won’t do a thing. The Ender 3 v2 has an <em>interesting</em> process for this — you place a .bin file onto an otherwise empty SD card and it&#39;ll install it.</p><p>I used a pre-compiled <a href="https://github.com/mriscoc/Marlin_Ender3v2">Marlin</a> firmware for this task.</p><p>If you, however, chose a wrong firmware, the display will just stay black or the machine will beep horribly loud.</p><p>Part of my wonders how it validates authenticity, of if it just executes random code. I have that theory that it’s the latter.</p><h4>OctoPrint</h4><p>While all these improvements were great, the process of printing anything on an Ender 3 is as follows:</p><ol><li>Find or design a CAD model</li><li>Use a slicer, such as <a href="https://ultimaker.com/software/ultimaker-cura">Cura</a>, to turn your CAD into sliced G-code that your printer understands</li><li>Move it onto an SD-card</li><li>Plug the SD-card into the printer</li><li>Print, run into the room with the printer every 10 minutes to check for inevitable failures</li></ol><p>However, a wonderful piece of software exists, called <a href="https://octoprint.org/">Octoprint</a> that can be used to control your printer remotely (or, rather, from the local network) via a Raspberry Pi!</p><p>First off, I printed enclosures for a Raspberry Pi (using charming “rainbow filament”, which explains the, uh, <em>interesting</em> color combinations):</p><ul><li><a href="https://www.thingiverse.com/thing:4192636">Ender 3 Dual Rail Raspberry Pi 4 case</a></li><li><a href="https://www.thingiverse.com/thing:3417079">Ender 3 Pi cam Boom w/ Swivel/Tilt</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q60x96kXCo9qN35U.jpg" /><figcaption>Enclosure Printing (by author)</figcaption></figure><p>And installed it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*ARgVXjxYmMC4QWX5.jpg" /><figcaption>Octoprint Case (by author)</figcaption></figure><p>And then installed Octoprint using docker-compose, after telling the DHCP server and the Pi to keep a static IP over WiFi:</p><pre>version: &#39;2.4&#39;<br><br>services:<br>  octoprint:<br>    image: octoprint/octoprint<br>    restart: always<br>    ports:<br>      - &quot;80:80&quot;<br>    devices:<br>      - /dev/ttyUSB0:/dev/ttyACM0<br>      - /dev/video0:/dev/video0<br>    volumes:<br>     - octoprint:/octoprint<br>    # uncomment the lines below to ensure camera streaming is enabled when<br>    # you add a video device<br>    environment:<br>      - ENABLE_MJPG_STREAMER=true<br>  <br>volumes:<br>  octoprint:</pre><p>(All you really need to check here is your dev ices - the container thinks its talking to a serial port, whereas in reality, it&#39;s the first USB device).</p><p>And once it was up and running, it was possible to upload G-Code and monitor prints in real-time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/0*0z3fG5MXGMaJZ-rr.png" /><figcaption>Octoprint UI (by author)</figcaption></figure><p>You can also see a print’s individual steps in real-time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/0*HYOhtiJH6G84snJZ.png" /><figcaption>Octoprint GCode Viewer (by author)</figcaption></figure><h4>Leveling and Elmer’s Glue</h4><p>Earlier, I mentioned that leveling is one of the key things that need doing — otherwise, they’ll produce spaghetti:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dQtCFJvAlN6ZKscS.jpg" /><figcaption>Misprint #2 (by author)</figcaption></figure><p>Fortunately, Octoprint has a <a href="https://plugins.octoprint.org/plugins/bedlevelvisualizer/">plugin</a> we can use to support this.</p><p>I’ve used the following GCODE:</p><pre>G28<br>M155 S30<br>@ BEDLEVELVISUALIZER<br>G29 T<br>M155 S3</pre><pre>G28<br>M155 S30<br>@ BEDLEVELVISUALIZER<br>G29 T<br>M155 S3</pre><p>And here’s the result, after manually leveling it before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*wZ5sdZ09FrGWgJVQ.png" /><figcaption>Octoprint Level (by author)</figcaption></figure><p>This process, however, took me a long time — and for some prints you see on the pictures above, I used Elmer’s glue to increase adhesion to avoid the print from moving. I’m not saying I recommend it — it does, however, make prints stick without supports on less-than-perfectly leveled beds.</p><h3>Test Prints and Progress</h3><p>This was the first print:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*oscqgO8sW60fwf22.jpg" /><figcaption>Misprint #3 (by author)</figcaption></figure><p>And here’s one of the later models — you can see the imperfections as I was trying to figure out — but it’s quite a bit better than the mess in the first attempt:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*1gAz4mZ1PpaQBSqd.jpg" /><figcaption>Tremendous Totoro Test (from ‘My Neighbor Totoro’ / となりのトト) / [Thingverse 4515916] (by author)</figcaption></figure><p>So far, so good!</p><h3>A New Component Layout</h3><p>Now that we can print anything from test cubes over anime figurines to enclosures, let’s also re-visit the layout of the initial prototype.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A0Ni35Aw9tKR6HET.png" /><figcaption>Original Layout (by author)</figcaption></figure><h3>Designing a new Layout</h3><p>This layout, naturally, wasted a ton of space. Using the same wiring as before, but using a 20-pin breadboard (as I won’t be etching a PCB, so much is for certain) as opposed to a 60-pin one and dropping the cobbler, we’re left with this tiny 9x6.5cm layout:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wVfk1KniF4poaaBp.png" /><figcaption>New Layout (by author)</figcaption></figure><p>I will accept that it isn’t super easy to maintain on that form-factor and that splicing the 5V channel might not be super-duper-smart — just don’t overload it. I2C can have issues with many devices in series (due to resistance on the same bus), but ultimately, I don&#39;t think this will be a problem here. It isn&#39;t super elegant, but it should work.</p><p>In any case, the layout is 2-dimensional in this Fritzing drawing — once we design an enclosure for a Pi Zero W, we can start stacking components and save even more space. We&#39;ll see to that below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D6j3126W2IO4fVCQ.jpg" /><figcaption>New Layout assembled (early version) (by author)</figcaption></figure><h3>New Components</h3><p>We’ve also replaced the UV with a new Lux sensor, the tiny NOYITO MAX44009. This sensor hooks up to I2C as usual (Power, GND, SCL, SDA), which is why we&#39;re re-using the same lanes on the board. It&#39;s also positively <em>tiny</em>, which is nice for a compact design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ly54RX0bz0ugC8w4.jpg" /><figcaption>MAX44009 after soldering (by author)</figcaption></figure><h3>Software Updates</h3><p>The next thing to re-visit is software.</p><h4>MAX44009 and the Quest for 0x4B</h4><p>Naturally, we’ll need to integrate the new sensor somehow. The documentation for this thing is available <a href="https://www.maximintegrated.com/en/products/interface/sensor-interface/MAX44009.html">here</a>, but there is no ready-to-use pip3 dependency.</p><p>People took the documentation and figured out the conversion math <a href="https://github.com/ControlEverythingCommunity/MAX44009/blob/master/Python/MAX44009.py">here</a> and <a href="https://github.com/rcolistete/MicroPython_MAX44009_driver/blob/master/max44009.py">here</a> — if you’re interested in doing this from scratch, please <a href="https://chollinger.com/blog/2021/04/raspberry-pi-gardening-monitoring-a-vegetable-garden-using-a-raspberry-pi-part-1/#implementing-mcp9808-communications-from-scratch">take a look at Part 1</a>.</p><p>This sensor has one disadvantage, though — every documentation mentions that it uses the I2C address 0x4A, but in my case, it used 0x4B, <em>but not consistently</em>:</p><pre>sudo i2cdetect -y 1<br>     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f<br>00:          -- -- -- -- -- -- -- -- -- -- -- -- -- <br>10: -- -- -- -- -- -- -- -- 18 -- -- -- -- -- -- -- <br>20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- <br>30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- <br>40: -- -- -- -- -- -- -- -- -- -- -- 4b -- -- -- -- <br>50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- <br>60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- <br>70: -- -- -- -- -- -- -- --</pre><p>And Amazon review said as such:</p><blockquote><em>These have a selectable I2C address 0x4a or 0x4b. But note that the address on the modules I received was NOT set by the manufacturer.</em></blockquote><blockquote><em>So you’ll need to solder the jumper pads on the board one way or another or the address will not be deterministic and may change on you between uses. (I found out the hard way).</em></blockquote><p>CTRL+F on the official docs yields no results for 0x4B and the sample code also defaults to 0x4A:</p><pre>class MAX44009 : public i2cSensor<br>{<br><br>    /** ######### Register-Map ################################################################# */<br><br>#define MAX_ADDRESS 				0x4a<br><br>#define INT_STATUS_REG				0x00<br>#define INT_ENABLE_REG              0x01<br>#define CONFIGURATION_REG           0x02<br>#define   CONFIG_CONT_MASK          (bit(7))  // CONTINOUS MODE<br>#define     CONFIG_CONT_ON          (1&lt;&lt;7)<br>#define     CONFIG_CONT_OFF         (0)<br>#define   CONFIG_MANUAL_MASK        (bit(6))  // MANUAL Set CDR and TIME</pre><p>Isn’t that <em>fun</em>?! (╯°□°）╯︵ ┻━┻</p><p>Anyways, I’ve simply created a customized version that worked with the existing code base from the first iteration and my odd address masking:</p><pre>from smbus2 import SMBus<br>import time<br><br>class MAX44009:<br>    # Thanks to https://github.com/rcolistete/MicroPython_MAX44009_driver/blob/master/max44009.py<br>    # With slight adjustments by chollinger93 for Python3 etc.<br>    MAX44009_I2C_DEFAULT_ADDRESS = 0x4A<br>    MAX44009_I2C_FALLBACK_ADDRESS = 0x4B<br><br>    MAX44009_REG_CONFIGURATION = 0x02<br>    MAX44009_REG_LUX_HIGH_BYTE = 0x03<br>    MAX44009_REG_LUX_LOW_BYTE  = 0x04<br>    <br>    MAX44009_REG_CONFIG_CONTMODE_DEFAULT     = 0x00    # Default mode, low power, measures only once every 800ms regardless of integration time<br>    MAX44009_REG_CONFIG_CONTMODE_CONTINUOUS  = 0x80    # Continuous mode, readings are taken every integration time<br>    MAX44009_REG_CONFIG_MANUAL_OFF           = 0x00    # Automatic mode with CDR and Integration Time are are automatically determined by autoranging<br>    MAX44009_REG_CONFIG_MANUAL_ON            = 0x40    # Manual mode and range with CDR and Integration Time programmed by the user<br>    MAX44009_REG_CONFIG_CDR_NODIVIDED        = 0x00    # CDR (Current Division Ratio) not divided, all of the photodiode current goes to the ADC<br>    MAX44009_REG_CONFIG_CDR_DIVIDED          = 0x08    # CDR (Current Division Ratio) divided by 8, used in high-brightness situations<br>    MAX44009_REG_CONFIG_INTRTIMER_800        = 0x00    # Integration Time = 800ms, preferred mode for boosting low-light sensitivity<br>    MAX44009_REG_CONFIG_INTRTIMER_400        = 0x01    # Integration Time = 400ms<br>    MAX44009_REG_CONFIG_INTRTIMER_200        = 0x02    # Integration Time = 200ms<br>    MAX44009_REG_CONFIG_INTRTIMER_100        = 0x03    # Integration Time = 100ms, preferred mode for high-brightness applications<br>    MAX44009_REG_CONFIG_INTRTIMER_50         = 0x04    # Integration Time = 50ms, manual mode only<br>    MAX44009_REG_CONFIG_INTRTIMER_25         = 0x05    # Integration Time = 25ms, manual mode only<br>    MAX44009_REG_CONFIG_INTRTIMER_12_5       = 0x06    # Integration Time = 12.5ms, manual mode only<br>    MAX44009_REG_CONFIG_INTRTIMER_6_25       = 0x07    # Integration Time = 6.25ms, manual mode only<br><br>    def __init__(self, bus=None) -&gt; None:<br>        if not bus:<br>            bus = SMBus(1)<br>        self.bus = bus<br>        self.addr = self.MAX44009_I2C_DEFAULT_ADDRESS<br>        self.configure()<br><br>    def configure(self):<br>        try:<br>            self.bus.write_byte_data(self.addr, <br>                self.MAX44009_REG_CONFIGURATION, <br>                self.MAX44009_REG_CONFIG_MANUAL_ON)<br>        except Exception as e:<br>            print(e)<br><br>    def _convert_lumen(self, raw) -&gt; float:<br>        exponent = (raw[0] &amp; 0xF0) &gt;&gt; 4<br>        mantissa = ((raw[0] &amp; 0x0F) &lt;&lt; 4) | (raw[1] &amp; 0x0F)<br>        return ((2 ** exponent) * mantissa) * 0.045<br><br>    def read_lumen(self)-&gt; float:<br>        data = self.bus.read_i2c_block_data(self.addr,<br>            self.MAX44009_REG_LUX_HIGH_BYTE, 2)<br>        return self._convert_lumen(data)<br>    <br>    def _switch_addr(self):<br>        if self.addr == self.MAX44009_I2C_DEFAULT_ADDRESS:<br>            self.addr = self.MAX44009_I2C_FALLBACK_ADDRESS<br>        else:<br>            self.addr = self.MAX44009_I2C_DEFAULT_ADDRESS<br><br>    def read_lumen_with_retry(self):<br>        # To avoid 121 I/O error<br>        # Sometimes, the sensor listens on 0x4A,<br>        # sometimes, on 0x4B (ಠ.ಠ)<br>        try:<br>            return self.read_lumen()<br>        except Exception as e:<br>            print(f&#39;Error reading lumen on {self.addr}, retrying&#39;)<br>            self._switch_addr()<br>            self.configure()<br>            return self.read_lumen_with_retry()<br><br>if __name__ == &#39;__main__&#39;:<br>    # Get I2C bus<br>    bus = SMBus(1)<br>    # Let I2C settle<br>    time.sleep(0.5)<br>    MAX44009 = MAX44009(bus)<br>    # Convert the data to lux<br>    luminance = MAX44009.read_lumen_with_retry()<br><br>    # Output data to screen<br>    print(f&#39;Ambient Light luminance : {luminance} lux&#39;)</pre><h3>Re-Writing the Client</h3><p>Other than that, I updated the main code a bit to be a bit more flexible, by using a class hierarchy that allows the various sensor implementations from libraries, custom code, SPI etc.</p><p>It’s not exactly a marvel of engineering — but it is better than it was before. The full code, as usual, is on <a href="https://github.com/chollinger93/raspberry-gardener">GitHub</a>.</p><pre>from board import *<br># ...<br><br>class Sensor():<br>    def __init__(self, sensor: object) -&gt; None:<br>        self.sensor = sensor<br><br>    def read_metric(self) -&gt; dict:<br>        &quot;&quot;&quot;Implemented in each sensor<br><br>        Returns a `dict` of readings, mapping to the SQL schema.<br><br>        Return None if no reading. Equals NULL in DB.<br><br>        Returns:<br>            dict: Column -&gt; Reading<br>        &quot;&quot;&quot;<br>        pass<br><br># Temp<br>class MCP9808_S(Sensor):<br>    def read_metric(self):<br>        with busio.I2C(SCL, SDA) as i2c:<br>            t = adafruit_mcp9808.MCP9808(i2c)<br>            return {<br>                &#39;tempC&#39;: t.temperature<br>            }<br><br># UV<br>class SI1145_S(Sensor):<br>    def read_metric(self):<br>        vis = self.sensor.readVisible()<br>        IR = self.sensor.readIR()<br>        UV = self.sensor.readUV() <br>        uvIndex = UV / 100.0<br>        # UV sensor sometimes doesn&#39;t play along<br>        if int(vis) == 0 or int(IR) == 0:<br>            return None<br><br>        return {<br>            &#39;visLight&#39;: vis,<br>            &#39;irLight&#39;: IR,<br>            &#39;uvIx&#39;: uvIndex<br>        }<br><br># Moisture: HD-38 (Aliexpress/Amazon)<br># pass spi_chan<br>class HD38_S(Sensor):<br>    def read_metric(self):<br>        raw_moisture = self.sensor.value<br>        volt_moisture = self.sensor.voltage<br>        if int(raw_moisture) == 0:<br>            return None<br>        return {<br>            &#39;rawMoisture&#39;: raw_moisture, <br>            &#39;voltMoisture&#39;: volt_moisture<br>        }<br><br># Lumen: pass MAX44009<br>class MAX44009_S(Sensor):<br>    def read_metric(self):<br>        return {<br>            &#39;lumen&#39;: self.sensor.read_lumen_with_retry()<br>            }<br><br>__sensor_map__ = {<br>    &#39;uv&#39;: SI1145_S,<br>    &#39;temp&#39;: MCP9808_S,<br>    &#39;lumen&#39;: MAX44009_S,<br>    &#39;moisture&#39;: HD38_S<br>}<br><br>def get_machine_id():<br>    return &#39;{}-{}&#39;.format(platform.uname().node, getmac.get_mac_address())<br><br>def main(rest_endpoint: str, frequency_s=1, buffer_max=10, spi_in=0x0, disable_rest=False, *sensor_keys):<br>    if disable_rest:<br>        logger.warning(&#39;Rest endpoint disabled&#39;)<br>    buffer=[]<br><br>    # Create sensor objects<br>    sensors =  {}<br>    for k in sensor_keys:<br>        if k == &#39;uv&#39;:     <br>            # UV<br>            sensor = SI1145.SI1145()<br>        elif k == &#39;temp&#39;:<br>            # TODO: library behaves oddly<br>            sensor = None <br>        elif k == &#39;lumen&#39;:<br>            sensor = m4.MAX44009(SMBus(1))<br>        elif k == &#39;moisture&#39;:<br>            ## SPI<br>            # create the spi bus<br>            spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)<br>            # create the cs (chip select)<br>            cs = digitalio.DigitalInOut(board.CE0)<br>            # create the mcp object<br>            mcp = MCP.MCP3008(spi, cs)<br>            # create an analog input channel on pin 0<br>            sensor = AnalogIn(mcp, spi_in)<br>        else:<br>            logger.error(f&#39;Unknown sensor key {k}&#39;)<br>            continue<br>        # Create<br>        sensors[k] = __sensor_map__[k](sensor=sensor)<br>    <br>    while True:<br>        try:<br>            # Target JSON<br>            reading = {<br>                &#39;sensorId&#39;: get_machine_id(),<br>                # Metrics will come from Sensor object<br>                &#39;tempC&#39;: None,<br>                &#39;visLight&#39;: None,<br>                &#39;irLight&#39;: None,<br>                &#39;uvIx&#39;: None,<br>                &#39;rawMoisture&#39;: None,<br>                &#39;voltMoisture&#39;: None,<br>                &#39;lumen&#39;: None,<br>                &#39;measurementTs&#39;: datetime.now(timezone.utc).isoformat() # RFC 3339<br>            }<br><br>            # Read all<br>            for k in sensors:<br>                try:<br>                    sensor = sensors[k]<br>                    logger.debug(f&#39;Reading {sensor}&#39;)<br>                    metrics = sensor.read_metric()<br>                    if not metrics:<br>                        logger.error(f&#39;No data for sensor {k}&#39;)<br>                        continue<br>                except Exception as e:<br>                    logger.error(f&#39;Error reading sensor {k}: {e}&#39;)<br>                    continue<br>                # Combine <br>                reading = {**reading, **metrics}<br><br>    <br>            # Only send if its not disabled       <br>            if not disable_rest:<br>                buffer.append(reading)<br>                logger.debug(reading)<br>                if len(buffer) &gt;= buffer_max:<br>                    logger.debug(&#39;Flushing buffer&#39;)<br>                    # Send<br>                    logger.debug(&#39;Sending: {}&#39;.format(json.dumps(buffer)))<br>                    response = requests.post(rest_endpoint, json=buffer)<br>                    logger.debug(response)<br>                    # Reset<br>                    buffer = []<br>            else:<br>                logger.info(reading)<br>        except Exception as e:<br>            logger.exception(e)<br>        finally:<br>            time.sleep(frequency_s)<br><br><br>if __name__ == &#39;__main__&#39;:<br>    # Args<br>    parser = argparse.ArgumentParser(description=&#39;Collect sensor data&#39;)<br>    # ...<br><br>    # Start<br>    logger.warning(&#39;Starting&#39;)<br>    main(args.rest_endpoint, args.frequency_s, args.buffer_max, args.spi_in, args.disable_rest, *args.sensors)</pre><p>The whole if/ else switch can of course be avoided, for instance with a plugin model like I <a href="https://github.com/chollinger93/scarecrow/tree/master/scarecrow_core/plugins">wrote here for </a><a href="https://github.com/chollinger93/scarecrow/tree/master/scarecrow_core/plugins">scarecrow-cam</a>, another RasPi project. But that&#39;s a bit more effort than I&#39;m willing to spend right now.</p><p>Anyways, we can test locally with:</p><pre>python3 monitor.py --disable_rest --rest_endpoint na --sensors temp lumen moisture</pre><p>And update the systemd service.</p><h3>Updating the Backend</h3><p>Of course, the addition of the sensor requires schema updates, which is easy in go, because go has structs and doesn’t hate you:</p><pre>type Sensor struct {<br>	SensorId      string<br>	TempC         float32<br>	VisLight      int32<br>	IrLight       int32<br>	UvIx          float32<br>	RawMoisture   int32<br>	VoltMoisture  float32<br>	Lumen         float32<br>	MeasurementTs string<br>}<br><br>func (a *App) storeData(sensors []Sensor) error {<br>	q := squirrel.Insert(&quot;data&quot;).Columns(&quot;sensorId&quot;, &quot;tempC&quot;, &quot;visLight&quot;, &quot;irLight&quot;, &quot;uvIx&quot;, &quot;rawMoisture&quot;, &quot;voltMoisture&quot;, &quot;lumen&quot;, &quot;measurementTs&quot;, &quot;lastUpdateTimestamp&quot;)<br>	for _, s := range sensors {<br>		// RFC 3339<br>		measurementTs, err := time.Parse(time.RFC3339, s.MeasurementTs)<br>		if err != nil {<br>			zap.S().Errorf(&quot;Cannot parse TS %v to RFC3339&quot;, err)<br>			continue<br>		}<br>		q = q.Values(s.SensorId, s.TempC, s.VisLight, s.IrLight, s.UvIx, s.RawMoisture, s.VoltMoisture, s.Lumen, measurementTs, time.Now())<br>	}<br>	sql, args, err := q.ToSql()<br>	if err != nil {<br>		return err<br>	}<br><br>	res := a.DB.MustExec(sql, args...)<br>	zap.S().Info(res)<br>	return nil<br>}</pre><p>The same goes for the SQL interface/DDL - a fairly standard exercise.</p><h3>Adding new Features</h3><p>Another useful feature, apart from collecting data, would be to notify the gardener of any issues. For that, I implemented a simple notification system in go, i.e. on the server.</p><p>The implementation is straightforward — we define constants for thresholds:</p><pre>// Hard coded alert values for now<br>const MIN_TEMP_C = 5<br>const MAX_TEMP_C = 40<br>const LOW_MOISTURE_THRESHOLD_V = 2.2<br><br><br>func (a *App) checkSensorThresholds(sensor *Sensor) bool {<br>	if sensor.VoltMoisture &gt;= LOW_MOISTURE_THRESHOLD_V || sensor.TempC &lt;= MIN_TEMP_C || sensor.TempC &gt;= MAX_TEMP_C {<br>		return true<br>	}<br>	return false<br>}</pre><p><em>Using thresholds as </em><em>constants is, to be fair, like re-compiling your Kernel for a </em><em>ulimit adjustment - but I&#39;m trying to avoid </em><em>config files.</em></p><p>An in order not to send notifications every time the sensor triggers, we also implement a timer, which for the sake of simplicity uses a global map and a mutex:</p><pre>// Simple mutex pattern to avoid race conditions<br>var mu sync.Mutex<br>var notificationTimeouts = map[string]time.Time{}<br><br>const NOTIFICATION_TIMEOUT = time.Duration(12 * time.Hour)<br><br><br>func (a *App) validateSensor(sensor *Sensor) error {<br>	// Check the values first<br>	if !a.checkSensorThresholds(sensor) {<br>		zap.S().Debugf(&quot;Values for %s are below thresholds&quot;, sensor.SensorId)<br>		return nil<br>	}<br>	// Otherwise, notify<br>	mu.Lock()<br>	// If we already have the sensor stored in-memory, check whether its time to notify again<br>	if lastCheckedTime, ok := notificationTimeouts[sensor.SensorId]; ok {<br>		if time.Now().Sub(lastCheckedTime) &lt; NOTIFICATION_TIMEOUT {<br>			// Not time yet<br>			zap.S().Debug(&quot;Timeout not reached&quot;)<br>			return nil<br>		}<br>	}<br>	// Reset the timer<br>	notificationTimeouts[sensor.SensorId] = time.Now()<br>	// Otherwise, notify<br>	err := a.notifyUser(sensor)<br>	// Release the mutex late<br>	mu.Unlock()<br>	return err<br>}</pre><p>Sending the notifications happens via smtp, and similar to the previous iteration, we keep secrets in environment variables, rather than a config file - for simplicity&#39;s sake, once again:</p><pre>type SmtpConfig struct {<br>	smtpUser              string<br>	smtpPassword          string<br>	smtpAuthHost          string<br>	smtpSendHost          string<br>	notificationRecipient string<br>}<br><br>func NewSmtpConfig() *SmtpConfig {<br>	return &amp;SmtpConfig{<br>		smtpUser:              mustGetenv(&quot;SMTP_USER&quot;),<br>		smtpPassword:          mustGetenv(&quot;SMTP_PASSWORD&quot;),<br>		smtpAuthHost:          mustGetenv(&quot;SMTP_AUTH_HOST&quot;),<br>		smtpSendHost:          mustGetenv(&quot;SMTP_SEND_HOST&quot;),<br>		notificationRecipient: mustGetenv(&quot;SMTP_NOTIFICATION_RECIPIENT&quot;),<br>	}<br>}</pre><p>And the sending part can be done natively in go:</p><pre>func (a *App) notifyUser(sensor *Sensor) error {<br>	header := fmt.Sprintf(&quot;To: %s \r\n&quot;, a.SmtpCfg.notificationRecipient) +<br>		fmt.Sprintf(&quot;Subject: Sensor %v reached thresholds! \r\n&quot;, sensor.SensorId) +<br>		&quot;\r\n&quot;<br>	msg := header + fmt.Sprintf(`Sensor %s encountered the following threshold failure at %v:<br>	Temperature: %v (Thresholds: Min: %v / Max: %v)<br>	Moisture: %v (Thresholds: Min: %v / Max: N/A)`, sensor.SensorId, sensor.MeasurementTs,<br>		sensor.TempC, MIN_TEMP_C, MAX_TEMP_C, sensor.VoltMoisture, LOW_MOISTURE_THRESHOLD_V)<br>	zap.S().Warn(msg)<br>	// Get config<br>	// Auth to mail server<br>	auth := smtp.PlainAuth(&quot;&quot;, a.SmtpCfg.smtpUser, a.SmtpCfg.smtpPassword, a.SmtpCfg.smtpAuthHost)<br>	err := smtp.SendMail(a.SmtpCfg.smtpSendHost, auth, a.SmtpCfg.smtpUser,<br>		[]string{a.SmtpCfg.notificationRecipient}, []byte(msg))<br>	if err != nil {<br>		zap.S().Errorf(&quot;Error sending notification email: %v&quot;, err)<br>		return err<br>	}<br>	return nil<br>}</pre><p>Which will send a message like this:</p><blockquote><em>Sensor unit_test encountered the following threshold failure at 2021–07–01T10:00:00: Temperature: 4 (Thresholds: Min: 5 / Max: 40) Moisture: 1.5 (Thresholds: Min: 2.2 / Max: N/A)</em></blockquote><p>Useful! As we’ll see below, 40C is pretty low, but that can always be adjusted.</p><h3>Re-Deploying the Pi Zero W</h3><p>Now that we have all software up-to-date, it’s time to set up a new Raspberry Pi Zero W.</p><h3>Physical Assembly</h3><p>This one’s simple: I slapped an aluminum heatsink on it (potentially pointless, but I do have those lying around — I have no idea how hot it’ll get outside) and soldered the I2C headers onto some pins.</p><p>Part of the reason the Pi Zero is so cheap is the fact that you need to solder the pins yourself - which I did &quot;upside down&quot; (as if to put the Pi onto a breadboard) in order to save space for the final design. The idea here is to slap the breadboard onto the back of the board, without obstructing the APU and hence, without creating a thermal nightmare for the little Pi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kWqqLjz7bgjv9lnK.jpg" /><figcaption>Pi Zero — I ran out of pins (by author)</figcaption></figure><p>Of course, one could solder the cables on the Pi directly, but I wanted to leave room for potential adjustments down the road. As you’ll see in a bit, that was a wise choice.</p><h3>Software Deployment</h3><p>Now, of course, I was thinking about writing an actual deployment pipeline, or even to build Docker images — but when faced with a conflict between “fishing on the lake and doing nothing” and “configuring CI/CD from scratch”, the former (fortunately) wins.</p><p>First, use <a href="https://www.raspberrypi.org/blog/raspberry-pi-imager-imaging-utility/">Raspi Imager</a> to install a Raspbian OS. This should mount boot and root onto your PC.</p><p><em>chroot, in case you&#39;re not familiar, is like </em><em>docker, just not as hipster. :)</em></p><p>First, enable ssh by doing a touch ssh onto the mount point of boot.</p><p>Then, to enable WiFi, copy your existing /etc/wpa_supplicant/wpa_supplicant.conf onto the same partition. If you don&#39;t have one or use macOS/Windows customize this:</p><pre>ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev<br>update_config=1<br>country=US<br><br>network={<br>       ssid=&quot;YourNetworkSSID&quot;<br>       psk=&quot;Password&quot;<br>       key_mgmt=WPA-PSK<br>    }</pre><p>Then, chroot the main partition:</p><pre>sudo proot -q qemu-arm -S /media/$USER/rootfs</pre><p>And run this setup script:</p><pre>#!/bin/bash<br><br>if [[ $EUID -ne 0 ]]; then <br>    echo &quot;This script must be run as root&quot;<br>    exit 1<br>fi<br><br>if [[ -z &quot;${PI_IP}&quot; || -z ${PI_DNS} || -z ${REST_ENDPOINT} || -z ${PI_ROUTER} ]]; then <br>    echo &quot;Usage: PI_IP=192.168.1.2 PI_ROUTER=192.168.1.1 PI_DNS=8.8.8.8 REST_ENDPOINT=http://server.local:7777 ./setup_pi_zero.sh&quot;<br>fi <br><br># Install dependencies<br>apt-get update<br>apt-get install git python3 python3-pip python3-venv i2c-tools vim ntpdate<br><br># Enable I2C, SPI<br>echo &quot;Enable I2C and SPI manually by running raspi-config over ssh&quot;<br>#raspi-config <br><br># Static IP<br>echo &quot;interface wlan0&quot; &gt;&gt; /etc/dhcpcd.conf<br>echo &quot;static ip_address=${PI_IP}/24&quot; &gt;&gt; /etc/dhcpcd.conf<br>echo &quot;static routers=${PI_ROUTER}&quot; &gt;&gt; /etc/dhcpcd.conf<br>echo &quot;static domain_name_servers=${PI_DNS} 1.1.1.1 fd51:42f8:caae:d92e::1&quot; &gt;&gt; /etc/dhcpcd.conf<br>echo &quot;nameserver ${PI_DNS}&quot; &gt;&gt; /etc/resolv.conf <br><br># Time<br>timedatectl set-timezone America/New_York<br>timedatectl set-ntp True<br><br># Clone code <br>cd /home/pi<br>mkdir -p /home/pi/workspace<br>cd /home/pi/workspace<br>git clone https://github.com/chollinger93/raspberry-gardener<br>cd raspberry-gardener/client<br>SENSORS=&quot;temp lumen moisture&quot; # Customize<br><br># Install <br>mkdir -p /opt/raspberry-gardener<br>touch /opt/raspberry-gardener/.env.sensor.sh<br>echo &quot;REST_ENDPOINT=$REST_ENDPOINT&quot; &gt; /opt/raspberry-gardener/.env.sensor.sh<br>echo &quot;SENSORS=$SENSORS&quot; &gt;&gt; /opt/raspberry-gardener/.env.sensor.sh<br>cp monitor.py /opt/raspberry-gardener/<br>cp -r max44009/ /opt/raspberry-gardener/<br><br># Install packages as sudo if the sensor runs as sudo<br>pip3 install -r requirements.txt<br><br># Systemd<br>mkdir -p /var/log/raspberry-gardener/<br>cp garden-sensor.service /etc/systemd/system/<br>systemctl start garden-sensor<br>systemctl enable garden-sensor # Autostart<br><br># logrotate.d<br>cat &gt; /etc/logrotate.d/raspberry-gardener.conf &lt;&lt; EOF<br>/var/log/raspberry-gardener/* {<br>    daily<br>    rotate 1<br>    size 10M<br>    compress<br>    delaycompress<br>}<br>EOF</pre><p>And run:</p><pre>export PI_IP=192.168.1.2 <br>export PI_DNS=8.8.8.8 <br>export REST_ENDPOINT=http://server.local:7777 <br>./setup_pi_zero.sh</pre><p>Of course, you could do that over SSH as well — which would be easier, but slower. raspi-config, however, must be run on an actual device, as it loads Kernel modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*xG5X1Q2fQvxZshtX.png" /><figcaption>raspi-config (by author)</figcaption></figure><p>You might also want to customize the logrotate config in /etc/logrotate.d:</p><pre>/var/log/raspberry-gardener/* {<br>    daily<br>    rotate 1<br>    size 10M<br>    compress<br>    delaycompress<br>}</pre><p>We only need to run this once and dd the entire SD card to another Pi, or run it on each Pi - it doesn’t really make a difference.</p><p>If you want to dd, I suggest you do that after booting the Pi and running sudo raspi-config:</p><pre>sudo umount /media/$USER/rootfs<br>sudo umount /media/$USER/boot<br><br>sudo dd of=$HOME/$(date --iso)_raspberry_rootfs.img if=/dev/mmcblk0p2 bs=4M<br>sudo dd of=$HOME/$(date --iso)_raspberry_boot.img if=/dev/mmcblk0p1 bs=4M</pre><p>Having an image is useful, so you might want to do this once it’s working.</p><h3>A Quick Test</h3><p>At this point, it would be advised to test the entire setup, for instance looking at the load:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*08976zQibB-RxE0-.png" /><figcaption>Pi Zero Load (by author)</figcaption></figure><p>And maybe check out Grafana, as the service will start running once you enable I2C and SPI via raspi-config.</p><h3>Building a new Enclosure</h3><p>Let’s get to building a new case!</p><p>Originally, I wanted to “remix” (fork) an existing Pi Zero enclosure, like <a href="https://www.thingiverse.com/thing:2171313">this</a> one, but quickly learned that my CAD skills are way too fresh to work on actually functional models. So I started from scratch.</p><h3>Test Assembly</h3><p>Before anything else, we must assemble the whole thing without a case to get a feel for how everything will fit together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZJ1LcUhTlgFwCKuz.jpg" /><figcaption>Breadboard Assembly (by author)</figcaption></figure><h3>Take Measurements</h3><p>Next, I used some decently accurate calipers to measure all dimensions and drew some rough ideas on paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*CXEjRJa1EpcsBCFL.jpg" /><figcaption>Measurements (by author)</figcaption></figure><p>I will spare you from seeing the rough sketches.</p><h3>Foray into CAD</h3><p>There are a lot of options available when it comes to CAD — but I chose Autodesk’s free <a href="https://www.tinkercad.com/">Tinkercad</a>, because it’s pretty simple. Fusion 360 does have a free version for personal use, but it doesn’t run on Linux.</p><p>While I can’t <em>stand</em> browser-based tools (eLeCtrOn wEb aPpS), they are sometimes easier than trying to force other software to play nice with Linux. It is what it is, as they say.</p><p>Anyways, Tinkercad is aimed at hobbyists and students and comes with a colorful tutorial, which even I understood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mgSSD3k2aDLLY7Oe.png" /><figcaption>Tinkercad (by author)</figcaption></figure><h3>The Design (v.1.0)</h3><p>My design was very, very simple — but that might be because it was my first CAD design I’ve ever built — I am usually the type to measure once, cut twice.</p><p>Fun Fact: There’s a little piece of 2x4 in my shed with measurements written on it in sharpie. They do not match the 2x4’s dimensions at all. That’s all you should know — but, it usually works out. I did build all the raised beds on this property, after all!</p><p>Well, turns out, CAD needs more prevision than a circular saw. The idea behind the design isn’t much different to other, commercial cases: 4 Pins stick together to hold the case together. Small cutouts support the exact placement of cables I need — just less cutouts than commercial cases. Also, the case has a lot more wasted space than it needs to, to support dupont cables without the need to solder things directly onto the headers.</p><p>Once I had something resembling a model based on these ideas and measurements, I exported the .stl file, loaded it into Cura and got to printing.</p><p>Naturally, I messed up the print settings and over-estimated the capabilities of the printer (which, ultimately, are dependent on the slicer settings) — the little support beams turned to spaghetti.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*wy8m5XpqldMp5oBh.png" /><figcaption>Print in progress (by author)</figcaption></figure><p>I also realized that the tolerances that I measured were a little too detailed for the print settings I set up in Cura, and I messed up other measurements altogether — in other words, the design wasn’t very good.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jWx8EqP8-P88rGt6.jpg" /><figcaption>That doesn’t fit (by author)</figcaption></figure><h3>Design (v2.0)</h3><p>The second design followed a different philosophy: Larger tolerances that can be filled in later.</p><p>It also avoided flimsy support beams and relied on a top piece that was ever so slightly smaller than the bottom. It also moved the cutout for the moisture sensor to the top, giving the fit more play.</p><p>Last but not least, it added 2 support pyramids for the Pi itself, so it could sit safely on the bottom of the enclosure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D36OdGwa2uQLwfTx.png" /><figcaption>2nd design (by author)</figcaption></figure><h3>The Waterproofing Issue</h3><p>One thing was unfortunately not solved by this design: Water (or weather) proofing.</p><p>Now, while a purpose-built case will undoubtedly be a better fit than any commercial case (if you’d be able to find that that fits all the components), designing and printing something that takes seals and has very little tolerances is not within my current CAD skillset.</p><p>There are alternatives, however — namely <em>nail polish</em> and electrical tape, which I already used liberally last time. Nail polish is not electrically conductive, creates a good seal, but isn’t particularly heat safe — supposedly until about 120C (248F). Given that this will only be applied to the 2 external sensors, I am not terribly worried about that part — I don’t think my peppers are that heat-safe.</p><p>While I don’t plan to douse the entire Pi in nail polish, we can somewhat weather-proof the sensors, which <em>have</em> to be outside the case for accurate measurements. The connection between the sensors and the case are precise enough to be sealed with, you guessed it!, electrical tape.</p><p>There have been a lot of smart experiments conducted, regarding nail polish as a conformal coating alternative — from what I can tell, it works, but since there is no standard nail polish formula (as I found out at my local Kroger), some additives might mess with the plastic on the PCB.</p><p>Of course, if you foresee never having to access the Pi again, one could douse the entire thing in resin or silicone as well — but we’ll stick to nail polish for now.</p><h3>Assembly</h3><p>With the 2nd design printed, assembly was relatively straightforward: Just throw everything in, accept some design flaws for now and use more electrical tape for keeping it in place, and place the sensors into the top cutouts.</p><p>Naturally, everything being on a breadboard caused an issue everybody who built a desktop PC before knows to well — cable management. It was tight with standard-length cables, to say the least:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1d-eNRLLSB_VcoWB.jpg" /><figcaption>First assembly (by author)</figcaption></figure><p>Options here include crimping some tiny cables myself or buying smaller cables. Or, of course, the school of redneck engineering always helps: De-sleeve a cable and tin the end with a soldering iron until it fits into the breadboard’s slot (believe it or not, this works). A roll of 24AWG wiring would work too.</p><p>While I’m not trying to tell you how to live your life, I may be able to offer a word of advice: It is not worth spending an hour trying to frankenstein cables together and inhaling a lot of bad fumes while doing so, just to save $10 for a handful of wires. Or so I heard. Version 3.0 down below heeds some of that advice.</p><p>One related issue were the moisture sensors — I didn’t account for long dupont end pieces in that spot. So I did what any sane person would do and just de-sleeved some cables and soldered them onto the PC directly, rather than doing another 4+hr print for ~5mm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*cmstgq9ruoNIDK9h.jpg" /><figcaption>It works™ (by author)</figcaption></figure><h3>Beta Testing Outdoors</h3><p>With all that out of the way and the new backend service deployed (stop the systemd service, re-compile from git, copy the new binary over, and re-start the service - adjust the .env.sh file if you want emails), we are ready to test!</p><h3>Finding a spot</h3><p>For this test, I moved the little box onto the deck first to keep watch over some of our pepper plants, namely a tremendously happy Capsicum Chinense “Habanero” (also just known as “Habanero Pepper” if you’re a normal human being).</p><p>The only issue left is still the one of power delivery — I don’t own an waterproof USB power brick.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-BY_lhwnAn38CoHo.jpg" /><figcaption>First Outdoor Test (by author)</figcaption></figure><p><em>(Ignore the tape — see the cable comment above — the next iteration won’t need it)</em></p><p>In any case, I threw the box out there at about noon before heading off to buy pesticides to try and save about 30 cauliflower plants from pests, as well 10 cu-ft of mulch, because obviously, the garden-ride never stops.</p><p>Before leaving though, a quick peak at the database shows that the little box starts collecting data as soon as it gets power, thanks to the systemd service (I&#39;d call that &quot;plug and play&quot;).</p><p>And after about 2 hours, we can find good data for Light and Temp:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/0*i8hA7-VgII9bsCbk.png" /><figcaption>Lumen on the deck (by author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/0*YtZswmL13vOxs6E2.png" /><figcaption>Temp on the deck (by author)</figcaption></figure><p>We can see some seriously impressive peaks here — over 60C (140F) in direct sunlight (much higher than the 40C peak we configured in the backend!). This isn’t overly surprising — cars parked in the sun can reach similar temperatures (in hindsight, that would explain why my truck seemingly tries to boil my sunglasses practically every day).</p><p>However, we can see that the ADC didn’t collect data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/0*iWWZJ3Ah10SrMzzU.png" /><figcaption>Broken Moisture Sensor (by author)</figcaption></figure><p>Which, turns out, was an invalid pin wiring on the MCP3008 - so we get voltage fluctuations reading as data. Please see <a href="https://chollinger.com/blog/2021/04/raspberry-pi-gardening-monitoring-a-vegetable-garden-using-a-raspberry-pi-part-1/#analog-sensors--soil-moisture">Part 1</a> for a deep dive on that - the summary is, an ADC will always report values, even if they&#39;re not really based on anything.</p><h3>Fine-Tuning and Troubleshooting</h3><p>After fixing that mistake, I also printed the top case another 10mm taller, although that didn’t solve all problems — the case was still a very tight fit and some printing imperfections made fitting both parts together not easier.</p><p>It also happened way too often that some of the dupont cables fell out during assembly — something you’d only realize once the whole thing is sending data.</p><p>I2C and SPI are also especially charming in that regard, because once there is current on the data or sync line, they show up as connected, despite there maybe being no power on the sensor (because the cable decided to fall out). The sheer size of the 10–20cm cables got in the way too often.</p><p>This won’t do.</p><h3>Version 3.0 and Deployment</h3><p>This would be the final version for the purpose of this article.</p><h3>Assembly</h3><p>The only way I could use to optimize this was to actually solder everything together with regular standard 24 AWG wire directly, as well as using some 50mm dupont cables — reducing the wire length and density around all connections that are not on the breadboard itself (as it’s easy to use jumper wires here).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kgw11be4U_iosLFU.jpg" /><figcaption>Final Assembly (by author)</figcaption></figure><p>More on that later.</p><h3>A Final Test Indoors</h3><p>Finally, the little box was ready for its deployment in the (literal) field. Before doing that, though, I left it run over night hooked up to a low-light plant in the kitchen, to make sure everything worked properly for the last time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kLHr5PGl-iEFxPeH.jpg" /><figcaption>Indoor Test (by author)</figcaption></figure><p>Which I’m sure glad I did, because if you short SDA and SCL, this is what i2detect does:</p><pre>pi@raspberrypi:/var/log/raspberry-gardener $ sudo i2cdetect -y 1<br>     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f<br>00:          03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f <br>10: 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f <br>20: 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f <br>30: 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f <br>40: 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f <br>50: 50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f <br>60: 60 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f <br>70: 70 71 72 73 74 75 76 77</pre><p>Oh well. ヽ(´ー` )┌</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aEuDkauVV4q_PG_n.png" /><figcaption>Indoor Monitoring (by author)</figcaption></figure><p>Indoors, especially at night, the only somewhat relevant metrics are temperature — 25C/77F seems reasonable with the AC off at night — and soil moisture, which won’t change that quickly. As we remember from the last article, 1.5V is “damp soil”. It works!</p><p>Lumen is constantly at zero, however — please see <a href="https://chollinger.com/blog/2021/07/raspberry-pi-gardening-monitoring-a-vegetable-garden-using-a-raspberry-pi-part-2-3d-printing/#data-analysis--reminders">below</a> for an attempt at explaining that.</p><h3>Outdoor Deployment &amp; Data Collection</h3><p>The next morning around 8:30am, I finally deployed the little green box inbetween my carrots and cucumbers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gbcAeWEhVl2l6ekO.jpg" /><figcaption>Outdoor Deployment #1 (by author)</figcaption></figure><p>Godspeed, little one!</p><h3>Data Analysis &amp; Reminders</h3><p>And what a day it had! I turned off the RasPi at around 10:30pm, after a gorgeous evening with many a magical firefly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K596U7grheYH-uaH.jpg" /><figcaption>Shortly before the little Pi got to go to bed (by author)</figcaption></figure><p>So let’s take a look at all the metrics throughout the day!</p><h4>Lumen/Light</h4><p>This one is really interesting — you can see the peak at about 900 Lux.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/0*oT58fLzWON2_tRg2.png" /><figcaption>Light (by author)</figcaption></figure><p>Now, looking at Wiki, 900 lux is roughly an “Overcast day”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*09KjHi6TvwIwXlG1.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Lux">https://en.wikipedia.org/wiki/Lux</a></figcaption></figure><p>The whole scale is logarithmic, so looking at values &lt;= 0 is a bit of a challenge with Grafana — we can, however, find those values on the database. However, looking at the sensor’s <a href="https://datasheets.maximintegrated.com/en/ds/MAX44009.pdf">spec sheet</a>, I don’t think values &lt;= 0 should be regarded as valid (as the python program on the Pi is running with fairly standard settings).</p><p>Also -</p><blockquote><em>The illuminance provided by a light source on a surface perpendicular to the direction to the source is a measure of the strength of that source as perceived from that location.</em></blockquote><blockquote><em>For instance, a star of apparent magnitude 0 provides 2.08 microlux (μlx) at the Earth’s surface.</em></blockquote><blockquote><em>A barely perceptible magnitude 6 star provides 8 nanolux (nlx). The unobscured Sun provides an illumination of up to 100 kilolux (klx) on the Earth’s surface, the exact value depending on time of year and atmospheric conditions.</em></blockquote><blockquote><em>This direct normal illuminance is related to the solar illuminance constant Esc, equal to 128000 lux (see Sunlight and Solar constant)</em></blockquote><p>So the angle — that being parallel to the ground — might have played quite a big role. As any measurement of a I2C sensor is relative by nature, let’s take a look at…</p><h4>Temperature</h4><p>….the temperature and see if we can correlate the two to compensate for less-than-ideal calibrations. The iOS weather app said 84–86F during the day (29–30C), which is a pretty average summer day around here.</p><p>Looking at the sensor’s metric, we’ll find peaks of up to 50C (122F), which correlate to the peaks in lumen, but are not nearly as strong as they were on the deck (which is, if you recall from part 1, right above the observed raised bed):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/0*efLC-du2KWlUF6D1.png" /><figcaption>Temperature (by author)</figcaption></figure><p>So we can reasonably conclude: The carrots, cucumbers, and bell peppers under observation do <em>not</em> get 6 hours of full sunlight a day (the common metric for “full sun”), but closer to ~3hrs, which would qualify as “part sun”. All the hot peppers, however, get to deal with 60C+ and ~1.5k lumen — which probably explains why they’re growing at the rate they are, mere feet away from the other plants.</p><h4>Moisture</h4><p>This one is rather boring — while I did water the beds at around 5:30pm, given the sheer volume of top soil (they are raised beds, after all), a couple of gallons across ~50sqft probably didn’t make a difference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/0*K7GS82AoffZd2YRi.png" /><figcaption>Moisture (by auhor)</figcaption></figure><p>Unless you water the specific spot where the prongs are, the measurement won’t change too much, unless the entire bed is dried out, at which point you probably shouldn’t be looking at Grafana, but be out there with a watering can or a hose in your hand.</p><p>They do work well on small pots, however — in raised beds, maybe a different method might be in order.</p><h3>Criticism and next Steps</h3><p>Let’s to another retrospective after all those improvements — or at least, something of the sort.</p><p>The new enclosure turned out to be a bit of a Frankenstein — I do have some solderable mini breadboards on the way, but at the time of writing, I did not — so it’s a mix of soldered cables, semi-fixed connections, and electrical tape. Connections to get lose and cause issues, and it’s hard to figure out why, as a single strand of copper can short it. The i2c lanes especially are loose all the time.</p><p>But the box does finally close and due to the lack of precision (0.2/0.4mm print with PLA @ 210C), sticks together really, really tight (which is good!). It is impossible to tell whether it’s on, though — a status LED would be a good addition.</p><p>I also only have one MCP9808 here, so short of de-soldering the pins or soldering wires onto them, I had to use more DuPont cables here. It does work fairly well though, as they keep the sensor in place without a special enclosure.</p><p>Besides the mix of cables, the (new) Pi also flops around a bit, needing to be held in place with tape, as my little pyramid-spacers only apply pressure from the bottom, and my precision measuring, designing, and printing skills leave too much to be desired to do anything complicated. Folks with a lot more experience under their belt have built some amazing cases, however — so there’s something to strive towards.</p><p>All things considered, it’s far from perfect, but still pretty a-OK, considering my starting position. But like so many things, one can always optimize away further and further.</p><p>In this <em>case</em> (heh), I’ll probably try and work on a version 4.0, but mostly for my own enjoyment. In terms of functionality, it’s already there: It fits together, it works, it’s small at 75.8x54.7x57.5mm, and with a bit of sealant around the sensor spots, I’m pretty sure its decently weather-proof.</p><p>When it comes to software, I actually have nothing to complain about (apart from code quality, which wasn’t the focus of this project). The base image on the SD card we built earlier works like a charm (I tested it by using a fresh Pi for the soldered version), and the Pi starts the service on boot, doesn’t run hot, therefore doesn’t use a ton of resources, and just does what it’s told.</p><p>So, in summary, an eventual version 4.0 should -</p><ul><li>Have a little status LED</li><li>Don’t rely on DuPont connectors, anywhere</li><li>Use soldered connections and no breadboards</li><li>Keep the Pi safely in place</li><li>Maybe provide more purpose-built enclosures for the sensors themselves</li><li>And be a lot more sturdy overall</li></ul><h3>Conclusion</h3><p>Well, I must say, I enjoyed this project quite a bit, and probably more than previous ones. Granted (and I’ve said it before), I wouldn’t exactly describe it as <em>necessary</em> — but I’d also wager that growing that many vegetables and then turning them into pickles (because 2 people can’t eat that much) or lacto-fermenting peppers into hot sauce (for the same reason), or smoking and curing my own bacon (for the reasons of store-bought bacon being rather lackluster) is <em>necessary</em>, especially if you have a grocery store 10 minutes away from the house.</p><p>However, if we ignore the time and money spent on it, the resulting green box is actually pretty useful: It does take a lof of guesswork out of the gardening work. Sure, it doesn’t solve many of the other problems, like the poor Sugar Snap Peas that succumbed to a fungus — but it does supply interesting data.</p><p>Take a look at those guys, for instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*tACWSD3deggjPPKk.jpg" /><figcaption>Small carrots (by author)</figcaption></figure><p><em>Daucus carota</em> should have matured, i.e. be around 5&quot; long and 1 1/2&quot; across, 10–20 days before this picture was taken. Carrots enjoy full sun — and where they’re sowed, presumably, they won’t get full sun. With the power of technology, I probably won’t plant them down there again, because I now know, that they don’t get the ~6hrs of full sun they need.</p><p>On a more broader level, however, this was also an amazing learning experience throughout. If you spend your day job as a Software Engineer (or anything vaguely related), be it Junior or Principal, you might be in the same position I found myself in: You have no idea how electronics, computer aided design, soldering, middle school physics, I2C/SPI, or any of the above really work. It’s simply not part of the daily job, albeit technically pretty closely related to that.</p><p>However, as the last few sections of this article demonstrate, the whole process is also very (and I hate myself for using the word) <em>agile</em>. The product is never finished, but at a certain point (in my case, near the end of my staycation), an MVP must be delivered — even though I have a lot to complain about (i.e., a lot to improve). Having this particular mindset is a core attribute of a good engineer, at least in my opinion.</p><p>You will probably notice this iterative approach while reading the article, as I wrote sections shortly after I worked on the thing, as opposed to supplying a summary at the end — so you can follow this journey along, if you are so inclined.</p><p>Going through a project like this, meaning starting from scratch and figuring things out as they come along, all the way to integrating it with known technologies (from a Data Engineering perspective, specifically go, SQL, python) is just… <em>neat</em>. It&#39;s a fun way of using existing skills, enhancing them, and learning a lot of completely new things along the way, and much more so than &quot;just&quot; a software project (unless it&#39;s TempleOS, maybe).</p><p>In any case — I hope you learned something as well or, at the very least, found this journey as entertaining to read as I found building it.</p><p>And if you want to build one yourself: All code is available on <a href="https://github.com/chollinger93/raspberry-gardener">GitHub</a>. You can also find all <a href="https://github.com/chollinger93/raspberry-gardener/tree/master/cad">CAD</a> files there.</p><p><em>All development and benchmarking was done under GNU/Linux [PopOS! 20.10 on Kernel 5.11] with 12 Intel i7–9750H vCores @ 4.5Ghz and 16GB RAM on a 2019 System76 Gazelle Laptop, as well as a Raspberry Pi Zero W, using </em><a href="https://chollinger.com/blog/2019/04/building-a-home-server/"><em>bigiron.local</em></a><em> as endpoint</em></p><p><em>Originally published at </em><a href="https://chollinger.com/blog/2021/07/raspberry-pi-gardening-monitoring-a-vegetable-garden-using-a-raspberry-pi-part-2-3d-printing/"><em>https://chollinger.com</em></a><em> on July 3, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40471bd061dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/raspberry-pi-gardening-monitoring-a-vegetable-garden-using-a-raspberry-pi-part-2-3d-printing-40471bd061dc">Raspberry Pi Gardening: Monitoring a Vegetable Garden using a Raspberry Pi — Part 2: 3D Printing</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Raspberry Pi Gardening: Monitoring a Vegetable Garden using a Raspberry Pi — Part 1]]></title>
            <link>https://medium.com/data-science/raspberry-pi-gardening-monitoring-a-vegetable-garden-using-a-raspberry-pi-part-1-fd231c7c6275?source=rss-7af40a2161c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd231c7c6275</guid>
            <category><![CDATA[gardening]]></category>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <dc:creator><![CDATA[Christian Hollinger]]></dc:creator>
            <pubDate>Sun, 25 Apr 2021 00:00:00 GMT</pubDate>
            <atom:updated>2021-06-17T14:23:28.861Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/hands-on-tutorials">Hands-on Tutorials</a></h4><h3>Raspberry Pi Gardening: Monitoring a Vegetable Garden using a Raspberry Pi — Part 1</h3><h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s5cDup0Lzv5TIGpR.png" /><figcaption><em>A journey through the project; </em>CC BY-SA 3.0 / <a href="https://chollinger.com/blog/2021/04/raspberry-pi-gardening-monitoring-a-vegetable-garden-using-a-raspberry-pi-part-1/">chollinger.com/blog</a></figcaption></figure><p>Like many others during a certain time period around 2020/2021 (in case you’re reading this on holotape, captured in an arctic vault, during your “Ancient American History” class in the year 3000 — I am talking about Covid-19), both my SO and I found joy in gardening and growing vegetables.</p><p>While the hobby of growing plants might be a joyful one in theory, I think the best description of gardening I heard was “It’s 80% pain, 15% worry, and 5% victory and satisfaction, and 100% waiting”. There are simply a lot of things that you need to take into account — sun exposure, pH content of your soil, nutrients in your soil, pests, fungi, squirrels, deer, birds (and all sorts of critters) — and naturally, all of those are different for each type of plant.</p><p>Because of this inherent complexity, there have been a lot of struggles with growing things. Radishes that I failed to thin properly and that produced sad little sticks, rather than voluptuous bulbs; cucumbers, tomatoes and pumpkins eaten away by blight, squirrels attacking and digging out seeds, aphids descending upon everything leafy and green like a biblical plague, frost damage where there shouldn’t have been any frost damage to a poor aloe, monkey grass (liriope muscari) taking over raised beds, and plants growing in odd shapes before finally dying off due to a lack of sunlight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*kVIJv5-RnKuag1in.jpg" /><figcaption>Sad bulb (by <a href="https://chollinger.com/blog/2021/04/raspberry-pi-gardening-monitoring-a-vegetable-garden-using-a-raspberry-pi-part-1/">author</a>)</figcaption></figure><p>For a lot of those problems, we’ve found analog solutions: A cage of bird netting on a frame of PVC pipes, constructed using cable ties, Alan Jackson songs, and cheap beer against squirrels (believe it or not, it actually works, and you can see it in the “Sad Bulb” picture above). Praying mantis eggs against aphids. Weed barriers against liriope and other weeds. Copper fungicide against fungi.</p><p>Some things, however, are still plaguing me and keep me up at night. Naturally, there is only one solution to this: Using technology where one should not use technology to collect data where one does not need to collect data, and of course doing all of it in the most over-engineered way possible.</p><h3>Scope</h3><p>So what are we going to do?</p><h3>Overall Idea</h3><p>I took this opportunity of a semi-real need to finally gets my hands dirty in the world of physical electronics and micro-controllers. <strong>This is a topic that is entirely new to me</strong>, and given that I am the worst “learning by doing”-type person you could think of, there was no better opportunity than this to haphazardly soldering together some circuits to collect data.</p><p>So if you are reading this with at least a bit of experience in the field of electronics, microcontrollers, or gardening, for that matter — my email for complaints can be found on my website.</p><p>If you are more like me, though, and haven’t dabbled in the <em>real world</em> of electronics at all, you might find this interesting.</p><h3>Architecture</h3><p>Anyways, data is what I am after here — data on sun exposure, soil moisture, and temperature. This is actually a bit of an interesting question, because these metrics are hyper-localized and can be entirely different only a couple of feet away.</p><p>So we’ll be collecting metrics like soil moisture, sun exposure UV, plus metadata like device ID and timestamp, send it to a server on the network using a REST API (<a href="https://chollinger.com/blog/2019/04/building-a-home-server/">bigiron.local</a>, of course), store it in MariaDB, and analyze it using Grafana.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/0*ixBAC98LYiu8nCdY.png" /><figcaption>Architecture (by author)</figcaption></figure><h3>Data Points</h3><p>Here’s how 3 of our 6 total raised beds are layed out (not at all to scale):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/0*mOWN0kEKgw0YRpBa.png" /><figcaption>Real world layout (by author)</figcaption></figure><p>These beds are on the south side, but are also lodged in-between 2 cars, a deck, and a toolshed and flanked by trees. While, in theory, these beds should be getting ample sun, it is hard to estimate how much sun they actually get. Last year, we planted herbs down there that were “part to full sun”, such as lavender, that unceremoniously died. You can grow bell peppers though — which, just like their counterparts in the spheres of <em>capsaicin annum</em> and <em>capsicum chinense</em>, actually do need quite a bit of sun.</p><p>Soil moisture is also surprisingly hard to measure: You might stick your finger in the soil, but that doesn’t necessarily mean it’s actually “young carrot”-wet. It might just be “the citrus tree doesn’t care”-wet. Quantifying this as well would be a bonus.</p><p>Temperature and humidity are pretty obvious — I’ve actually built a little thing with the “Shortcuts” app on my iPhone to alert us of cold fronts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jwnLorrA0zDsPC3f.jpg" /><figcaption>iOS Shortcuts (by author)</figcaption></figure><p>But of course, that is <em>way too easy</em>.</p><h3>Components</h3><p>The idea for this is pretty simple: A Raspberry Pi powered (simply because I have several) machine that can capture these metrics and send them to a sever, so we can use the good ole Data Engineering toolbox to learn all there is to know about the far distant, real world out there.</p><p>For this, I chose the following components:</p><ul><li><strong>Temperature</strong>: <a href="https://www.adafruit.com/product/1782">MCP9808 High Accuracy I2C Temperature Sensor</a> — $4.95</li><li><strong>UV</strong>: <a href="https://www.adafruit.com/product/1777">SI1145 Digital UV Index / IR / Visible Light Sensor</a> — $9.95</li><li>or <a href="https://www.adafruit.com/product/2899">Adafruit VEML6070 UV Index Sensor Breakout</a> — $5.95</li><li><strong>Light</strong>: <a href="https://www.adafruit.com/product/4162">Adafruit VEML7700</a> (up to 120k lux) — $4.95</li><li>or <a href="https://www.adafruit.com/product/1980">Adafruit TSL2591</a> (up to 88k lux) — $6.95</li><li>or the <a href="https://smile.amazon.com/NOYITO-MAX44009-Intensity-Interface-Development/dp/B07HFRS8XX">NOYITO MAX44009</a> — $5.99</li><li><strong>Moisture</strong>: <a href="https://smile.amazon.com/gp/product/B076DDWDJK/ref=ppx_yo_dt_b_asin_image_o01_s00?ie=UTF8&amp;psc=1">Any resistive humidity sensor</a> — $4.99 — $8</li><li>Any Raspberry PI you have lying around, like a <a href="https://www.microcenter.com/product/486498/zero-v13-development-board---camera-ready?storeid=041">Raspberry Zero</a> or the fancy <a href="https://www.microcenter.com/product/609038/raspberry-pi-4-model-b-4gb-ddr4">Raspberry Pi 4 Model B</a> — or the tiny <a href="https://www.raspberrypi.org/products/raspberry-pi-pico/">Pico</a> — $4.99 — $54.99</li><li>A soldering iron, jumper cables, LEDs, breakout boards etc.</li></ul><p>There are, naturally, tons of options here — but with a minimal setup, we could build one of those sensors for ~$25 a pop (and less when ordering them in bulk, of course). I’ll be covering the different types of sensors below.</p><p>I personally do not overly care about cost for this iteration — while it would be fun to have one deployed at all time, that also requires a wired power connection (or lithium batteries), an internet connection, and a waterproof case. All these things might make it worth buying a 3D printer for me (and to squeeze another article out of this), but for the scope of this article, I’ll be focussing on actually building it.</p><h3>An analog circuit</h3><p>But before we do any of this: I personally haven’t dabbled in electronic since <em>middle school</em> — so it’s been a while.</p><p>Naturally, I went “back to basics” and started building a really simple circuit: Powering an LED.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*h_NVMmQ5qkssssUY.jpg" /><figcaption>A simple LED circuit (by author)</figcaption></figure><p>This was a good exercise to remember some fundamentals. An standard LED circuit looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*iskyLXix8Cd4IfEC.png" /><figcaption>A simple LED circuit diagram (<a href="https://en.wikipedia.org/wiki/LED_circuit">https://en.wikipedia.org/wiki/LED_circuit</a>)</figcaption></figure><p>Because we need to limit the current hitting the LED using a resistor, in order to prevent it from burning out.</p><p>In order to find the right resistance, we can use:</p><p>R = (V_power - V_led) / I_led</p><p>where R is the resistance in ohms, V_power is the power supply voltage in volts, V_led is the LED forward voltage drop across the LED in volts, and I_led is the desired current of the LED in amps.</p><p>For a red LED, we’ll be looking at 2–2.2V at a 20mA current, i.e. on a 5V power supply (as shown above), a 93Ω resistor would do the trick (closest one I have was a 100Ω one). For a blue LED, we’d be looking at 3.2–3.4V, so a 54Ω resistor (and so on and so forth).</p><p>It’s fun to play around with this — but for the record, I’ve used a 330Ω for most of the pictures you’ll see.</p><p>Also, the little power supply you see on the picture is pretty neat (a <a href="https://www.cafago.com/en/p-e8575.html">HW-131</a> for $2), as it can take 3.3V and 5V and power via a PSU, batteries, or USB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ARU95hGqRCMiP19Y.jpg" /><figcaption>Multimeter (by author)</figcaption></figure><h3>Using the Raspberry &amp; GPIO</h3><p>The real fun begins once we start controlling the thing via the Raspberry. However, before the “controlling” parts start, we can start by simply connecting the a 3.3 or 5V pin to the same circuit.</p><h3>Pin Layout</h3><p>For this <a href="https://pinout.xyz/">pinout.xyz</a> is a handy resource: It shows you the layout of your respective Raspberry. Generally, it looks as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*k5d9JoKV_egVhzEK.png" /><figcaption>from <a href="https://pinout.xyz/">pinout.xyz</a></figcaption></figure><p>Adafruit seels a handy-dandy little connector piece, the <a href="https://www.adafruit.com/product/2028">T-Cobbler</a>, that extends those pins and labels them for use on a breadboard.</p><p>Equipped with this knowledge, we can connect pin 1, 2, 4, or 17 as well as a ground of our choice and get pretty lights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*oE4BGaMTjRiJQ40g.jpg" /><figcaption>Digital I/O (by author)</figcaption></figure><p>However, this is still analog, just getting a power source from a computer. In order to control it via software, we’ll be using GPIO, or “General Purpose Input/Output”. The aptly named library can address all GPIO pins.</p><p>The simplest way to address those is to give one of 2 inputs: GPIO.HIGH (3.3V) or GPIO.LOW (0V).</p><h3>Exercise: Morse Code</h3><p>A fun little exercise I’ve done to use this knowledge was to write a morse-code sender using GPIO and the following circuit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Py_AFrGQG5cNGZUn.png" /><figcaption>Morse code circuit (by author)</figcaption></figure><p>Which is pretty much the same as the LED one, just with an added speaker and a UV LED for indicating a complete “send”. The version in the gif below also includes a pointless “done sending” signal LED.</p><p>Which works out like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*tHfKCPjceGJ7_D7q.gif" /><figcaption>Morse code in action (by author)</figcaption></figure><p>Garbage code is here, in case you care:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb2c721c0fda5632f69649a45cfa80d3/href">https://medium.com/media/bb2c721c0fda5632f69649a45cfa80d3/href</a></iframe><p>It’s really pointless, but fun to see it in action — it simply translates the Morse alphabet into defined lengths and breaks and sends an GPIO.HIGH signal, followed by a sleep timer, and a GPIO.LOW signal to turn it off.</p><p>Now, we went from powering an LED to controlling an LED and a speaker via code — pretty neat!</p><h3>Breakout boards and I2C</h3><p>With those basics out of the way, we can finally take a look at the breakout boards — little circuits with digital or analog outputs that we can talk to via software (and do more than say “power on” / “power off”). Here’s where things get a little more interesting, software wise.</p><p>We’ll take a look at the arguably simplest sensor in the bunch, the MCP9808 temperature sensor.</p><h3>Soldering</h3><p>No matter which board you chose, the first step should be to solder the board onto the (usually supplied) header connector — it’ll be impossible to get a stable connection otherwise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9mBdX9AWvpa_KufJ.jpg" /><figcaption>Solder #1 (by author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ftqr0sk4GEgyBd-A.jpg" /><figcaption>Solder #1 (by author, evidently)</figcaption></figure><p>I can give zero advice on this — the best advice I’ve gotten on the matter is to use more soldering wire than you need and then some, and to make sure the piece sits on a stable base (such as a breadboard). It fits in right with “PVC pipes and bird netting against squirrels”-type approach to life, but it works.</p><p>Adafruit has a great <a href="https://learn.adafruit.com/adafruit-guide-excellent-soldering">guide</a> on it, however.</p><h3>I2C</h3><p>From there, we can actually start using I2C:</p><blockquote><strong><em>I2C</em></strong><em> ( </em><strong><em>Inter-Integrated Circuit</em></strong><em>), pronounced I-squared-C, is a synchronous, multi-master, multi-slave, packet switched, single-ended, serial communication bus invented in 1982 by Philips Semiconductor (now NXP Semiconductors). It is widely used for attaching lower-speed peripheral ICs to processors and microcontrollers in short-distance, intra-board communication. Alternatively, I2C is sometimes spelled I2C (pronounced I-two-C) or IIC (pronounced I-I-C).</em></blockquote><blockquote><a href="https://en.wikipedia.org/wiki/I%C2%B2C"><em>https://en.wikipedia.org/wiki/I%C2%B2C</em></a></blockquote><p>I2C, simply put, can do a lot more than just telling our circuit “power on” and “power off”. It’s a low-level messaging bus.</p><p>I2C uses 2 lines — SCL and SDA. SCL synchronizes data, whereas SDA sends and receives data. In addition to that, 2 other wires carry power and ground. I2C, being a messaging bus, also follows a master-slave pattern: We can use many devices connected to a single messaging bus. Devices can use registers, and those registers can be user-addressable.</p><h3>Implementing MCP9808 communications from scratch</h3><p>Physical communication is outlined by the vendors of the respective chips. For instance, the little <a href="https://www.microchip.com/wwwproducts/en/MCP9808">MCP9808</a> explains exactly how it works down to the last bit in its <a href="https://ww1.microchip.com/downloads/en/DeviceDoc/MCP9808-0.5C-Maximum-Accuracy-Digital-Temperature-Sensor-Data-Sheet-DS20005095B.pdf">specification</a>.</p><p>We’ll need to connect it first:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ev7-jXor4nU74uBn.png" /><figcaption><a href="https://learn.adafruit.com/assets/58808">Source</a>, Kattni Rembor, CC BY-SA 3.0</figcaption></figure><p>Or physically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0dewK8EUJTgHs_J6.jpg" /><figcaption>Spaghetti (by author)</figcaption></figure><p>And using i2cdetect, we can observe connected i2c devices:</p><pre>pi @ 4g-raspberrypi ➜  ~  sudo i2cdetect -y 1<br><br>     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f<br>00:          -- -- -- -- -- -- -- -- -- -- -- -- -- <br>10: -- -- -- -- -- -- -- -- 18 -- -- -- -- -- -- -- <br>20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- <br>30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- <br>40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- <br>50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- <br>60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- <br>70: -- -- -- -- -- -- -- --</pre><p>If we now wanted to get the temperature from the we know that the default <em>address</em> is 0x18, and that the registers are mapped as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*5qhpUpkEoPELelvESP5GKQ.png" /><figcaption>Pinout (by author)</figcaption></figure><p>With TA, or 0x05, being the current temperature&#39;s registers (and that register is readonly).</p><p>Once the circuit is physically connected, we can check the status via software:</p><p>If we were to just read them in Python using the <a href="https://pypi.org/project/smbus2/">smbus2 library</a>:</p><pre>from smbus2 import SMBus<br>import time<br><br>registers = {<br>    &#39;CONFIG&#39;: 0x01,<br>    &#39;TUPPER&#39;: 0x02,<br>    &#39;TLOWERL&#39;: 0x03,<br>    &#39;TCRIT&#39;: 0x04,<br>    &#39;TA&#39;: 0x05,<br>    &#39;MANUFACTURER_ID&#39;: 0x06,<br>    &#39;DEVICE_ID&#39;: 0x07,<br>    &#39;RESOLUTION&#39;: 0x08,<br>}<br><br>bus = SMBus(1)<br>address = 0x18<br><br>for k in registers:<br>    dat = bus.read_word_data(0x18, registers[k])<br>    print(&#39;{} -&gt; {}&#39;.format(k, dat))</pre><p>We’d see:</p><pre>CONFIG -&gt; 0<br>TUPPER -&gt; 0<br>TLOWERL -&gt; 0<br>TCRIT -&gt; 0<br>TA -&gt; 26817<br>MANUFACTURER_ID -&gt; 21504<br>DEVICE_ID -&gt; 4<br>RESOLUTION -&gt; 259</pre><p>Which are obviously not usable values quite yet.</p><p>Now, naturally, we need to parse this data to make sense of it.</p><blockquote><em>The digital word is loaded to a 16-bit read-only Ambient Temperature register (TA) that contains 13-bit temperature data in two’s complement format</em></blockquote><blockquote><em>…</em></blockquote><blockquote><em>To convert the TA bits to decimal temperature, the upper three boundary bits (TA&lt;15:13&gt;) must bem asked out. Then, determine the SIGN bit (bit 12) to check positive or negative temperature, shift the bits accordingly, and combine the upper and lower bytes of the 16-bit register.</em></blockquote><blockquote><em>The upper byte contains data for temperatures greater than +32°C while the lower byte contains data for temperature less than +32°C, including fractional data.</em></blockquote><blockquote><em>When combining the upper and lower bytes, the upper byte must be right-shifted by 4 bits (or multiply by 2⁴) and the lower byte must be left-shifted by 4 bits (or multiply by 2⁴).</em></blockquote><blockquote><em>Adding the results of the shifted values provides the temperature data in decimal format (see Equation 5–1).</em></blockquote><blockquote><em>( </em><a href="https://ww1.microchip.com/downloads/en/DeviceDoc/MCP9808-0.5C-Maximum-Accuracy-Digital-Temperature-Sensor-Data-Sheet-DS20005095B.pdf"><em>https://ww1.microchip.com/downloads/en/DeviceDoc/MCP9808-0.5C-Maximum-Accuracy-Digital-Temperature-Sensor-Data-Sheet-DS20005095B.pdf</em></a><em>)</em></blockquote><p>If we want to keep it simple, all we need to do is follow that documentation:</p><pre># Parse temp<br>v = bus.read_word_data(0x18, 0x05)<br># Split in 2-complements<br>ub=v &amp; 0xFF<br>lb=(v &gt;&gt; 8) &amp; 0xFF<br># Clear flags / take lower 13<br>ub = ub &amp; 0x1F<br># Check for negative values<br>if (ub &amp; 0x10) == 0x10:<br>    ub = ub &amp; 0x0F<br>    t = 256 - (ub * 16 + lb/16)<br>else:<br>    t = ub * 16 + lb / 16<br>print(&#39;Current temp: {}C&#39;.format(t))</pre><p>And we get 22.6875C, which is 72.8F, which matches the other thermometers in the room.</p><p>Now, if you are anything like me, you haven’t done a lot of bit-shifting since college, but here’s my best attempt at explaining what where doing here and why:</p><ul><li>Raw reading is 27585 in decimal, so 110 1011 1100 0001 in binary</li><li>v &amp; 0xFF is a bitmask (XOR) against 1111 1111 to get the upper 8 bit (as we get a 16bit register that contains integer and decimal components). A &amp; is a logical XOR (exclusive or) operation and used for, well, bit masking (extracting bits, if you will).</li></ul><pre>1	1	0	1	0	1	1	1	1	0	0	0	0	0	1 XOR 1	1	1	1	1	1	1	1 1	1	0	0	0	0	0	1</pre><pre>1	1	0	1	0	1	1	1	1	0	0	0	0	0	1 &gt;&gt; 8 0	1	1	0	1	0	1	1 XOR 1	1	1	1	1	1	1	1 0	1	1	0	1	0	1	1</pre><pre>1	1	0	0	0	0	0	1 XOR 1	1	1	1	1 1</pre><p>Which we can now multiply by 2⁴=16 to get a floating point result: t = ub * 16 + lb / 16</p><p>Or use more bitwise logic and get the result as an integer: (lb &gt;&gt; 4) + (ub &lt;&lt; 4)</p><p>Tadaa! Only took a <em>bit</em> of bitwise math to read the board’s sensor. Of course, we can also write to the registers, but I digress.</p><h3>Using a library</h3><p>Now, while this was undoubtedly educational for me to understand how vendors implement these chips, how they can be addressed “low level”, and write the code for it myself, naturally, there are almost always drivers and/or libraries available.</p><p><a href="https://github.com/adafruit/Adafruit_MCP9808_Library">Here</a> is one in C++, and <a href="https://github.com/adafruit/Adafruit_CircuitPython_MCP9808">here</a> is Adafruit’s current Python implementation which simplifies this a lot:</p><pre>from board import *<br>import busio<br>import adafruit_mcp9808<br><br># Do one reading<br>with busio.I2C(SCL, SDA) as i2c:<br>    t = adafruit_mcp9808.MCP9808(i2c)<br><br>    # Finally, read the temperature property and print it out<br>    print(t.temperature)</pre><p>So that’s what we’ll be using going forward.</p><h3>Light Sensors</h3><p>The exercise above covers temperature — whether we do the math ourselves or rely on a library, we can get temps. Sunlight is a different problem.</p><h3>UV Index vs. Light Levels &amp; Pyranometers</h3><p>Since we’re looking at plant maintenance, we are looking for the abstract metric of “sun exposure” that every package of seeds and every plant from Home Depot to your local nursery mentions.</p><p>The thing about this metric is that it is surprisingly subjective and unscientific, at least for consumer-facing products. Generally speaking, we’d want to look at W/sqm of solar irradiance, but we&#39;ll get to why that is not straightforward in a second.</p><p>Can we look at UV, something that is frequently measured and reported (and hence available as cheap boards) as a proxy?</p><blockquote><em>The UV index is a number linearly related to the intensity of sunburn-producing UV radiation at a given point on the earth’s surface.</em></blockquote><blockquote><em>It cannot be simply related to the irradiance (measured in W/m2) because the UV of greatest concern occupies a spectrum of wavelength from 295 to 325 nm, and shorter wavelengths have already been absorbed a great deal when they arrive at the earth’s surface</em></blockquote><blockquote><a href="https://en.wikipedia.org/wiki/Ultraviolet_index"><em>https://en.wikipedia.org/wiki/Ultraviolet_index</em></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/0*_jdSpGo_Ahoi11BE.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Ultraviolet_index"><em>https://en.wikipedia.org/wiki/Ultraviolet_index</em></a></figcaption></figure><p>What we do know is the following: Plants <em>do</em> react to UV, or ultraviolet radiation, specifically UV-B (280–320nm) and UV-A (320–400nm), the same way humans do — it can cause cellular damage and it has been hypothesized that plants can anticipate UV patterns and react accordingly. [1] [2] [3]</p><p>The UV index ranges from 0 to 12 and is really designed to give us an idea on how risky being in the sun is for humans.</p><p>With that said, UV is a side-effect (or subset, if you will) of the <em>sunlight</em> that plants need to grow — UV-A makes up about 4.9% of solar energy, whereas UV-B makes up about 0.1% and can be barely measurable during the winter months.[4]</p><p>What we really want to know about is <em>solar intensity</em>. In order to measure solar intensity, one uses a device called a <em>pyranometer</em>, an (expensive) machine that uses silicon photocells (think photovoltaics), compensates for solar angles, and yields a deterministic way of determining solar irradiance, usually in W/sqm. [5]</p><p>The problem with pyranometers (which by the way, means “sky fire measure”, which is pretty metal) is their super-niche use case and hence enormous cost — even the cheapest ones for hobby meteorologists are way above $100. And I just want to grow some peppers.</p><p>[1] <a href="https://www.frontiersin.org/articles/10.3389/fpls.2014.00474/full">https://www.frontiersin.org/articles/10.3389/fpls.2014.00474/full</a> [2] <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC160223/pdf/041353.pdf">https://www.ncbi.nlm.nih.gov/pmc/articles/PMC160223/pdf/041353.pdf</a> [3] <a href="https://www.rs-online.com/designspark/the-importance-of-ultraviolet-in-horticultural-lighting">https://www.rs-online.com/designspark/the-importance-of-ultraviolet-in-horticultural-lighting</a> [4] <a href="https://www.vishay.com/docs/84310/designingveml6070.pdf">https://www.vishay.com/docs/84310/designingveml6070.pdf</a> [5] <a href="https://www.campbellsci.com/blog/pyranometers-need-to-know">https://www.campbellsci.com/blog/pyranometers-need-to-know</a></p><h3>UV Sensors</h3><p>As I’ve eluded to before, for UV sensors, I looked at 2 options: The <a href="https://www.adafruit.com/product/1777">SI1145</a> or the <a href="https://www.adafruit.com/product/2899">VEML6070</a>, with the former being the more expensive option.</p><p>The VEML6070 contains an actual UV-A sensor.</p><p>The SI1145 on the other hand can calculate the UV index, but <em>doesn&#39;t</em> contain an actual UV sensor. As per the product description, it uses visible and infrared light to calculate the UV index.</p><p>What makes the SI1145 interesting is the fact that we could use it to bypass its selling point, the UV readings, to get get visible and infrared (IR) light readings.</p><p>Using the <a href="https://github.com/THP-JOE/Python_SI1145">library</a> for it, we can collect <a href="https://cdn-shop.adafruit.com/datasheets/Si1145-46-47.pdf">metrics</a> as such:</p><pre>import SI1145.SI1145 as SI1145<br><br>sensor = SI1145.SI1145()<br>vis = sensor.readVisible()<br>IR = sensor.readIR()<br>UV = sensor.readUV()<br>uvIndex = UV / 100.0<br>print(&#39;Visible:  {}&#39;.format(vis))<br>print(&#39;IR:       {}&#39;.format(IR))<br>print(&#39;UV Index: {}&#39;.format(uvIndex))</pre><p>Sadly, those are relative metrics that don’t mean a whole lot on their own — but it’s a start for collecting both UV index (mostly for the gardeners) and some sort of visible and infrared light metric.</p><h3>Lux Sensors</h3><p>The “next best thing” to W/sqm for growing plants (at least that I could come up with) would be the SI unit lux:</p><blockquote><em>[…] It is equal to one lumen per square metre. In photometry, this is used as a measure of the intensity, as perceived by the human eye, of light that hits or passes through a surface. It is analogous to the radiometric unit watt per square metre, but with the power at each wavelength weighted according to the luminosity function, a standardized model of human visual brightness perception. In English, “lux” is used as both the singular and plural form.</em></blockquote><blockquote><a href="https://en.wikipedia.org/wiki/Lux"><em>https://en.wikipedia.org/wiki/Lux</em></a></blockquote><p>While this measures visible light, rather than “raw” energy used for photosynthesis, it can still be a good metric in addition to looking at “relative” visible light and UV. In other words, while it might give us a diluted metrics (as it’s aligned to the spectrum of visible light), it still might be useful in combination with out other metrics.</p><p>For this, I found 3 sensors: The <a href="https://www.adafruit.com/product/4162">Adafruit VEML7700</a> (up to 120k lux), the <a href="https://www.adafruit.com/product/1980">Adafruit TSL2591</a> (up to 88k lux), and the <a href="https://smile.amazon.com/NOYITO-MAX44009-Intensity-Interface-Development/dp/B07HFRS8XX">NOYITO MAX44009</a> (up to 188k lux). Naturally, there are other options available.</p><p>Bright sunlight can reach over 100,000 Lux, so the first and last sensor in that list might be preferable.</p><p><strong>Note</strong>: <em>At the time of writing, neither lux sensor has arrived yet. Most of the things you’ll read below hence only support relative measurements of visible light from the UV sensor</em>.</p><h3>Analog Sensors &amp; Soil Moisture</h3><p>The previous sensors we used were all I2C sensors with a <em>digital</em> output. But what about analog?</p><p>Well, fear not — the resistive soil moisture sensor I bought provides digital and analog output. The Amazon reviews, however, complain that “Manual and digital output are limited, analog works okay”. So how does one read analog data?</p><p>Well with an ADC, of course! For those of you who are into HiFi, you might own a DAC (Schiit makes great ones starting at $99, by the way) — a Digital to Analog converter. In this use case, however, we need an Analog to Digital converter.</p><p>I am using the <a href="https://www.adafruit.com/product/856">MCP3008 8-Channel 10bit ADC With SPI Interface</a>. It uses SPI, or Serial Peripheral Interface, as opposed to I2C. Without being an expert at either, as evidenced by this article, SPI and I2C are similar — but SPI uses more pins:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*9lhcNU80XhVFqXX1.gif" /><figcaption><a href="https://learn.adafruit.com/assets/1222">Source</a>, Michael Sklar, CC BY-SA 3.0</figcaption></figure><p>Which means we can connect it as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BG9PdpE0y_tZlODD.png" /></figure><p>Connected, it looks like this, using this positively adorable giraffe pot as a subject:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y4Dx5Ud0yRLmGGu_.jpg" /><figcaption>Giraffe, PhD (by author)</figcaption></figure><p>(Please ignore the electrical tape, I operate under highly professional standards)</p><p>What we’re trying to read is resistance — if the resistance between the two probes rises, the soil is drier. This measure, of course, is somewhat subjective, so we’ll have to calibrate it.</p><p>For digitally reading raw data from pin 0 on board I/O pin 25 (fot 60 seconds), we can use this little snippet of code:</p><pre>import busio<br>import digitalio<br>import board<br>import adafruit_mcp3xxx.mcp3008 as MCP<br>from adafruit_mcp3xxx.analog_in import AnalogIn<br> <br># create the spi bus<br>spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)<br> <br># create the cs (chip select)<br>cs = digitalio.DigitalInOut(board.25)<br> <br># create the mcp object<br>mcp = MCP.MCP3008(spi, cs)<br> <br># create an analog input channel on pin 0<br>chan0 = AnalogIn(mcp, MCP.P0)<br><br>readings = []<br>i = 0<br>for x in range(0,60):<br>    i += 1<br>    val = chan0.value<br>    volt = chan0.voltage<br>    readings.append(volt)<br>    if int(val) != 0:<br>        print(&#39;Raw ADC Value: {}&#39;.format(val))<br>        print(&#39;ADC Voltage: {} V&#39;.format(chan0.voltage))<br>    time.sleep(1)<br><br>avg = statistics.mean(readings)<br>print(&#39;Avg voltage: {}&#39;.format(avg))</pre><p>Which gives us one raw reading per second.</p><p>In a decently moist giraffe pot, we get a reading of about</p><pre>Raw ADC Value: 30144<br>ADC Voltage: 1.5146715495536736 V</pre><p>Or, on average, 1.5144.</p><p>Now, keep in mind that this also gives you readings if you don’t connect a thing:</p><pre># Reading on an unconnected channel P2<br>Raw ADC Value: 448<br>ADC Voltage: 0.0 V<br>Raw ADC Value: 512<br>ADC Voltage: 0.0 V<br>Avg voltage: 0.004619211108567941</pre><p><em>But you can ignore those readings</em>. I think this is an artifact of the nature of any ADC — natural fluctuations in current + Python’s inherent float imprecision.</p><p>If you connect a potentiometer on a different channel (you can see it in the picture above!), you can actually see those fluctuations — technically, the voltage should stay exactly the same, but yet it doesn’t:</p><pre>readings = [3.2968276493476765, 3.280714122224765, 3.280714122224765, 3.280714122224765, 3.2839368276493475, 3.280714122224765, 3.280714122224765, 3.2936049439230946, 3.2839368276493475, 3.2839368276493475, 3.277491416800183, 3.280714122224765, 3.280714122224765, 3.277491416800183, 3.2936049439230946, 3.28715953307393, 3.280714122224765, 3.277491416800183, 3.2936049439230946, 3.277491416800183, 3.2839368276493475, 3.28715953307393, 3.280714122224765, 3.280714122224765, 3.2839368276493475, 3.280714122224765, 3.2839368276493475, 3.28715953307393, 3.280714122224765, 3.280714122224765, 3.280714122224765, 3.2839368276493475, 3.280714122224765, 3.277491416800183, 3.2936049439230946, 3.2710460059510185, 3.2839368276493475, 3.280714122224765, 3.290382238498512, 3.280714122224765, 3.277491416800183, 3.280714122224765, 3.28715953307393, 3.2839368276493475, 3.280714122224765, 3.280714122224765, 3.28715953307393, 3.2839368276493475, 3.2839368276493475, 3.2839368276493475, 3.2839368276493475, 3.2839368276493475, 3.2742687113756004, 3.290382238498512, 3.2936049439230946, 3.28715953307393, 3.277491416800183, 3.280714122224765, 3.28715953307393, 3.290382238498512]<br>statistics.stdev(v)<br># 0.0051783580637861605</pre><p>The stdev is only 0.005178, but it’s there. The moisture sensor is just introducing equally strong fluctuations at a stdev of 0.002305.</p><p>In any case, the same experiment on a bone dry pot of soil yields a mean voltage of 2.6.</p><p>So we can conclude:</p><ul><li><strong>Dry soil</strong>: 2.6V</li><li><strong>Damp soil</strong>: 1.5V</li><li><strong>Glass of water</strong>: 0.77V</li></ul><h3>Putting it all together</h3><p>Final assembly!</p><h3>Final Breadboard Layout</h3><p>With all sensors connected, this is the layout:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VZd86TF5yuOsRwSC.png" /><figcaption>Final layout (by author)</figcaption></figure><h3>A Simple REST API can do the trick</h3><p>We can send the collected data over the network. One could come up with a fancy messaging queue, but I think a simple, localized REST API would do the trick for now — AWS Greengrass, Meme-Microservices, Kafka and others will have to wait. We just send a packet of data every 10 seconds and store it into a database like this:</p><pre>CREATE OR REPLACE TABLE `sensors`.`data` (<br>    `sensorId`	            TEXT,<br>    `TempC`	                FLOAT,<br>    `VisLight`	            FLOAT,<br>    `IrLight`               FLOAT,<br>    `UvIx`                  FLOAT,<br>    `RawMoisture`           FLOAT,<br>    `VoltMoisture`          FLOAT,<br>    `MeasurementTs`         TIMESTAMP,<br>    `lastUpdateTimestamp`   TIMESTAMP<br>);</pre><p>The REST endpoint is written in go and compiled for x86, rather than ARM and gets deployed on a remote server, so that we can support many small microcontrollers that just need to send data every once in a while.</p><p>You can find the full code on <a href="https://github.com/chollinger93/raspberry-gardener">GitHub</a>, as usual, so I’ll only talk about some noteworthy points (which are generic go topics, but worth a mention).</p><p>First of all, the use of <a href="https://github.com/jmoiron/sqlx">github.com/jmoiron/sqlx</a> and <a href="https://github.com/Masterminds/squirrel">github.com/Masterminds/squirrel</a> with a ConnectionPool setup similar to the type one would use for a large CloudSQL instance has been treating me well - sqlx extends go&#39;s regular sql interface wonderfully and squirrel can be used to automate some tasks for database I/O away.</p><pre>type Sensor struct {<br>	SensorId     string<br>	TempC        float32<br>	VisLight     float32<br>	IrLight      float32<br>	UvIx         float32<br>	RawMoisture  float32<br>	VoltMoisture float32<br>    MeasurementTs string<br>}<br><br>func (a *App) storeData(sensors []Sensor) error {<br>	q := squirrel.Insert(&quot;data&quot;).Columns(&quot;sensorId&quot;, &quot;tempC&quot;, &quot;visLight&quot;, &quot;irLight&quot;, &quot;uvIx&quot;, &quot;rawMoisture&quot;, &quot;voltMoisture&quot;, &quot;measurementTs&quot;, &quot;lastUpdateTimestamp&quot;)<br>	for _, s := range sensors {<br>        // RFC 3339<br>		measurementTs, err := time.Parse(time.RFC3339, s.MeasurementTs)<br>		if err != nil {<br>			zap.S().Errorf(&quot;Cannot parse TS %v to RFC3339&quot;, err)<br>			continue<br>		}<br>		q = q.Values(s.SensorId, s.TempC, s.VisLight, s.IrLight, s.UvIx, s.RawMoisture, s.VoltMoisture, measurementTs, time.Now())<br>	}<br>	sql, args, err := q.ToSql()<br>	if err != nil {<br>		return err<br>	}<br><br>	res := a.DB.MustExec(sql, args...)<br>	zap.S().Info(res)<br>	return nil<br>}</pre><p>I’ve also started using <a href="https://github.com/uber-go/zap">go.uber.org/zap</a> more and more, as go&#39;s standard logging interface leaves <em>a lot</em> to be desired.</p><pre>// Logger<br>logger, _ := zap.NewDevelopment()<br>defer logger.Sync() // flushes buffer, if any<br>zap.ReplaceGlobals(logger)</pre><p>Other than that, the code is a pretty standard REST API — an App struct keeps a pointer to the DB connection pool (shared across threads), and secrets are handled via environment variables, rather than having to implement config files and viper (maybe in the future).</p><pre>type App struct {<br>	Router *mux.Router<br>	DB     *sqlx.DB<br>}<br><br>func initTCPConnectionPool() (*sqlx.DB, error) {<br>	var (<br>		dbUser    = mustGetenv(&quot;DB_USER&quot;)<br>		dbPwd     = mustGetenv(&quot;DB_PASS&quot;)<br>		dbTCPHost = mustGetenv(&quot;DB_HOST&quot;)<br>		dbPort    = mustGetenv(&quot;DB_PORT&quot;)<br>		dbName    = mustGetenv(&quot;DB_NAME&quot;)<br>	)<br><br>	var dbURI string<br>	dbURI = fmt.Sprintf(&quot;%s:%s@tcp(%s:%s)/%s?parseTime=true&quot;, dbUser, dbPwd, dbTCPHost, dbPort, dbName)<br><br>	dbPool, err := sqlx.Open(&quot;mysql&quot;, dbURI)<br>	if err != nil {<br>		return nil, fmt.Errorf(&quot;sql.Open: %v&quot;, err)<br>	}<br><br>	configureConnectionPool(dbPool)<br>	return dbPool, nil<br>}</pre><p>Build as such:</p><pre># For x86<br>GOARCH=amd64 GOOS=linux go build -o /tmp/sensor-server *.go <br>sudo mkdir -p /opt/raspberry-gardener<br>sudo cp /tmp/sensor-server /opt/raspberry-gardener<br>sudo cp ./.env.sh /opt/raspberry-gardener/<br>sudo sed -i &#39;s/export //g&#39; /opt/raspberry-gardener/.env.sh</pre><p>We can then install a systemd service:</p><pre>[Unit]<br>After=network.target<br>Wants=network-online.target<br><br>[Service]<br>Restart=always<br>EnvironmentFile=/opt/raspberry-gardener/.env.sh<br>WorkingDirectory=/opt/raspberry-gardener<br>ExecStart=/opt/raspberry-gardener/sensor-server <br><br>[Install]<br>WantedBy=multi-user.target</pre><p>And deploy:</p><pre># Install `systemd` service:<br>sudo cp raspberry-gardener.service /etc/systemd/system/<br>sudo systemctl start raspberry-gardener<br>sudo systemctl enable raspberry-gardener # Autostart</pre><p>And check:</p><pre>christian @ bigiron ➜  raspberry-gardener  sudo systemctl status raspberry-gardener<br>   Loaded: loaded (/etc/systemd/system/raspberry-gardener.service; disabled; vendor preset: enabled)<br>   Active: active (running) since Sat 2021-04-24 14:12:56 EDT; 17min ago<br> Main PID: 12312 (sensor-server)<br>    Tasks: 7 (limit: 4915)<br>   Memory: 3.0M</pre><p>We’ll do the same for the sensor client below — see GitHub for details.</p><h3>One Script to Rule Them All</h3><p>For putting the sending part together, all we need to do is combine all individual scripts for each sensor, wildly mix SPI and I2C, and send the data.</p><p>Imports and collecting data is pretty straightforward:</p><pre>from board import *<br>import busio<br>import adafruit_mcp9808<br>import SI1145.SI1145 as SI1145<br>import os<br>import time<br>import busio<br>import digitalio<br>import board<br>import adafruit_mcp3xxx.mcp3008 as MCP<br>from adafruit_mcp3xxx.analog_in import AnalogIn<br>import platform<br>import getmac<br>import requests<br>import logging<br>import json<br>import argparse<br><br># mcp9808<br>def read_temp() -&gt; int:<br>    with busio.I2C(SCL, SDA) as i2c:<br>        t = adafruit_mcp9808.MCP9808(i2c)<br>        return t.temperature<br><br># SI1145<br>def read_uv(sensor: object) -&gt; set:<br>    vis = sensor.readVisible()<br>    IR = sensor.readIR()<br>    UV = sensor.readUV() <br>    uvIndex = UV / 100.0<br>    return (vis, IR, uvIndex)<br><br># HD-38 (Aliexpress/Amazon)<br>def read_moisture(spi_chan: object) -&gt; tuple:<br>    val = spi_chan.value<br>    volt = spi_chan.voltage<br>    return (val, volt)</pre><p>Since we want a unique ID per sensor (if we deploy multiple), we’re combining hostname and network MAC address into one string:</p><pre>def get_machine_id():<br>    return &#39;{}-{}&#39;.format(platform.uname().node, getmac.get_mac_address())</pre><p>The collecting loop creates all access objects, buffers the data, filters invalid data, and sends it to the REST API:</p><pre>def main(rest_endpoint: str, frequency_s=1, buffer_max=10, spi_in=0x0):<br>    buffer=[]<br>    ## UV<br>    uv_sensor = SI1145.SI1145()<br><br>    ## SPI<br>    # create the spi bus<br>    spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)<br>    # create the cs (chip select)<br>    cs = digitalio.DigitalInOut(board.CE0)<br>    # create the mcp object<br>    mcp = MCP.MCP3008(spi, cs)<br>    # create an analog input channel on pin 0<br>    chan0 = AnalogIn(mcp, spi_in)<br><br>    while True:<br>        try:<br>            # Read<br>            temp_c = read_temp()<br>            vis, ir, uv_ix = read_uv(uv_sensor)<br>            raw_moisture, volt_moisture = read_moisture(chan0)<br><br>            # Write<br>            # temp_c,vis_light,ir_light,uv_ix,raw_moisture,volt_moisture<br>            reading = {<br>                &#39;sensorId&#39;: get_machine_id(),<br>                &#39;tempC&#39;: temp_c,<br>                &#39;visLight&#39;: vis,<br>                &#39;irLight&#39;: ir,<br>                &#39;uvIx&#39;: uv_ix,<br>                &#39;rawMoisture&#39;: raw_moisture,<br>                &#39;voltMoisture&#39;: volt_moisture,<br>                &#39;measurementTs&#39;: datetime.now(timezone.utc).isoformat() # RFC 333<br>            }<br><br>            # Only send if we have all <br>            # UV sensor sometimes doesn&#39;t play along<br>            if int(vis) == 0 or int(ir) == 0 or int(volt_moisture) == 0:<br>                logger.warning(&#39;No measurements: {}&#39;.format(reading))<br>                continue<br><br>            buffer.append(reading)<br>            logger.debug(reading)<br>            if len(buffer) &gt;= buffer_max:<br>                logger.debug(&#39;Flushing buffer&#39;)<br>                # Send<br>                logger.debug(&#39;Sending: {}&#39;.format(json.dumps(buffer)))<br>                response = requests.post(rest_endpoint, json=buffer)<br>                logger.debug(response)<br>                # Reset<br>                buffer = []<br>        except Exception as e:<br>            logger.exception(e)<br>        finally:<br>            time.sleep(frequency_s)</pre><p>It uses about 16MB of memory despite the buffer, so we should be good to go!</p><h3>Physical Deployment</h3><p>Usually, when I write software, it ends here: I wrote the software. Now run it. Go away.</p><p>In this little experiment, however, there is also a component of actually physically deploying it involed. Since it had to be outside, the housing for the PI and boards would need to be at least semi-protected against water, and even if its just ambient moisture from the ground.</p><h3>Stupid Problems Require a Dremel</h3><p>Since I don’t own a 3D printer (or even a smaller breadboard), but do own old Ikea plastic boxes and a dremel, the solution was obvious: Remove the Pi Cobbler, connect some dupont cables directly, put them in a plastic box, drill holes, use electrical tape to “seal” it, and change over from ethernet to WiFi. Simple, yet elegant (citation needed). I’ve also connected the camera for good measure — even though I haven’t programmed it yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/0*JTp0RhqcP3CrEkdW.jpg" /><figcaption>Majestic box #1 (by author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WnvHJQ-44On1eIcH.jpg" /><figcaption>Majestic box #2 (by author)</figcaption></figure><h3>First Outdoor Test: The Deck</h3><p>I then moved it outside on a sunny day to the deck (after a bad storm) for its first big day in the field (in April!):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ygNc0vCjoOe8UeoZ.jpg" /><figcaption>Deployment #1 (by author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3puDg8YZt0bCQl4x.jpg" /><figcaption>UV Sensor (by author)</figcaption></figure><p>And for the pictures the camera takes (I triggered this one via SSH):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZEzfZU6sei6_-v9Z.jpg" /><figcaption>Skyward camera (by author)</figcaption></figure><p>Then I started both systemd services and waited for a bit.</p><h3>Analyzing the Preliminary Data</h3><p>As this really only ran for a short time, the following query must suffice:</p><pre>SELECT *, TIMESTAMPDIFF(MINUTE, startTS, endTs) as totalMinMeasured,<br>CASE WHEN avgVoltMoisture &lt;= 0.90 THEN &quot;wet&quot; <br>WHEN avgVoltMoisture &gt; 0.9 AND avgVoltMoisture &lt;= 1.7 THEN &quot;moist&quot;<br>ELSE &quot;dry&quot;  END AS avgWetness<br>FROM (<br>	SELECT AVG(TempC) AS avgTemp, AVG(VisLight) AS avgVisLight, AVG(UvIx) as avgUvIx, AVG(VoltMoisture) as avgVoltMoisture,<br>	MAX(MeasurementTs) as endTS, MIN(MeasurementTs) as startTs<br>	FROM `sensors`.`data` as d<br>	WHERE d.MeasurementTs &lt;= TIMESTAMP(&#39;2021-04-25 18:25:00&#39;)<br>) e</pre><p>Which yields the unsurprising results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*0SmwjG-Hi9-W4sbf6J74Jg.png" /><figcaption>Deployment #1 results (by author)</figcaption></figure><p>That at around 2pm, the deck is sunny, and that after a heavy storm the night before, the plants are wet.</p><p>But this was just to make sure it works!</p><h3>Second Outdoor Test: The Flower Beds</h3><p>Once confirmed that everything works, it’s time for the garden bed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1UzWDoXPi5_gtiOc.jpg" /><figcaption>Deployment #2 (by author)</figcaption></figure><p>The camera now also has a much more interesting point of view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G6WcRbfpmChb4J0q.jpg" /><figcaption>The sky and a tree (by author)</figcaption></figure><h3>Analysis: Part 2 (w/ Grafana)</h3><p>To be fair, analysis of this dataset isn’t going to look much different — letting it run a little longer gives us the ability to visualize it using Grafana:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f0rh2HFR61lazO8t.png" /><figcaption>Grafana #1 (by author)</figcaption></figure><p>( <em>Sensor was moved from the sunny deck to the garden beds at around 1420hrs</em>)</p><p>I’ve also manually taken pictures over SSH:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BvUQ9Rr8stHRFVJq.jpg" /><figcaption>The sky and a tree #2 (by author)</figcaption></figure><p>This picture was taken at the tail-end of the Grafana graphs (around 1800hrs), whereas the one above was taken at about 1430. You can undoubtedly spot that pattern on the graphs.</p><p>Another peak in both light index and UV (and by proxy, temperature) can be oberved around 1700hrs — that is when the sun is not obscured by trees.</p><p>And another picture taken at 1930 hrs — you can see the angle of the sun changing on the plant in the bottom left of the picture, but not much change in any other metric in the graphs above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OwG8Zr_8K6EZ7DrV.jpg" /><figcaption>The sky and a tree #3 (by author)</figcaption></figure><p>Despite the lack of Lux sensor, we can also make some informed guesses on “Part Shade” vs. “Full Sun” here — comparing Light and UV index here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*LGnsixHCUd_bVYnq.png" /><figcaption>Grafana #2 (by author)</figcaption></figure><p>Knowing that the sensor was moved at around 1420hrs, we can compare the peaks between the obviously super-sunny deck and the beds — both peak at 1.65–1.5k “light units (“visible light” from the sensor).</p><p>This correlates with temperature as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/0*Ux5giMkj4Csa_uSH.png" /><figcaption>Grafana #3 (by author)</figcaption></figure><p>You can see peaks up to ~29C (84.2F) during the “high sun” period in the late afternoon, with the peaks on the deck reaching 40C (104F).</p><p>Interestingly enough, the temperature doesn’t match the recorded temperatures as per the iPhone weather app — that should have been a constant 72F (or 22.2C), whereas during non-high intensity periods, the beds are hovering around 18–19.C (64.4–67F)!</p><p>I think it is fair to say: At least this particular garden bed qualifies as “part shade” and doesn’t get the same intense sun that other parts of the house are getting.</p><p>Of course, ideally, you’d want to observe this for several full days in different conditions — but I, surprisingly, don’t trust my tupperware-electrical-tape-dremel-box <em>too much</em> just yet. But it’s a start!</p><h3>Next Steps &amp; Conclusion</h3><p>This is part 1 — while it was super interesting for me (and seeing the graphs at the end is just delightful), I won’t even pretend that this project is overly useful, economical, or even <em>necessary</em> (my office window faces the garden…), there are still a ton of things we can do better!</p><ul><li>Use a much cheaper board, e.g. a Raspberry Zero</li><li>Solder the connections and build one compact package</li><li>3D print a proper enclosure that could actually be watertight</li><li>Deploy several of those and collect data for a week or so</li><li>Implement the camera code</li><li>Implement the Lux sensor (see above)</li><li>Deploy it for much longer periods of time to collect a lot more data</li><li>Fine tune some collection parameters — it’s currently collecting 3,600 datapoints / hour, which is probably unncessary</li><li>Run some form of ML model on the sturctured + unstructured data from the camera</li></ul><p>So a part 2 might be in order — but I feel part 1 is long enough as it is.</p><p>In any case, I hope you enjoyed this little journey from a refresher on middle school physics, to basics on I2C and SPI, to bit-shifting by hand for no good reason, to writing a REST API and SQL queries, to moving a plastic box with holes on the side into the yard, and finally using some more normal data wrangling toolsets to look at it. I know I had fun!</p><p><em>All code is available on </em><a href="https://github.com/chollinger93/raspberry-gardener"><em>GitHub</em></a><em>.</em> <em>All development and benchmarking was done under GNU/Linux [PopOS! 20.04 on Kernel 5.8] with 12 Intel i7–9750H vCores @ 4.5Ghz and 16GB RAM on a 2019 System76 Gazelle Laptop, as well as a Raspberry Pi 4 Model B, using </em><a href="https://chollinger.com/blog/2019/04/building-a-home-server/"><em>bigiron.local</em></a><em> as endpoint</em></p><p><em>Originally published at </em><a href="https://chollinger.com/blog/2021/04/raspberry-pi-gardening-monitoring-a-vegetable-garden-using-a-raspberry-pi-part-1/"><em>https://chollinger.com</em></a><em> on April 25, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd231c7c6275" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/raspberry-pi-gardening-monitoring-a-vegetable-garden-using-a-raspberry-pi-part-1-fd231c7c6275">Raspberry Pi Gardening: Monitoring a Vegetable Garden using a Raspberry Pi — Part 1</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I use Linux]]></title>
            <link>https://medium.com/data-science/why-i-use-linux-5fc70e370b24?source=rss-7af40a2161c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fc70e370b24</guid>
            <category><![CDATA[unix]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[posix]]></category>
            <dc:creator><![CDATA[Christian Hollinger]]></dc:creator>
            <pubDate>Mon, 21 Dec 2020 00:00:00 GMT</pubDate>
            <atom:updated>2020-12-23T14:02:30.438Z</atom:updated>
            <content:encoded><![CDATA[<h4>One question I do get in earnest quite frequently is why I put up with running GNU/Linux distributions for development work. An attempt at a simple response.</h4><h3>Introduction</h3><p>This article aims to clear some of the confusion, without getting lost in technical details or long ramblings about the shortcomings of systemd.</p><p>I will also refrain from comparing it to Windows too much - I use Windows for video games and am sure that with modern Powershell, some of the things I&#39;ll be talking about are covered there as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/0*_aPxQHono1uxAdjb.jpg" /><figcaption>The original Tux (<a href="https://en.wikipedia.org/wiki/Tux_(mascot)#/media/File:Ccpenguin,_the_ancestor_of_Tux.jpg">https://en.wikipedia.org/wiki/Tux_(mascot)#/media/File:Ccpenguin,_the_ancestor_of_Tux.jpg</a>)</figcaption></figure><h3>Cross Platform is slang for “only some things work properly”</h3><p>The best way to describe my daily work is “Data Engineering”: Code, usually in Python, go, Scala, or Java, running on a distributed cluster of different machines and/or containers, churning away at large amounts of data.</p><p>But be it my line of work or more traditional backend work (like writing API endpoints for your favorite websites and apps), at the end of the day, the software I write will inevitably run on servers that run Linux, mostly LTS-variants, such as Debian or RHEL. They run Linux because it&#39;s free (as in cost and source), it&#39;s stable and doesn&#39;t require reboots, it is extendable and customizable, it can be easily audited, there is tons of software available that was designed for UNIX-likes when Windows was a single-user OS, it&#39;s lightweight, there&#39;s tons of fun kernel tricks to make sure things run as fast as possible, and people spend a lot of time on making sure there&#39;s no security vulnerabilities.</p><p>The ability to work on a system that is close to, if not identical to your target platform, avoids many issues that usually occur when going from “Well, it works on my machine!” to production.</p><p>The interesting part about Data Engineering in particular is the distributed nature of the work, and the inherently high demand for computational capacity it entails. While a lot of us, even the ones with CS degrees, view the workings of an Operating System something abstract, low-level, and completely irrelevant to the average developer (a for loop is a for loop, right?), even fairly high-level languages, such as Python, have to interact with the OS turning your hardware into more than a shiny block of silicon.</p><p>To give you a tangible example: What does this code do?</p><pre>import multiprocessing as mp <br>import time <br>import os <br>def worker(i: int):<br>    print(f&#39;{os.getpid()}: Working hard on {i}&#39;)<br>    time.sleep(2500)<br>    print(f&#39;{os.getpid()}: Done with {i}!&#39;)<br><br>def main():<br>    pool = mp.Pool(4)<br>    pool.map(worker, (0,1,2,3,))<br>    pool.close()<br>    pool.join()<br>    print(&#39;All done!&#39;)<br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>Correct: Pretty much nothing, 4 times in parallel — but for a long time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_ZH7gFgmCOilMqd-.png" /><figcaption>htop (Image by author)</figcaption></figure><p>If it were an actual problem, we’d need to find out what does it actually <em>does right now</em>? We now could take a look at /proc/$pid/ to see all the different process details.</p><p>For instance /proc/$pid/stack gives us the main thread&#39;s stack:</p><pre>christian @ pop-os ➜  326589  sudo cat ./stack<br>[&lt;0&gt;] futex_wait_queue_me+0xbb/0x120<br>[&lt;0&gt;] futex_wait+0x105/0x240<br>[&lt;0&gt;] do_futex+0x14d/0x890<br>[&lt;0&gt;] __x64_sys_futex+0x13f/0x16c<br>[&lt;0&gt;] do_syscall_64+0x49/0xc0<br>[&lt;0&gt;] entry_SYSCALL_64_after_hwframe+0x44/0xa9</pre><p>This, for instance, leads us to <a href="https://www.kernel.org/doc/htmldocs/kernel-locking/API-futex-wait-queue-me.html">futex_wait_queue_me</a>, which &quot;queue_me and wait for wakeup, timeout, or signal&quot;, which could be caused by a deadlock, as described in <a href="https://github.com/torvalds/linux/commit/76835b0ebf8a7fe85beb03c75121419a7dec52f0">this commit</a> (in this example, we&#39;re intentionally waiting for nothing in particular, of course).</p><p>Or maybe we’re creating too many file descriptors due to network activity? We can always check /proc/$pid/fd. The list goes on.</p><p>In any case, chances are that we’d encounter this issue on the local development Linux machine, as well as on our production machines — under Windows, for instance, the spawning of processes works very differently and is, if I may say so, not nearly as transparent.</p><p>And even if we are on different Kernel versions — the approach to debugging will stay the same.</p><p>Most tools are also incredibly portable. I maintain <a href="https://github.com/chollinger93/debian-scripts">this little repo on GitHub</a> that contains configuration files and other little helper script that I just clone whenever I get to a new machine (unless I cannot, in which case, I can always manually re-create my favorite .zshrc).</p><h3>Do one thing, and do it well</h3><p>The “Unix philosophy” is something that might be regarded as archaic by some, given the modern trend of colossal pieces of software that do everything short of making coffee — web browsers are a great example — but here’s the summary straight from Wiki regardless:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/0*YUopODosyU4e38tZ.jpeg" /><figcaption><em>Doug McIlroy by Denise Panyik-Dale, CC BY 2.0: </em><a href="https://en.wikipedia.org/wiki/Douglas_McIlroy#/media/File:Douglas_McIlroy.jpeg"><em>https://en.wikipedia.org/wiki/Douglas_McIlroy#/media/File:Douglas_McIlroy.jpe</em></a></figcaption></figure><blockquote><em>Make each program do one thing well. To do a new job, build afresh rather than complicate old programs by adding new “features”.</em></blockquote><blockquote><em>Expect the output of every program to become the input to another, as yet unknown, program. Don’t clutter output with extraneous information. Avoid stringently columnar or binary input formats. Don’t insist on interactive input.</em></blockquote><blockquote>…</blockquote><blockquote>Doug McIlroy, 1978</blockquote><p>These principles might not be 100% applicable for actual software development in $CURRENT_YEAR, but that doesn&#39;t mean the general idea is obsolete.</p><p>In any modern Linux-based environment, many daily, repeatable, and ad-hoc tasks can be achieved by piping simple, often single-purpose commands on any shell.</p><blockquote><em>In Unix-like computer operating systems, a pipeline is a mechanism for inter-process communication using message passing. A pipeline is a set of processes chained together by their standard streams, so that the output text of each process (stdout) is passed directly as input (stdin) to the next one.</em></blockquote><blockquote><a href="https://en.wikipedia.org/wiki/Pipeline_(Unix)">https://en.wikipedia.org/wiki/Pipeline_(Unix)</a></blockquote><p>Take this example: <em>In this blog’s repository, how many images are stored in the various sub-folders?</em> This might be the baseline for a query to make sure all files are compressed, which they are not.</p><p>We can get to that answer by simply piping together (“daisy-chaining”) some commands:</p><pre>find ./content -type f -regex &#39;.*\.\(jpg\|jpeg\|png\|svg\|gif\)&#39; | uniq | wc -l</pre><p>And to break it down:</p><pre>find ./content -type f -regex &#39;.*\.\(jpg\|jpeg\|png\|svg\|gif\)&#39; # Find every file in the folder `content` that matches the regex (which means &quot;a file ending in either of those suffixes&quot;)<br>uniq # Only show unique results<br>wc -l # Count the lines on stdout</pre><p>Each one of those 3 commands does one specific thing:</p><ul><li>find - search for files in a directory hierarchy</li><li>uniq - report or omit repeated lines</li><li>wc - print newline, word, and byte counts for each file</li></ul><p>The ability to build queries for a task, almost based on the English language ( <strong>find</strong> files, then make sure they are <strong>uniq</strong>ue, then <strong>w</strong>ord <strong>c</strong> ount them) can automate daily tasks fascinatingly quickly, as it is provides simple, yet effective interfaces that are compatible with one another across environments.</p><h3>Dependency Management: On War and Peace</h3><p>Generally speaking, installing software — or installing software to write software — has always been an ordeal. On Windows (which, see above, I use for video games), I find myself dealing with the following:</p><ul><li>Binary blobs (.exe files) that ...</li><li>… don’t ship their own update tool. This software will remain on the version it was shipped as, unless I upgrade manually</li><li>… ship their custom updater, providing a custom way to “check for updates”</li><li>… ship one, but just ask you to download a new .exe file from a website</li><li>Portable, binary blobs with the same update-permutations as above</li><li>Windows-store apps</li><li>Custom stores with their own update-processes, such as GoG or Steam</li><li>Some with checksum/signing checks from Windows, others without it</li></ul><p>Take a look at the updater for the software that my brand-new, shiny Gigabyte RTX 3080 came with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*32cVSQPtvY9V0n3h.png" /><figcaption>Gigabyte Updater (Image by author)</figcaption></figure><p>And now, compare that against say, Steam, which neatly updates my games automatically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kvHeDwbW5Tn4hE7x.png" /><figcaption>Steam Updater (Image by author)</figcaption></figure><p>Now, as long as we are talking about relatively unimportant software, having a less-than-streamlined process for installing and updating software can be dealt with.</p><p>However, once we reach a point where stability, unified management and control, as well as security are important, having a unified package manager that takes care of these things for us becomes paramount.</p><p>Depending on your flavor of Linux, you&#39;ll be dealing with various package managers - apt, yum, pacman - and naturally, you will not get away from cross-platform apps shipping with their own updater. I won&#39;t even mention the endless permutations of tools like snap or flatpack.</p><p>However, just using apt on PopOS as an example, take a look at the dependency tree for hugo, which this blog is rendered with:</p><pre>christian @ pop-os ➜  ~  apt-rdepends hugo      <br>Reading package lists... Done<br>Building dependency tree       <br>Reading state information... Done<br>hugo<br>  Depends: libc6 (&gt;= 2.4)<br>  Depends: libsass1 (&gt;= 3.6.3)<br>libc6<br>  Depends: libcrypt1 (&gt;= 1:4.4.10-10ubuntu4)<br>  Depends: libgcc-s1<br>libcrypt1<br>  Depends: libc6 (&gt;= 2.25)<br>libgcc-s1<br>  Depends: gcc-10-base (= 10.2.0-5ubuntu1~20.04)<br>  Depends: libc6 (&gt;= 2.14)<br>gcc-10-base<br>libsass1<br>  Depends: libc6 (&gt;= 2.29)<br>  Depends: libgcc-s1 (&gt;= 3.0)<br>  Depends: libstdc++6 (&gt;= 9)<br>libstdc++6<br>  Depends: gcc-10-base (= 10.2.0-5ubuntu1~20.04)<br>  Depends: libc6 (&gt;= 2.18)<br>  Depends: libgcc-s1 (&gt;= 4.2)</pre><p>Or, if you care for pretty pictures:</p><pre>debtree --with-suggests hugo | dot -T png -o hugo-deptree.png</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/0*0mxodTu7_4bK9jED.png" /><figcaption>Dependency graph (Image by author)</figcaption></figure><p>We can see the exact dependencies, including version strings, for each library that hugo asks for. apt will not only install it for us, it can also keep everything up-to-date.</p><p>Interestingly, the concept of a package manager like apt (initial release 1998) is pretty much the basis for any modern &quot;app store&quot; - a centralized (albeit expandable) repository of software binaries or src that keep a tree of their respective dependencies.</p><p>This, of course, is great if it works. I haven’t actually read Tolstoy’s monstrosity, but any form of dependency management is always a story of times of peace and harmony (you update, it works) and war and anguish (you update, it doesn’t work), as signatures expire, repositories cease to exist, or dependencies get so out of whack that sometimes installing a package from scratch is the best way to go.</p><p>That being said, in the theme of the article, I much prefer apt install $package over trying to find some sketchy binary or hoping for it to be in some overly-curated &quot;app store&quot; that I cannot extend with repositories for more obscure use-cases.</p><h3>Permissions: Computer says no</h3><p>Unix-likes have this wonderful system, called chmod and chown, that controls permissions on each file on the system, which in term make up the system as a whole (as everything is a file). This was invented in 1971 and the idea (independent of the implementation) hasn&#39;t changed too much since.</p><p>Each user on the system has exactly one name and potentially many groups.</p><pre>christian @ pop-os ➜  ~  id    <br>uid=1000(christian) gid=1000(christian) groups=1000(christian),4(adm),27(sudo),998(docker)</pre><p>Each file has 3 permission elements: The user, the group, and others. Each of those can have one of multiple modes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*-AASi4N8O1TA-hdqn19iPQ.png" /><figcaption>Write modes (Image by author)</figcaption></figure><p>While (like with any topics in this article) you can go into the details on Wikipedia or the <a href="https://wiki.archlinux.org/index.php/File_permissions_and_attributes">Arch Wiki</a>, a dead simple system like this makes working on systems with many users possible.</p><p>My home directory, for instance, can only be edited by myself (and root, of course). A service user, such as http, might only be able to read and write data in /var/www. Or a CI/CD service user might be eternally damned to a life in a chroot jail.</p><p>It also adds a security benefit, as files without the +x bit cannot be executed - independent of whether they are actually executable files in the first place.</p><pre>christian @ pop-os ➜  images git:(development) ✗  ./hugo-deptree.png <br>zsh: permission denied: ./hugo-deptree.png<br>christian @ pop-os ➜  images git:(development) ✗  chmod +x ./hugo-deptree.png <br>christian @ pop-os ➜  images git:(development) ✗  ./hugo-deptree.png <br>zsh: exec format error: ./hugo-deptree.png</pre><p>Windows (for instance) uses Access Control Entires under NTFS ( <a href="https://docs.microsoft.com/en-us/windows/win32/secauthz/access-control-entries">ACE</a>) that work similarly, but are rarely exposed to the user and an order of magnitude more complicated that the simple &amp; secure system on Linux. macOS is POSIX certified, but doesn&#39;t expose the root user by default.</p><p>Permissions can also be easily validated (for instance, ssh keys should not be exposed) and have an equally simple CLI attached to them. They also happen to work on any major file system. As with other examples, simplicity is key.</p><h3>GUIs and Terminals: The Metamorphosis</h3><p>This is certainly a controversial one, but one thing that throws people off when having to deal with Linux is the frequent use of Terminal Emulators (shells). While many consumer focussed distributions, such as PopOS or Ubuntu, ship with many tools these days that abstract the user from having to deal with them, at the end of the day, a shell is always available.</p><p>And my take on that is simple: Working with a shell is faster than working with a GUI, once you are used to it. It also exposes any tool that you have installed (be it on the PATH or not) with a couple of keystrokes - you can even launch GUIs from the terminal.</p><p>The key to speed, besides the obvious “getting used to a workflow”, is little to no context switches and avoid using the mouse. That’s why many people, myself included, love vim for what is is: A powerful editor that is entirely keyboard based. This philosophy has come to light even in the graphical world, with window managers like <a href="https://wiki.archlinux.org/index.php/i3">i3</a>.</p><p>Modern shells, such as zsh, provide tons of comfort features such as auto-completion, powerful pattern-matching or fully-indexed search histories - even Bash (3+) has a lot of options hidden in the .bashrc file that enable similar feature sets.</p><p>So, here’s a workflow a lot of you will be familiar with: In a Python project, create a new local git branch, enable a fresh virtual environment, make sure it&#39;s ignored by git, install some packages, get some test data, and run your magical code.</p><p>On a shell, it’ll look a little something like this:</p><pre>git checkout -b feature/magic<br>python3 -m venv env<br>echo &quot;env&quot; &gt;&gt; .gitignore<br>source env/bin/activate<br>pip3 install pandas --upgrade<br>wget https://example.com/files/abc.csv<br>python3 main.py</pre><p>Shells also support forms of multi-threading that I won’t get into, but having something like a download run in a browser to not block a shell session is not a concern.</p><p>The same workflow, using large IDEs or GUIs in general, would work as such:</p><ol><li>Create a new branch in your IDE by going to the VCS tab and creating one</li><li>Open a shell regardless to activate the venv or hope for a plugin</li><li>Open an editor to add “env” to your .gitignore</li><li>Jump to a package manager interface to install your packages</li><li>Go to your browser to download a file and move it to your target directory</li><li>Context switch to the Run tab of your IDE</li></ol><p>The fact that I do not do that often might show here.</p><p>Furthermore, GUIs expose inherent complexity and design challenges, whereas CLIs are to ship with a man page that exposes all options:</p><pre>christian @ pop-os ➜  ~ ✗  man git | head -15<br>GIT(1)                                                                                 Git Manual                                                                                 GIT(1)<br><br>NAME<br>       git - the stupid content tracker<br><br>SYNOPSIS<br>       git [--version] [--help] [-C &lt;path&gt;] [-c &lt;name&gt;=&lt;value&gt;]<br>           [--exec-path[=&lt;path&gt;]] [--html-path] [--man-path] [--info-path]<br>           [-p|--paginate|-P|--no-pager] [--no-replace-objects] [--bare]<br>           [--git-dir=&lt;path&gt;] [--work-tree=&lt;path&gt;] [--namespace=&lt;name&gt;]<br>           [--super-prefix=&lt;path&gt;]<br>           &lt;command&gt; [&lt;args&gt;]<br><br>DESCRIPTION<br>       Git is a fast, scalable, distributed revision control system with an unusually rich command set that provides both high-level operations and full access to internals.</pre><p>GUIs have to, one way or another, expose all their options eventually, either through deep setting window trees, or straight up on one screen (or, in recent history, just don’t give you any options at all). Take a look at Tortoise Git for Windows’ context menu:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*GSR2OsJlv_KMc0Mi.png" /><figcaption><a href="https://tortoisegit.org/about/screenshots">https://tortoisegit.org/about/screenshots</a></figcaption></figure><p>It might just be me, but I haven’t had to create a patch in a long time - I did, however, use git archive very recently.</p><p>Obviously, I don’t want to be the “Old Man Yells at Cloud” guy — there is a time and a place for GUIs (I am writing this in VS code with a handful of shell sessions as part of the window), but once you are used to doing things by writing (and frequent use of tabs), rather than “point and click”, you will find it hard to go back for most daily development tasks.</p><p>I’d also wager to say that most applications are CLI first, GUI second — it’s easy to slap a GUI on a tool, once it already does what it needs to do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*KG9a-vRUb5solTNTcH_vJg.png" /><figcaption>A somewhat overused example of a complex GUI, despite the author just trying to add something to the world of Open Source (<a href="https://www.jensroesner.com/wgetgui/#screen">https://www.jensroesner.com/wgetgui/#screen</a>)</figcaption></figure><p>My last point here is also a problem that I have encountered primarily with junior developers: Dependence on GUIs abstracts people from the fundamental workings of systems, such as git. Every time I find myself in a teaching role, I try to <em>explain</em> how git works, rather than where to click or what commands to copy-paste: Working directory, staging, local and remote repositories, and where e.g. a git add actually affects anything.</p><p>Similar to how people who rely on sat-nav have difficulties remembering which interstate goes where (I am certainly one of them), relying on too many helpers and abstractions will prevent a learning curve that is important to really understand and, eventually, debug issues that inevitably will arise with complex systems. And this is coming from somebody who cannot remember the standard flags to decompress a tar.gz bundle. Do as I say, not as I do. :)</p><h3>Speed has never killed anyone. Suddenly becoming stationary, however&amp;mldr;</h3><p>My <a href="https://chollinger.com/">website</a> is very, well, minimalistic. The reason for that is simple: I don’t expect everybody to access is on a 10Gbit SFP+ link on a AMD Threadripper with 128GB memory with a set of RTX 3090s.</p><p>Depending on your flavor of Linux, it runs on figuratively anything: AMD, Intel, ARM, RISC-V, a lot of memory, not a lot of memory, a screen, many screens, or no screens (&amp;mldr;) — it’ll run. requires a total of 46MB of RAM.</p><p>Now, a maybe more common use case is ssh. While, yes, you can use X11 forwarding, by default, you&#39;ll be greeted with a blinking cursor on a black screen. Remembering what I said above: Now, you can do everything (except for things that absolutely require a window sever) that the Kernel and your applications can do, all over a very, very slim network link.</p><p>The operating principles are identical to using Linux locally — your permissions, programs, editors (&amp;mldr;) work just the same, and from the bed of a truck with a satellite link in rural Wyoming, if you so desire. I’ve been subject to horrible connections that can barely handle drawing a single image on the screen, not to mention 30, 60, or 120 a second. As the system itself is fundamentally based on being controlled by a shell, you don’t really lose anything of value — if you are comfortable with it.</p><p>Also, SSH can be very information-dense — because it’s text. Here’s a picture of my server’s UPS (which counts as a GUI, right?):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KcZ7XKZS5zeRcjII.jpg" /><figcaption>My Hurricane Season UPS (Image by author)</figcaption></figure><p>And here’s a lot more information via SSH:</p><pre>christian @ bigiron ➜  ~  sudo pwrstat -status  <br>The UPS information shows as following:<br><br>	Properties:<br>		Model Name................... OR1500LCDRM1Ua<br>		Firmware Number.............. xxx<br>		Rating Voltage............... 120 V<br>		Rating Power................. 900 Watt(1500 VA)<br><br>	Current UPS status:<br>		State........................ Normal<br>		Power Supply by.............. Utility Power<br>		Utility Voltage.............. 121 V<br>		Output Voltage............... 121 V<br>		Battery Capacity............. 100 %<br>		Remaining Runtime............ 90 min.<br>		Load......................... 108 Watt(12 %)<br>		Line Interaction............. None<br>		Test Result.................. Unknown<br>		Last Power Event............. Blackout at xxxx for 70 min.</pre><h3>Flexibility &amp; Open Source</h3><p>My last point will be kept short, as it has been the inspiration for countless philosophical debates for decades now (do yourself a favor and read some posts from the early 1990’s on <a href="https://www.usenetarchives.com/groups.php?c=comp&amp;p=31">Usenet archives</a>), but having control and insights is better than the opposite.</p><p>Everything on a truly free GNU/Linux system is Open Source and licensed appropriately. Issues you encounter can be explained, in most cases, by looking at the code that caused the issue. Configurations and behaviors of seemingly obscure problems (did you know there’s limits on the Kernel’s keyring in /proc/sys/kernel/keys/maxkeys?) can be explained if the system they operate in is transparent.</p><p>And if you don’t like something about the way your system works, there’s virtually nothing stopping you from changing it. Don’t like the file manager? Get a new one. Don’t like the limit on open file descriptors? Remove it. Don’t like the way syscall abc works? Change it and build a new Kernel.</p><p>You don’t <em>have</em> to do any of these — but you certainly can. And sometimes, you might even need to, if you find yourself being responsible for a highly-specific use case.</p><h3>Conclusion</h3><p>I’ve only outlined a handful of points as to why I prefer GNU/Linux over Windows (and even macOS, which I quite enjoy, purely for it’s UNIX roots). This is by no means a complete list, or even a very in-depth one; but I hope I was able to enlighten some of you as to why I do what I do and why maybe, you should give it a shot some time.</p><p>And, naturally, this is only <em>my perspective</em>. I’m simply not a “Windows guy” — but just like with most things, you should be able to use what you feel most comfortable with. Microsoft’s WSL adventures to seem to indicate that I am not alone in this, however. :)</p><p><em>Originally published at </em><a href="https://chollinger.com/blog/2020/12/why-i-use-linux/"><em>https://chollinger.com</em></a><em> on December 21, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fc70e370b24" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/why-i-use-linux-5fc70e370b24">Why I use Linux</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Data Engineering Perspective on Go vs. Python (Part 2 — Dataflow)]]></title>
            <link>https://medium.com/data-science/a-data-engineering-perspective-on-go-vs-python-part-2-dataflow-472b42a14f9?source=rss-7af40a2161c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/472b42a14f9</guid>
            <category><![CDATA[apache-beam]]></category>
            <category><![CDATA[dataflow]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Christian Hollinger]]></dc:creator>
            <pubDate>Mon, 06 Jul 2020 00:00:00 GMT</pubDate>
            <atom:updated>2020-07-07T14:01:16.988Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Data Engineering Perspective on Go vs. Python (Part 2 — Dataflow)</h3><h4>Exploring, profiling, and benchmarking the go SDK with Apache Beam &amp; Dataflow</h4><h3>Introduction</h3><p>In Part 2 of our comparison of Python and go from a Data Engineering perspective, we’ll finally take a look at Apache Beam and Google Dataflow and how the go SDK and the Python SDK differ, what drawbacks we’re dealing with, how fast it is by running extensive benchmarks, and how feasible it is to make the switch.</p><p>You can find <a href="https://chollinger.com/blog/2020/06/a-data-engineering-perspective-on-go-vs.-python-part-1/">Part 1 here</a>.</p><h3>Apache Beam &amp; Google Dataflow</h3><p>While we have used <a href="https://beam.apache.org/">Apache Beam</a> on several occasions <a href="https://chollinger.com/blog/2018/06/analyzing-reddits-top-posts-images-with-google-cloud-part-1/#introducing-data-flow">before</a>, allow me to give another short introduction.</p><blockquote><em>Apache Beam is an open source, unified model for defining both batch and streaming data-parallel processing pipelines. Using one of the open source Beam SDKs, you build a program that defines the pipeline. The pipeline is then executed by one of Beam’s supported distributed processing back-ends, which include Apache Flink, Apache Spark, and Google Cloud Dataflow.</em></blockquote><blockquote><a href="https://beam.apache.org/get-started/beam-overview/"><em>https://beam.apache.org/get-started/beam-overview/</em></a></blockquote><p>Beam can be used for a variety of data use cases, not unlike Apache Spark — ETL (Extract, Transform, Load) pipelines, stream analytics, or simple data movement from, for instance, a file system to an RDMBS.</p><h3>Why Beam is interesting</h3><p>One of the best professional advice I ever got is to ask “So What?”. That being said: So what, why do I care about Beam?</p><p>For me, one of the most interesting aspects of Beam’s model is the decoupling of pipeline logic, language, and execution environment. I can design my logic on a piece of paper (i.e., draw a DAG with some Beam-specific terminology - we’ll do that in a second), implement it in any of the major languages - even multiple - and run it on any of the supported Runners.</p><p>The last time we used it on this blog, we used it to write a Pipeline to analyze reddit posts and executed it on the Dataflow runner as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T9YQYRKtvQpNF4Oj.png" /></figure><p>As this pipeline was written in Python, there is nothing stopping us from running <em>the exact same job</em> on a on-premise Hadoop cluster, on AWS EMR, or just run it locally using the DirectRunner. This level of portability, in combination with a programming model that I happen to find more streamlined than say Spark&#39;s, makes Beam a very interesting framework.</p><p>We’ll actually do exactly that in the example section of this article and design a pipeline, write it in both Python and go, and run it on different Runners.</p><h3>Core Concepts</h3><p>Everything in Beam starts with a Pipeline. The Beam programming model works by exposing high-level abstractions through code that allow your Pipeline to execute a graph of PTransforms on a given dataset, which in term is operating on immutable collections, called PCollections, which can be moved to a persistent state through IO operations. Jobs can be executed on different Runners to provide a (distributed) execution environment.</p><p>Let’s dig into those concepts before we look at a real-world example.</p><blockquote><em>This is a condensed version of the </em><a href="https://beam.apache.org/documentation/programming-guide/"><em>official Apache Beam documentation</em></a><em>, which I suggest you read in full for a more in-depth view</em></blockquote><h3>Pipeline</h3><p>A Pipeline object is the starting point of any job, which is usually initialized with a configuration object that defines <em>how</em> and <em>where</em> your pipeline runs.</p><h3>PCollections</h3><p>A PCollection, not unlike a Spark RDD or DataFrame, are immutable collections of data that can be modified in-memory through the lifecycle of a pipeline.</p><p>The data within a PCollection can be of any arbitrary type, as long as the elements can be encoded as string for serializing them across the workers.</p><p>PCollections can be of any size, but their elements might be worked on by different workers, if the collection is too large to fit into memory on a single worker node. Furthermore, they can be either <em>bounded</em> (i.e., have a fixed size) or <em>unbounded</em> (i.e., are &quot;open ended&quot;, like in a streaming scenario).</p><h3>Transforms</h3><p>Transforms apply logic on individual elements of a PCollection, by applying user code and logic, and returning a full PCollection that can be used in a subsequent step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P7jek9Tc2xwyPcS6vJaWWQ.png" /><figcaption><a href="https://beam.apache.org/documentation/programming-guide/#applying-transforms">https://beam.apache.org/documentation/programming-guide/#applying-transforms</a></figcaption></figure><p>It is also possible to branch a pipeline, by splitting the DAG into multiple, independent steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QAWIQnSs6-Cn-BL7LHkAFA.png" /><figcaption><a href="https://beam.apache.org/documentation/programming-guide/#applying-transforms">https://beam.apache.org/documentation/programming-guide/#applying-transforms</a></figcaption></figure><p>Custom transforms need to adhere to some rules, most notably <strong>serializability</strong> (as data needs to be transmitted between workers), <strong>single threaded execution</strong> (as each element should be worked on, as orchestrated by the underlying Runner, in its own thread), and <strong>idempotence</strong> (as re-tries might occur).</p><p>Beam provides several core transforms that can be utilized out-of-the-box:</p><ul><li>ParDo</li><li>GroupByKey</li><li>CoGroupByKey</li><li>Combine</li><li>Flatten</li><li>Partition</li></ul><h4>ParDo</h4><p>A ParDo transform is probably the most common one, as it is comparable to a map operation: Applying logic to each element of a PCollection and returning said element (or not returning it and hence, filtering the collection).</p><p>Thing of ParDo as your fundamental building blog of a job that applies logic on a flat stream of data, which can then be further enhanced by grouping, flattening, and other aggregation logic down the line.</p><p>To understand what a ParDo actually does, the Beam docs provide a great explanation of the lifecycle of a ParDo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f1Fq8A8v_W2qRzl9Gp5QJQ.png" /><figcaption><a href="https://beam.apache.org/documentation/programming-guide/#applying-transforms">https://beam.apache.org/documentation/programming-guide/#applying-transforms</a></figcaption></figure><h4>CoGroupByKey</h4><p>CoGroupByKey aggregates all input elements by their key over multiple input collections. CoGroupByKey performs a relational join of two or more key/value PCollections that have the same key type - a very useful thing we&#39;ll be using in the example below.</p><h3>Schemas</h3><p>A Schema defines the logical structure and data types for the elements within a PCollection. Beam Schemas, similar to a parquet or database schema, should define names, types, and information on whether a field can be NULL.</p><p>Beam supports the following primitive types:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*QtZX1EKMKhqn_JU6c-9Gaw.png" /><figcaption><a href="https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#schemas">https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#schemas</a></figcaption></figure><h3>I/O</h3><p>I/O is needed for providing input data and giving the pipeline one or multiple defined outputs. I will refer to <a href="https://chollinger.com/blog/2020/06/a-data-engineering-perspective-on-go-vs.-python-part-1/#io">Part 1</a> for a somewhat complete list of all I/O connectors by SDK.</p><p>I/O connectors can also be customized, by inheriting from the existing Base classes to read non-supported file types. This can be challenging (as you want to be able to split a file source so it can be worked on by multiple workers), but after a while, becomes quite straightforward.</p><h3>Runners</h3><p>Runners define which system executes the pipeline, for instance by running locally (DirectRunner), on Google Dataflow, or via Apache Spark.</p><p>Similar to I/O, please refer to <a href="https://chollinger.com/blog/2020/06/a-data-engineering-perspective-on-go-vs.-python-part-1/#runners">Part 1</a> for an overview.</p><h3>The Use Case for a Sample Job</h3><p>In order to demonstrate some of the fundamental differences, let’s define a sample use case that we can implement in both Python and go.</p><p>In this example, we follow this simple user story: “As a <em>movie enthusiast</em>, I want to <em>find movies that fit my preferences</em>, so that <em>I can watch a new movie”</em>.</p><p>Our <em>preferences</em> shall be:</p><ol><li>We want to parse both titles and ratings (<em>Reading data</em>)</li><li>We are only interested in movies, not TV shows; furthermore, movies should be made after 1970, to get some more reliable metadata to base our decision on, as older titles often only have basic information (<em>Filtering data</em>)</li><li>We want both basic title as well as rating information from different sources (<em>Combining data</em>)</li><li>We want the data in a useable format (<em>Writing data</em>) [0]</li></ol><p>For this, we’ll use the <a href="https://www.imdb.com/interfaces/">IMDb DataSet</a>, which can be utilized for non-commercial use and is refreshed daily.</p><p><em>The full source code is available on </em><a href="https://github.com/chollinger93/beam-examples"><em>GitHub</em></a><em>.</em></p><p><em>[0] You might have gathered by now that these “preferences” are to demonstrate various </em><em>Beam functionality - this is not a fancy recommendation engine and we don&#39;t really care about the output</em></p><h3>Drawing the design</h3><p>As I’ve said in the introduction, we can start by designing our pipeline first and then cover the language-specific logic later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*olttE5JeFlUr_7zfAEatyA.png" /><figcaption><a href="https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#drawing-the-design">https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#drawing-the-design</a></figcaption></figure><p>We have 2 main flows here, both of which do similar things: They read data, parse their format, and apply custom filters to the data. Next, they are being combined into one coherent set and written to one or multiple I/O targets.</p><p>Let’s so how to translate this into code.</p><h3>Getting data</h3><p>If you agree with IMDb’s license, you can find the data <a href="https://datasets.imdbws.com/">here</a>.</p><p>We’ll start with the basic title data and make sure we start with a small test set, so we can develop locally without a cluster. In order to do that, we’ll grab random test data, as well as a movie we know fits our criteria, the 1971 classic “Vanishing Point”, with the id tt0067927 (as it is unlikely we&#39;ll find more matches between the 2 data sets we&#39;ll be using otherwise, given the volume).</p><pre>wget https://datasets.imdbws.com/title.basics.tsv.gz &amp;&amp; gunzip title.basics.tsv.gz <br># Create a small test file<br>head -1 title.basics.tsv &gt; title.basics.100.tsv<br>shuf -n 100 title.basics.tsv &gt;&gt; title.basics.100.tsv<br>grep &quot;tt0067927&quot; title.basics.tsv &gt;&gt; title.basics.100.tsv</pre><h4>title.basics</h4><p>This datasets contains basic title information as such and is a <em>564MB Tab Separated file</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*3gwisM-KmNRFJ9CSHjfqDA.png" /><figcaption><a href="https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#getting-data">https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#getting-data</a></figcaption></figure><p>We’ll be using this to filter the majority of the records.</p><h4>title.ratings</h4><p>This dataset contains ratings of all titles and is a <em>18MB Tab Separated file</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*pK9fG-PkpEdKWFdLSKbPMw.png" /><figcaption><a href="https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#getting-data">https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#getting-data</a></figcaption></figure><h3>Creating the Pipeline</h3><p>The first step in our Beam Pipeline is to create a skeleton code that creates the Pipeline object, parsing arguments, and setting up a logger.</p><h3>Python</h3><p>We first need to install Beam by running pip3 install --upgrade pip and pip3 install apache-beam==2.22.0 --upgrade.</p><p>Our skeleton uses Python&#39;s standard logger module for logging and argparse to read arguments that will be passed to the pipeline.</p><pre>from __future__ import absolute_import<br><br>import argparse<br>import logging<br>import apache_beam as beam<br>from apache_beam.io import ReadFromText<br>from apache_beam.io import WriteToText<br>from apache_beam.options.pipeline_options import PipelineOptions, GoogleCloudOptions<br>from apache_beam.options.pipeline_options import SetupOptions<br><br>def run(argv=None):<br>    # Parse arguments<br>    parser = argparse.ArgumentParser()<br>    parser.add_argument(&#39;--input-ratings&#39;,<br>                        dest=&#39;input_ratings&#39;,<br>                        required=True,<br>                        help=&#39;Input rating file to process.&#39;)<br>    parser.add_argument(&#39;--input-titles&#39;,<br>                        dest=&#39;input_titles&#39;,<br>                        required=True,<br>                        help=&#39;Input title file to process.&#39;)<br>    parser.add_argument(&#39;--output&#39;,<br>                        dest=&#39;output&#39;,<br>                        required=True,<br>                        help=&#39;Output to write results to.&#39;)<br>    known_args, pipeline_args = parser.parse_known_args(argv)<br><br>    pipeline_options = PipelineOptions(pipeline_args)<br>    pipeline_options.view_as(SetupOptions).save_main_session = True<br><br>    # Create the pipeline<br>    with beam.Pipeline(options=pipeline_options) as p:<br>        # TODO: Run it<br>        pass<br><br>if __name__ == &#39;__main__&#39;:<br>    # Set the logger<br>    logging.getLogger().setLevel(logging.INFO)<br>    logging.basicConfig(format=&#39;%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s&#39;,<br>        datefmt=&#39;%Y-%m-%d:%H:%M:%S&#39;,<br>        level=logging.INFO)<br>    # Run the core pipeline<br>    logging.info(&#39;Starting&#39;)<br>    run()</pre><p>There is not much else of note here — all of our pipeline code will be under the with block, which will define the DAG we just designed once we wrote our individual steps.</p><h3>Go</h3><p>For go, we can install beam via go get as opposed to pip via go get -u github.com/apache/beam/sdks/go/...</p><p>Next, our pipeline skeleton will use the flags package for arguments, as well as log for logging.</p><pre>package main<br><br>import (<br>	&quot;context&quot;<br>	&quot;flag&quot;<br>	&quot;log&quot;<br><br>	&quot;github.com/apache/beam/sdks/go/pkg/beam&quot;<br>	&quot;github.com/apache/beam/sdks/go/pkg/beam/io/textio&quot;<br>	&quot;github.com/apache/beam/sdks/go/pkg/beam/x/beamx&quot;<br>)<br><br>func main() {<br>	// Define arguments<br>	var inputBasePath = flag.String(&quot;input-basics&quot;, &quot;&quot;, &quot;Input base file&quot;)<br>	var inputRatingsPath = flag.String(&quot;input-ratings&quot;, &quot;&quot;, &quot;Input ratings file&quot;)<br>	var outputPath = flag.String(&quot;output&quot;, &quot;&quot;, &quot;Output path&quot;)<br>	// Parse flags<br>	flag.Parse()<br><br>	// Initialize Beam<br>	beam.Init()<br><br>	// Input validation. Must be after Init().<br>	if *inputBasePath == &quot;&quot; || *inputRatingsPath == &quot;&quot; || *outputPath == &quot;&quot; {<br>		log.Fatal(&quot;Usage: movie_pipeline --input-basics $PATH, --input-ratings $PATH --output $PATH&quot;)<br>	}<br><br>	// Create a Pipeline<br>	p := beam.NewPipeline()<br>	s := p.Root()<br><br>    // Pipeline code<br><br>	// Concept #1: The beamx.Run convenience wrapper allows a number of<br>	// pre-defined runners to be used via the --runner flag.<br>	if err := beamx.Run(context.Background(), p); err != nil {<br>		log.Fatalf(&quot;Failed to execute job: %v&quot;, err)<br>	}<br>}</pre><p>There are a couple of noteworthy points here. First off, the flags package does not support mandatory attributes and as such, we must check the String pointers passed by flag.Parse() manually. You will find similar blocks throughout the code, as go does not know the concept of an Exception and therefore, errors are return elements (i.e., a function might return a tuple of data and an optional error) and need to be checked against manually.</p><p>Furthermore, note how beam.Init() has to be called before the input validation.</p><h3>Reading &amp; Parsing Data</h3><p>Next, we need to read the data and parse the TSV format. We can use our first ParDo call to achieve this.</p><h3>Python</h3><p>First, let’s define a ParDo operation by creating a subclass of beam.DoFn as such:</p><pre>class ParseCsv(beam.DoFn):<br>    def __init__(self, col_names: list):<br>        self.col_names = col_names<br><br>    def process(self, string: str):<br>        reader = csv.DictReader(string.splitlines(), fieldnames=self.col_names, delimiter=&#39;\t&#39;)<br>        for row in reader:<br>            yield row</pre><p>This class will simply parse our CSV from rows of str into a dict, giving us dict as individual elements to work with in the next transforms.</p><p>For a custom ParDo, the method process must be overwritten. process should be a generator and hence, has to yield individual records. The function will be called <em>for each record in the </em><em>PCollection</em>. You will see what happens if we use return instead of yield in a second.</p><p>Custom arguments can be passed to the class by overwriting the constructor in __init__().</p><p>For integrating this with the pipeline, we need to define the flow. In the Beam Python SDK, the &gt;&gt; and | operators define our individual processing (apply) steps on top of a PCollection.</p><p>For each step, we can call beam.ParDo and provide an Instance of our DoFn subclass.</p><pre>with beam.Pipeline(options=pipeline_options) as p:<br>    (p  | &#39;Read data&#39; &gt;&gt; beam.io.ReadFromText(known_args.input_titles, skip_header_lines=1)<br>        | &#39;Parse CSV&#39; &gt;&gt; beam.ParDo(ParseCsv([&#39;titleId&#39;, &#39;ordering&#39;,&#39;title&#39;,&#39;region&#39;,&#39;language&#39;,&#39;types&#39;,&#39;attributes&#39;,&#39;isOriginalTitle&#39;]))<br>        | &#39;Print&#39; &gt;&gt; beam.Map(print)<br>    )</pre><p>This will read the Text file, parse the TSV, yield a PCollection, and use map to simply print the values.</p><p>The output looks like this:</p><pre>{&#39;titleId&#39;: &#39;tt0000001&#39;, &#39;ordering&#39;: &#39;1&#39;, &#39;title&#39;: &#39;Карменсіта&#39;, &#39;region&#39;: &#39;UA&#39;, &#39;language&#39;: &#39;\\N&#39;, &#39;types&#39;: &#39;imdbDisplay&#39;, &#39;attributes&#39;: &#39;\\N&#39;, &#39;isOriginalTitle&#39;: &#39;0&#39;}<br>{&#39;titleId&#39;: &#39;tt0000001&#39;, &#39;ordering&#39;: &#39;2&#39;, &#39;title&#39;: &#39;Carmencita&#39;, &#39;region&#39;: &#39;DE&#39;, &#39;language&#39;: &#39;\\N&#39;, &#39;types&#39;: &#39;\\N&#39;, &#39;attributes&#39;: &#39;literal title&#39;, &#39;isOriginalTitle&#39;: &#39;0&#39;}</pre><p>This simple starting point shows the very specific syntax that Beam uses with Python. While it does create a clear, readable logic, it certainly can be more confusing to read than a regular method-chaining approach.</p><h3>Go</h3><p>Here, we will probably see some of the most striking differences between Python and go - but as I&#39;ve found, also evenly striking similarities.</p><p>Reading the data and applying the next ParDo does not follow Python&#39;s overloaded syntax (using &gt;&gt; and |), <em>but rather results in various </em><em>PCollections returned after each step</em>:</p><pre>// Parse the movies file<br>	lines_movies := textio.Read(s, *inputBasePath)<br>	base_movies := beam.ParDo(s, &amp;movieFn{}, lines_movies)</pre><p>While this might look very different from Python, fundamentally, the same thing is happening: Every step of the graph returns a <em>new </em><em>PCollection</em>, which can be worked on by the next step.</p><p>Another thing to mention here is the use of pointers. *inputBasePath is a pointer to the flags argument we gave earlier. In go, a *string can be nil, whereas normal strings cannot (as nil in go means &quot;it does not point to anything&quot;, whereas a string can only ever be empty or filled with characters - more on that below). Python, rather famously, does not have exposed Pointers (and neither does Java, Beam&#39;s other major language).</p><p>The next seemingly very different thing is the actual ParDo. Let&#39;s break this down.</p><p>Beam&#39;s generic ParDo function signature looks like this:</p><pre>func ParDo(s Scope, dofn interface{}, col PCollection, opts ...Option) PCollection {<br>	ret := MustN(TryParDo(s, dofn, col, opts...))<br>	if len(ret) != 1 {<br>		panic(formatParDoError(dofn, len(ret), 1))<br>	}<br>	return ret[0]<br>}</pre><p>Where s Scope is your pipeline object, dofn interface{} uses go&#39;s empty interface logic to define an interface that may hold values of any type (I’ll get back to that in a second), and col is obviously our PCollection, similar to what we saw in Python.</p><p>This means that beam.ParDo(s, &amp;movieFn{}, lines_movies) simply states: Apply the function moveFn, which has to be a ParDo (remember: static typing!), and give it the PCollection called line_movies as an input.</p><p>Once you got over the syntax, this is very similar (if not to say, identical) to what happens with</p><pre>| &#39;Parse CSV&#39; &gt;&gt; beam.ParDo(ParseCsv([&#39;titleId&#39;, &#39;ordering&#39;,&#39;title&#39;,&#39;region&#39;,&#39;language&#39;,&#39;types&#39;,&#39;attributes&#39;,&#39;isOriginalTitle&#39;]))</pre><p>In Python.</p><p>We’ll take a look at what &amp;movieFn{} does in the next section. In any case, at this point, we have a structured representation of each row in the input TSV.</p><h3>Transforming data</h3><p>Next, we need to transform our data to make sure we have the right data types that we can use in our output and to make sure our filter logic in the next steps is clear.</p><h3>Python</h3><p>Notice how NULL in the above output is referenced as \N and how isOriginalTitle sounds like a boolean, but is actually an integer.</p><p>We can simply create another ParDo transformation to handle this scenario. In order to avoid a single ParDo class for each file, we&#39;ll make it dynamic.</p><pre>class CleanData(beam.DoFn):<br>    def __init__(self, bool_cols=[]):<br>        self.bool_cols = bool_cols<br><br>    def process(self, record: dict):<br>        for k in record:<br>            # Map \N to None<br>            if record[k] == &#39;\\N&#39;:<br>                record[k] = None<br>        # Convert e.g., `isOriginalTitle` to Boolean<br>        for col in self.bool_cols:<br>            if record[col] == &#39;0&#39;: <br>                record[col] = False<br>            else:<br>                record[col] = True<br>        # Return<br>        yield record</pre><p>As Python dicts can accept arbitrary types, simply changing values within the dict is easy. Please note how we have to treat 0 as a string, as Python, being dynamically typed, does not enforce the type here and given the TSV input, everything is a str.</p><p>At this point, you might find yourself in one of two schools of thought: Either, you are happy that Python allows you to write your Pipeline using dicts that do not care about their respective types (or even the number or names of fields within the dict!) - which makes writing pipelines a lot easier.</p><p>Or, you are missing the strict typing that Java and go force. In both cases, we are actively forced to care about structure and types before persisting any data anywhere, avoiding invalid conversions or wrong outputs into our target system.</p><h3>Go</h3><p>For go, let&#39;s re-visit the &amp;movieFn{} argument from earlier.</p><p>We’ve created a struct called moveFn, which holds the structure of our data and their types:</p><pre>type movieFn struct {<br>	tconst, titleType, primaryTitle, originalTitle string<br>	isAdult                                        bool<br>	startYear, endYear, runtimeMinutes             int64<br>	genres                                         string<br>}</pre><p>We then define a ParDo method on this struct:</p><pre>func (f *movieFn) ProcessElement(line string, emit func(movieFn)) {<br>	row := strings.Split(line, &quot;\t&quot;)<br>	fmt.Printf(&quot;%v\n&quot;, row)<br>	// Skip the header<br>	if row[0] != &quot;tconst&quot; {<br>		// Map nulls<br><br>		// Convert the types<br>		startYear, err1 := strconv.ParseInt(row[5], 10, 64)<br>		endYear, _ := strconv.ParseInt(row[6], 10, 64)<br>		runtimeMinutes, err3 := strconv.ParseInt(row[7], 10, 64)<br>		// Convert Boolean<br>		isAdultInt, err4 := strconv.ParseInt(row[4], 10, 64)<br>		var isAdult bool<br>		if isAdultInt == 0 {<br>			isAdult = false<br>		} else {<br>			isAdult = true<br>		}<br>		if err1 == nil &amp;&amp; err3 == nil &amp;&amp; err4 == nil {<br>			// If the types match, return a rating struct<br>			m := movieFn{<br>				tconst:         row[0],<br>				titleType:      row[1],<br>				primaryTitle:   row[2],<br>				originalTitle:  row[3],<br>				isAdult:        isAdult,<br>				startYear:      startYear,<br>				endYear:        endYear,<br>				runtimeMinutes: runtimeMinutes,<br>				genres:         row[8],<br>			}<br>			fmt.Printf(&quot;%v\n&quot;, m)<br>			emit(m)<br>		}<br>	}<br>}</pre><p>Which combines both parsing the row and converting the types into a single ParDo. We’ve split this up in Python to explain the concepts, but fundamentally, the same thing happens: We need to split the line by the delimiter, a tab, and create a json like structure (which is what this struct will be serialized to internally!).</p><p>In order to avoid having to deal with multiple structs, as we (as opposed to Python) cannot simply &quot;re-use&quot; the dict and change the type[0], we are doing the conversion in a single step.</p><p>In the actual call to ParDo, &amp;movieFn{} simply translates to “a reference to the memory location of the movieFn struct, which is initialized as empty”.</p><p>Last but not least, note how the return of the function is emit func(movieFn)). The Beam SDK uses reflection to gather the type from the incoming and outgoing PCollections, in our case, an input as line string and output as movieFn - by specifying a function as an <em>input</em>, which we then call similar to Python&#39;s native yield. Please note how the actual function <em>does not return anything</em>, as the emit function is an argument to our ParDo!</p><p>You can call this function anything — emit is simply the style found in the <a href="https://github.com/apache/beam/tree/master/sdks/go/examples">go examples</a>.</p><p>It should be noted that this struct can of course also hold custom methods (similar to the Python class) by simply providing more methods.</p><p>Let’s re-visit the string and nil comment and try to convert &#39;\N&#39; to nil to match our Python pipeline, assuming we want a NULL like type for writing data into e.g. BigQuery:</p><pre>func (f *movieFn) CleanNulls(row []string, nullColIds []int) []string {<br>	for i, _ := range row {<br>		if row[i] == &quot;\\N&quot; {<br>			row[i] = nil<br>		}<br>	}<br>	return row<br>}</pre><p>Which of course, the compiler doesn’t accept:</p><pre>cannot use nil as type string in assignment</pre><p>One way around that is to either use *string or to follow, e.g. <a href="https://godoc.org/cloud.google.com/go/bigquery#InferSchema">bigquery-&gt;InterSchema</a> to map NULL to systems that expect it for Strings.</p><p>Furthermore, we need to make sure we don’t accidentally export this method, as otherwise, we’ll get:</p><pre>graph.AsDoFn: unexpected exported method CleanNulls present. Valid methods are: [Setup StartBundle ProcessElement FinishBundle Teardown CreateInitialRestriction SplitRestriction RestrictionSize CreateTracker</pre><p>Which can be fixed by simply not exporting it by starting the function with a lower-case “c”:</p><pre>func (f *movieFn) cleanNulls(row []string) []string {<br>	for i, _ := range row {<br>		if row[i] == &quot;\\N&quot; {<br>			row[i] = &quot;&quot;<br>		}<br>	}<br>	return row<br>}</pre><p>This is yet another difference to Python, as go ensures we follow the interface that is expected.</p><p>While I personally do think that the logic go imposes - a String is either empty or not, and having two different “empty” types doesn’t add much value - I can see this being very off-putting for somebody coming at go from a Python or Java perspective.</p><p><em>[0] I assume we could use an </em><em>interface{}</em></p><h3>Filtering data</h3><p>Next, we want to filter the data to make sure we only get the movies and ratings we’re after.</p><h3>Python</h3><p>Filtering data can be done by using yet another ParDo class, but with a catch. Let&#39;s try this:</p><pre>class FilterBasicData(beam.DoFn):<br>    def process(self, record: dict):<br>        if record[&#39;titleType&#39;] == &#39;movie&#39; and not record[&#39;isAdult&#39;]:<br>            yield record<br>        else:<br>            yield None</pre><p>The output looks unfortunate:</p><pre>None<br>{&#39;tconst&#39;: &#39;tt3080844&#39;, &#39;titleType&#39;: &#39;movie&#39;, &#39;primaryTitle&#39;: &#39;Almost Holy&#39;, &#39;originalTitle&#39;: &#39;Crocodile Gennadiy&#39;, &#39;isAdult&#39;: False, &#39;startYear&#39;: &#39;2015&#39;, &#39;endYear&#39;: None, &#39;runtimeMinutes&#39;: &#39;96&#39;, &#39;genres&#39;: &#39;Biography,Documentary,Drama&#39;}<br>None</pre><p>If we, however, recall that DoFn is a generator (and not just a method that for some reason uses yield instead of return), we can make quick use of that and simply <em>not return invalid records</em> (as well as add our other filter criteria) and hence, create a smaller PCollection to work with:</p><pre>class FilterBasicData(beam.DoFn):<br>    def process(self, record: dict):<br>        if record[&#39;titleType&#39;] == &#39;movie&#39; and not record[&#39;isAdult&#39;]: <br>            yield record<br>        # No else - no yield</pre><p>And get a decent looking output:</p><pre>{&#39;tconst&#39;: &#39;tt3080844&#39;, &#39;titleType&#39;: &#39;movie&#39;, &#39;primaryTitle&#39;: &#39;Almost Holy&#39;, &#39;originalTitle&#39;: &#39;Crocodile Gennadiy&#39;, &#39;isAdult&#39;: False, &#39;startYear&#39;: &#39;2015&#39;, &#39;endYear&#39;: None, &#39;runtimeMinutes&#39;: &#39;96&#39;, &#39;genres&#39;: &#39;Biography,Documentary,Drama&#39;}<br>{&#39;tconst&#39;: &#39;tt7497202&#39;, &#39;titleType&#39;: &#39;movie&#39;, &#39;primaryTitle&#39;: &#39;Wonderful Losers: A Different World&#39;, &#39;originalTitle&#39;: &#39;Wonderful Losers: A Different World&#39;, &#39;isAdult&#39;: False, &#39;startYear&#39;: &#39;2017&#39;, &#39;endYear&#39;: None, &#39;runtimeMinutes&#39;: &#39;71&#39;, &#39;genres&#39;: None}</pre><p>But what about our filter by year? If we were to try and record[&#39;startYear&#39;] &gt;= 1970: as a condition, we&#39;re met with:</p><pre>TypeError: &#39;&gt;=&#39; not supported between instances of &#39;str&#39; and &#39;int&#39; [while running &#39;Filter data&#39;]</pre><p>Due to Python’s lack of strict typing (remember how we did not define a schema anywhere). We can hotfix this by extending CleanData:</p><pre>class CleanData(beam.DoFn):<br>    def __init__(self, bool_cols=[], int_cols=[]):<br>        self.bool_cols = bool_cols<br>        self.int_cols = int_cols<br><br>    def process(self, record: dict):<br>        for k in record:<br>            # Map \N to None<br>            if record[k] == &#39;\\N&#39;:<br>                record[k] = None<br>        # Convert e.g., `isOriginalTitle` to Boolean<br>        for col in self.bool_cols:<br>            if record[col] == &#39;0&#39;:<br>                record[col] = False<br>            else:<br>                record[col] = True<br>        # Force-parse numeric values<br>        for col in self.int_cols:<br>            if record[col] and record[col].isdigit():<br>                record[col] = int(record[col])<br>        # Return<br>        yield record</pre><p>And adjust our filter to:</p><pre>class FilterBasicData(beam.DoFn):<br>    def process(self, record: dict):<br>        if record[&#39;titleType&#39;] == &#39;movie&#39; and not record[&#39;isAdult&#39;] and record[&#39;startYear&#39;] and record[&#39;startYear&#39;] &gt;= 1970:<br>            yield record<br>        # No else - no yield</pre><p>Which gives us a list of movies.</p><h3>Go</h3><p>Filtering here is not much different in go. We can make the same mistake as we did in Python, but confusing return and (in this case) a emit function:</p><pre>// Filters Movies<br>func filterMovies(movie movieFn) movieFn {<br>	if !movie.isAdult &amp;&amp; movie.startYear &gt;= 1970 {<br>		return movie<br>	}<br>	return movieFn{}<br>}</pre><p>Which will return</p><pre>{    false 0 0 0 }<br>{tt3080844 movie Almost Holy Crocodile Gennadiy false 2015 0 96 Biography,Documentary,Drama}<br>{    false 0 0 0 }</pre><p>Whereas the approach we discussed in the last section works:</p><pre>// Filters Movies<br>func filterMovies(movie movieFn, emit func(movieFn)) {<br>	if !movie.isAdult &amp;&amp; movie.startYear &gt;= 1970 {<br>		emit(movie)<br>	}<br>}</pre><p>Please note how we won’t have any TypeError: &#39;&gt;=&#39; not supported between instances of &#39;str&#39; and &#39;int&#39; type issues with our statically typed struct s.</p><h3>Side Inputs, CoGroupByKey, and Joins</h3><p>Due to the relational nature of the IMDb data, we will have to deal with multiple files to get all criteria we need.</p><p>There are two main ways of doing this: Side Inputs, if the data is small enough to comfortably fit in memory, or CoGroupByKey, which is a much more expensive variant that will cause a shuffle.</p><p>We’ll look at both, even though we only need one way of doing it.</p><p>Let’s get the ratings data and grab a handful of records from the above output to ensure we’ll have at least one match:</p><pre>wget https://datasets.imdbws.com/title.ratings.tsv.gz &amp;&amp; gunzip title.ratings.tsv.gz <br># Create a small test file<br>head -1 title.ratings.tsv &gt; title.ratings.100.tsv # header<br>shuf -n 100 title.ratings.tsv &gt;&gt; title.ratings.100.tsv<br>grep &quot;tt0067927&quot; title.ratings.tsv &gt;&gt; title.ratings.100.tsv</pre><h3>CoGroupByKey</h3><p>First, let’s look at CoGroupByKey. This is often the more sensible option, unless one of the datasets is a lot smaller in size and can be passed as in-memory Side Input.</p><h3>Python</h3><p>We can simply split our pipeline and this time, return a PCollection instead of passing it to beam.Map(print).</p><pre>with beam.Pipeline(options=pipeline_options) as p:<br>        basic_data = (p | &#39;Read data&#39; &gt;&gt; beam.io.ReadFromText(known_args.input_basics, skip_header_lines=1)<br>           | &#39;Parse CSV&#39; &gt;&gt; beam.ParDo(ParseCsv(columns_title_basic))<br>           | &#39;Clean data&#39; &gt;&gt; beam.ParDo(CleanData(bool_cols=[&#39;isAdult&#39;], int_cols=[&#39;startYear&#39;, &#39;endYear&#39;, &#39;runtimeMinutes&#39;]))<br>           | &#39;Filter data&#39; &gt;&gt; beam.ParDo(FilterBasicData())<br>         )</pre><p>As side inputs are not PCollections, we can transform the ratings one to a static json using Map:</p><pre>rating_data = (p | &#39;Read data (Details)&#39; &gt;&gt; beam.io.ReadFromText(known_args.input_ratings, skip_header_lines=1)<br>           | &#39;Parse CSV (Details)&#39; &gt;&gt; beam.ParDo(ParseCsv(columns_ratings))<br>           | &#39;Clean data (Details)&#39; &gt;&gt; beam.ParDo(CleanData(int_cols=[&#39;numVotes&#39;], float_cols=[&#39;averageRating&#39;]))<br>           | &#39;Filter data (Details)&#39; &gt;&gt; beam.ParDo(FilterRatingData())<br>         )<br><br>        rating_data = (p | &#39;Read data (Details)&#39; &gt;&gt; beam.io.ReadFromText(known_args.input_ratings, skip_header_lines=1)<br>           | &#39;Parse CSV (Details)&#39; &gt;&gt; beam.ParDo(ParseCsv(columns_ratings))<br>           | &#39;Clean data (Details)&#39; &gt;&gt; beam.ParDo(CleanData(int_cols=[&#39;numVotes&#39;], float_cols=[&#39;averageRating&#39;]))<br>           | &#39;Filter data (Details)&#39; &gt;&gt; beam.ParDo(FilterRatingData())<br>         )</pre><p>Once we have both PCollections, we can prepare the data for CoGroupByKey:</p><pre># Create keys<br>        movie_keys = (basic_data<br>               | &#39;movie key&#39; &gt;&gt; beam.Map(lambda r: (r[&#39;tconst&#39;], r))<br>               #| &#39;Print&#39; &gt;&gt; beam.Map(print)<br>        )<br>        rating_keys = (rating_data<br>               | &#39;rating key&#39; &gt;&gt; beam.Map(lambda r: (r[&#39;tconst&#39;], r))<br>        )</pre><p>And finally, apply the CoGroupByKey transform and FlatMap them together:</p><pre>joined_dicts = (<br>            {&#39;movie_keys&#39;: movie_keys, &#39;rating_keys&#39;: rating_keys} <br>            | beam.CoGroupByKey()    <br>            | beam.FlatMap(join_ratings)<br>            | &#39;mergedicts&#39; &gt;&gt; beam.Map(lambda dd: {**dd[0], **dd[1]})<br>            | &#39;Print&#39; &gt;&gt; beam.Map(print)<br>        )</pre><p>Yielding one record (as we chose our input randomly):</p><pre>{&#39;tconst&#39;: &#39;tt0067927&#39;, &#39;titleType&#39;: &#39;movie&#39;, &#39;primaryTitle&#39;: &#39;Vanishing Point&#39;, &#39;originalTitle&#39;: &#39;Vanishing Point&#39;, &#39;isAdult&#39;: False, &#39;startYear&#39;: 1971, &#39;endYear&#39;: None, &#39;runtimeMinutes&#39;: 99, &#39;genres&#39;: &#39;Action,Crime,Thriller&#39;, &#39;averageRating&#39;: 7.2, &#39;numVotes&#39;: 25933}</pre><h3>Go</h3><p>One thing you will notice is the lack of examples for these more “advanced” topics, such as CoGroupByKey, even though they do in fact exist in the <a href="https://godoc.org/github.com/apache/beam/sdks/go/pkg/beam#CoGroupByKey">godocs</a>. Therefore, figuring this part out took quite a bit longer than I wanted it to, but it makes sense once the logic is understood.</p><p>In order to use CoGroupByKey, we need to create a KV pair per PCollection:</p><pre>func extractRatingId(r ratingFn) (string, ratingFn) {<br>	return r.tconst, r<br>}<br><br>func extractMovieId(m movieFn) (string, movieFn) {<br>	return m.tconst, m<br>}</pre><p>And transform our collections:</p><pre>// Combine<br>	combined := beam.CoGroupByKey(s,<br>		beam.ParDo(s, extractMovieId, filtered_movies),<br>		beam.ParDo(s, extractRatingId, filtered_ratings))</pre><p>And match them as follows:</p><pre>func combineFn(tconst string, movieIter func(*movieFn) bool, ratingIter func(*ratingFn) bool, emit func(targetMovie)) {<br>	// Pointers to structs<br>	m := &amp;movieFn{tconst: tconst}<br>	r := &amp;ratingFn{tconst: tconst}<br>	// If match, emit<br>	if movieIter(m) &amp;&amp; ratingIter(r) {<br>		fmt.Printf(&quot;%v %v\n&quot;, tconst, m)<br>		emit(targetMovie{<br>			Id:             m.tconst,<br>			TitleType:      m.titleType,<br>			PrimaryTitle:   m.primaryTitle,<br>			OriginalTitle:  m.originalTitle,<br>			IsAdult:        m.isAdult,<br>			StartYear:      m.startYear,<br>			EndYear:        m.endYear,<br>			RuntimeMinutes: m.runtimeMinutes,<br>			Genres:         m.genres,<br>			AverageRating:  r.averageRating,<br>			NumVotes:       r.numVotes,<br>		})<br>	}<br>}</pre><p>Note the func(*movieFn) bool, expecting a pointer to a struct that will tell us whether we have a match or not.</p><h3>Side Inputs</h3><p>Side Inputs are a lot trickier than they seem in go, but relatively straightforward in Python.</p><h3>Python</h3><p>If we want to use Side Inputs, we can pass our smaller ratings PCollection as list:</p><pre>joined_dicts = (<br>        basic_data<br>        | &#39;Join&#39; &gt;&gt; beam.ParDo(JoinRatings(), AsList(rating_data))<br>    )</pre><p>To a new ParDo:</p><pre>class JoinRatings(beam.DoFn):<br>    def process(self, movie: dict, ratings_side):<br>        for k in ratings_side:<br>            if k[&#39;tconst&#39;] == movie[&#39;tconst&#39;]:<br>                yield {**movie, **k}</pre><p>Or with a AsDict call[0]:</p><pre>class JoinRatings(beam.DoFn):<br>    def process(self, movie: dict, ratings_side):<br>        if &#39;tconst&#39; in movie and movie[&#39;tconst&#39;] in ratings_side:<br>            yield {**movie, **ratings_side[movie[&#39;tconst&#39;]]}</pre><p>And get the same result, this time using a side input.</p><p><em>[0] A </em><em>dict here would be a lot more efficient than a list; however, as far as I see it, the </em><em>go SDK does not support SideInputs as a </em><em>map; I have therefore implemented both </em><em>Python and </em><em>go with </em><em>SideInputs using both </em><em>lists and </em><em>maps/</em><em>dicts.</em></p><h3>Go</h3><p>We’ll be SideInput here to highlight what I’ve pointed out is possible in the Python section.</p><p>First, we need another Struct that will be our output structure:</p><pre>type targetMovie struct {<br>	Id             string<br>	TitleType      string<br>	PrimaryTitle   string<br>	OriginalTitle  string<br>	IsAdult        bool<br>	StartYear      int64<br>	EndYear        int64<br>	RuntimeMinutes int64<br>	Genres         string<br>	// Ratings<br>	AverageRating float64<br>	NumVotes      int64<br>}</pre><p>Note the values are <a href="https://golang.org/ref/spec#Exported_identifiers">exported</a>, i.e. start with an Uppercase letter.</p><p>We simply define a combine type function that expects a slice or ratingFn, as opposed to a PCollection:</p><pre>func combineMoviesRatings(movie movieFn, ratings []ratingFn, emit func(targetMovie)) {<br>	for _, r := range ratings {<br>		if r.tconst == movie.tconst {<br>			emit(targetMovie{<br>				Id:             movie.tconst,<br>				TitleType:      movie.titleType,<br>				PrimaryTitle:   movie.primaryTitle,<br>				OriginalTitle:  movie.originalTitle,<br>				IsAdult:        movie.isAdult,<br>				StartYear:      movie.startYear,<br>				EndYear:        movie.endYear,<br>				RuntimeMinutes: movie.runtimeMinutes,<br>				Genres:         movie.genres,<br>				AverageRating:  r.averageRating,<br>				NumVotes:       r.numVotes,<br>			})<br>		}<br>	}<br>}</pre><p>And call it with a Side Input as such:</p><pre>combined := beam.ParDo(s, combineMoviesRatings, filtered_movies,<br>		beam.SideInput{Input: filtered_ratings})</pre><p>And with that, we get the same output:</p><pre>{&quot;Id&quot;:&quot;tt0067927&quot;,&quot;TitleType&quot;:&quot;movie&quot;,&quot;PrimaryTitle&quot;:&quot;Vanishing Point&quot;,&quot;OriginalTitle&quot;:&quot;Vanishing Point&quot;,&quot;IsAdult&quot;:false,&quot;StartYear&quot;:1971,&quot;EndYear&quot;:0,&quot;RuntimeMinutes&quot;:99,&quot;Genres&quot;:&quot;Action,Crime,Thriller&quot;,&quot;AverageRating&quot;:7.2,&quot;NumVotes&quot;:25933}</pre><p>Similar to what we’ve seen in Python, doing this list comparison n times gives us O(n*n) and will be <em>tremendously</em> ineffective.</p><p>As I still don’t know whether the go SDK has an equivalent to Python&#39;s apache_beam.pvalue.AsDict, I’ve come up with this horrifying workaround that passes a single PCollection as Singleton SideInput to a ParDo and creates a map[string]ratingFn:</p><pre>func makeRatingsMap(rr int, ratings []ratingFn, emit func(map[string]ratingFn)) {<br>	m := make(map[string]ratingFn)<br>	for _, r := range ratings {<br>		m[r.tconst] = r<br>	}<br>	emit(m)<br>}<br><br>func combineMoviesRatings(movie movieFn, ratings map[string]ratingFn, emit func(targetMovie)) {<br>	r, ok := ratings[movie.tconst]<br>	if ok {<br>		emit(targetMovie{<br>			Id:             movie.tconst,<br>			TitleType:      movie.titleType,<br>			PrimaryTitle:   movie.primaryTitle,<br>			OriginalTitle:  movie.originalTitle,<br>			IsAdult:        movie.isAdult,<br>			StartYear:      movie.startYear,<br>			EndYear:        movie.endYear,<br>			RuntimeMinutes: movie.runtimeMinutes,<br>			Genres:         movie.genres,<br>			AverageRating:  r.averageRating,<br>			NumVotes:       r.numVotes,<br>		})<br>	}<br>}</pre><p>Which we call as such:</p><pre>// Fake PCollection to only run the next parDo once<br>	fakePCol := beam.CreateList(s, [1]int{<br>		0,<br>	})<br>	// To Map<br>	filteredRatingsMap := beam.ParDo(s, makeRatingsMap, fakePCol, beam.SideInput{Input: filtered_ratings})<br>	// And match<br>	combined := beam.ParDo(s, combineMoviesRatings, filtered_movies,<br>		beam.SideInput{Input: filteredRatingsMap})</pre><p>While this might fall under “It’s not stupid if it works!”, we’ll take a look at a lot of issues this caused when trying to use Dataflow in a later section - note that this code does work on the DirectRunner, however.</p><h3>I/O</h3><p>Finally, let’s write our data. We’ll focus on writing to disk first.</p><h3>Python</h3><p>In Python, a simple call will create a txt file, containing the above json:</p><pre>joined_dicts | &#39;write&#39; &gt;&gt; beam.io.WriteToText(&#39;./movies.txt&#39;)</pre><h3>Go</h3><p>Go is once again very similar in that regard - we do, however, have to “encode” our struct as JSON in an inline ParDo:</p><pre>combinedString := beam.ParDo(s, func(v targetMovie) string {<br>		j, _ := json.Marshal(v)<br>		return fmt.Sprintf(string(j))<br>	}, combined)<br>	// Write<br>	textio.Write(s, *output, combinedString)</pre><h3>DirectRunner (locally)</h3><p>Let’s run this and talk performance real quick. Last time, go was almost x45 faster than Python in our Mandelbrot benchmark. Let’s see how Beam holds up.</p><p>Comparing performance on the DirectRunner is almost a pointless exercise, as this runner is designed for local debugging and development, not production use.</p><h3>Benchmarking</h3><p>That being said I did run some benchmarks, comparing go and Python, both using Side Inputs with lists or dicts/maps respectively, as well as CoGroupByKey, using three different test data sets: 100 records @ ~9KB, 100,000 records @ ~9MB, and 1M records @ 100MB.</p><p>Looking at various Side Inputs first:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/0*0UMjbYmIn49TnKdn.png" /><figcaption><a href="https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#directrunner-locally">https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#directrunner-locally</a></figcaption></figure><p>go here is significantly faster, but that was expected due to this running essentially single-threaded. Using lists as side inputs is a lot slower, to the point where I’ve given up trying to run the as list use case for go and Python at 1M records.</p><p>Now, for CoGroupByKey:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/0*StJ0ymg2i-vqylyD.png" /><figcaption><a href="https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#directrunner-locally">https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#directrunner-locally</a></figcaption></figure><p>Where we see a very similar trend with go being orders of magnitude faster. Impressive!</p><h3>A Reference Job</h3><p>I’ve also benchmarked the wordcount example with the title.basics data on the DirectRunner to ensure I did not compare apples to oranges by writing fundamentally different code by accident.</p><p>I did this in go:</p><pre>go install github.com/apache/beam/sdks/go/examples/wordcount<br>time wordcount --input ~/workspace/beam-examples/data/title.basics.tsv --output countsgo.txt</pre><p>And python:</p><pre>time python3 -m apache_beam.examples.wordcount --input ~/workspace/beam-examples/data/title.basics.tsv --output wordcountpy.txt # without multiple workers</pre><p>Which yielded:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/0*ZBB5yt0GgCpYit4W.png" /><figcaption><a href="https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#a-reference-job">https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#a-reference-job</a></figcaption></figure><p>Which does fall in line with our observation that, Beam with go is still a fair bit faster than Python.</p><h3>Dataflow (Google Cloud)</h3><p>Now, running this on an external runner only leaves us with one option (as go doesn’t support other runners), Google Cloud&#39;s Dataflow. I should add that the Dataflow for go is still in version 0.5 and not officially supported yet.</p><p>Ensure that you have:</p><ol><li>A Google Cloud Project</li><li>Billing enabled (or a Free-Tier eligible account)</li><li>DataFlow APIs enabled</li><li>gcloud sdk installed, ran gcloud init, and gcloud auth login</li><li>GOOGLE_APPLICATION_CREDENTIALS is set</li><li>If you are reading this at Google, ensure Christian gets more free credits <em>(optional step)</em></li></ol><h3>Python</h3><p>For Python, we need to run it with an authenticated gcloud sdk:</p><pre>pip3 install --upgrade &quot;apache-beam[gcp]&quot;<br>python3 movie_pipeline.py --input-basics &quot;${BUCKET}/title.basics.tsv&quot; \<br>    --input-ratings &quot;${BUCKET}/title.ratings.tsv&quot; \<br>    --output &quot;${BUCKET}/out&quot; \<br>    --runner dataflow \<br>    --project &quot;${PROJECT}&quot; \<br>    --region &quot;${REGION}&quot; \<br>    --temp_location &quot;${BUCKET}/tmp/&quot; \<br>    --staging_location &quot;${BUCKET}/binaries/&quot; #\<br>    #--num_workers 4</pre><p>It will, however, fail on Python 3.8 with</p><pre>Exception: Dataflow only supports Python versions 2 and 3.5+, got: (3, 8)</pre><p>So use an older Python version here, 3.7 works well.</p><p>While the job is running, it’ll look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/0*biCzgmzaPhHrGvRU.png" /><figcaption><a href="https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#dataflow-google-cloud">https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#dataflow-google-cloud</a></figcaption></figure><p>And once completed, something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/0*VYkoBwMnzKFbGbcE.png" /><figcaption><a href="https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#dataflow-google-cloud">https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#dataflow-google-cloud</a></figcaption></figure><h3>Dataflow with Go</h3><p><em>This section will walk you through the full exploration and development process, including dead-ends to illustrate some of the challenges I’ve faced. If you are interested in the solution, jump to the </em><a href="https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#finally-running-on-dataflow"><em>last section</em></a><em>.</em></p><p>For go, we need to build and run it with an authenticated gcloud sdk.</p><p>Fist, ensure all custom structs are registered in init(), similar to what you would do with Kryo in Spark with Scala.</p><pre>func init() {<br>	beam.RegisterType(reflect.TypeOf((*ratingFn)(nil)).Elem())<br>	beam.RegisterType(reflect.TypeOf((*movieFn)(nil)).Elem())<br>	beam.RegisterType(reflect.TypeOf((*targetMovie)(nil)).Elem())<br>}</pre><p>And build and run:</p><pre>go build movie_pipeline.go<br>./movie_pipeline --input-basics &quot;${BUCKET}/title.basics.tsv&quot; \<br>    --input-ratings &quot;${BUCKET}/title.ratings.tsv&quot; \<br>    --output &quot;${BUCKET}/out&quot; \<br>    --runner dataflow \<br>    --project &quot;${PROJECT}&quot; \<br>    --region &quot;${REGION}&quot; \<br>    --temp_location &quot;${BUCKET}/tmp/&quot; \<br>    --staging_location &quot;${BUCKET}/binaries/&quot; \<br>    --worker_harness_container_image=apache/beam_go_sdk:latest #\<br>    #--num_workers 4</pre><p>But it won’t run <strong>when trying to use the </strong><strong>Side Input with a </strong><strong>map route</strong>:</p><pre>panic: Failed to encode custom coder for type json. Make sure the type was registered before calling beam.Init. For example: beam.RegisterType(reflect.TypeOf((*TypeName)(nil)).Elem())</pre><h3>Registering types for Dataflow</h3><p>The obvious route here is to simply register the type. However, I’ve encountered some nasty issues with registering Types in Beam.</p><blockquote><em>RegisterType inserts “external” types into a global type registry to bypass serialization and preserve full method information. It should be called in init() only. TODO(wcn): the canonical definition of “external” is in v1.proto. We need user facing copy for this important concept.</em></blockquote><blockquote><a href="https://godoc.org/github.com/apache/beam/sdks/go/pkg/beam#RegisterType"><em>https://godoc.org/github.com/apache/beam/sdks/go/pkg/beam#RegisterType</em></a></blockquote><p>We can try to register the map as such:</p><pre>func init() {<br>	// ..<br>	var m map[string]ratingFn<br>	beam.RegisterType(reflect.TypeOf(m).Elem())<br>}</pre><p>Yields:</p><pre>panic: Failed to encode custom coder for type json. Make sure the type was registered before calling beam.Init. For example: beam.RegisterType(reflect.TypeOf((*TypeName)(nil)).Elem())<br>Full error:<br>        encoding custom coder map[string]main.ratingFn[json] for type map[string]main.ratingFn<br>unencodable type map[string]main.ratingFn</pre><p>Of course, we can try to register a map:</p><pre>beam.RegisterType(reflect.MapOf(reflect.TypeOf(&quot;&quot;), reflect.TypeOf((*ratingFn)(nil)).Elem()))</pre><p>But that did not have the desired effect. Why?</p><p>Digging into the go SDK source, I found the following function:</p><pre>// TypeKey returns the external key of a given type. Returns false if not a<br>// candidate for registration.<br>func TypeKey(t reflect.Type) (string, bool) {<br>	fmt.Printf(&quot;%v =&gt; PckPath: %v Name: %v Kind: %v\n&quot;, t, t.PkgPath(), t.Name(), t.Kind())<br>	if t.PkgPath() == &quot;&quot; || t.Name() == &quot;&quot; {<br>		return &quot;&quot;, false // no pre-declared or unnamed types<br>	}<br>	return fmt.Sprintf(&quot;%v.%v&quot;, t.PkgPath(), t.Name()), true<br>}</pre><p>I’ve added the fmt.Printf for debugging.</p><pre>main.ratingFn =&gt; PckPath: main Name: ratingFn Kind: struct<br>main.movieFn =&gt; PckPath: main Name: movieFn Kind: struct<br>main.targetMovie =&gt; PckPath: main Name: targetMovie Kind: struct<br>map[string]main.ratingFn =&gt; PckPath:  Name:  Kind: map<br>panic: invalid registration type: map[string]main.ratingFn</pre><p>This function checks whether the registered type is actually a custom type; a map is not. PckPath and Name are never set, as map is not a custom type that can be registered through reflection.</p><p>Going through <a href="https://issues.apache.org/jira/browse/BEAM-6652?jql=project%20%3D%20BEAM%20AND%20component%20%3D%20sdk-go%20AND%20text%20~%20%22map%22">Jira</a>, I find this <a href="https://github.com/apache/beam/pull/7857">PR</a>, leading me to <a href="https://github.com/lostluck/beam/blob/master/sdks/go/pkg/beam/core/typex/class_test.go#L55">this</a> unit test — letting me to believe that the go SDK does not allow for maps with custom types.</p><p>Can we use a list for the Side Input instead to make our lives easier? I guess you know the answer - but let’s talk debugging, since we’re at it.</p><h3>Perf Tools — Profiling Go</h3><p>Let’s quickly use to profile what’s going on under the hood if we were to use a list instead of a map.</p><p>For this test, I’m using a file with 5,000,000 rows, combined clocking in at about ~500MB.</p><p>First, run the job after following the instructions to add additional flags for the profiler:</p><pre>go run movie_pipeline.go --input-basics ../data/title.basics.5M.tsv --input-ratings ../data/title.ratings.5M.tsv --output ./test.txt  -cpuprofile ../profiler/cpu.out -memprofile ../profiler/mem.out</pre><p>This job took <em>84 Minutes locally</em>, despite having an Intel i7–9750H, 16GB of DDR4 memory, and an M.2 NVMe SSD at its disposal.</p><p>Listen to your poor Laptop sound like a Jet Engine, and print the results:</p><pre>go tool pprof --svg ./cpu.out &gt; cpu.svg<br>go tool pprof --svg ./mem.out &gt; mem.svg</pre><p>And that is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W6_ZRjyncgFAmfXC.png" /><figcaption><a href="https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#perf-tools---profiling-go">https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#perf-tools---profiling-go</a></figcaption></figure><p>We can see that the combineMovieRatings, the inefficient list-iteration, took the majority of the time - and from monitoring htop, I can tell you that the job used a single thread the entire time.</p><p>Now, seeing that iterating a list is very inefficient should not be a surprise — but that in combination with the single threaded execution (which I believe to be caused by the Splittable DoFn issue), is causing a massive runtime spike.</p><h3>A journey to a custom coder</h3><p>After more digging through Jira and GitHub Pull Requests, I stumbled upon <a href="https://godoc.org/github.com/apache/beam/sdks/go/pkg/beam#Coder">Custom Coders</a> and their <a href="https://github.com/apache/beam/blob/master/sdks/go/pkg/beam/core/runtime/coderx/string.go">usage for internal Types</a>.</p><p>I had the brilliant idea to register a custom coder for our map type:</p><pre>func NewCustomMap() (*coder.CustomCoder, error) {<br>	return coder.NewCustomCoder(&quot;customMap&quot;, reflect.MapOf(reflect.TypeOf(&quot;&quot;), reflect.TypeOf((*ratingFn)(nil)).Elem()), encCustomMap, decCustomMap)<br>}<br><br>func encCustomMap(v typex.T) []byte {<br>	dat, _ := json.Marshal(v)<br>	return dat<br>}<br><br>func decCustomMap(data []byte) typex.T {<br>	return string(data)<br>}</pre><p>Unfortunately, <a href="https://github.com/apache/beam/blob/master/sdks/go/pkg/beam/forward.go#L95">RegisterCoder</a> looks like this:</p><pre>func RegisterCoder(t reflect.Type, encoder, decoder interface{}) {<br>	runtime.RegisterType(t)<br>	runtime.RegisterFunction(encoder)<br>	runtime.RegisterFunction(decoder)<br>	coder.RegisterCoder(t, encoder, decoder)<br>}</pre><p>And hence, also calls RegisterType(t), which will once again fail to register our type or Coder.</p><h3>Map -&gt; JSON -&gt; Map</h3><p>While there’s a decent chance I am misinterpreting all the above go code and Jira tickets, my next approach was to do the json parsing myself.</p><p>First, instead of returning a map, we return []byte, which returns a json string:</p><pre>func makeRatingsMap(rr int, ratings []ratingFn, emit func([]byte)) {<br>	m := make(map[string]ratingFn)<br>	for _, r := range ratings {<br>		m[r.tconst] = r<br>	}<br>	jsonMap, err := json.Marshal(m)<br>	if err != nil {<br>		log.Fatal(err)<br>	}<br>	emit(jsonMap)<br>}</pre><p>Then, in our combination function, we unmarshall that data into a map[string]ratingFn.</p><pre>func combineMoviesRatings(movie movieFn, ratings []byte, emit func(targetMovie)) {<br>	ratingsMap := make(map[string]ratingFn)<br>	err := json.Unmarshal(ratings, &amp;ratingsMap)<br>	if err != nil {<br>		log.Fatal(err)<br>	}<br>	r, ok := ratingsMap[movie.tconst]<br>	if ok {<br>		emit(targetMovie{<br>			Id:             movie.tconst,<br>			TitleType:      movie.titleType,<br>			PrimaryTitle:   movie.primaryTitle,<br>			OriginalTitle:  movie.originalTitle,<br>			IsAdult:        movie.isAdult,<br>			StartYear:      movie.startYear,<br>			EndYear:        movie.endYear,<br>			RuntimeMinutes: movie.runtimeMinutes,<br>			Genres:         movie.genres,<br>			AverageRating:  r.averageRating,<br>			NumVotes:       r.numVotes,<br>		})<br>	}<br>}</pre><p>Now, unfortunately, the marshalling needs to be done on every step, which did change the local performance numbers quite drastically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M4AAM2wlJFbXsMgu.png" /><figcaption><a href="https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#map---json---map">https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#map---json---map</a></figcaption></figure><p>As you can see, json (*decodeState) and mapassign cause a massive overhead for the job and, at least on the DirectRunner, this is <strong>not a viable alternative</strong>.</p><h3>Back to the drawing board</h3><p>At this point, we have to re-visit CoGroupByKey or other options; these issues do, however, show some of the more odd (and, I might add, completely undocumented) issues and shortfalls of the go SDK.</p><p>It is debatable to say a Side Input is a <em>better</em> solution than a CoGroupByKey, but in my case, I was unable to use a map as a Side Input in general.</p><h3>Finally running on Dataflow</h3><p>After switching back to CoGroupByKey, finally, these changes allow me to submit the job to Dataflow. Keep in mind that the <em>go SDK is not officially supported by DataFlow yet</em>.</p><p>Here, we can also add another output for BigQuery by adding metadata to our struct:</p><pre>type targetMovie struct {<br>	Id             string `bigquery:&quot;Id&quot;`<br>	TitleType      string `bigquery:&quot;TitleType&quot;`<br>	PrimaryTitle   string `bigquery:&quot;PrimaryTitle&quot;`<br>	OriginalTitle  string `bigquery:&quot;OriginalTitle&quot;`<br>	IsAdult        bool   `bigquery:&quot;IsAdult&quot;`<br>	StartYear      int64  `bigquery:&quot;StartYear&quot;`<br>	EndYear        int64  `bigquery:&quot;EndYear&quot;`<br>	RuntimeMinutes int64  `bigquery:&quot;RuntimeMinutes&quot;`<br>	Genres         string `bigquery:&quot;Genres&quot;`<br>	// Ratings<br>	AverageRating float64 `bigquery:&quot;AverageRating&quot;`<br>	NumVotes      int64   `bigquery:&quot;NumVotes&quot;`<br>}</pre><p>And writing to BQ:</p><pre>if *bq != &quot;&quot; {<br>		project := gcpopts.GetProject(ctx)<br>		bigqueryio.Write(s, project, *bq, combined)<br>	}</pre><p>Once, submitted, we’ll see our DAG:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*2acfqB3oCrDtrZvi.png" /><figcaption><a href="https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#finally-running-on-dataflow">https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#finally-running-on-dataflow</a></figcaption></figure><h3>Splittable DoFns</h3><p><strong>Disclaimer</strong>: The go SDK might lack behind Python&#39;s and Java&#39;s performance with use cases where <em>large files need to be loaded</em>.</p><p>This is due to the fact that <strong>the </strong><strong>go SDK does not support </strong><a href="https://beam.apache.org/blog/splittable-do-fn/"><strong>Splittable DoFns</strong></a>. See <a href="https://issues.apache.org/jira/browse/BEAM-3301">BEAM-3301</a> for reference.</p><h3>Dataflow Performance</h3><p>When comparing performance, we’ll look at all 3 approaches:</p><ol><li>Using a simple list as Side Input</li><li>Using a dict as Side Input <em>(Python only)</em></li><li>Using CoGroupByKey</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/0*WJaGsrp9uTfXwQuy.png" /><figcaption><a href="https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#dataflow-performance">https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#dataflow-performance</a></figcaption></figure><p>I’ve actually had to calculate the list performance on Python, as the job was still running after ~2hrs, with ~8-15 elements/s. I’ve approximated the runtime by looking at the expected output from the CoGroupByKey run and the elapsed time, so the real numbers might be worse!</p><p>This falls in-line with what we’ve seen on the DirectRunner - go is faster, even though not as much as “regular” go vs Python code in the last Mandelbrot example. We couldn’t compare the dict/map logic, as this only ran on the DirectRunner.</p><p><em>[0] I am not sure why the </em><em>go SDK does not produce a “Records/s” metric</em></p><h3>Performance Summary</h3><p>Last time, go was almost x45 faster than Python in our Mandelbrot benchmark.</p><p>This time, this is how the summary looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*XDCU-pgrrwGAmeGEIA5VLQ.png" /><figcaption><a href="https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#dataflow-performance">https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/#dataflow-performance</a></figcaption></figure><p>The average performance gain, across all runners and use cases (excluding 100 records due to overhead and the approximated runtime) is <strong>1290.19%</strong> — and if we were to take the approximation from the list runtime, we&#39;re looking at <em>1351.40%</em>, even though that is not really fair.</p><p>In any case, this is truly impressive.</p><h3>Conclusion</h3><p>What have we learned?</p><h3>Dynamic vs. Static Typing &amp; dict vs. struct</h3><p>This part, while tremendously subjective, got me thinking quite a bit. When I first started digging into Part 1, it seemed obvious to me that Python&#39;s lack of static typing tends to be a curse, rather than a blessing, more often than not. The amount of times I had to spend long nights to figure out why on earth a job (be that Beam, Spark, Pandas, Dask, or anything else) does not do what I want it to or, more pressingly, when I’m getting feedback from users that their data looks “off”, it was so frequently caused by issues with types.</p><p>I’ve elaborated on it in part 1 — Python does not enforce typing. I often result to external libraries, like numpy, to write classes that force typing using external configurations when dealing with data pipelines. This might follow a logic like “Your dict should have the attribute averageTemp (if &#39;averageTemp&#39; in dict), and that is a FLOAT64. FLOAT64 maps to numpy’s np.float64; to ensure it is actually FLOAT64, we’ll try a parse at some point of the job; if that fails, silently catch it using except and set it to None”.</p><p>In go, on the other hand, I cannot comfortably do that. I am forced to abide to structures and types - I can’t even set a string to nil, even though I might be very used to it.</p><p>Now, what is better? Well, I believe it to be a matter of perspective on style and design. While I find “production” grade jobs to often be difficult in Python, due to the above edge cases and workarounds (keep in mind: if my data does not follow the format dictated by the database, I am the one at fault!), can be a challenge.</p><p>At the same time, it took me <em>personally</em> a lot longer to write my jobs in go than it did in Python - because I needed to think about what I was going to do a lot more. In often treat Python like I treat bash or zsh - type something in, hope it works. Leading me to…</p><h3>Compiler</h3><p>…the compiler. The go compiler is a thing I&#39;ve learned to both hate and adore. Since I haven&#39;t mentioned it, let me tell you what the compiler (or rather, the go toolchain) does, using a few select examples:</p><ol><li>You cannot have unused variables</li><li>You cannot have unused imports</li><li>You cannot use the wrong types</li></ol><p>And by cannot I mean: “Neither go run nor go build will produce a binary”.</p><p>Seems reasonable, right? Well — piggybacking on my Python as bash comment, I find it both helpful and tedious at the same time. Writing go code is like writing Python code with pylint on high-alert - it won’t let you do anything that might make the compilers life uncomfortable, while at the same time, ensuring what you are producing will actually work and not have side effects.</p><p>At the same time, specific to Dataflow, it obviously won’t catch anything tool-specific - for instance, not registering classes in init() only becomes an issue once you submit your job.</p><p>Python, on the other hand, lets me write code that gets a 1/10 pyLint score and that can be future me’s problem.</p><h3>Readability</h3><p>I love Beam&#39;s syntax in Python. Once you get over how “odd” it looks, it really is a beautiful way to build a DAG with something that almost resembles pseudo-code.</p><p>go&#39;s approach is a lot more academic. It follows a standard language flow - each function returns a PCollection. This is a lot more intuitive, but I find it looses the benefits of Python&#39;s “DAG-as-code” logic.</p><p>But I’ll let you judge for yourself — check out the full code for both Python and go on <a href="https://github.com/chollinger93/beam-examples">GitHub</a>.</p><h3>Splittable DoFns &amp; Performance</h3><p>The performance gain in go was massive and, quite honestly, unexpected. An improvement of, on average, <em>1290.19%</em> is nothing to scoff at.</p><p>Splittable DoFns, on the other ahnd, is in fact a big deal - if not even a deal breaker and makes this exercise mostly academic in nature, once we move past relatively small data sets and start talking multiple GB or TB.</p><h3>Documentation</h3><p>This is one of my biggest gripes with the go SDK and I feel bad by complaining, because absolutely nothing is stopping me from committing to it (besides time).</p><p>The Beam docs for go are very lackluster - a lot of functionality and examples are only available for Python and Java. Finding examples, logic, and overall architecture details around go is challenging, to say the least. I mostly relied on the godocs and reading a fair bit of source code.</p><p>The write-up above should be proof of this — there were a lot of dead ends I encountered.</p><p>My process when working with the go SDK looked a little something like this:</p><ol><li>Is it on Beam’s website? (Usually no)</li><li>Is there an example with comments in there? I cloned the repo and used grep to search for keyword; there is no good overview of examples, and the ones provided often don’t have comments</li><li>Is it in the godocs? If so, do they give examples or explain how to use the funcionality? (See the coder dead-end above)</li><li>Read the go SDK source code</li></ol><p>Needless to say, there are almost zero Google / StackOverflow results to be found.</p><h3>Compatibility</h3><p>I’ve mentioned this in Part 1 already, but given the experimental nature of the go SDK, the compatibility with Beam features and Runners obviously is not nearly as good as it is in Python or Java. However, for simple pipelines and using Dataflow as a runner, go covers the basics for sure. You do lose some of the benefits I’ve mentioned in the introduction, however - fewer runners mean less options.</p><h3>So What?</h3><p>go is a fun language to play with, but after spending many hours on both writing these articles, playing with the code, documentation, and environments, I simply cannot recommend using go for a Beam pipeline at this point - at least not as a blanket statement.</p><p>Sure — it has advantages over Python, the language itself is clear, well documented, and fast.</p><p>However, the lack of functionality once you move past standard use case, Splittable DoFns issue, documentation, and compatible environments make using Python (or Java) as a default a lot more reasonable. While someone who is a lot more familiar with the go SDK for Beam could surely iron out some of my issues - like the map question above - there are still to many things which make using go in production for a Dataflow pipeline questionable at least.</p><p>For simpler pipelines, however — I believe the performance gain to be worth the other trade offs, if you can live with an officially not-yet-supported runner (Dataflow).</p><p>That being said, I will surely closely monitor the progress of the Beam SDK and, given the chance, hopefully commit to it in the future - because go is too interesting a language to just ignore.</p><p><em>All development and benchmarking was done under GNU/Linux [PopOS! 20.04 on Kernel 5.4] with 12 Intel i7–9750H vCores @ 4.5Ghz and 16GB RAM on a 2019 System76 Gazelle Laptop, using Dataflows Go Runner in Version 0.5</em></p><blockquote>Originally published @<a href="https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/"> chollinger.com/blog</a></blockquote><p><em>Originally published at </em><a href="https://chollinger.com/blog/2020/07/a-data-engineering-perspective-on-go-vs.-python-part-2-dataflow/"><em>https://chollinger.com</em></a><em> on July 6, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=472b42a14f9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-data-engineering-perspective-on-go-vs-python-part-2-dataflow-472b42a14f9">A Data Engineering Perspective on Go vs. Python (Part 2 — Dataflow)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Data Engineering Perspective on Go vs. Python (Part 1)]]></title>
            <link>https://medium.com/data-science/a-data-engineering-perspective-on-go-vs-python-part-1-5dfb8bc08e7?source=rss-7af40a2161c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dfb8bc08e7</guid>
            <category><![CDATA[dataflow]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Christian Hollinger]]></dc:creator>
            <pubDate>Thu, 11 Jun 2020 00:00:00 GMT</pubDate>
            <atom:updated>2020-06-13T17:33:57.177Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><blockquote><em>Exploring golang — can we ditch Python for go? And have we (as in “folks that work with a lot of data regularly”) finally found a use case for go? Part 1 explores high-level differences between Python and go and gives specific examples on the two languages, aiming to answer the question based on Apache Beam and Google Dataflow as a real-world example.</em></blockquote><p><a href="https://beam.apache.org/">Apache Beam</a> is something I’ve used on this blog a couple of times before: It’s a unified programming model for both batch and streaming use cases that can handle <a href="https://en.wikipedia.org/wiki/Embarrassingly_parallel">delightfully parallel workloads</a>, allows for a lot of custom I/O and other connectors, and runs on a multitude of execution platforms, most notably Flink, Spark, and Google Cloud’s Dataflow.</p><p>You can use it for streaming or batching data to analyze it, run ETL, enrich it — you name it. I’ve actually used Beam some years ago <a href="https://chollinger.com/blog/2018/06/analyzing-reddits-top-posts-images-with-google-cloud-part-1/#introducing-data-flow">here</a>.</p><p>Now, if you were to go to Beam’s website, you’ll find this wonderful graphic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*Dag5_h5osKPOm446.png" /><figcaption><a href="https://beam.apache.org/">https://beam.apache.org/</a></figcaption></figure><p>Which tells you that Beam is to be written in either Java or Python and everything else falls under &quot;Other Languages&quot;.</p><p>There is, however, an “experimental” ( <a href="https://github.com/apache/beam/tree/master/sdks/go">GitHub</a>) that promises us to use go instead of Python - and that&#39;s what got me excited.</p><p>The next section will poorly attempt to give a “short” (~3,000 word) introduction to go and compare it to Python based on the different handling data engineering specific use cases and when using multi-threaded applications. Please note that this is by no means a full comparison.</p><blockquote><em>This is Part 1 of 2, focussing on the two languages and the current state of the Apache Beam SDK. In part 2 (coming soon), we’ll explore how to use the </em><em>Beam </em><em>go SDK, what limitations we&#39;ll face on GCP, and where the journey for </em><em>go for data engineers is headed.</em></blockquote><p><em>All example code is available on </em><a href="https://github.com/otter-in-a-suit/chollinger-blog/tree/master/content/posts/2020/06/a-data-engineering-perspective-on-go-vs-python-part-1/code"><em>GitHub</em></a><em>.</em></p><p><em>Originally published at </em><a href="https://chollinger.com/blog/2020/06/a-data-engineering-perspective-on-go-vs.-python-part-1"><em>https://chollinger.com</em></a></p><h3>Go vs. Python</h3><p>In case you are not familiar, let me quote Wikipedia:</p><blockquote><em>Go is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. Go is syntactically similar to C, but with memory safety, garbage collection, structural typing, and CSP-style concurrency.</em></blockquote><blockquote><a href="https://en.wikipedia.org/wiki/Go_(programming_language)"><em>https://en.wikipedia.org/wiki/Go_(programming_language)</em></a></blockquote><p>Go has a lot of concepts that should get you excited for a parallel execution framework that handles data. In the following sections, we&#39;ll explore some hand-picked concepts and examples and conclude with a longer, more in-depth concurrency sample.</p><h3>Speed</h3><p>go, being a complied as opposed to an interpreted language, is <a href="https://benchmarksgame-team.pages.debian.net/benchmarksgame/fastest/go-python3.html">supposed to be faster than Python</a>. It also has a tendency to compile things really quickly and shipping compiled code to end-users is orders of magnitude easier than attempting to do the same with Python.</p><p>You can find some hands-on examples below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*Ec_vgwQk6MNMJAOA.png" /><figcaption>Generated using matplotlib; CC BY-SA 3.0</figcaption></figure><h3>Static typing</h3><p>Static, as opposed to Python&#39;s dynamic typing, avoids a lot type headaches with using the right data type in the right moment.</p><blockquote><em>I am not attempting to start a general comparison between static and dynamic typing and the intricacies of Python, but merely looking at it from my experience, specifically in the data space, on a day-to-day basis.</em></blockquote><p>In data-driven projects, you will constantly find yourself dealing with very strict data type definitions, often an artifact (and rightfully so) of an area where all corporate data was inevitably stored in a large RDMBs, such as Oracle, enforcing strict typing.</p><p>Python-based frameworks, such as pySpark or even pandas, ship with their own abstraction layer for providing types ( <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dtypes.html">see dtypes</a>).</p><p>Take this code, written for pySpark, a popular data processing framework that is available in Python (amongst others) for instance, using the NYC Yellow Cab data [0].</p><p>First, read a CSV file into an RDD, a &quot;resilient, distributed dataset&quot;, and apply some transformation lambdas on each line in the data set.</p><pre># Read data<br>rdd = sc.textFile(&#39;data/yellow_tripdata_2019-01.csv&#39;)<br># Parse the RDD<br>rdd = rdd.map(lambda r: r.split(&#39;,&#39;))\<br>         .map(lambda r: (r[10],r[13])) # Take &#39;fare_amount&#39; and &#39;tip_amount&#39;<br>rdd = rdd.filter(lambda r: &#39;fare_amount&#39; not in r) # filter header<br>rdd.take(1)</pre><p>Which yields:</p><pre>[(&#39;7&#39;, &#39;1.65&#39;), (&#39;14&#39;, &#39;1&#39;), (&#39;4.5&#39;, &#39;0&#39;), (&#39;3.5&#39;, &#39;0&#39;), (&#39;52&#39;, &#39;0&#39;)]</pre><p>If we look into one of the tuples:</p><pre>type(rdd.take(1)[0][0])</pre><p>We’ll see str as the data type.</p><p>Now, if we were to reduce this to sum up the Taxi fare and tip amount:</p><pre>def sum_fares(fare, tip):<br>    return fare + tip<br><br>rdd.map(lambda r: sum_fares(*r)).take(5)</pre><p>As the quotes in the above output indicate, the result is a list of concatenated strings.</p><pre>[&#39;71.65&#39;, &#39;141&#39;, &#39;4.50&#39;, &#39;3.50&#39;, &#39;520&#39;]</pre><p>Instead of the mathematically correct:</p><pre>rdd.map(lambda r: sum_fares(*[float(x) for x in r])).take(5)<br># [8.65, 15.0, 4.5, 3.5, 52.0]</pre><p>Newer versions of Python support type hints and the Python interpreter keeps track of variable types. However, as the above example highlights, I personally find it hard to maintain a consistent, readable, and maintainable code base, especially on complex applications.</p><p>go, on the other hand, is statically typed.</p><pre>package main<br><br>import (<br>	&quot;fmt&quot;<br>	&quot;reflect&quot;<br>)<br><br>func main() {<br>    // Implicit<br>	str := &quot;A String&quot;<br>	fmt.Printf(&quot;%s is %s\n&quot;, str, reflect.TypeOf(str))<br><br>    // Explicit<br>	var x float64 = 3.14<br>	fmt.Printf(&quot;%v is %s\n&quot;, x, reflect.TypeOf(x))<br>}</pre><p>Will yield:</p><pre>go run test.go<br>A String is string<br>3.14 is float64</pre><p>Whereas this:</p><pre>str = x</pre><p>Won’t compile:</p><pre>go run testvar.go<br># command-line-arguments<br>./test.go:15:6: cannot use x (type float64) as type string in assignment</pre><p>Go does not support Generics, but neither does Python.</p><blockquote><em>I have skipped over </em><em>go&#39;s </em><em>empty interface{} concept to support arbitrary values and to handle unknown types; it is possible to use this concept for several corner cases where an abstraction of weak types are required</em></blockquote><p><em>[0] </em><em>Spark&#39;s SQL interface will infer string types and allows for mathematical operations on Strings, if they are consistent</em></p><h3>Interfaces and Structs</h3><p>Python does have a class structure (and I&#39;ve used it extensively), whereas go uses structs and interfaces (and this is a terrible simplification). go does not have inheritance and relies on interfaces and composition.</p><p>In the data world, having a strict class structure, for instance to abstract transformations, statistical models, or just plain old data structures, can be both a pain and a curse.</p><p>Python makes extensive use of dicts that can hold arbitrary key-value pairs and nested structures and are similar in syntax to JSON, as well as defined classes for structured abstractions of data. Almost every data framework ships with their own schema classes. go, in theory, could avoid that through a combination of interfaces (for standards), static typing (to ensure the right data type is used at the right moment), and structs to define structure and logic.</p><p>Here’s an questionably useful example that uses the interface CoordinateData, with the function calculateDistance, to calculate a distance between 2 coordinate tuples in the world&#39;s worst GIS analytics platform :)</p><pre>package main<br><br>import (<br>	&quot;fmt&quot;<br>	&quot;math&quot;<br>)<br><br>// A Resource we&#39;re trying to access<br>type CoordinateData interface {<br>	calculateDistance(latTo, lonTo float64) float64<br>}</pre><p>We then implement Geospatial data and the Haversine function (to approximate distance on earth):</p><pre>type GeospatialData struct {<br>	lat, lon float64<br>}<br><br>const earthRadius = float64(6371)<br>func (d GeospatialData) calculateDistance(latTo, lonTo float64) float64 {<br>	// Haversine distance<br>	var deltaLat = (latTo - d.lat) * (math.Pi / 180)<br>	var deltaLon = (lonTo - d.lon) * (math.Pi / 180)<br>	<br>	var a = math.Sin(deltaLat / 2) * math.Sin(deltaLat / 2) + <br>		math.Cos(d.lat * (math.Pi / 180)) * math.Cos(latTo * (math.Pi / 180)) *<br>		math.Sin(deltaLon / 2) * math.Sin(deltaLon / 2)<br>	var c = 2 * math.Atan2(math.Sqrt(a),math.Sqrt(1-a))<br>	<br>	return earthRadius * c<br>}</pre><p>And the same on a simple, 2-dimensional plane:</p><pre>type CartesianPlaneData struct {<br>	x, y float64<br>}<br><br>func (d CartesianPlaneData) calculateDistance(xTo, yTo float64) float64 {<br>	// Simple 2-dimensional Euclidean distance <br>	dx := (xTo - d.x)<br>	dy := (yTo - d.y)<br>	return math.Sqrt( dx*dx + dy*dy )<br>}</pre><p>In this case, the main() function simply calculates 2 completely different types of distance:</p><pre>func main() {<br>	atlanta := GeospatialData{33.753746, -84.386330}<br>	distance := atlanta.calculateDistance(33.957409, -83.376801) // to Athens, GA<br>	fmt.Printf(&quot;The Haversine distance between Atlanta, GA and Athens, GA is %v\n&quot;, distance)<br><br>	pointA := CartesianPlaneData{1, 1}<br>	distanceA := pointA.calculateDistance(5, 5) <br>	fmt.Printf(&quot;The Pythagorean distance from (1,1) to (5,5) is %v\n&quot;, distanceA)<br>}</pre><p>Of course, this is a very simplistic example that simply forces structure onto your structs. However, comparing it to Python, my options are limited:</p><pre>class CoordinateData:<br>    def calculateDistance(self, latTo, lonTo):<br>        pass <br><br>class GeospatialData(CoordinateData):<br>    def __init__(self, lat, lon):<br>        self.lat = lat<br>        self.long = lon<br><br>    def calculateDistance(self, latTo, lonTo):<br>        # Haversine goes here :)<br>        return 95.93196816811724<br><br>class CartesianPlaneData(CoordinateData):<br>    def __init__(self, x, y):<br>        self.x = y<br>        self.x = y<br><br>    # Let&#39;s not implement calculateDistance()<br><br>if __name__ == &quot;__main__&quot;:<br>    atlanta = GeospatialData(33.753746, -84.386330)<br>    distance = atlanta.calculateDistance(33.957409, -83.376801) # to Athens, GA<br>    print(&#39;The Haversine distance between Atlanta, GA and Athens, GA is {}&#39;.format(distance))<br><br>    pointA = CartesianPlaneData(1,1)<br>    distanceA = pointA.calculateDistance(5, 5)<br>    print(&#39;The Pythagorean distance from (1,1) to (5,5) is {}&#39;.format(distanceA))<br>    print(&#39;pointA is of type {}&#39;.format(pointA.__class__.__bases__))</pre><p>This is valid Python — CartesianPlaneData is a subclass ( <em>not an interface</em> - Python uses duck-typing) of CoordinateData and hence, simply uses the calculateDistance method without a return type (see above for static vs. dynamic typing), runs, and returns:</p><pre>python3 interface_example.py<br>The Haversine distance between Atlanta, GA and Athens, GA is 95.93196816811724<br>The Pythagorean distance from (1,1) to (5,5) is None<br>pointA is of type (&lt;class &#39;__main__.CoordinateData&#39;&gt;,)</pre><p>Python does still allow for interface abstractions and you can absolutely use classes to define hierarchies and logic, as I’ve done with the below PluginInterceptor to determine whether a custom Plugin is part of a defined base class; this, however, is not enforced during runtime and might go belly-up if you implement it incorrectly.</p><pre>class PluginInterceptor:<br>    &quot;&quot;&quot;Loads all allowed plugins, when they are a subclass of `BasePlugin` and have the constant `name` set (not `__name__`)<br>    &quot;&quot;&quot;<br>    def __init__(self):<br>        self.cls = BasePlugin<br>        self.allowed_plugins = self.__load__allowed_plugins__()<br>        <br>    def __get_all_subclasses__(self, cls):<br>        return set(cls.__subclasses__()).union(<br>            [s for c in cls.__subclasses__() for s in self.__get_all_subclasses__(c)]) <br>    <br>    def __load__allowed_plugins__(self):<br>        __allowed_plugins__ = {}<br>        for cls in self.__get_all_subclasses__(self.cls):<br>            if cls.name:<br>                __allowed_plugins__[cls.name] = cls<br>        return __allowed_plugins__</pre><p><a href="https://github.com/otter-in-a-suit/scarecrow/blob/master/plugin_base/interceptor.py#L5">https://github.com/otter-in-a-suit/scarecrow/blob/master/plugin_base/interceptor.py#L5</a></p><p>You will also find an example of a struct used in the Mandelbrot example below.</p><h3>Pointers</h3><p>go knows pointers, but no pointer arithmetic. Pointers in go are used for pass-by-pointer operations, as opposed to pass-by-value. I won&#39;t go into this too much and leave you with an example from go and refer you to <a href="https://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/">this wonderful post</a> for Python.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>	i, j := 42, 2701<br><br>	p := &amp;i         // point to i<br>	fmt.Println(*p) // read i through the pointer<br>	*p = 21         // set i through the pointer<br>	fmt.Println(i)  // see the new value of i<br><br>	p = &amp;j         // point to j<br>	*p = *p / 37   // divide j through the pointer<br>	fmt.Println(j) // see the new value of j<br>}</pre><p>(From <a href="https://tour.golang.org/moretypes/1">https://tour.golang.org/moretypes/1</a>)</p><p>My short summary for go would be: As a developer, I am able to control whether I&#39;d like the standard C-style behavior - pass-by-value - or a pointer, where I still pass by value - but in this case, a <em>pointer to the value</em> as function argument.</p><h3>Concurrency with a Mandelbrot Set</h3><p>Easy, out-of-the-box, easy-to-use concurrency is one of the most wonderful things in go. It takes a total of two letters - go - to move something from synchronous to concurrent.</p><p>Let’s use a “pleasingly parallel” algorithm, the <strong>Mandelbrot Set</strong>.</p><blockquote>The <strong>Mandelbrot set</strong> is the set of complex numbers c for which the function f_c(z) = z² + c does not diverge when iterated from z = 0 , i.e., for which the sequence f_c(0, f_c(f_c(0)), etc., remains bounded in absolute value.</blockquote><blockquote><a href="https://en.wikipedia.org/wiki/Mandelbrot_set">https://en.wikipedia.org/wiki/Mandelbrot_set</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GMDBZ1MRtBUcaNih.png" /><figcaption>Output of the Mandelbrot algorithm; CC BY-SA 3.0</figcaption></figure><h3>Python</h3><p>Let’s look at Python first.</p><p>Python offers a multitude of ways to express concurrency — threading, multiprocessing, subprocesses, concurrent.futures to name a few - but choosing the correct one <em>and</em> writing legible code is a challenge. Allow me to quote the docs:</p><blockquote><em>The modules described in this chapter provide support for concurrent execution of code. The appropriate choice of tool will depend on the task to be executed (CPU bound vs IO bound) and preferred style of development (event driven cooperative multitasking vs preemptive multitasking) </em><a href="https://docs.python.org/3/library/concurrency.html"><em>https://docs.python.org/3/library/concurrency.html</em></a></blockquote><p>I will not go into the details on what is the right choice for which situation, how the Global Python Interpreter (GIL) affects it, or how everything works under the hood, as there are hundreds of great articles on the topic that can be easily found online. What I would like to focus on, however, are code style, ease-of-use, and performance.</p><h4>Single-Threaded</h4><p>This can be expressed as such (by <a href="https://github.com/danyaal/mandelbrot">danyaal</a>, with adjustments by yours truly):</p><blockquote><em>Keep in mind that there are a lot more, quicker, optimized, but also more </em>complex<em> versions; the below examples are supposed to be simple &amp; straightforward and can be translated almost 1:1 between </em><em>go and </em><em>Python</em></blockquote><p>First, we define the iterations for the algorithm. This is the part that can be run in parallel, as we’ll see in a second.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br><br># counts the number of iterations until the function diverges or<br># returns the iteration threshold that we check until<br>def countIterationsUntilDivergent(c, threshold):<br>    z = complex(0, 0)<br>    for iteration in range(threshold):<br>        z = (z*z) + c<br><br>        if abs(z) &gt; 4:<br>            break<br>            pass<br>        pass<br>    return iteration</pre><p>The next function is a bit of a monolith, but in the end, simply creates both the real and imaginary axis, assigns them to a 2-dimensional array, and runs the loop.</p><pre>def mandelbrot(threshold, density):<br>    # location and size of the atlas rectangle<br>    # realAxis = np.linspace(-2.25, 0.75, density)<br>    # imaginaryAxis = np.linspace(-1.5, 1.5, density)<br>    realAxis = np.linspace(-0.22, -0.219, 1000)<br>    imaginaryAxis = np.linspace(-0.70, -0.699, 1000)<br>    realAxisLen = len(realAxis)<br>    imaginaryAxisLen = len(imaginaryAxis)<br><br>    # 2-D array to represent mandelbrot atlas<br>    atlas = np.empty((realAxisLen, imaginaryAxisLen))<br><br>    print(&#39;realAxisLen: {}, imaginaryAxisLen: {}&#39;.format(realAxisLen, imaginaryAxisLen))<br>    <br>    # color each point in the atlas depending on the iteration count<br>    for ix in range(realAxisLen):<br>        for iy in range(imaginaryAxisLen):<br>            cx = realAxis[ix]<br>            cy = imaginaryAxis[iy]<br>            c = complex(cx, cy)<br><br>            atlas[ix, iy] = countIterationsUntilDivergent(c, threshold)<br>            pass<br>        pass<br><br>    return atlas.T</pre><p>The computation happens on a single thread, as can be seen here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B8MAauJWaCDTMk3Z.png" /><figcaption>htop</figcaption></figure><h4>Multi-Threaded</h4><p>Now, for running it in multiple threads, we can use the multiprocessing module and run it like this.</p><p>The calc_row() function can be simplified, but it indicates what we&#39;re doing differently: Calculating the image row-by-row, as opposed to one point at a time.</p><pre>import multiprocessing as mp<br>import itertools<br><br>def calc_row(cx, cy, threshold=120):<br>    c = complex(cx[1], cy[1])<br>    return (cx[0], cy[0], countIterationsUntilDivergent(c, threshold))</pre><p>Next, I made the questionable decision to simplify the loop by using starmap and a Pool, giving it permutations of the nested loop directly as arguments.</p><p>In other words, we’re running calc_row(cx, cy, threshold) on however many processes we give the process pool. The multiprocessing library takes care of passing the arguments from our list or iterator respectively.</p><p>We are also returning a funky-looking tuple, so we can keep track of the index in the image.</p><pre>def mandelbrot_multi(threshold, density, cpus=4):<br>    realAxis = np.linspace(-0.22, -0.219, 1000)<br>    imaginaryAxis = np.linspace(-0.70, -0.699, 1000)<br>    realAxisLen = len(realAxis)<br>    imaginaryAxisLen = len(imaginaryAxis)<br>    atlas = np.empty((realAxisLen, imaginaryAxisLen))<br>    <br>    # Create list of permutations<br>    realAxis = [(i,e ) for i,e in enumerate(realAxis)] <br>    imaginaryAxis = [(i,e ) for i,e in enumerate(imaginaryAxis)] <br><br>    paramlist = list(itertools.product(realAxis, imaginaryAxis))<br>    paramlist = list(map(lambda t: t + (threshold,),paramlist))<br>    <br>    # Create a multiprocessing pool<br>    pool = mp.Pool(cpus)<br>    <br>    n = pool.starmap(calc_row, paramlist)<br>    pool.close()<br>    pool.join()<br>    return n, atlas</pre><p>Which uses our available resources a lot more cleverly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p_F-ILDOCHlr33e9.png" /><figcaption>htop</figcaption></figure><p>From a performance standpoint, we’re looking at <strong>8.4s</strong> on a single CPU and <strong>2.53s</strong> concurrently, with a noticeable memory overhead due to the use of the mutliprocessing module.</p><blockquote><em>There are of course a lot of different ways of speeding this up — </em><em>Cython, optimized </em><em>numpy, </em><em>tensorflow, to name a few - but looking at out-of-the-box concurrency, let&#39;s compare that to </em><em>go. I am not good at choosing examples and fractals are pretty. :)</em></blockquote><h3>Go</h3><p>Let’s look at how it looks in go.</p><h4>Single-Threaded</h4><p>The single threaded version isn’t too different. I’m re-using the same code, but simply re-wrote it in go.</p><blockquote><em>Most </em><em>go implementations are using the </em><em>Image package to generate the image in go - and that makes sense for a self-contained project. Here, however, I wrote the array to disk and read it in </em><em>numpy and therefore, </em><em>Python, to keep the code concise. Performance numbers for both </em><em>Python and </em><em>go are </em><strong><em>just the calculation</em></strong><em>, not I/O or drawing pixels!</em></blockquote><p>First, we import the required packages and write a np.linespace() equivalent that returns evenly spaced numbers over a specified interval.</p><pre>package main<br><br>import (<br>	&quot;bytes&quot;<br>	&quot;fmt&quot;<br>	&quot;log&quot;<br>	&quot;math/cmplx&quot;<br>	&quot;os&quot;<br>	&quot;strings&quot;<br>	&quot;time&quot;<br><br>	&quot;encoding/binary&quot;<br>)<br><br>func linspace(start, end float64, num int) []float64 {<br>	result := make([]float64, num)<br>	step := (end - start) / float64(num-1)<br>	for i := range result {<br>		result[i] = start + float64(i)*step<br>	}<br>	return result<br>}</pre><p>The rest of the code should look familiar — note the very specific, strongly typed data types, and return types.</p><pre>func countIterationsUntilDivergent(c complex128, threshold int64) int64 {<br>	z := complex(0, 0)<br>	var ix int64 = 0<br>	for i := int64(0); i &lt; threshold; i++ {<br>		ix = i<br>		z = (z * z) + c<br>		if cmplx.Abs(z) &gt; 4 {<br>			return i<br>		}<br>	}<br>	return ix<br>}<br><br>func mandelbrot(threshold, density int64) [][]int64 {<br>	realAxis := linspace(-0.22, -0.219, 1000)<br>	imaginaryAxis := linspace(-0.70, -0.699, 1000)<br>	fmt.Printf(&quot;realAxis %v\n&quot;, len(realAxis))<br>	fmt.Printf(&quot;imaginaryAxis %v\n&quot;, len(imaginaryAxis))<br>	atlas := make([][]int64, len(realAxis))<br>	for i := range atlas {<br>		atlas[i] = make([]int64, len(imaginaryAxis))<br>	}<br>	fmt.Printf(&quot;atlas %v\n&quot;, len(atlas))<br>	for ix, _ := range realAxis {<br>		for iy, _ := range imaginaryAxis {<br>			cx := realAxis[ix]<br>			cy := imaginaryAxis[iy]<br>			c := complex(cx, cy)<br>			//fmt.Printf(&quot;ix, iy: %v %v\n&quot;, ix, iy)<br>			atlas[ix][iy] = countIterationsUntilDivergent(c, threshold)<br>		}<br>	}<br>	return atlas<br>}</pre><h4>Multi-Threaded</h4><p>Go makes this a lot easier, by using a concept called goroutines. Instead of having to deal with the Python mutltiprocessing module, pools, map vs. starmap and the intricacies of the Python Interpreter, we can simply use the go directive.</p><blockquote><em>As I’ve mentioned earlier, the code here is intentionally simple and could be trivially optimized, but I tried to keep the </em><em>go code as close to the </em><em>Python code as possible. Please forgive any simplifications.</em></blockquote><p>First, we’ll re-create the calc_row method from Python, this time using a struct to return the indexes and the value, as the channel we&#39;ll use in second won&#39;t take multiple return types:</p><pre>type triple struct {<br>	ix, iy int64<br>	c      int64<br>}<br><br>func calcRow(ix, iy int64, c complex128, threshold int64) triple {<br>	return triple{ix, iy, countIterationsUntilDivergent(c, threshold)}<br>}</pre><p>Our main function will use 2 concepts: channels and the aforementioned goroutine.</p><p>A <a href="https://golang.org/doc/effective_go.html#goroutines">goroutine</a> has a simple model: it is a function executing concurrently with other goroutines in the same address space. The go docs compare it to the Unix shell &amp; operator, which I find to be a great analogy.</p><p>The <a href="https://golang.org/doc/effective_go.html#channels">channel</a> we are using is a <em>buffered</em> channel that acts like a pipe for our concurrent function, as non-buffered channels are blocking by nature.</p><p>Which leads to the following code that wraps the inner loop (see above for comments on trivial optimization and the lack thereof here — I believe even a pointer to a WaitGroup in the goroutine and a smaller channel buffer might speed this up, but I haven&#39;t tested it yet) in a goroutine.</p><pre>func mandelbrot(threshold, density int64) [][]int64 {<br>	realAxis := linspace(-0.22, -0.219, 1000)<br>	imaginaryAxis := linspace(-0.70, -0.699, 1000)<br>	atlas := make([][]int64, len(realAxis))<br>	for i := range atlas {<br>		atlas[i] = make([]int64, len(imaginaryAxis))<br>	}<br>	// Make a buffered channel<br>	ch := make(chan triple, int64(len(realAxis))*int64(len(imaginaryAxis)))<br><br>	for ix, _ := range realAxis {<br>		go func(ix int) {<br>			for iy, _ := range imaginaryAxis {<br>				cx := realAxis[ix]<br>				cy := imaginaryAxis[iy]<br>				c := complex(cx, cy)<br>				res := calcRow(int64(ix), int64(iy), c, threshold)<br>				ch &lt;- res<br>			}<br>		}(ix)<br>	}<br><br>	for i := int64(0); i &lt; int64(len(realAxis))*int64(len(imaginaryAxis)); i++ {<br>		select {<br>		case res := &lt;-ch:<br>			atlas[res.ix][res.iy] = res.c<br>		}<br>	}<br>	return atlas<br>}</pre><p>Now, for go, we&#39;re looking at <strong>0.38s</strong> on a single CPU and <strong>0.18s</strong> concurrently in code that, while similar, is a lot more concise.</p><h3>Final Performance</h3><p>I’m just going to leave this here. As I’ve outlined previously, both the go and Python code can be further optimized, but we still get a speedup of ~45x</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*zt-XWZ4Xya91xeZo.png" /><figcaption>Generated using matplotlib; CC BY-SA 3.0</figcaption></figure><h3>Real-Life Considerations</h3><p>Talking about theoretical concepts might be interesting, but that is only a relatively small part of the puzzle. While I am sure 2020 will be the year of Haskell in widespread production use, my approach to choosing, using, and recommending people to learn a language is mostly based around real-life uses, less so academic ideals.</p><h3>Language Popularity</h3><p>This is always a fun one.</p><p>As per <a href="https://insights.stackoverflow.com/trends?tags=go%2Cpython">StackOverflow</a>, the popularity of go-related questions doesn’t even come close to the major player that is Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZI_NEIKDBKjR0hhyxmNxA.png" /><figcaption><a href="https://insights.stackoverflow.com/trends?tags=go%2Cpython">https://insights.stackoverflow.com/trends?tags=go%2Cpython</a></figcaption></figure><p>Plotting this against some other big and small players — Java, Haskell, Scala, Lisp — shows similar results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XRTBAfjCUBo89vuKGNUvgw.png" /><figcaption><a href="https://insights.stackoverflow.com/trends?tags=go%2Cpython%2Cjava%2Cscala%2Chaskell%2Clisp">https://insights.stackoverflow.com/trends?tags=go%2Cpython%2Cjava%2Cscala%2Chaskell%2Clisp</a></figcaption></figure><p>Now: Is “% of questions asked” a great metric? Probably not. Python is a very popular language to learn — I was just involved in preparing a training for it myself — and will naturally attract a huge crowd from both beginners and seasoned professionals.</p><p>The Google trends show a similar story:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/0*NETPMV82EJae-aC_.png" /><figcaption><a href="https://trends.google.com/">https://trends.google.com</a></figcaption></figure><p>(red — Python; blue - go)</p><p>I think its fair to say that Python is a lot more popular — but also that go has at least a niche, if not one one an upward trajectory. With the power of deceptive visualization, we can zoom into the above StackOverflow Graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zLm27sDA0M2EGC6GamIGzQ.png" /><figcaption><a href="https://insights.stackoverflow.com/trends?tags=go">https://insights.stackoverflow.com/trends?tags=go</a></figcaption></figure><p>And do, in fact, find an upward trajectory.</p><p>Furthermore, if StackOverflow’s yearly <a href="https://insights.stackoverflow.com/survey/2019#most-popular-technologies">developer survey</a> is to be believed, go went up from 7.2% in 2018, to 8.8% in 2019, and up to 9.4% in <a href="https://insights.stackoverflow.com/survey/2020#technology-programming-scripting-and-markup-languages-professional-developers">2020</a> when asked about &quot;Most Popular Technologies&quot;.</p><p>As per the <a href="https://insights.stackoverflow.com/survey/2020#technology-what-languages-are-associated-with-the-highest-salaries-worldwide-united-states">same survey</a>, go programmers in the United States also rank #2 (up from #3 in 2019) in pay at $140,000 p.a., just behind Scala ($150,000).</p><p>There is hope! :)</p><h3>Ecosystem</h3><p>Part of what explains the previous 2 graphs is the enormously wide ecosystem for Python — backend, frontend, statistics, machine learning, deep learning, graph analysis, GIS, robotics — it is there and it will have thousands of contributors and tens or hundreds of thousands users.</p><p>There are equivalents and I’ve tried to sum them up, alongside their relative popularity on GitHub here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*cxiO1fHcQIXGsw18qkwj5w.png" /><figcaption>Links here: <a href="https://chollinger.com/blog/2020/06/a-data-engineering-perspective-on-go-vs.-python-part-1/#ecosystem">https://chollinger.com/blog/2020/06/a-data-engineering-perspective-on-go-vs.-python-part-1/#ecosystem</a></figcaption></figure><p>It is fairly clear that, at least from a data engineering and data science perspective, the go ecosystem has a long way to go.</p><p><em>[1] Apache Beam is not a replacement for Spark</em></p><h3>Learning Curve</h3><p>This one is subjective — I personally find Python to be easier to learn only on the surface. Python is truly a rabbit hole, not unlike Java, if you really want to understand underlying concepts, architectures, and libraries.</p><p>go, on the other hand, is a fairly simple language that focusses on certain elements. Allow me to quote:</p><blockquote><em>When Go was designed, Java and C++ were the most commonly used languages for writing servers, at least at Google. We felt that these languages required too much bookkeeping and repetition. Some programmers reacted by moving towards more dynamic, fluid languages like Python, at the cost of efficiency and type safety. We felt it should be possible to have the efficiency, the safety, and the fluidity in a single language.</em></blockquote><blockquote><em>Go attempts to reduce the amount of typing in both senses of the word. Throughout its design, we have tried to reduce clutter and complexity. There are no forward declarations and no header files; everything is declared exactly once. Initialization is expressive, automatic, and easy to use. Syntax is clean and light on keywords. Stuttering (foo.Foo* myFoo = new(foo.Foo)) is reduced by simple type derivation using the := declare-and-initialize construct. And perhaps most radically, there is no type hierarchy: types just are, they don’t have to announce their relationships. These simplifications allow Go to be expressive yet comprehensible without sacrificing, well, sophistication.</em></blockquote><blockquote><em>Another important principle is to keep the concepts orthogonal. Methods can be implemented for any type; structures represent data while interfaces represent abstraction; and so on. Orthogonality makes it easier to understand what happens when things combine.</em></blockquote><blockquote><a href="https://golang.org/doc/faq#creating_a_new_language"><em>https://golang.org/doc/faq#creating_a_new_language</em></a></blockquote><p>A quick peek at for instance LinkedIn Learning shows a total of 4 courses for go and 168 for Python.</p><p>In my very own experience, the most helpful thing was to go through <a href="https://gobyexample.com/">go by example</a> and actually read the docs. Python, on the other hand, as a much broader level of external tutorials, courses, certifications, blog posts [&amp;mldr;] from people like me, universities, and large companies.</p><blockquote><em>The query “go language tutorial” returns 1.7bn results on Google, whereas “python language tutorial” clocks in at 162bn results</em></blockquote><h3>Apache Beam</h3><p>Now, we’ve talked a lot about go vs Python in general. But what about the opener of this post - where do Beam and Dataflow come in?</p><blockquote><em>This section will be brief an extended upon in part 2 of this article</em></blockquote><p>In general, the beam go SDK does provide the core functionalities you need to run a relatively simple job. It does, however, have a list of drawbacks at the time of writing (2020-06-11).</p><h3>Transformations</h3><p>Let’s look at available transformations across beam&#39;s languages. I&#39;ve cherry picked a couple, but feel free to refer to the overall docs to get a full picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*fTicxtGPSsmxJYtComOhqw.png" /><figcaption><a href="https://chollinger.com/blog/2020/06/a-data-engineering-perspective-on-go-vs.-python-part-1/#transformations">https://chollinger.com/blog/2020/06/a-data-engineering-perspective-on-go-vs.-python-part-1/#transformations</a></figcaption></figure><p>The most notable difference for people coming from Python will be the overall look of the pipeline.</p><p>This is how it’s done in Python (Side note: There is nothing stoping you from calling data.apply(func), as the operators are simply overloaded):</p><pre>class CountWords(beam.PTransform):<br>  def expand(self, pcoll):<br>    return (<br>        pcoll<br>        # Convert lines of text into individual words.<br>        | &#39;ExtractWords&#39; &gt;&gt;<br>        beam.FlatMap(lambda x: re.findall(r&#39;[A-Za-z\&#39;]+&#39;, x))<br><br>        # Count the number of times each word occurs.<br>        | beam.combiners.Count.PerElement())<br><br>counts = lines | CountWords()</pre><p>In go, it looks a lot more like a regular old function:</p><pre>func CountWords(s beam.Scope, lines beam.PCollection) beam.PCollection {<br>	s = s.Scope(&quot;CountWords&quot;)<br><br>	// Convert lines of text into individual words.<br>	col := beam.ParDo(s, extractFn, lines)<br><br>	// Count the number of times each word occurs.<br>	return stats.Count(s, col)<br>}</pre><blockquote><em>We will explore these details specificallt in part 2</em></blockquote><h3>I/O</h3><p>I/O is probably the most limited part of the go sdk, with a lot of connectors not being available for go.</p><blockquote><em>Please see </em><a href="https://beam.apache.org/documentation/io/built-in/"><em>this link</em></a><em> for an up-to-date overview.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*4CMl6z-i9PBlZXU_Cu-i5g.png" /><figcaption><a href="https://beam.apache.org/documentation/io/built-in/">https://beam.apache.org/documentation/io/built-in/</a></figcaption></figure><p>If I had to give a summary: go on beam supports essential Google Cloud services and local development, whereas Java covers almost all cases. [2]</p><p><em>[2] Keep in mind that some connectors, like </em><em>DatabaseIO, are inherently language-specific</em></p><h3>Runners</h3><p>Finally, looking the available runners, go is more or less limited to Direct and Dataflow, falling in line with my statement on I/O.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*PuxMbuwVcIGg9kVS-7Li4Q.png" /><figcaption><a href="https://chollinger.com/blog/2020/06/a-data-engineering-perspective-on-go-vs.-python-part-1/#runners">https://chollinger.com/blog/2020/06/a-data-engineering-perspective-on-go-vs.-python-part-1/#runners</a></figcaption></figure><blockquote><em>A (yes) means that there are limitations to these runners</em></blockquote><h3>Line-by-Line Example</h3><p>I suggest going through<a href="https://beam.apache.org/get-started/wordcount-example/#minimalwordcount-example">WordCount</a>.</p><p>WordCount is a great example, as it demonstrates the following concepts:</p><ul><li>Creating the Pipeline</li><li>Applying transforms to the Pipeline</li><li>Reading input</li><li>Applying ParDo transforms</li><li>Applying SDK-provided transforms</li><li>Writing output (in this example: writing to a text file)</li><li>Running the Pipeline</li></ul><p>For the sake of brevity, I won’t go into those details at this point.</p><h3>Conclusion</h3><p>One of the first questions to ask should be: Is there even a point in comparing the two languages? My answer to that might be obvious — while go might have been designed for different use cases (general purpose scripting and machine learning use cases vs. systems / &quot;cloud&quot; programming), the concepts outlined above still make me excited from a data engineering perspective.</p><p>go has many a concept that work without a massive pip dependency tree, produces clean code, is easy to compile, really fast, and (in my opinion) has a lot of potential for future data and ML use cases.</p><p><strong>In summary: </strong><strong>go and </strong><strong>Python are obviously very different languages - as I hopefully successfully outlined with my cherry-picked examples above</strong>.</p><h3>Next Steps</h3><p>As I’ve only skimmed the surface of Apache Beam in this article, the next one will focus on the following questions to use Dataflow as a real-world example for &quot; go in the wild&quot;:</p><ul><li>How mature is the go Beam SDK?</li><li>What does it support? What is missing?</li><li>What are fundamental differences?</li><li>(How) can we run a Dataflow job on GCP?</li></ul><p><em>All development and benchmarking was done under GNU/Linux [PopOS! 19.10 on Kernel 5.4] with 12 Intel i7–9750H vCores @ 4.5Ghz and 16GB RAM on a 2019 System76 Gazelle Laptop</em></p><p><em>Originally published at </em><a href="https://chollinger.com/blog/2020/06/a-data-engineering-perspective-on-go-vs.-python-part-1"><em>https://chollinger.com</em></a><em> on June 11, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dfb8bc08e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-data-engineering-perspective-on-go-vs-python-part-1-5dfb8bc08e7">A Data Engineering Perspective on Go vs. Python (Part 1)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How a broken memory module hid in plain sight — and how I blamed the Linux Kernel and two innocent…]]></title>
            <link>https://medium.com/data-science/how-a-broken-memory-module-hid-in-plain-sight-and-how-i-blamed-the-linux-kernel-and-two-innocent-ef8ce7560ecc?source=rss-7af40a2161c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef8ce7560ecc</guid>
            <category><![CDATA[ext4]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[deadlock]]></category>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[hardware]]></category>
            <dc:creator><![CDATA[Christian Hollinger]]></dc:creator>
            <pubDate>Tue, 25 Feb 2020 03:58:23 GMT</pubDate>
            <atom:updated>2020-02-25T19:39:45.018Z</atom:updated>
            <content:encoded><![CDATA[<h3>How a broken memory module hid in plain sight — and how I blamed the Linux Kernel and two innocent hard drives</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/0*oUbQ1RZqbkGt2qFx.jpg" /><figcaption>memtest is not happy —<em> Source: Christian Hollinger</em></figcaption></figure><p>Most of us have seen, debugged, and solved a lot of tech issues in our lives — from understanding that cheap PSU means a lot of smoke, through off-by-one errors in your favorite programming language, all the way to <a href="http://blog.loadzero.com/blog/tracking-down-a-segfault-in-grep/">finding segfaults in grep</a>.</p><p>This is the story on how a broken stick of DDR-4 memory was hiding in plain sight for almost a year.</p><h3>Humble beginnings</h3><p>In April of 2019, <a href="https://chollinger.com/blog/2019/04/building-a-home-server/">I built a home server</a>. It ran great, for the most part. The only thing that was always weird: My two oldest drives, a pair of WD Red 3TB NAS drives, young for their age with only ~20,000 or so hours on the clock, seemingly refused to accept larger volumes of data.</p><p>A simple rsync run like this:</p><pre>sudo rsync -P -aht --out-format=&quot;%t %f %b&quot; /mnt/3TB/ /mnt/6TB/ --exclude=&quot;.Trash-1000&quot; --exclude=&quot;Thumbs.db&quot;</pre><p>Would randomly stop, seemingly for no good reason. Not only did it stop, but it also rendered the entire machine unusable.</p><p>When piping the whole thing to a log, including stderr, the output would stop like such:</p><pre>3TB/Photos/2002/02/dad/IMG-0814.JPG # &lt;- nothing here</pre><h3>Configuration mishaps</h3><p>The drives in question were up as software RAID-1 with mdadm, LUKS encryption on top of ext4 as file system, it wasn&#39;t exactly a very sophisticated setup that caused me to believe I messed up the configuration. Still, worth a look.</p><p>Checking the array with mdadm --detail didn&#39;t show any signs of issues, pending resyncs, or any other obvious misconfigurations. The same could be said about cryptsetup luksDump - all was set up as desired (comments on the lack of ZFS, btrfs, or even LVMs will be piped to /dev/null).</p><p>Even badblocks, the tool to check for bad sectors, didn&#39;t yield any results.</p><pre>nohup badblocks -nvs /dev/sda 1&gt;&amp;2 | tee sda.out &amp;</pre><p>I even tried to hunt down the original command using strace:</p><pre>sudo strace -o strace-output.log -f rsync -P -aht --out-format=&quot;%t %f %b&quot; /mnt/3TB/ /mnt/6TB/ --exclude=&quot;.Trash-1000&quot; --exclude=&quot;Thumbs.db&quot;</pre><p>To no avail.</p><p>So, must be a dead hard-drive (or maybe a SATA cable or a dying PCI-to-SATA card). Granted, the chances that both drives die at the same time are low, but not impossible.</p><h3>Blaming the wrong thing</h3><p>So, I proceeded to simply not mount the array. After all, the server was brand new and still had plenty of space until I finally migrate all existing backup drives to it. So why bother?</p><p>My laziness was quick to bite me. After a couple of months, I migrated my pihole, a DNS-based, network-level ad and tracking blocker, on the server. It also happens to be a DHCP server.</p><p>The thing about DHCP servers is that their lack of availability isn’t immediately obvious. If every device on the network has an IP assigned, there is little cause for concern. The same can be said for DNS — most devices will simply talk to their fallback DNS, like 8.8.8.8 or 1.1.1.1.</p><p>One day, my internet was seemingly down. Quick to blame Comcast, I furiously proceed to restart both modem and router, to no avail. WiFi is there, but devices don’t get IPs. Hm, weird.</p><p>After a while, it clicked — the server is the one doing the address assignment. If it’s down, no device can join the network. Being stressed for time, I restarted the server, decrypted the drives, and went on my merry way, blaming a freak accident.</p><p>Back later, I proceed to look through /var/log, angrily searching for the delinquent. Probably the Hipster technology&#39;s fault - Kubernetes, Docker, nodejs, golang - devil&#39;s work, I do declare!</p><p>Well, finding logs on a dead kernel is difficult — after all, without a kernel to do I/O, the dead kernel writing to logs is unlikely. But one thing stood out: munin.</p><p>The last log that came in before the inevitable hard reset looked as follows:</p><pre>bigiron smartd[786]: Device: /dev/sdd [SAT], SMART Usage Attribute: 194 Temperature_Celsius changed from 113 to 112<br>22:43:15 bigiron smartd[786]: Device: /dev/sdf [SAT], 1 Currently unreadable (pending) sectors<br>22:43:15 bigiron smartd[786]: Device: /dev/sdf [SAT], SMART Usage Attribute: 194 Temperature_Celsius changed from 61 to 60<br>22:50:01 bigiron CRON[9239]: (root) CMD (if [ -x /etc/munin/plugins/apt_all ]; then /etc/munin/plugins/apt_all update 7200 12 &gt;/dev/null; elif [ -x /etc/munin/plug<br>ins/apt ]; then /etc/munin/plugins/apt update 7200 12 &gt;/dev/null; fi)<br>08:09:52 bigiron systemd-modules-load[465]: Inserted module &#39;lp&#39;</pre><p>Munin, being the battle-hardened monitoring software it is, probably suffered from a bad configuration, outdated packages, or anything of that nature. Makes sense — a single server in a house somewhere in North America uncovers a game-breaking bug on software that monitors thousands and thousands of machines worldwide.</p><p>Not wanting to bother with it any further, I removed munin. I’m too stupid for it anyways.</p><h3>Farenheit 233</h3><p>But another thing bothered me: Hard-drive temparatures of &gt;110C are also not exactly likely — most will probably fail at around 80C. On a reddit thread (about my very server, no less!), user Tired8281 posted:</p><blockquote><em>Unfortunately I made a single stupid mistake with the hardware setup and the software setup I used didn&#39;t catch it, and three months later half of the drives died</em></blockquote><blockquote><em>Promise you won&#39;t laugh? I installed the fan wrong. Instead of sucking the hot air from the CPU out of the case, it sent that hot air into the drive cage, slow roasting my hard drives</em></blockquote><blockquote><a href="https://old.reddit.com/r/linux/comments/cq9few/building_a_home_server/ewvcx9o/"><em>https://old.reddit.com/r/linux/comments/cq9few/building_a_home_server/ewvcx9o/</em></a></blockquote><p>I did not laugh. I thought I did the same thing. Sitting down, taking the thing apart, checking airflow, even searching “how to install case fans” — something I have done dozens upon dozens of times (I have way too many computers) — only to realize that everything was fine and in fact, nothing in there seemed absurdly warm. There is an A/C vent right next to the box and I use plenty of high-quality fans.</p><p>Must be S.M.A.R.T. Stupid thing, never reliable. And even more reason to blame the drives!</p><p>Only… /dev/sdf was never part of the seemingly broken 3TB array.</p><h3>Chasing the wrong thing</h3><p>Let’s summarize: Melting hard drives. A deadlocked system when copying data. Log messages right before the system locks up by monitoring software, probably doing plenty of I/O.</p><p>Time to track this down: Starting yet another rsync on the “bad” drives, I am greeted with this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*6XeC6NaMWJMg0dJz.jpg" /><figcaption>ext4_finish_bio — <em>Source: Christian Hollinger</em></figcaption></figure><p>Ha, <strong>I knew it</strong>! ext4_finish_bio! Ext4! fs module! It must be the hard drive! Here is the pesky thing:</p><pre>static void ext4_finish_bio(struct bio *bio)<br>{<br> int i;<br> struct bio_vec *bvec;</pre><pre>bio_for_each_segment_all(bvec, bio, i) {<br>  struct page *page = bvec-&gt;bv_page;<br>#ifdef CONFIG_EXT4_FS_ENCRYPTION<br>  struct page *data_page = NULL;<br>#endif<br>  struct buffer_head *bh, *head;<br>  unsigned bio_start = bvec-&gt;bv_offset;<br>  unsigned bio_end = bio_start + bvec-&gt;bv_len;<br>  unsigned under_io = 0;<br>  unsigned long flags;</pre><pre>if (!page)<br>   continue;</pre><pre>#ifdef CONFIG_EXT4_FS_ENCRYPTION<br>  if (!page-&gt;mapping) {<br>   /* The bounce data pages are unmapped. */<br>   data_page = page;<br>   fscrypt_pullback_bio_page(&amp;page, false);<br>  }<br>#endif</pre><pre>if (bio-&gt;bi_status) {<br>   SetPageError(page);<br>   mapping_set_error(page-&gt;mapping, -EIO);<br>  }<br>  bh = head = page_buffers(page);<br>  /*<br>   * We check all buffers in the page under BH_Uptodate_Lock<br>   * to avoid races with other end io clearing async_write flags<br>   */<br>  local_irq_save(flags);<br>  bit_spin_lock(BH_Uptodate_Lock, &amp;head-&gt;b_state);<br>  do {<br>   if (bh_offset(bh) &lt; bio_start ||<br>       bh_offset(bh) + bh-&gt;b_size &gt; bio_end) {<br>    if (buffer_async_write(bh))<br>     under_io++;<br>    continue;<br>   }<br>   clear_buffer_async_write(bh);<br>   if (bio-&gt;bi_status)<br>    buffer_io_error(bh);<br>  } while ((bh = bh-&gt;b_this_page) != head);<br>  bit_spin_unlock(BH_Uptodate_Lock, &amp;head-&gt;b_state);<br>  local_irq_restore(flags);<br>  if (!under_io) {<br>#ifdef CONFIG_EXT4_FS_ENCRYPTION<br>   if (data_page)<br>    fscrypt_restore_control_page(data_page);<br>#endif<br>   end_page_writeback(page);<br>  }<br> }<br>}</pre><p><a href="https://elixir.bootlin.com/linux/v4.19.106/source/fs/ext4/page-io.c#L62">https://elixir.bootlin.com/linux/v4.19.106/source/fs/ext4/page-io.c#L62</a></p><p>After searching for it, here’s the entirety of the internet’s wisdom on it, in mailing list thread from 2005: <a href="https://www.redhat.com/archives/dm-devel/2015-October/msg00046.html">https://www.redhat.com/archives/dm-devel/2015-October/msg00046.html</a></p><p>Only… I’m running Debian 10, Kernel 4.19.</p><p>More confused than ever before — how a standard call in the ext4 kernel module could cause a deadlock, on a recent (stable) kernel, that was beyond me.</p><p>Also, we can see this:</p><pre>invalid_op+0x14/0x20</pre><p>Uh, an invalid op code?</p><pre>ENTRY(invalid_op) ASM_CLAC pushl $0 pushl $do_invalid_op jmp error_code END(invalid_op)</pre><p><a href="https://elixir.bootlin.com/linux/v4.2/source/arch/x86/entry/entry_32.S#L743">https://elixir.bootlin.com/linux/v4.2/source/arch/x86/entry/entry_32.S#L743</a></p><p>Hm, a CPU problem? Knowing the types of issues older BIOS version can cause with AMD Ryzen CPUs, I now proceed to update the BIOS, hoping for change. It did not happen.</p><h3>Finding a clue</h3><p>Frustrated, I’m almost ready to spend the hundreds of dollars a fresh pair of NAS drives would cost me. Fortunately, one Sunday afternoon at Costco, my partner and I see an 8TB external drive on sale for $120. That seemed like a good investment to run some additional backups before finally replacing the drives. Alongside a gallon of olive oil and chicken stock in restaurant-supply quantities, we get home and I start setting up the drive.</p><p>Naive like I am, I plug it into the server, format it to ext4, add LUKS… and am met with an “Invalid Passphrase”, even for a single-character password. Blaming a broken USB port, I plug it into my Laptop — running popOS! and a more recent kernel, I might add — and it works like a charm.</p><p>Back to the server it goes, start rsync, and I leave it alone.</p><p>This greeted me the next morning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qZdIbxAqekaKVM76.jpg" /><figcaption>_raw_spin_lock — <em>Source: Christian Hollinger</em></figcaption></figure><p>Excuse me? <a href="https://www.kernel.org/doc/Documentation/locking/spinlocks.txt">_raw_sping_lock</a>? What does <strong>THAT</strong> have to do with anything? Well, I suppose it the machine locks up, getting an exception from a call for multi-threading and interrupts makes some sense, but this time I couldn&#39;t blame ext4. What was going on?</p><h3>Realizing the true evil</h3><p>Then it dawned on me. The server usually crashes at night. Automated backups run at night, but oftentimes, they don’t do a whole lot, given their incremental nature (especially if all I do is to play World of Warcraft on a Windows box). As these backups never hit the seemingly dead drives, I never fully made that connection.</p><p>rsync reads, compares, and writes data. The underlying kernel calls cache data, allocate pages, and process through all required modules - the file system, mdadm, dm-crypt (which in term uses the kernel&#39;s crypto APIs) - and all while handling multiple threads.</p><p>While those operations might not cause a huge load on the system — in absolute terms, as in percentage of CPU cores used — it does a lot of small operations which all require synchronization</p><p>If at any point of these, bad memory causes the kernel to mess up the respective locks, it might very well deadlock and render the system unusable, without greeting me with an actual Kernel Panic.</p><p>The more I started looking into this, the more I found:</p><pre>Message from syslogd@bigiron at Feb 22 12:38:40 ... <br>kernel:[ 7467.252060] page:ffffe29fc735a400 count:-1 mapcount:-1 mapping:0000000000000000 index:0x1 <br>kernel:[53370.089111] watchdog: BUG: soft lockup - CPU#0 stuck for 22s! [smbd:21214]</pre><p>Memory corruption can also explain a lot of the weirder issues — like hard drives seemingly about to melt into a fiery death, despite being at a comfortable temperature.</p><h3>Checking the hypothesis</h3><p>This was easy: I ran memtester on the live system and found multiple issues; then, I used used memtest86 on a bootable USB drive, only find plenty of issues. Theory confirmed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*faUZYskgcLfxT4sT.jpg" /><figcaption>memtest is not happy — <em>Source: Christian Hollinger</em></figcaption></figure><p>After switching out the RAM — the one in question is a set of CORSAIR Vengeance LPX 2x8GB DDR4 CMK8GX4M1A2400C16 — force a large rsync job, and watch the machine do its job like it was built for it.</p><h3>Conclusion</h3><p>I’m not entirely sure what to say — but I sincerely hope somebody finds this while searching for an obscure, seemingly random and unrelated issue, and is stopped from going insane.</p><p>I, for one, will start replacing RAM modules before going down the latter route.</p><p><em>Originally published at </em><a href="https://chollinger.com/blog/2020/02/how-a-broken-memory-module-hid-in-plain-sight-and-how-i-blamed-the-linux-kernel-and-two-innocent-hard-drives/?preview=true&amp;_thumbnail_id=475"><em>https://chollinger.com</em></a><em> on February 25, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef8ce7560ecc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-a-broken-memory-module-hid-in-plain-sight-and-how-i-blamed-the-linux-kernel-and-two-innocent-ef8ce7560ecc">How a broken memory module hid in plain sight — and how I blamed the Linux Kernel and two innocent…</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tensorflow on edge, or — Building a “smart” security camera with a Raspberry Pi]]></title>
            <link>https://medium.com/data-science/tensorflow-on-edge-or-building-a-smart-security-camera-with-a-raspberry-pi-5bb2fc039b0f?source=rss-7af40a2161c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bb2fc039b0f</guid>
            <category><![CDATA[surveillance]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Christian Hollinger]]></dc:creator>
            <pubDate>Mon, 09 Dec 2019 07:41:29 GMT</pubDate>
            <atom:updated>2019-12-11T05:36:10.112Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tensorflow on edge, or — Building a “smart” security camera with a Raspberry Pi</h3><h4>Building a “smart”, Raspberry Pi powered edge-computing camera setup that runs a Tensorflow object detection model to detect trespassers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/0*j66y6X231bB5Djzr.png" /></figure><p>The amount of time my outdoor cameras are being set off by light, wind, cars, or anything other than a human is insane. Overly cautious security cameras might be a feature, but an annoying one at that.</p><p>I needed a solution for this problem, without going completely overboard. Something simple, elegant, yet effective.</p><p>Folks, meet what I lovingly call “<a href="https://github.com/otter-in-a-suit/scarecrow"><strong>Scarecrow-Cam</strong></a>”. A <strong>Raspberry Pi </strong>powered camera that detects people with <strong>Tensorflow Object Detection</strong> and greets them with exceptionally loud and harsh music (or a warning sound) the second they step onto my porch.</p><p>Using real-time object detection with Tensorflow, a Raspberry Pi, a camera, a speaker, and Wifi, this ensures quiet evenings. Somewhat.</p><h3>What are we doing?</h3><p>On more serious terms, using real-time video streams and machine-learning for object detection is an actual real-world use case. While most use cases are arguably incredibly creepy, I do find some value in detecting objects or people <em>Originally published at </em><a href="https://chollinger.com/blog/?p=424&amp;preview=true&amp;_thumbnail_id=429"><em>https://chollinger.com</em></a><em> on December 9, 2019.</em>on private security cameras.</p><p>If a network of security cameras at home would be able to detect real, potential threats — humans and squirrels — and would react accordingly (for instance, by sending an alert), this would greatly improve the usefulness of these devices, which mostly rely on either motion detection or continuous video recordings — both either incredibly error-prone or reactive at most (showing you what happened after the fact).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F378429321%3Fapp_id%3D122963&amp;dntp=1&amp;url=https%3A%2F%2Fvimeo.com%2F378429321&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F838185125_640.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="848" height="464" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1efc6762299453bc6b6120c287309bf/href">https://medium.com/media/d1efc6762299453bc6b6120c287309bf/href</a></iframe><h3>On the topic of security cameras</h3><p>However — Most consumer-grade video surveillance systems are awful, plain and simple. Either they require expensive hard-wiring or rely on janky infrared and motion detection that sets of every 10 minutes because a car drives past the house, are dependent on the grace and software updates of 3 rdparty companies, often come as a subscription model, and are generally inaccessible via an API.</p><p>My unnamed outdoor camera setup usually gets set off by Old Glory waving in the wind, as opposed to by a person.</p><h3>The solution</h3><p>Here’s what we’re going to do:</p><p>We’ll use a <a href="https://www.raspberrypi.org/products/raspberry-pi-4-model-b/">Raspberry Pi 4</a> with the <a href="https://www.raspberrypi.org/products/camera-module-v2/">camera module</a> to detect video. This can run continuously and won’t need to rely on motion sensors to set off.</p><p>In order to detect objects, we’ll use the <a href="https://github.com/tensorflow/models/tree/master/research/object_detection">Tensor Flow Object Detection API</a> by Google. This library enables us to pretty much use object detection out of the box (more on that later), without the need for manually training and tuning a model or the need for a <a href="https://chollinger.com/blog/2019/07/a-look-at-apache-hadoop-in-2019/">cloud deployment</a>.</p><p>In order to talk to the camera, we’ll rely on <a href="https://opencv.org/">OpenCV</a>.</p><p>Now, here’s an issue for you: My old RasPi runs a 32bit version of Raspbian. Tensorflow does not work with 32bit operating systems (granted, there might be <a href="https://www.balena.io/blog/balena-releases-first-fully-functional-64-bit-os-for-the-raspberry-pi-4/">alternatives</a>). Furthermore, while the new Raspberry is a powerful little machine, it is not remotely comparable to a modern computer — especially on 3 and earlier revisions.</p><p>In order to mitigate this, we will <strong>stream the video over the network</strong> on the Pi to a more powerful machine — a <a href="https://chollinger.com/blog/2019/04/building-a-home-server/">home server</a>, NAS, computer, an old laptop — and process the information there.</p><p>This is a concept called <strong>edge computing</strong>. With this concept, we essentially use less powerful, smaller machines to achieve low-latency communication by doing the heavy lifting on a machine physically close to the edge node — in this case, running the Tensorflow Object detection. By doing so, we avoid roundtrips over the internet, as well as having to pay for Cloud compute on e.g., AWS or GCP.</p><p>In order to achieve this, we’ll use <a href="https://github.com/abhiTronix/vidgear">VidGear</a>, specifically it’s <a href="https://github.com/abhiTronix/vidgear/wiki/NetGear#netgear-api">NetGear API</a>, an API designed for streaming video over the network, using ZeroMQ. Just be wary of a <a href="https://github.com/abhiTronix/vidgear/issues/45">bug,</a> requiring you to use the development branch.</p><p>Once we’ve detected that there’s a human in the stream, we can send a signal to the Raspberry, using ZeroMQ, to play some really loud, annoying <strong>audio </strong>to scare people off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/0*fmmEQWr-SzYxXjna.png" /></figure><h3>Setting up a development environment</h3><p>While arguably not the most fun part, first, we need a development environment. I am using Jupyter Notebooks with Python 3.7 on Linux for this.</p><p>We are going to base the work on the following tutorial: <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb">https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb</a></p><p>Side-note: As I’m using the Tensorflow 2.0 beta, I had to hack the API for tf.gfile to tf.io.gfile in ~/.local/lib/python3.7/site-packages/object_detection/utils/label_map_util.py.</p><p>Clone the notebook, follow the instructions to set up a virtual environment, and install all dependencies.</p><h3>Testing Tensorflow locally</h3><p>Once that is done, we do probably want to loop a local video with test data without having to actually connect a live camera just yet.</p><p>All we really need to do here is to change the “while True” loop to bind to the OpenCV session. VideoCapture conveniently accepts either an integer (for a webcam) or a path to a video file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/191b508c716391ab76f92d5e08c90429/href">https://medium.com/media/191b508c716391ab76f92d5e08c90429/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/0*wAmhrOyU4U_tYmiB.png" /><figcaption>Some parts of the image were manually blurred for privacy — also, those are invited visitors 😊</figcaption></figure><p>As soon as you run the notebook, you should see the overlay of the detection model. Wonderful, the model works, and we can fine tune later.</p><h3>Network, network!</h3><p>As elaborated on before, we won’t rely on our Rasberry Pi to run the detection — so we’ll set up some network communication. I was originally thinking of writing this myself (I’m currently learning go, so that would have been a nice use case), but why bother if there’s a library?[1]</p><p>What you’ll need:</p><p>Here’s a sample writeup on how I’ve set up my Pi:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8abff8c8ec0d458b4831babe5a32de4d/href">https://medium.com/media/8abff8c8ec0d458b4831babe5a32de4d/href</a></iframe><p>Next, we’ll have to take the development branch of VidGear, as a certain bugfix is not on the master at the time of writing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2880b155d4b3e34c20e1df4e0055fa8/href">https://medium.com/media/b2880b155d4b3e34c20e1df4e0055fa8/href</a></iframe><p>Now, we can test streaming video locally:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75ffb28b3c6bf165cc8903c45f8b668e/href">https://medium.com/media/75ffb28b3c6bf165cc8903c45f8b668e/href</a></iframe><p>You should see the video playing back. You will notice some use of the multiprocessing library — we use this for ensuring the while loop gets terminated after a defined timeout, for development purposes.</p><p><em>[1] Jokes aside: Richard Hipp, the creator of SQLite, gives a lot of good reasons as to why that might be a bad idea in </em><a href="https://changelog.com/podcast/201"><em>his interview</em></a><em> on The Changelog Podcast — but for the sake of simplicity, we’ll stick to a library</em></p><h3>Putting 2 and 2 together</h3><p>Next, let’s actually deploy this onto 2 separate machines — as long as the server that will execute Tensorflow runs a 64-bit flavor of Linux (as in, a Linux kernel), we should be good to go. At home, I have a local gitlab and jenkins instance that does this for me. But realistically, any deployment option works — scp can be your friend.</p><p>We’ll need to make some small adjustments to the code by specifying IP address and port:</p><pre>client = NetGear(address = &#39;192.168.1.xxx, port = &#39;5454&#39;, protocol = &#39;tcp&#39;, pattern = 0, receive_mode = True, logging = True) server = NetGear(address=&#39;192.168.1.xxx, port=&#39;5454&#39;, protocol=&#39;tcp&#39;,pattern=0, receive_mode=False, logging=True)</pre><p>Now, we can start the sender.py on the server, receiver.py on the client, and there we go: Video over the network. Neat!</p><h3>Integrating Tensorflow</h3><p>The integration of tensorflow is trivial at this point: As we’ve already established how to do the following:</p><ul><li>Using OpenCV to loop a local video</li><li>Using Tensorflow Object Detection to run the actual model on a local video</li><li>Streaming video from one machine to the next</li></ul><p>The last step can simply be achieved by importing our tensorflow_detector module, casting the received image to a numpy array (as this is what the API expects), and calling “run_inference_for_single_image(2)”. Easy peasy!</p><h3>Talking to a camera</h3><p>Now, we can adjust our server code to actually use Tensorflow to detect images coming in from a different machine. But we don’t want canned images — we need a live stream.</p><p>Fortunately, this is pretty straightforward, as we’ve already enabled the camera module during the setup of the Pi: Connect the ribbon cable of the camera to the Pi, boot it up, and run:</p><p>raspistill -o ~/image.jpg</p><p>This should take a picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/0*CHpVF36XEtLLnOVI.jpeg" /></figure><p>In order to do the same with Python, OpenCV’s API is equally straightforward: By changing the source from a video file to the ID of the camera — 0, as we only have one — on the pi’s end, OpenCV will pick up the camera stream and send it to our server.</p><p>Once we run this, we should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/0*Es6B4XFuVO_CV9R9.jpeg" /></figure><h3>Triggering audio on the camera</h3><p>Now, we are able to stream video from the Raspberry to the server and detect a person. The missing link now is to play audio, using the <a href="https://github.com/TaylorSMarks/playsound">playsound</a> library, with GStreamer under the hood. Other alternatives are using an <strong>ossubprocess </strong>call or <strong>pygame</strong> — a configuration option can be set to change this behavior.</p><p>(You can set the audio volume on the Pi by using `alsamixer`).</p><p>In order to do that, we are going to employ <strong>ZMQ </strong>again by starting a listener thread on the Pi that waits on inputs from the server, setting predefined enum values. Once the client receives those, it triggers an audio signal and plays a sound.</p><p>All of this is blocking the respective threads — meaning, as long as the audio plays, the listener won’t care about new messages and the server won’t be able to send a new message.</p><p>In order to avoid blasting the same message, we can employ a simple sempahore structure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3537b0f2695e249b8757572e03b94bf3/href">https://medium.com/media/3537b0f2695e249b8757572e03b94bf3/href</a></iframe><h3>Testing everything</h3><p>Now that everything is working, here comes the fun part: Setting it up.</p><p>First, let’s position the camera somewhere:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*2sWccjkTDfr69IDQ.jpeg" /></figure><p>And start both server and client end and see what happens when we walk into the room!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F378429321%3Fapp_id%3D122963&amp;dntp=1&amp;url=https%3A%2F%2Fvimeo.com%2F378429321&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F838185125_640.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="848" height="464" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1efc6762299453bc6b6120c287309bf/href">https://medium.com/media/d1efc6762299453bc6b6120c287309bf/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F378429663%3Fapp_id%3D122963&amp;dntp=1&amp;url=https%3A%2F%2Fvimeo.com%2F378429663&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F838185491_1280.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddc44472c91c9b5334167885c92b24b0/href">https://medium.com/media/ddc44472c91c9b5334167885c92b24b0/href</a></iframe><p>As you can see, it takes a second to detect me — partly because of the camera angle, the model we chose, and some network latency. In a real-life scenario where a person needs to walk up the door, this is less of an issue.</p><blockquote><em>The message saying “Warning, you are…” is coming from that little speaker!</em></blockquote><h3>Next Steps</h3><p>While this already works fairly well — it streams video, detects people, and sends a signal to send audio — there is surely work to be done here.</p><p>However, there are several things we’ve ignored for the purpose of this project: The model we’re using is simply a <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md">pre-trained</a> one that has neither been tuned for our specific use case, nor does it necessarily offer the best balance for the machines that we’re using.</p><p>Furthermore, some things in the code could use some improvements — the network latency is decent but could use some work, the audio gets triggered very quickly in succession, and with our current ZeroMQ pattern, we can only support one client.</p><p>While using a cardboard box is almost the definition of perfection, a custom, 3D-printed Raspberry case and slightly better cooling would be probably a good idea.</p><h3>Conclusion</h3><p>In any case — I am happy with this little project, as it illustrates how relatively simple it can be to build your own security camera, connect it to the network, run object detection, and trigger an external factor — in this case, audio, but that could easily be a phone notification or something else — without using any Public Cloud offering, to save on latency on residential internet as well as cost.</p><p><em>All development was done under PopOS! 19.04 on Kernel 5.5.1 with 12 Intel i7–9750H vCores @ 2.6Ghz and 16GB RAM on a 2019 System76 Gazelle Laptop</em>,<em> as well as a Raspberry Pi 4 4GB on Raspian 10.</em></p><p><em>The full source is available on </em><a href="https://github.com/otter-in-a-suit/scarecrow"><em>GitHub</em></a><em>.</em></p><p><em>Originally published at </em><a href="https://chollinger.com/blog/?p=424&amp;preview=true&amp;_thumbnail_id=429"><em>https://chollinger.com</em></a><em> on December 9, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bb2fc039b0f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/tensorflow-on-edge-or-building-a-smart-security-camera-with-a-raspberry-pi-5bb2fc039b0f">Tensorflow on edge, or — Building a “smart” security camera with a Raspberry Pi</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I built a (tiny) real-time Telematics application on AWS]]></title>
            <link>https://medium.com/data-science/how-i-built-a-tiny-real-time-telematics-application-on-aws-a9956f5afe65?source=rss-7af40a2161c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9956f5afe65</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[telematics]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Christian Hollinger]]></dc:creator>
            <pubDate>Wed, 07 Aug 2019 22:25:44 GMT</pubDate>
            <atom:updated>2019-08-09T19:02:37.443Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This story was originally published on my blog </em><a href="https://chollinger.com/blog/2019/08/how-i-built-a-tiny-real-time-telematics-application-on-aws/"><em>@ chollinger.com</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/0*mbb_eDAVFb2AvW3e.jpg" /></figure><p>In 2017, <a href="https://chollinger.com/blog/2017/03/tiny-telematics-with-spark-and-zeppelin/">I wrote about </a>how to build a basic, Open Source, Hadoop-driven Telematics application (using Spark, Hive, HDFS, and Zeppelin) that can track your movements while driving, show you how your driving skills are, or how often you go over the speed limit — all without relying on 3rd party vendors processing and using that data on your behalf.</p><p>This time around, we will re-vamp this application and transform it into a more modern[1], “serverless”, real-time application by using Amazon’s AWS, an actual GPS receiver, and a GNU/Linux machine.</p><p><em>[1] See conclusion</em></p><h3>Tiny Telematics in 2019</h3><p>I recently wrote about <a href="https://chollinger.com/blog/2019/07/a-look-at-apache-hadoop-in-2019/">Hadoop vs. Public Clouds.</a> Part of the conclusion was that Public Cloud Provider (like AWS, GCP, and Azure) can provide big benefits at the cost of autonomy over your tech-stack.</p><p>In this article, we will see how the benefits of this new development can help us to re-design a 2 year old project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z8P12M3acbnyOxow.png" /></figure><h3>Architecture</h3><h3>Goals</h3><p>Our goals are simple:</p><ol><li>Every trip that is taken in a car should be captured and collected; we should be able to see where we went, when we went there, what route we took, and how fast we were going</li><li>A visualization should show us the route and our speed</li><li>Simple queries, like “What was my top speed today?” should be possible</li><li>The running costs should be reasonable</li></ol><h3>Guiding Principles</h3><p>Our guiding principles should be the following:</p><ol><li>Data should be ingested and processed in real-time; if you are moving and data is being collected, the output should be available within a couple of minutes at the latest; if you have no internet connection, the data should be cached and sent later [1]</li><li>We don’t want to bother with infrastructure and server management; everything should be running in a fully managed environment (“severless”)</li><li>The architecture and code should be simple and straightforward; we want this to be ready-to-go in a couple of hours</li></ol><h3>Out of Scope</h3><p>Last but not least, we also ignore some things:</p><ol><li>The device used will be a laptop; a similar setup will work on Android, a RaspberryPI, or any SOC device, as long as it has a Linux kernel</li><li>Internet connectivity will be provided via a phone’s hotspot; no separate SIM card to provide native connectivity will be used</li><li>Power delivery will be done either via 12V or a battery</li><li>Certain “enterprise” components — LDAP integration, VPCs, long rule sets, ACLs etc. — are out of scope; we assume that those would be per-existing in an enterprise cloud</li><li>Authentication will be simplified; no Oauth/SSAO flow will be used — we will use the device’s MAC ID as a unique ID (even though it really isn’t)</li><li>We stick to querying S3 data; more scalable solutions, such as DynamoDB, won’t be in scope</li></ol><h3>Architecture Diagram</h3><p>This leads us to the following AWS architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SyxRjKCaF3R9AZdO.png" /></figure><p>With these steps -</p><ol><li>A mobile client collects data in real-time by using the <strong>gpsd</strong> Linux daemon</li><li>The AWS <strong>IoT Greengrass Core</strong> library simulates a local AWS environment by running a Lambda function <em>directly on the device</em>. <strong>IoT Greengrass</strong> manages deployment, authentication, network and various other things for us — this makes our data collection code very simple. A local <strong>Lambda</strong> function will process the data</li><li><strong>Kinesis Firehose</strong> will take the data, run some basic transformation and validation using <strong>Lambda</strong>, and stores it to AWS S3</li><li>Amazon <strong>Athena</strong> + <strong>QuickSight</strong> will be used to analyze and visualize the data. The main reason for QuickSight is its capability to visualize geospatial data without the need for external tools or databases like Nominatim</li></ol><p><em>[1] Quicker processing is easily achieved with more money, for instance through Kinesis polling intervals (see below) — hence, we define a “near real time” goal, as somebody — me — has to pay for this 😉</em></p><h3>Step 1: Getting Real Time GPS Data</h3><p>In the original article, we used <a href="https://apps.apple.com/us/app/sensorlog/id388014573">SensorLog</a>, a great little app for iOS, to get all the iPhone’s sensor data and stored it into a CSV file that was then processed later in a <strong>batch</strong> load scenario. This is an easy solution, but with the investment of ~$15, you can get your hands on an actual GPS receiver that works almost out of the box with any GNU/Linux device, such as a RaspberryPI or a Laptop.</p><h3>Set up gpsd</h3><p>So, this time around we will be relying on <a href="https://gpsd.gitlab.io/gpsd/gpsd.html"><strong>gpsd</strong></a>, the Linux kernel’s interface daemon for GPS receivers. Using this and an inexpensive GPS dongle, we can get real-time GPS data, straight from the USB TTY. We will also be able to use Python to parse this data.</p><p>We will be using this GPS receiver: <a href="https://smile.amazon.com/gp/product/B00NWEEWW8/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&amp;psc=1">Diymall Vk-172</a>, and for the hardware, I am using my System76 Gazelle Laptop, running Pop!_OS 19.04 x86_64 with the 5.0.0–21 Kernel. Other options are available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3TP7WScLzgOQPNdI.jpg" /></figure><p>Setting this up is straightforward:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32b78e9c96919a0c8dbf494ba97cbffd/href">https://medium.com/media/32b78e9c96919a0c8dbf494ba97cbffd/href</a></iframe><p>Essentially, we are configuring the gpsd daemon to read from the right TTY and display it on screen. The above script is just a guideline — your TTY interface might be different.</p><p>Test this with</p><pre>christian @ pop-os ➜ ~ gpsmon</pre><p>And you should see data coming in.</p><p>Just make sure you are near a window or outside in order to get a connection, otherwise you might see timeouts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ySWyqoLp7R0vaNBc.jpg" /></figure><pre>TypeDescriptionDBUS_TYPE_DOUBLETime (seconds since Unix epoch)DBUS_TYPE_INT32modeDBUS_TYPE_DOUBLETime uncertainty (seconds).DBUS_TYPE_DOUBLELatitude in degrees.DBUS_TYPE_DOUBLELongitude in degrees.DBUS_TYPE_DOUBLEHorizontal uncertainty in meters, 95% confidence.DBUS_TYPE_DOUBLEAltitude in meters.DBUS_TYPE_DOUBLEAltitude uncertainty in meters, 95% confidence.DBUS_TYPE_DOUBLECourse in degrees from true north.DBUS_TYPE_DOUBLECourse uncertainty in meters, 95% confidence.DBUS_TYPE_DOUBLESpeed, meters per second.DBUS_TYPE_DOUBLESpeed uncertainty in meters per second,  95% confidence.DBUS_TYPE_DOUBLEClimb, meters per second.DBUS_TYPE_DOUBLEClimb uncertainty in meters per second,  95% confidence.DBUS_TYPE_STRINGDevice name</pre><p>And for the sake of simplicity, we will focus on latitude, longitude, altitude, speed, and time.</p><h3>Step 2: AWS IoT Core &amp; Greengrass</h3><p>The AWS IoT core will deploy a <strong>Lambda</strong> function to your device. This function will run locally, collect the GPS data, and sends it back to AWS via MQTT. It will also handle caching in case an internet connection is not available.</p><h3>A Local Lambda Function</h3><p>First off, we’ll have to write a function to do just that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8e8f0e7080d1b906b7c125de325ff2f/href">https://medium.com/media/e8e8f0e7080d1b906b7c125de325ff2f/href</a></iframe><p>This function uses the gps and greengrass module to collect the data in pre-defined batches.</p><p>At this point, we also define our default values in the common case that a certain attribute — like latitude, longitude, or speed — cannot be read. We will use some ETL/filters on this later on.</p><h3>AWS IoT Group</h3><p>Next, create an <strong>AWS IoT Core Group </strong>(please see the <a href="https://docs.aws.amazon.com/greengrass/latest/developerguide/gg-config.html">AWS documentation</a> for details).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/0*7VkA6_2PhKFjD7w_.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/0*ZJ8GsLiHMz9NTKtt.png" /></figure><p>Once the group has been created, download the certificate and key files and ensure you get the right client data for your r <a href="https://docs.aws.amazon.com/greengrass/latest/developerguide/what-is-gg.html#gg-core-download-tab">espective architecture</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/0*eU5YnGlIQj_MH1Pn.png" /></figure><h3>Deploying the Greengrass client</h3><p>We can then deploy the <strong>Greengrass client</strong> to our device. The default configuration assumes a dedicated root folder, but we will run this in our user’s home directory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9136140391b4a393127733ca554cba8c/href">https://medium.com/media/9136140391b4a393127733ca554cba8c/href</a></iframe><p>If you are deploying this to a dedicated device (where the daemon will be running constantly, e.g. on a Raspberry Pi), I suggest sticking to the default of using /greengrass.</p><h3>Deploying the Function to AWS</h3><p>Next, we need to deploy our <strong>Lambda</strong> <strong>function</strong> to AWS. As we are using custom pip dependencies, please see the <strong>deploy_venv.sh</strong> script that uses a Python Virtual Environment to package dependencies:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59df347b3d57b8ef99564517109d3cba/href">https://medium.com/media/59df347b3d57b8ef99564517109d3cba/href</a></iframe><p>On the AWS console, you can now upload the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YBozgjGvFKtyGHIJ.png" /></figure><p>It is important you create an <strong>alias</strong> and a <strong>version</strong>, as this will be referenced later on when configuring the IoT pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4Hjjmth0_t2gW1Up.png" /></figure><h3>Configuring Lambda on AWS IoT Core</h3><p>Next, head back to the AWS IoT Core Group we created earlier and add a Lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/0*OmFIREGOXuN2k9H_.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/0*JbQ0CIobI2UV29Qz.png" /></figure><p>Keep in mind: As we won’t be able to run containers (as we need to talk to the USB GPS device via TTY), ensure that this is configured correctly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/0*IbhwK3gjXVb3B_eU.png" /></figure><p>Another thing worth mentioning is the custom user ID. The client runs under a certain username and I strongly suggest setting up a service account for it.</p><p>Once that is completed, click on deploy and the Lambda function will be deployed to your clients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IkJBWf41bx3MX8c9.png" /></figure><h3>Test the Function locally</h3><p>Finally, after deployment, ensure the user is running the container and check the local logs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J_B_YUYBgJdK13xo.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ropQWBPqWtcvEtAM.png" /></figure><p>(This is running in my office and hence only shows lat/long as 0/0)</p><p>Great! Now our Lambda function runs locally and sends our location to AWS every second. Neat.</p><h3>Step 3: Kinesis Firehose &amp; ETL</h3><p>Next, we send the data to Kinesis Firehose, which will run a Lambda function and stores the data to S3 so we can query it later.</p><p>By doing this (as opposed to triggering Lambda directly), we bundle our data into manageable packages, so that we don’t have to invoke (and pay for) a Lambda function for every handful of records. We also don’t need to handle the logic to organize the keys on the S3 bucket.</p><h3>Creating an ETL Lambda Function</h3><p>First off, we’ll create a Lambda function again. This time, this function will <strong>run on AWS</strong> and not on the device. We’ll call it <strong>telematics-etl</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36ec6774ac4874923f805084001c22e3/href">https://medium.com/media/36ec6774ac4874923f805084001c22e3/href</a></iframe><p>The function simply filters invalid records (those with a latitude/longitude pair of 0, the default we defined earlier) and changes “nan” Strings for speed and altitude to an integer of -999, which we define as error code.</p><p>The function’s output is the base64 encoded data alongside an “ <strong>Ok</strong>” status as well as the original <strong>recordID</strong>.</p><p>We also need to make sure we have one <strong>JSON per line</strong> <strong>and no array</strong>, as would be default with json.dumps(data). This is a limitation of the JSON Hive parser Athena uses. Please forgive the nasty hack in the code.<br>Naturally, more complex processing can be done here.</p><p>Once done, deploy the function to AWS.</p><h3>Test the Function</h3><p>Once done, we can test this with a test record that can look like this:</p><pre>{ &quot;invocationId&quot;: &quot;85f5da9d-e841-4ea7-8503-434dbb7d1eeb&quot;, &quot;deliveryStreamArn&quot;: &quot;arn:aws:firehose:us-east-1:301732185910:deliverystream/telematics-target&quot;, &quot;region&quot;: &quot;us-east-1&quot;, &quot;records&quot;: [ { &quot;recordId&quot;: &quot;49598251732893957663814002186639229698740907093727903746000000&quot;, &quot;approximateArrivalTimestamp&quot;: 1564954575255, &quot;data&quot;: &quot;WyJ7XCJsYXRcIjogMC4wLCBcImxvbmdcIjogMC4wLCBcImFsdGl0dWRlXCI6IFwibmFuXCIsIFwidGltZXN0YW1wXCI6IFwiMjAxOS0wOC0wNFQyMTozNjoxMC4wMDBaXCIsIFwic3BlZWRcIjogXCJuYW5cIn0iLCAie1wibGF0XCI6IDAuMCwgXCJsb25nXCI6IDAuMCwgXCJhbHRpdHVkZVwiOiBcIm5hblwiLCBcInRpbWVzdGFtcFwiOiBcIjIwMTktMDgtMDRUMjE6MzY6MTAuMDAwWlwiLCBcInNwZWVkXCI6IFwibmFuXCJ9IiwgIntcImxhdFwiOiAwLjAsIFwibG9uZ1wiOiAwLjAsIFwiYWx0aXR1ZGVcIjogXCJuYW5cIiwgXCJ0aW1lc3RhbXBcIjogXCIyMDE5LTA4LTA0VDIxOjM2OjExLjAwMFpcIiwgXCJzcGVlZFwiOiBcIm5hblwifSIsICJ7XCJsYXRcIjogMC4wLCBcImxvbmdcIjogMC4wLCBcImFsdGl0dWRlXCI6IFwibmFuXCIsIFwidGltZXN0YW1wXCI6IFwiMjAxOS0wOC0wNFQyMTozNjoxMS4wMDBaXCIsIFwic3BlZWRcIjogXCJuYW5cIn0iLCAie1wibGF0XCI6IDAuMCwgXCJsb25nXCI6IDAuMCwgXCJhbHRpdHVkZVwiOiBcIm5hblwiLCBcInRpbWVzdGFtcFwiOiBcIjIwMTktMDgtMDRUMjE6MzY6MTIuMDAwWlwiLCBcInNwZWVkXCI6IFwibmFuXCJ9IiwgIntcImxhdFwiOiAwLjAsIFwibG9uZ1wiOiAwLjAsIFwiYWx0aXR1ZGVcIjogXCJuYW5cIiwgXCJ0aW1lc3RhbXBcIjogXCIyMDE5LTA4LTA0VDIxOjM2OjEyLjAwMFpcIiwgXCJzcGVlZFwiOiBcIm5hblwifSIsICJ7XCJsYXRcIjogMC4wLCBcImxvbmdcIjogMC4wLCBcImFsdGl0dWRlXCI6IFwibmFuXCIsIFwidGltZXN0YW1wXCI6IFwiMjAxOS0wOC0wNFQyMTozNjoxMy4wMDBaXCIsIFwic3BlZWRcIjogXCJuYW5cIn0iLCAie1wibGF0XCI6IDAuMCwgXCJsb25nXCI6IDAuMCwgXCJhbHRpdHVkZVwiOiBcIm5hblwiLCBcInRpbWVzdGFtcFwiOiBcIjIwMTktMDgtMDRUMjE6MzY6MTMuMDAwWlwiLCBcInNwZWVkXCI6IFwibmFuXCJ9IiwgIntcImxhdFwiOiAwLjAsIFwibG9uZ1wiOiAwLjAsIFwiYWx0aXR1ZGVcIjogXCJuYW5cIiwgXCJ0aW1lc3RhbXBcIjogXCIyMDE5LTA4LTA0VDIxOjM2OjE0LjAwMFpcIiwgXCJzcGVlZFwiOiBcIm5hblwifSIsICJ7XCJsYXRcIjogMC4wLCBcImxvbmdcIjogMC4wLCBcImFsdGl0dWRlXCI6IFwibmFuXCIsIFwidGltZXN0YW1wXCI6IFwiMjAxOS0wOC0wNFQyMTozNjoxNC4wMDBaXCIsIFwic3BlZWRcIjogXCJuYW5cIn0iLCAie1wibGF0XCI6IDAuMCwgXCJsb25nXCI6IDAuMCwgXCJhbHRpdHVkZVwiOiBcIm5hblwiLCBcInRpbWVzdGFtcFwiOiBcIjIwMTktMDgtMDRUMjE6MzY6MTUuMDAwWlwiLCBcInNwZWVkXCI6IFwibmFuXCJ9Il0=&quot; }, ...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/0*iTekbXKroUduIY6A.png" /></figure><h3>AWS Kinesis Firehose</h3><p>Once our function is working, we want to make sure all incoming data from the device is automatically calling this function, runs the ETL, and stores the data to AWS S3.</p><p>We can configure our Firehose stream as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*849bt9zRoLnVetvw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qZUd5jg-C72I0FLv.png" /></figure><p>In the 2nd step, we tell the stream to use the telematics-etl Lambda function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A9VF5oDQQ3BF9pW1.png" /></figure><p>As well as the target as S3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vfc_mi23xXAzWgz2" /></figure><p>The following settings define the threshold and delay to push the data to S3; at this point, tuning can be applied to make the pipeline run quicker or more frequently.</p><h3>Connect IoT Core and Kinesis Firehose</h3><p>And in order for it to be triggered automatically, all we need is a IoT Core Action that will send our queue data to Firehose:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0q2266n7gPUd_367.png" /></figure><h3>Step 3.5: End-to-end testing</h3><p>At this point, it is advisable to test the entire pipeline end-to-end by simply starting the <strong>greengrassd</strong> service and checking the output along the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sy5czH6VBnwhzDbV.png" /></figure><p>Once the service is started, we can ensure that the function is running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lzqCd4BluseMUPXc.png" /></figure><p>On the <a href="https://us-east-1.console.aws.amazon.com/iot/home?region=us-east-1#/test">IoT console</a>, we can follow along all MQTT messages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jUWtGw2v4RD6CNC6.png" /></figure><p>Once we see data here, they should show up in Kinesis Firehose:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nG2_vS2imlUBjED5.png" /></figure><p>Next, check the CloudWatch logs for the telematics-etl Lambda function and finally, the data on S3.</p><h3>A note on collecting real data</h3><p>As you can imagine, collecting data can be tricky when using a Laptop — unless you happen to be a police officer, most commercial cars (and traffic laws 😉 ) don’t account for using a Terminal on the road.</p><p>While relying on a headless box is certainly possible (and more realistic for daily use), I do suggest running at least one set of data collection with something that has a screen so you can validate the accuracy of GPS data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tMKmQjdpgVpw4FEW.jpg" /></figure><h3>Step 4: Analyze &amp; Visualize the Data</h3><p>Once we collected some data, we can head over to AWS Athena to attach a SQL interface to our JSON files on S3.<br><strong>Athena</strong> is using the <strong>Apache Hive</strong> dialect, but does offer several helpers to make our lives easier. We’ll start by creating a database and mapping a table to our S3 output:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97843c301822b534693e9f8c797f1653/href">https://medium.com/media/97843c301822b534693e9f8c797f1653/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/0*pSbWoV8hZamsfZk0.png" /></figure><p>We can now query the data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p0AY62szivajusUQ.png" /></figure><p>And see our trip output.</p><p>As you may have noticed, we are skipping a more complex, SQL based ETL step that would automatically group trips or at least organize the data in a meaningful way. For the sake of a simple process, we skipped this — but it certainly belongs on the “to do” list of things to improve.</p><h3>Sample Queries</h3><blockquote><em>“We should be able to see where we went, when we went there, what route we took, and how fast we were going”</em></blockquote><p>As indicated in our goals, we want to know some things. For instance, what was our top speed on a trip on 2019–08–05?</p><p>Simple — we multiply the speed (in m/s) with 2.237 to get it in miles per hour, select the max of that speed, and group it by the day:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d02ceb0c36380f4afc1879800a526ea0/href">https://medium.com/media/d02ceb0c36380f4afc1879800a526ea0/href</a></iframe><p>Which gives us 58.7 mph, which seems about right for a trip on the interstate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/0*PTwNo8-Xgwy4QA5V.png" /></figure><h3>Visualizing</h3><p>Queries are nice. But what about visuals?</p><p>As highlighted in the overview, we use <strong>QuickSight</strong> to visualize the data. QuickSight is a simple choice for this use case, as it provides geospatial visualization out of the box and behaves similarly to Tableau and other enterprise visualization toolkits. Do keep in mind that a custom dashboard on e.g. Elastic Beanstalk with d3.js could provide the same value with a quicker data refresh rate — QuickSight Standaed requires manual refreshes, whereas QuickSight Enterprise can refresh the data once per hour automatically.</p><p>While this does defeat the purpose of “real time”, it makes for a simple, basic analysis out of the box. Refreshing the data on the road yields about a 1 minute delay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/0*6yBv-aLPYa-mhP2v.jpg" /></figure><p>The set up is easy — sign up for QuickSight on the AWS console, add Athena as a data set, and drag-and-drop the fields you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IYi9OfitRnjFPGRb.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/0*nZWvdLVzk_1ex5OX.png" /></figure><p>When editing the data set, you can define double fields as latitude and longitude for geospatial analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_aX8YXN4IYitXSYd.png" /></figure><p>And by simply dragging the right fields into some analysis, we get a nifty little map, showing a trip:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OE7O14pWAjrVYA0w.png" /></figure><p>Often times, you don’t even need SQL. If we want to show our average speed by the minute, we can build a chart by using the timestamp value with a custom format (HH:mm) and changing the default sum(mph) to average(mph) as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OqJcYFHtmrmYjRiH.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/0*5gba6jpSkluHcD4L.png" /></figure><p>Using more customized SQL to do fancier things is trivial as well. For instance, seeing “high speed” scenarios on the dataset can be done as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ei2ffkU4ht_kZ2d9.png" /></figure><p>And then added to the data set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5PrCs1zPaNKgz-6a.png" /></figure><p>And all of a sudden, you can almost see all traffic lights on that route through the East of Atlanta.</p><p>Do keep in mind that QuickSight is a fairly simple tool that does not compare to the functionality of other “big” BI tools or even a Jupyter Notebook. But, in the spirit of the article, it is easy to use and set up quickly.</p><h3>Conclusion</h3><p>Compared to the “Tiny Telematics” project 2 years ago, this pipeline much simpler, runs in near real-time, can scale much easier, and requires no infrastructure setup. The whole project can be set up within a couple of hours.</p><p>Granted, we have skipped a couple of steps — for instance, a more in-depth ETL module that could prepare a much cleaner data set or a more scalable long-term storage architecture, like DynamoDB.</p><p>The focus on a “serverless” architecture enabled us to quickly spin up and use the resources we need — no time was spent on architecture management.</p><p>However, all that glitters is not gold. While we did make quick progress and have a working solution at hand (granted, driving around with a laptop maybe only qualifies for a “proof of concept” state 😉 ), we gave up autonomy over a lot of components. It’s not quite a “vendor lockin” — the code is easy enough to port, but would not run out of the box on another system or Cloud proviers.</p><p><strong>IoT Core Greengrass</strong> handled deployment to clients, certificates, code execution, containerization, and message queues.</p><p><strong>Kinesis Firehose </strong>took over the role of a fully-fledged streaming framework like Spark Streaming, Kafka, or Flink; it handled code execution, transfer, scaling, ETL resources through Lambda, and sinks into the storage stage.</p><p><strong>Athena</strong> bridges the gap at little bit — by relying on the Hive dialect and an Open-Source SerDe framework, the table definitions and SQL can be easily ported to a local Hive instance.</p><p><strong>Lambda</strong> can be regarded in similar terms — it’s just Python with some additional libraries. Switching out those and use e.g. a Kafka queue would be trivial.</p><p>So, <strong>conclusion</strong> — once again, this was a completely and utterly pointless, albeit fun project. It shows how powerful even a small subset of AWS can be and how (relatively) easy it is to set up and how real-world hardware can be used in conjunction with “the Cloud” and how old ideas can be translated to a more hip — a word I prefer over “modern” — infrastructure and architecture.</p><p><em>All development was done under PopOS! 19.04 on Kernel 5.0.0 with 12 Intel i7–9750H vCores @ 2.6Ghz and 16GB RAM on a 2019 System76 Gazelle Laptop</em> <em>The full source is available on </em><a href="https://github.com/otter-in-a-suit/TinyTelematics"><em>GitHub</em></a><em>.</em></p><p><em>Originally published at </em><a href="https://chollinger.com/blog/2019/08/how-i-built-a-tiny-real-time-telematics-application-on-aws/"><em>https://chollinger.com</em></a><em> on August 7, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9956f5afe65" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-i-built-a-tiny-real-time-telematics-application-on-aws-a9956f5afe65">How I built a (tiny) real-time Telematics application on AWS</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>