<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kevin Kazmierczak on Medium]]></title>
        <description><![CDATA[Stories by Kevin Kazmierczak on Medium]]></description>
        <link>https://medium.com/@kazmiekr?source=rss-c7fa6524e952------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ZoFHvEJ39-DtxSJi.png</url>
            <title>Stories by Kevin Kazmierczak on Medium</title>
            <link>https://medium.com/@kazmiekr?source=rss-c7fa6524e952------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 04:23:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kazmiekr/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[Building a Gas Pump Scanner with OpenCV/Python/iOS]]></title>
            <link>https://medium.com/hackernoon/building-a-gas-pump-scanner-with-opencv-python-ios-116fe6c9ae8b?source=rss-c7fa6524e952------2</link>
            <guid isPermaLink="false">https://medium.com/p/116fe6c9ae8b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Kevin Kazmierczak]]></dc:creator>
            <pubDate>Thu, 06 Apr 2017 12:58:05 GMT</pubDate>
            <atom:updated>2019-05-16T07:09:10.108Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6m85MkbmckTPkg6jqWpqMw.png" /></figure><h3>Overview</h3><p>Last year I took the <a href="http://coursera.com/">Coursera</a> course on <a href="https://www.coursera.org/learn/machine-learning">Machine Learning</a> and one of my goals in taking that class was that I wanted to use something learned from that in one of my personal projects. Back in 2012, in an exercise in <a href="https://hackernoon.com/tagged/learning">learning</a> iOS <a href="https://hackernoon.com/tagged/development">development</a>, I released a Gas Tracking App named <a href="http://fuelmateapp.com/">FuelMate</a> in the iOS app store. You can use the app to track your gas mileage over time and has some fun features like an Apple Watch app, <a href="https://www.vin.li/">vin.li</a> integration, and visuals based on your trending mpg.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*vrHtQvDd2RI3UJMQvaWKxQ.png" /><figcaption>FuelMate</figcaption></figure><p>I had a new idea for it, how about adding a feature that instead of typing in the fuel information into the app, you could just scan it directly from the pump? Let’s dive into how we can make that happen.</p><h3>Technology</h3><p>Rather than starting with updating the iOS application, I wanted to prove it out using something easier/faster. I decided that my first goal of this project was to write a simple Python app to take an image of a gas pump, and try to read the digits from it. Once I’ve proved out the idea, I’d then work on integrating that into iOS.</p><p><a href="http://www.opencv.org/">OpenCV</a> is a popular cross platform library used for Computer Vision applications. It includes a wide variety of image manipulation utilities as well as some Machine Learning functionality. Since it’s cross platform, my hope was that I could prototype this in Python first, and then convert the processing code into C++ to run on the iOS app.</p><p>My Python skills aren’t very advanced, so this was also a learning exercise in Python. I’ve released all the Python code I’ve written for this project on <a href="https://github.com/kazmiekr/GasPumpOCR">GitHub</a>. This article isn’t a technical code review of the code, but rather a high level writeup on the thought process going into this project.</p><h4>Goals</h4><p>Before touching anything in the iOS code, I had two main ideas to prove:</p><ul><li><em>Can I isolate the digits from the image?</em></li><li><em>Can I determine which digit the image represents?</em></li></ul><p>Once I’ve validated these two, I’d then invest the time in updating the iOS app. Historically anytime I touch my iOS apps, it turns into a much larger time investment than I usually expect.</p><h3>Digit Isolation</h3><p>There are multiple ways in how you can determine the digits in the image, but I set forth using simple <a href="https://en.wikipedia.org/wiki/Thresholding_(image_processing)">image thresholding</a> to attempt to find the digits.</p><p>The basic idea of image thresholding is that you convert the image to grayscale, then say that any pixel where the grayscale value is less than some constant, then that pixel is one value, otherwise it’s another. In the end you have a binary image that is just two colors, which in most cases is just black and white.</p><p>This concept is very effective in OCR applications, but the main problem is deciding on what to use for that threshold value. You can either pick some constant, or with OpenCV, you have a few additional options. Rather than use the constant, you can use adaptive thresholding, this will use smaller portions of the image and determine different thresholds to use for you. This is extremely useful in applications with different lighting situations, especially in scanning gas pumps.</p><p>Once you have the image thresholded, you can use OpenCV’s findContours method to find areas of the image that have connected sections of white pixels. Once you have the contours, then you can crop out those areas and determine if they might be a digit and what digit it is.</p><h3><strong>Basic Image Processing Flow</strong></h3><p>Here is the original image I used in testing the image processing. It has a few glare spots, but is a fairly clean image. Let’s step through the process of taking this source image and try to break it down to the individual digits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*hRu8VgMNySaJOM1MBEpKEA.png" /><figcaption>Original Image</figcaption></figure><h4>Image Prep</h4><p>Before starting the image manipulation flow, I decided to adjust some of the image properties before continuing. This was a bit of trial and error, but I noticed that when I adjusted the exposure of the image, I was able to get better results. Below is the image after I adjusted the exposure(alpha) using the Python equivalent of cv::Mat::convertTo which is just a multiply action on the image mat cv2.multiply(some_img, np.array([some_alpha]) You can see the code <a href="https://github.com/kazmiekr/GasPumpOCR/blob/master/ImageProcessing/FrameProcessor.py#L57">here</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*uob3D1lMFFyGaHCP74hBzQ.png" /><figcaption>Adjusted exposure</figcaption></figure><h4>Grayscale</h4><p>Convert the image to grayscale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*cwJhNttO8q7b-dwFL0g_3A.png" /><figcaption>Converted to grayscale</figcaption></figure><h4>Blur</h4><p>Blur the image to reduce the noise. I tried a bunch of different blur options, but found the best results with just a mild blur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*-dDsQqeSn_YdRwf2jhY5qA.png" /><figcaption>Slightly blurred</figcaption></figure><h4>Threshold the image to convert to black and white</h4><p>In the image below, I’m using the cv2.adaptiveThresholdmethod with the cv2.ADAPTIVE_THRES_GAUSSIAN_C option. This method takes in two parameters, block size and a constant to adjust by. Determining these two took some trial and error, more on that below in the optimization section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*eAGLWVLcbtEkFazsH0tgzA.png" /><figcaption>Thresholded to black/white</figcaption></figure><h4>Fill the gaps</h4><p>Since most fuel pumps use some kind 7 segment lcd display, there are slight gaps in the digits that won’t work with the contouring method, so we need to make those segments seem connected. In this case, we’re going to erode the image to connect those gaps. That may seem backwards, since you might expect to use dilate , but those methods typically work on the white sections of the image. In our case we’re ‘eroding’ away the white background to make the digits seem bigger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*6Wa9M9XJPUaSCCtIQRWObg.png" /><figcaption>Eroded to bring out the digits</figcaption></figure><h4>Inverse the Image</h4><p>Before we try to find the contours in the image, we need to reverse the colors because the findContours method will find connected sections of white and currently the digits are black.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*FFqCMQpqCtRHmMpf1wFfuA.png" /><figcaption>Colors reversed</figcaption></figure><h4>Find the contours on the image</h4><p>The image below shows our original image with bounding boxes around each of the contours it found on the image above. You can see that it found the digits, but also a bunch of things that are not digits, so we’ll need to filter those out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*uzq62GSS5TGKV8WB74vlJw.png" /><figcaption>Red boxes show all found contours</figcaption></figure><h4>Contour Filtering</h4><p>Now that we have a bunch of contours, we need to figure out which contours we care about. After looking through a bunch of gas pump displays and scenarios, I came up with a quick set of rules it’ll apply to the contours.</p><ol><li>Collect any square contours that we’ll classify as a potential decimal.</li><li>Throw out anything that’s not a square or a tall rectangle.</li><li>Match contours with certain aspect ratios. Nine of the ten digits in an LCD display would have an aspect ratio similar to one of the blue box highlights below. The exception to that rule is the digit ‘1’, which has a slightly different aspect ratio. By using some sample contours, I determined the 0–9!1 aspect as 0.6 and the 1 aspect as 0.3 . It’ll use those ratios with a +/- buffer to determine if the contour is something we want, and collect those contours.</li><li>Apply an additional set of rules to the potential digits where we’ll determine if the contour bounds deviates from the average height or vertical position of all the other potential digits. Since the digits should be the same size and lined up on the same Y, we can throw away any contours that it think is a digit, but not lined up and sized like the others.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*m659veOZJ6Ryg6u33sDxtw.png" /><figcaption>Blue rectangles show our digits/decimal, red are ignored</figcaption></figure><h4>Predict</h4><p>With two buckets of contours, one with potential digits and one with potential decimals, we can crop the image with those contour bounds and feed those into a trained system to predict it’s value. More on that process below in the ‘Digit Training’ section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*7Li3JnbZKU4lX0WX2X9lkw.png" /></figure><h4>Find the Decimal</h4><p>Finding the decimal in the image is a bit of a different problem to solve. Since it’s small and sometimes gets connected to the digit next to it, it seemed problematic to determine it using the method we used on the digits. When we filtered the contours, we collected the square contours that could be a decimal. Once we have our validated digit contours from the previous step, we’ll find the leftmost x position of the digits and the rightmost x position, to determine the space we’d expect a decimal. Then we’ll loop over those potential decimals, determine if it’s in that space and in the lower half of that space and classify that as the decimal. With the decimal found, we can then insert that into the string of numbers we’ve predicted above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*ZoZBigNbgOthxtr3y044ew.png" /><figcaption>Only look for the decimal within the yellow section</figcaption></figure><h3>Digit Training</h3><p>In the world of Machine Learning, solving an OCR problem is a <a href="https://en.wikipedia.org/wiki/Statistical_classification">classification problem</a>. We build up a set of trained data, for example the digits from the image processing, classify them as something, and then use that data to match any new images. Once I got the basic image isolation working, I created a script that could loop over a folder of images, run the digit isolation code, and then save the cropped digits into a new folder for me to review. After that ran, I’d have a folder of untrained digits that I could then use to train a system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eJhtn6osKX1m1nPz4Pv61Q.png" /></figure><p>Since OpenCV already included a <a href="https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm">k-nearest neighbor</a> (k-NN) implementation, I figured I’d give that a try at first, so I wouldn’t have to bring in any additional libraries. In order to train that, I went through the folder of digit crops and then dropped them into new folders labeled 0–9, so each folder had a collection of different versions of the number in it. I didn’t have a ton of these images, but had enough to prove this would work. Since these digits are fairly standard, I don’t think I’d need a ton of trained images to be fairly accurate.</p><p>The basics of how k-NN works is that we’ll load up each image in black and white, store that image in an array where each pixel is either on or off, and then associate those on/off pixels with a specific digit. Then when we have a new image to predict, it’ll figure out of which of the trained images has the closest match of these pixels, and return us the value that matches the closest to.</p><p>Once I had my digits organized, I created a new script that would traverse those folders, take each image and associate that image with a digit. In most of the code so far, the general image processing concepts are applied the same in both Python and C++, but here is where I came across a slight difference.</p><p>In most Python examples of this type of application, the classifications are written to two files, one containing the classification, and the other containing the image contents for that classification. This usually done with <a href="http://www.numpy.org/">NumPy</a> and standard text files. However, since I wanted to reuse this system on my iOS application, I needed to come up with a way that I could have cross-platform classification files. At the time, I couldn’t find anything to do this, so ended up writing a quick utility that will take the classification data from Python and serialize that into a JSON file that I could use on the C++ side with OpenCV’s FileStorage system. It’s not pretty, but I wrote a simple Mat serialization method in Python that’ll create the proper structure for OpenCV to read on the iOS side. Now when I train the digits, I’ll get the NumPy files for use in my Python testing, and then a JSON doc I can drag into my iOS application. You can see that code <a href="https://github.com/kazmiekr/GasPumpOCR/blob/master/train_model.py">here</a>.</p><h3>Optimization</h3><p>Once I validated my two goals of digit isolation and prediction, it was a matter of optimizing the algorithm to predict digits on new images of pumps.</p><h4>Manual</h4><p>During the initial phases of optimization, I created a simple playground application that uses some of the simple UI components that OpenCV provides you. With these components, you can create some simple trackbars to slide around and change different values and reprocess the image. I created a little wrapper around the cv2.imshow method that would tile the shown windows because I got sick of always repositioning them, you can see that <a href="https://github.com/kazmiekr/GasPumpOCR/blob/master/DisplayUtils/TileDisplay.py">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*tpmqh72GPhu_6anM5a3jSg.jpeg" /><figcaption>Playground to try different variables</figcaption></figure><p>Using the playground, I was able to load up different images and try out different variations of the variables in the image processing and determined what I thought was the best combination. This got me close, but I wanted to validate these parameters more systematically.</p><h4>Automated</h4><p>Testing the different variables on each image was a good way to get started, but I wanted a better way to validate that if I changed the variables for one image, if that would have an affect on any of the other images. To do this, I came up with system to do some automated tests against these images.</p><p>I took each of my test images and put them in a folder. Then I named each file with the digits I expected in the image, using an ‘A’ for the decimal point. Then the application could load up each of the images in that directory and predict the digits and then compare that against the digits from the filename to determine if it was a match. This allowed me to try out my changes quickly against all the different images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PwDYaAEHInoHP__w6XXNyw.png" /><figcaption>Automated test output</figcaption></figure><p>Taking this a step further, I created a different version of this script that would try out almost every combination of variables for blur, thresholding, etc on this set of images and figure out what the most optimized set of variables would be that had the best accuracy. This script took quite a bit longer to run, around 7 hours on my machine, but in the end came up with a different set of variables that I didn’t find when I tested it manually.</p><h3>iOS Conversion</h3><p>With the process and code working in Python, it was time to convert this logic over to C++ (technically Objective C++) so I could embed this logic in my iOS application. Thankfully most of the code is really easy to port from Python to C++ since a lot of the methods and signatures are all the same. One of the main differences being that in C++ the methods operating on an Image Mat work on a pointer to the image where the Python code returns an image instead.</p><p>I won’t go into all the details of how to connect the iPhone camera to the image processing, but the basic idea is that you can use the AVFoundation classes to setup an AVCaptureSession that will take input from the phone camera and stream the pixels to a buffer delegate where you can run your processing logic. This processing typically happens on a dispatch queue to avoid blocking your main thread.</p><p>In my app’s code, I take the raw pixel data and pass that into the processor that will end up returning a predicted digit string, an optional raw image after processing for debugging, and a basic confidence level of it’s prediction. Once it’s fairly confident with a value, it’ll display that on the screen.</p><p>One note on the usability in the implementation is that in order capture the digits, the user has to tap a button on the screen. I noticed in testing that the movement of your hand to hit the button sometimes would cause the digits to recalculate and you might end up with digits you didn’t want. So rather than take the digits from the point when you press the button, the code will take a running average of the most calculated value over the duration and display that one. This helps with any sudden movements that occur when you tap the button to save and also avoids a constant jitter of readings while the processor is running.</p><p>Here is a quick clip of the app running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*SOa6w4RTLSqqSyZHh8ihzA.gif" /></figure><h3>Conclusion</h3><p>Whether or not this is a feature that anyone will actually ever use is yet to be determined, but it was a fun exercise in implementing some of the Machine Learning concepts and playing with OpenCV. Since I work from home, I don’t actually fill up my car very often, so I haven’t tested this a ton in the real world, but in the app you can send me your fuel pump images if the scanning doesn’t work and I can try to make it better in the future.</p><p>So far in my testing the biggest issue the app has is with the glare on the pump display. Depending on the lighting at the pump and the angle of the phone can lead to some scans that just don’t work. I’m still working on the best way to handle those issues.</p><p>For future releases, I’d love to be able to scan the entire pump display at once, and then find the digits and split them automatically into cost and amount. Due to the differences in pumps, it’s not always consistent where these numbers are and are sometimes in individual lcd panels.</p><p>I’m still messing with different ideas to isolate the digits, but figured I’d share what I have so far and see how it goes. Maybe there are much better ways to do this; if you know of any tips/tricks, let me know!</p><figure><a href="http://bit.ly/HackernoonFB"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hqOaABQ7XGPT-OYNgiUBg.png" /></a></figure><figure><a href="https://goo.gl/k7XYbx"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgw1jkA6hgnvwzTsfMlnpg.png" /></a></figure><figure><a href="https://goo.gl/4ofytp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKBpq1ruUi0FVK2UM_I4tQ.png" /></a></figure><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a> family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35tCjoPcvq6LbB3I6Wegqw.jpeg" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=116fe6c9ae8b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/building-a-gas-pump-scanner-with-opencv-python-ios-116fe6c9ae8b">Building a Gas Pump Scanner with OpenCV/Python/iOS</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Alexa, is my food ready?]]></title>
            <link>https://medium.com/@kazmiekr/alexa-is-my-food-ready-ace274589ad6?source=rss-c7fa6524e952------2</link>
            <guid isPermaLink="false">https://medium.com/p/ace274589ad6</guid>
            <category><![CDATA[internet-of-things]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[amazon-echo]]></category>
            <dc:creator><![CDATA[Kevin Kazmierczak]]></dc:creator>
            <pubDate>Tue, 08 Mar 2016 02:35:11 GMT</pubDate>
            <atom:updated>2016-03-08T02:42:55.106Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*YXm6HitZsP0JE6KpymZT3A.jpeg" /><figcaption>Photo credit: <a href="https://www.flickr.com/photos/13815526@N02/15728648871/">Stratageme.com</a> via <a href="https://visualhunt.com/">Visual hunt</a> / <a href="http://creativecommons.org/licenses/by-nc-sa/2.0/">CC BY-NC-SA</a></figcaption></figure><h4>Introduction</h4><p>A few months ago, I wrote up how I built an internet connected grill thermometer so I could check on my low and slow cooking from any of my devices and then get push notifications when it was ready. I recently aquired an Amazon Echo and was curious if I could somehow get this device to tell me the status of my grill with just my voice. For those that aren’t familiar with the device, it’s a product from Amazon that’s a standalone digital assistant similar to Siri, but it’s always on and ready for commands. It looks just like a small speaker that can sit in your house and any time you have a question for it, you can just say something like, ‘Alexa, what’s the weather’ and it’ll tell you the weather. It does much more than that, but that’s the general idea.</p><h4>Skills</h4><p>The question for me, was whether or not I could add some custom functionality to the device. It has a bunch of built in commands, but I wanted to make my own. Thankfully Amazon thought of this and added the concept of ‘Skills’ that your echo can use. A ‘Skill’ is a custom action that developers can create to do whatever they want and they can either use them on their own device or they could publish them publicly for others to use. There is a whole listing of skills on the Alexa app that you can add to your Echo.</p><p>Let’s take a look at how you can create your own skill and then we’ll see how we can connect that skill to our BBQ temperature data.</p><p>In order to initiate your custom skill, you have to speak to the echo is a very specific format. It’s worth noting that in order to work with a custom skill, you have to include a invocation name for your skill and tell Alexa to ask that name to do something. It’s not the most natural way to ask the echo to use your skill, but it’s required so it knows to use your skill versus some other skill. I’ve heard rumors that this might go away in the future, but for now, we need to deal with it. Let’s review in detail the exact format it requires:</p><p>User: “Alexa, <strong>ask</strong> Grill Log <strong>for</strong> the temperature”</p><ul><li>“Alexa” is the required <em>wake</em> word for the device, unless you changed it to ‘Amazon’</li><li>“ask…for…” is the phrase to request a specific skill to do something. There are multiple variations of words supported here, you can see them all <a href="https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/supported-phrases-to-begin-a-conversation">here</a></li><li>“Grill Log” is the <em>invocation</em> name I’ve registered my custom skill to use, it must be two words</li><li>“the temperature” is the <em>intent</em> of the user ( not related to Android intents ) and will get passed to your service for processing</li></ul><p>Now that we know how to interact with a custom skill, let’s take a closer look at how we can get that skill on our device. Getting the skill available on your device requires that you do two steps. First, you need to decide where you will processing the user’s requests, either in your own web service or using AWS Lambda. Second, you have to register the skill on the Amazon Developer site and provide it information about your skill such as the name, endpoint, and interaction model. Don’t worry if that doesn’t make sense yet, we’ll go through this in detail below.</p><h4>Processing User Requests</h4><p>As stated above, you have two options to process the user’s request, either in your own web service or using AWS Lambda. If you already have a web service infrastructure setup, it might make more sense for you to use the web service option, but I won’t go into the detail of what’s required to do this. You can read more about the details of that on the <a href="https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/deploying-a-sample-skill-as-a-web-service">Amazon dev site</a>. It’s much easier to use the Lambda functionality as it’s already within the Amazon suite of tools. If you aren’t familiar with Lambda, it’s a service that Amazon Web Services (AWS) provides that can run code in response to events. You can read more about Lambda <a href="https://aws.amazon.com/lambda/">here</a> and read through a tutorial <a href="http://docs.aws.amazon.com/lambda/latest/dg/getting-started.html">here</a>. That code can be written in a number of different languages, Javascript (Node.js), Java, or Python, so you can pick the one you are most familiar with. You pay for how many requests and processing time you use, but you get one million requests free per month using the free tier.</p><p>In our example, we’re going to use Lambda, so to create a new Lambda function, you login to the AWS console, click `Lambda`, and then `Create a Lambda Function`. From here you can filter a list of Lambda templates to get started, and they already have some Alexa ones to use. If you type `alexa` into the filter, you’ll get three different templates to choose from. Choose the `alexa-skills-kit-color-expert` template for Javascript and you’ll have a simple template to work from. This will have some sample code that shows how to process different intents and work with sessions. For now, let’s just create the function and leave it as is. Take note of the ARN name it gives your function as we’ll use that when we register our skill with the amazon developer site. It should be something like — `arn:aws:Lambda:us-east-1:123456789:function:yourFunctionName`. We’ll come back to filling out the details of our code after we setup the interaction model. I find it easier to work out the intents and data before finishing up the code. If you don’t have access to AWS, you can see what the sample looks like <a href="https://github.com/kazmiekr/GrillLog/blob/master/Alexa/alexa_sample.js">here</a> and see a screenshot of the AWS Lambda console below.</p><p><em>AWS Lambda Console</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lY2nRkMAk7_HmIfE." /></figure><h4>Interaction Model</h4><p>Now that you have some code that you can call hosted up in the AWS cloud, we can define our skill on the developer site. If you go to developer.amazon.com, and then go to the Alexa section, you can register your custom skill here. It’s worth noting that in order to test your custom skill, you must have your device registered with the account you have registered on the developer site. If you’d like to make that skill publicly available, you can complete the registration process and then Amazon will need to certify it for use. The certification process takes anywhere from a few days to a week. Once certified, it will be in the list of available skills that anyone could add to their device. In my experience, the review team is very particular about skills it certifies, which I think is a good thing, but I’d highly recommend you review the <a href="https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/alexa-skills-kit-submission-checklist">submission guidelines</a> before you send it for certification.</p><p>The major steps in registering your skill are, choosing an invocation name, pointing the skill to your endpoint, defining the intent schema file, defining any optional data slots, and defining the sample utterances that the user uses to interact with your skill. Let’s break those steps down and see what they are all about.</p><p>The invocation name is the word or set of words that identify your skill as the one the user wants to use. This can be tricky to choose as you want it to flow nicely in the required word order of the `ask` or `tell` pattern. The name shouldn’t be complicated and easy to pronounce. You’ll want to make sure you avoid any built in names like `weather` for example. For my skill, I’ll just name it `Grill Log`.</p><p>Next we set the endpoint of the custom skill to the Lambda function we created above. You’ll take the ARN name of the function and save it on the skill so it knows where to go when it sends the user’s requests. If you were using a custom web service, you’d put that here instead of the ARN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0Ct7bABXmX3UC46z." /></figure><p>On the Interaction Model screen, I think it’s best to walk through these sections from the bottom up. Let’s start with the `Sample Utterances`. Here we’ll list all the potential ways someone can interact with the skill. For my Grill Log skill, I’d like to have two types of intents. One where the user can get the temperature of the grill and the meat together, and one where I can tell it which one I want specifically. For the first intent, I’d list something like:</p><p><em>StatusIntent</em> what’s the status</p><p>In this line, the <em>StatusIntent</em> is the name of the intent I want to use. This is something you define and you’ll use this key in your service to check on which intent was passed in. So when the user says something like, ‘Alexa, ask Grill Log what’s the status’, the requested intent would be ‘StatusIntent’. Then in your processing code you’d react to that intent accordingly.</p><p>Now there could be multiple ways to say the same thing. For example:</p><p><em>StatusIntent</em> can you tell me the status</p><p><em>StatusIntent</em> what’s going on inside my grill</p><p><em>StatusIntent</em> what’s going on</p><p>You can list additional utterances that would request the same intent. You just use the same intent name you used for each of the different utterances and they’ll all end up processing the same way.</p><p>Those examples are pretty straightforward. For the other type of intent I want, I want to know what the temperature of the grill or the meat is. Well I could list them out as two different intent names, but that wouldn’t be optimal as I’d have to duplicate all the utterances for meat or grill. Instead we’ll use the concept of `slots` and `custom slot types`. You can think of a `slot` as a variable that you can use inside of your utterance. So to set up an utterance to check the grill or the meat, you’d do something like:</p><p><em>TemperatureIntent</em> what’s the temperature of the {temptype}</p><p>In this utterance, `temptype` is the slot that will be used in place of ‘meat’ or ‘grill’. When you want to use a custom slot like this, you need to define that slot type and what values it expects in the developer portal. To do this you’d click `Add Slot Type` on the Interaction Model screen. For our example, you’d give it a type of `LIST_OF_TYPES` and then list the values of `grill` and `meat`. You might ask why didn’t we use a type of ‘temptype` since that’s what we’re using in the utterance? When you define custom slot types, they are available for use in any of the utterances you create. You might have an example where you have two slots in your utterance both using the same data types. So think of the slot type as a reusable data type that’ll you map your slots to. That leads us to the last section we haven’t talked about, which is the `Intent Schema`.</p><p>The `Intent Schema` is a JSON configuration string that defines your list of intents and what slots map to what data types. So this configuration ties all of what we’ve been talking about together. This file will list out an array of all the intents you’ve set up utterances for. You will also want to include any of the built in intents like `AMAZON.HelpIntent`, if you want your skill to react to them. For our example, we’d have a configuration file like:</p><pre>{<br>   &quot;intents&quot;: [<br>      {<br>         &quot;intent&quot;: &quot;AMAZON.HelpIntent&quot;<br>      },<br>      {<br>         &quot;intent&quot;: &quot;StatusIntent&quot;<br>      },<br>      {<br>         &quot;intent&quot;: &quot;TemperatureIntent&quot;,<br>         &quot;slots&quot;: [<br>            {<br>               &quot;name&quot;: &quot;temptype&quot;,<br>               &quot;type&quot;: &quot;LIST_OF_TYPES&quot;<br>            }<br>         ]<br>      }<br>   ]<br>}</pre><p>Here we’ve listed our two intents we setup utterances for. For the <em>TemperatureIntent</em>, we’ve defined a section for the slots we’re using, and mapped the slot named temptype to use the data type of LIST_OF_TYPES. With this configuration file we’ve now tied all our configuration together and we’ll reference things from here in our processing code so we know what the user wants the skill to do.</p><h4>Processing Code</h4><p>Now that we’ve registered our skill and have a basic Lambda function setup, we need to fill out the detail of what the skill is going to actually do. Since our code is just a Node.js script, we can connect to whatever we need to assuming there is the ability to connect to it. For my skill, I need to connect to the database of BBQ temperatures and get the last reading.</p><p>Between the time I wrote the original BBQ article and now, Parse.com has unfortunately made the descision to close it’s operation, so I’m in the process of migrating my code from Parse to AWS. To replace the database that Parse was using, I’ve decided to use the AWS DynamoDB to hold the temperature data. I’m not going to go into the detail of how I’ve updated my existing scripts to use AWS instead of Parse, that could be a separate article. Let’s just assume that the Grill data is getting saved into DynamoDB and we need to the Alexa skill to read the data from it.</p><p>My approach to this would be to write a Javascript service file that would handle the logic on grabbing the data from the DB and return the details of it. Then I’d just have the Alexa script call this new Grill service to get the data. If I had to move the data to another database or change the processing code of that, I wouldn’t want it affecting the Alexa code. You can see my example Grill service code <a href="https://github.com/kazmiekr/GrillLog/blob/master/Alexa/GrillService.js">here</a>.</p><p>Following the code that’s used in the <a href="https://github.com/kazmiekr/GrillLog/blob/master/Alexa/alexa_sample.js">sample template</a>, let’s talk through the flow of what happens when your Lambda function gets called. It first enters the handler function where it’ll check to see what the request type is. A ‘LaunchRequest’ is the type when you invoke the skill without an intent. For this type of request, you’ll want to respond back with a welcoming message about what the skill does and how to use it. The other request type is ‘IntentRequest’. This type means that user has provided a specific intent they want. Inside your code you can pull out the intent and any slot values that it may have, and then figure out what to do with that intent. In the sample code, you can see how the intents are being checked in ‘onIntent’. Here you’d want to list out all the intents you want to respond to, including any of the built in ones. This list should match what you’ve setup on your interaction model.</p><p>Once we have an intent and slot information, we know what the user wants to do. In my code, I’m going to call the Grill Service method that will use the ‘aws-sdk’ node package’s ( which is automatically available on AWS, no need to have it in node_modules ) DynamoDB.DocumentClient to fetch the last record from the database. I’ll process the values and send them back to the Alexa code to process those values into a sentence to return to the user.</p><p>Now that you have a sentence you want to return to the user, you’ll have to build a response object that contains the information you want to send back to the user. This response object will contain four main pieces of information:</p><ol><li><em>outputSpeech</em> — The text string to speak to the user</li><li><em>card</em> — The information to put on the card object the user sees in the Alexa app</li><li><em>reprompt</em> — The text string to speak if the user doesn’t respond within a small time period</li><li><em>shouldEndSession</em> — A flag to either close the session or keep it open for the user to respond</li></ol><p>The sample code from the template you selected already has some utility methods in it to help create this response object, so I’d recommend that you just use those to handle the response back to the user.</p><p>Now that’s we handled the incoming request, fetched the data, and send back a response, our function is ready to test. You can view the completed Alexa skill file <a href="https://github.com/kazmiekr/GrillLog/blob/master/Alexa/index.js">here</a>.</p><h4>Testing Your Skill</h4><p>There are a few different ways you can test our your skill. The first way I’d test the skill is by directly testing the Lamdba function using the web tools. If you are logged into the AWS console, you can load up the Lambda function and configure it’s test data and test it there. The nice part to doing the testing here is that you immediately see the response and any console logging for that request. Hopefully when you test the function, you’ll see your response object with all the speech you’ve generated. It gets a little tricky if you have work with session data, but works well for simple tests.</p><p>Another way you can test your skill is in the Amazon Alexa Developer site. That’s the site you used to register your skill and define its interaction model. If you bring up your skill, you can go to the ‘Test’ section and you can test your skill there with the ‘Service Simulator’. What’s cool about this section is that you can hear the responses it would generate on the device. You can enter in an utterance to test, and it’ll show you the request and response from Lambda, but then you can click a play button to hear what the voice generation actually sounds like. On this page you can also test the Alexa speech generation directly by typing in anything you’d like to hear, so you can figure out if certain words might be problematic. Related to speech output, if you need to finer control over how things are said you can use <a href="https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/speech-synthesis-markup-language-ssml-reference">Speech Synthesis Markup Language</a> (SSML) to do things like insert audio files or speak words differently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/0*zI9sznc-suyyiAAY." /></figure><p>The last way you can test your skill is just by asking your device. Your skill will be setup on the device tied to your developer account, and you can just test it there. This is a good way to test how it actually sounds saying the different utterances and how you might need to change or add new ones if you feel it’s difficult to articulate exactly what you’d like it to do.</p><p>Once you’ve completed testing your skill, you can either just leave it in development so it’s only available to you or can you send it for certification for anyone to use. Amazon doesn’t charge to put your skills in the Alexa store, so if you think anyone could benefit from your developed skill, there is no reason to not try to get it certified. The process takes anywhere from a few days to a week and you’ll want to be sure you’ve reviewed the <a href="https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/alexa-skills-kit-submission-checklist">submission checklist</a> to ensure you’ve satisfied all their requirements. Some things that are easily overlooked before submission: not supporting the help intent, not responding to the stop/cancel intent, and not having enough variations of your utterances. You’ll also want to be sure that when you show any example phrases in your description, that they have a comma after ‘Alexa’, and include all the needed phrase words. What was a nice touch during the review process is that any issues they find or recommendations they have, they’ll email you and include examples that are specific to your code so it’s pretty painless to get fixed.</p><h4>Conclusion</h4><p>Here we’ve walked through the steps of creating an Alexa skill that can read the temperatures out of my Grill Log database. Amazon has made it pretty simple to create these skills as all you need to worry about is figuring out how you will connect to your data. In my case I was just simply calling into another AWS product, but you could be calling into anything that’s available on the internet. The format of invoking the skills on the device still feels a bit awkward at times, but I bet that gets improved over time. I’m amazed at how many things the Echo has already integrated with and it’ll be interesting to see if Apple ever creates something similar with Siri and HomeKit to compete in this space.</p><p>One common question I often hear is if/when the Echo will support the concept of push notifications. Right now the device only wakes when it’s told ( with the exception of timers/alarms ), so there is no way to have something wake it similar to getting a notification on your phone. This seems like it’ll be a tricky problem to solve as you’d not want your echo talking to you all day for your notifications that happen. I’d guess at some point they will release this feature and maybe have users opt in to them by ensuring that they know what they are going to get notified on.</p><p>Hopefully this article shows you how simple developing Alexa skills can be and how you could potentially have your users use their voice to interact with the services you have.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FlF6to5HntI0%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DlF6to5HntI0%26feature%3Dyoutu.be&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FlF6to5HntI0%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1da7f13692ed5c70ccf077635a81742d/href">https://medium.com/media/1da7f13692ed5c70ccf077635a81742d/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ace274589ad6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrospective on a Long-Term Large Javascript Project]]></title>
            <link>https://medium.com/@kazmiekr/retrospective-on-a-long-term-large-javascript-project-ec63437b139b?source=rss-c7fa6524e952------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec63437b139b</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Kevin Kazmierczak]]></dc:creator>
            <pubDate>Thu, 25 Feb 2016 14:27:23 GMT</pubDate>
            <atom:updated>2016-02-25T14:27:23.011Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>We recently finished up a fairly large Javascript/HTML5 project that spanned the course of about three years. Large is a somewhat relative term, so to put things into perspective, we’re talking about a project with around 700 Javascript files ( 75k lines ), 300 HTML templates (13k lines ), and around 100 LESS files ( 18k lines ) which excludes any 3rd party libraries that we brought in.</p><p>In the Javascript world, a lot has changed in the past three years, and before a lot of this information escapes my mind, I thought I’d compose a list of some things that we learned.</p><h4>Backbone</h4><p>We started this project in the winter of 2013 which was around that time that the Javascript framework wars were really picking up. <a href="https://angularjs.org/">Angular</a> was gaining popularity rapidly and <a href="http://emberjs.com/">Ember</a> was as well. The client we were working with already had some experience with <a href="http://backbonejs.org/">Backbone</a>, and prefered to stick with that, so we used that for this project. While not the hottest thing at the time, it quickly became one of our favorite frameworks to work with.</p><p>Backbone is a lightweight framework that has been around since 2010 and one of the best things about it is that it hasn’t changed much over the years. It’s established, used in a lot of very large websites, and most of the updates during our development were very minor. There is very little magic in it and the source is readable in a few hours. But because it’s so simple and lightweight, it doesn’t force you into a certain pattern of how to use it, which can be good or bad depending on the developers that are working with it. In our case we had three incredible developers lay down the initial architecture and patterns and then we were able to scale that code during the project. I know this is not always the case with development, and sometimes more guidance from your framework is desired, but I enjoyed the freedom of architecting our own solution that really fit their requirements.</p><p>It’s worth mentioning that the freedom of crafting that solution usually involves bringing in some of the best of breed libraries to fill the gaps that the main framework you chose leaves out. There seems to be a trend in Javascript development where either you build up your solution using building blocks of libraries that do certain things particularity well ( Backbone/React/Flux/Redux/etc ) or a more comprehensive solution that makes these choices for you ( Angular/Ember/Sencha ). Each way has it’s pros and cons, and the best choice really depends on the project you are building. If you don’t want to have to pick the best router or data management library, and want the framework to provide stricter guidance on how things should be done maybe a more comprehensive framework makes more sense for you. If you want that freedom to swap out different pieces and lay down your own architecture, using the building block approach would be better. In our case we wanted to have that finer level of control of what we were using and why. In general, we wanted to stay as close to the Javascript specs as possible and not bring in any libraries unless we absolutely needed them. This helped reduce the pain of upgrading when other libraries changed. After three years of development, this app is still very maintainable and has a solid foundation for the future. As ES6 nears, they will be able to easily bring in a lot of great features it has to offer.</p><h4>Dependencies</h4><p>It’s amazing to think how complicated Javascript development is becoming. There is a growing number of libraries you end up bringing in via Bower or NPM and become dependent on. Hopefully we won’t get to the point of DLL hell, but we are becoming more dependent on other developers maintaining these libraries and making sure they are not making breaking changes to their APIs.</p><p>I have to admit that over the course of the project, the number of issues we had with changes in third party libraries breaking our build was probably less than 10. Given the number of dependencies we had and builds we did, I would have expected more. After we got a burned a few times, we learned to stick with exact versions of libraries using specific version numbers instead of using the conventional tilda in the package.json and bower.json to grab any patch release updates. This way there weren’t any surprises during simple patch fixes, because we got those surprises and you will likely as well.</p><h4>Code Reviews</h4><p>When we first started the project, we didn’t do a whole lot of code reviews as we were rapidly trying to build out the skeleton of this new application. But after seeing a coworker describe their GitHub pull request workflow, it seemed like something very beneficial and didn’t seem to add a lot of overhead. At first we were worried at the amount of time it’d take to do the reviews and what it’d do to velocity, but after we were able to catch some potential issues during a review, we knew this was something very beneficial to the project.</p><p>The basic idea is to follow the <a href="http://nvie.com/posts/a-successful-git-branching-model/">Gitflow</a> style pattern where a developer works in a feature branch of the code repository and completes their task there. When they completed that feature, they’d then create a pull request from that branch to the main `develop` branch. Then someone would have a chance to review it and make sure it was working and met the requirements of the ticket.</p><p>At first we did this on just some features that we wanted an additional set of eyes on to help test, but it quickly turned into something we did all the time. Especially as we grew as a team, we wanted to ensure that the quality of code stayed high. This also cross trained developers into different sections of the app that they might not have been as familiar with. Some developers knew certain sections of the app better than others, by assigning them the pull request, they were able to share some additional edge cases in testing that maybe you didn’t think of. Pretty soon, anytime you committed something directly to develop, it immediately felt wrong and you’d have to wear the cowboy hat.</p><p>One thing worth mentioning is that it’s best to keep your pull requests small and focused. There was a saying that if the pull request had less than 10 lines of code changed, that we’d be more likely to reject it, but if it was fairl5y large touching a bunch of files, it’d likely be approved. It’s not that we didn’t test it, but it’s much harder to be comprehensive on a review of a large piece of work. Time crunches happen, and if it works, it sometimes gets in.</p><h4>Embracing New Paradigms</h4><p>While we were working on this project, React came out and we payed close to attention to what the community was doing with it. We even had one of our developers go to <a href="https://reactweek.com/">React Week</a> and immersed himself in it there. After dabbling around in it, we really wanted to bring it into our project, but by that time, we already had a solid architecture in place using Backbone, and even had developed a shared library for our service layer that additional projects where depending on. Introducing a new dependency on something that was still changing fairly rapidly was not something we decided on doing.</p><p>Stepping back from the immediate desire to bring in the hot new library, we thought more about why we wanted to bring it in. Sure the virtual DOM stuff was pretty awesome, and being able to create React components would have been useful, but we really didn’t need them at the time. Our performance was fine, and we already had most of our views somewhat ‘componentized’. Some things that we thought we could benefit from were some of the ideas of React manages data for its components and how it renders that state to the DOM. We ended up creating a React-like Backbone base view that added in the idea of state/options and a basic system to control how you wanted to render the view based on those data changes. Options would be things that were passed into the component and always read only, and state would be the data that the component managed and could change. When the state or options changed, you could attach your own handler to determine how to process that data and potentially update the DOM. Now you could target certain pieces of the DOM to update instead of re-rendering the whole thing. Someday we could potentially swap in a Virtual DOM implementation to make that even more magical, but for now, it allows developers to have fine grained control over what they want to update. This type of data management in the component also helped keep state out of the actual DOM and in the Javascript so there was only one place that controlled what was displayed.</p><p>While we never got to bring in React, I think we ended up with something pretty special that gave us the best of both worlds. Developers got familiar with the concepts and enjoyed working that way. If they ever move to a new project that’s using React, I’m sure they’ll be quick to pick up the rest. This is just an example of how you could potentially bring in new programming paradigms into your own code without the explicit dependency on it. When working in technology that is changing so often, you should be watching the current trends and be open to bringing in some things into your project.</p><h4>Code Structure</h4><p>Code organization is one of those things that you could do a whole bunch of different ways. I just wanted to mention this as one of the things we initially did one way, and then later in the project realized that maybe we shouldn’t have done it that way. You won’t always get things right the first time, so be prepared to recover, rethink, and redo.</p><p>When we first started the project, we had a ‘src’ directory, and that had subdirectories for ‘less’, ‘js’, and ‘html’ holding the corresponding file types. Initially our ‘js’ folder stayed somewhat organized into folders for each of the different sections of the app, but the ‘html’ templates folder and ‘less’ folder ended up become flat with a whole bunch of files in them without organization. The lack of organization is one thing, but what was extremely painful later on was finding what files went together for particular sections of the app. Especially for new developers that joined the project, it wasn’t always clear what went with what.</p><p>We used RequireJS to bundle our code into a handful of modules that got loaded at different times as you used the application. When you created new views, that view would require a bunch of Javascript to control the view, but also brought in some HTML templates for those views as well. As a developer working on these views, it felt more natural to see all the associated files together regardless of type in the same folder. By moving everything into these folders, you’d see it’s JS, HTML templates, Less files, and even some localizations that it might have used. It was nice to see all the pieces of what put that particular view together in one place. While we didn’t go back and update everything to this pattern, we’d highly recommend starting this way on the next project.</p><p>If you are interested in reading more about code organization, I’d recommend reading a post by one of our coworkers, Cliff Myers — ‘<a href="http://cliffmeyers.com/blog/2013/4/21/code-organization-angularjs-javascript">Code Organization in Angular/Javascript Projects</a>’.</p><h4>CSS</h4><p>CSS in a large project can become very problematic if you don’t architect it well initially. Without guidance, it’s easy to have styles trickle into certain selectors that you may have had no idea about. Then it becomes difficult to see why some things aren’t styled as you intended.</p><p>Initially, the developers would try to scope their css within certain sections of the app and then had a special file for anything that was truly a global style. This became problematic as we built more and more sections, we really need better guidance on how to keep this under control.</p><p>Later we adopted a new pattern in correlation with the code structure changes we made where your styles would be scoped to the views you were working on. Each view would have a class where it would scope everything under that. For example, in the following HTML, we have an OrderDetail view, and here is how we might style that.</p><p><strong>HTML</strong></p><pre>&lt;div class=”MainWorkspace”&gt;<br>  &lt;div class=”OrderDetailView”&gt;<br>    &lt;div class=”header”&gt;&lt;/div&gt;<br>    &lt;div class=”orderContainer”&gt;&lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p><strong>CSS</strong></p><pre>.OrderDetailView {<br>  .header { … }<br>  .orderContainer {<br>    .detailText { … }<br>  }<br>}</pre><p>This ensures that that things you styled for OrderDetailView would be only scoped to that view. If you needed to make something common, you’d move up to the highest level of the scope that included the pieces you wanted to make common and then define the style using that selector. For example. if you wanted to make `header` common to all the potential detail views, you would do something like:</p><pre>.MainWorkspace {<br>  .header {…}<br>}</pre><p>If you had to override that style for the ‘OrderDetailView’ for example, you could do it within the scope of that view. While in this example it seems straightforward, but when you are building a larger app, maintaining this hierarchy is not often as easy as it seems. Setting the rules at the beginning will help keep this consistent as your app grows.</p><p>It’s worth noting that we knew that performance of the browser takes a hit as you increase the number of selectors in your style, but we felt that the security it provided to the style outweighed the performance impact of it.</p><p>Another thing related to CSS and styling that I wanted to share is that you should make sure that you never hard code any colors in your Less/Sass. You should work with your designers to decide on a color palette for the app and ensure that you define variables for those colors and stick to them. Ideally you’d have some kind of style guide, but not all projects have the time/budget for one, so sometimes your color variables become the only guide to keep new designers from bringing in other variations of those colors into your app. It seems minor but it can become a huge headache trying to figure out which shade of that color is the right one. We had an issue where we had way too many versions of a particular color and during the refactor of fixing that, we wrote a script to color match the questionable color against the known set of colors to determine its closest match. Using that script we were able to reel in all the rogue colors.</p><p>There seems to be a lot of room for improvement in how CSS is used in large apps. <a href="https://github.com/css-modules/css-modules">CSS Modules</a> look promising, and provides answers to some of the issues we have with CSS, but only time will tell where this goes. If you are interested in CSS Modules, we just posted an article all about them <a href="http://www.universalmind.com/blog/css-modules%E2%80%8A-%E2%80%8Asolving-the-challenges-of-css-at-scale/">here</a>.</p><h4>Pragmatism</h4><p>During the course of the project we scaled in team size from around three to twelve developers. One thing that all developers commented on when joining the project was how readable and understandable the code was that they were working with. We focused on clarity of code over cleverness. One of our developers always said, ‘know that the next developer to look at this code will probably be yourself so be polite and focus on clarity’.</p><p>When working on features we tried not to over-engineer them, focusing only on the most immediate requirements. We were working in an agile environment and tried to keep things reasonable per sprint. Sometimes we ended up butting heads with the same pieces of code that were becoming problematic. By the third time we hit something, we’d regroup as a team and see if there was a better solution. The majority of the time it really revolved around creating a more generic solution. Which makes you think well why didn’t you make it more generic the first time? Making everything a generic solution doesn’t always make sense. It adds extra development time, additional cost, and might not be as performant as something targeting the exact features. What we found is that over time it sometimes took those intermediate versions to really figure out all the features that were really intended for it.</p><h4>Conclusion</h4><p>When you work on something for three years, there will always be some things you did right the first time, and others that you didn’t. Being able to look back and see things that you can improve will help you grow and help on the next project you work on. That process will likely repeat on and on during your career.</p><p>As Javascript and Web Technologies continue to evolve, the thought process on how you build these large apps will change. Trends will come and go and it’ll be up to you to decide what you think will work best for your project. Just because they make sense to you, doesn’t mean they are a good fit for your project. Sometimes it’ll make sense to bring in certain library or it might just be that you adapt some of those new ideas into how you develop your own code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec63437b139b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What every iOS Developer should be doing with Instruments]]></title>
            <link>https://medium.com/@kazmiekr/what-every-ios-developer-should-be-doing-with-instruments-d1661eeaf64f?source=rss-c7fa6524e952------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1661eeaf64f</guid>
            <category><![CDATA[objective-c]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Kevin Kazmierczak]]></dc:creator>
            <pubDate>Mon, 08 Feb 2016 21:27:09 GMT</pubDate>
            <atom:updated>2016-02-08T21:27:26.916Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Introduction</strong></h4><p>You’ve just wrapped up development on a shiny new iOS project and have done your best to ensure that the app doesn’t crash and it seems to run ok on your test devices, but is it ready to submit? If you haven’t done any profiling in Instruments, the answer is probably no. Just because it doesn’t crash doesn’t mean that it’s going to behave and run well on your user’s devices.</p><p>Xcode includes a performance tuning application named Instruments that you can use to profile your application using all sorts of different metrics. They have tools to inspect CPU usage, memory usage, leaks, file/network activity, and energy usage just to name a few. It’s really easy to start profiling your app from Xcode, but it’s sometimes not as easy to understand what you see when it’s profiling, which deters some developers from being able to use this tool to it’s fullest potential.</p><p>With so many things you can profile, how do you choose what to look at? Obviously if there are any immediate performance issues that you know about, like slow network requests or laggy scrolling, you should target those first. But if things seem to be going ok, I’d suggest that you at least look at your CPU and memory usage during a few runs of the application to ensure that everything is behaving as you might think.</p><h4><strong>When to Profile</strong></h4><p>Before going into this information I did want to note that I don’t expect every developer to be actively profiling their app all the time. Most of us have deadlines and expectations to meet, so profiling your application sometimes get shoved to the side, but let’s talk about some points where you should be profiling.</p><p>At a bare minimum, you should be doing this activity before you submit it to the app store. You don’t want your app to get past review and get into the hands of the users and have bad things happen while they are using your app. You’ll end up with lots of poor reviews, which will seriously hurt your downloads.</p><p>I’d suggest that after you finish up some major new features you should do some quick profiles to make sure everything is in order. The longer you wait, the more potential issues you might find and they might pile up into a larger work item to resolve that might delay your launch. As a team you could define some of these check in’s as part of your dev plan so there is time allocated.</p><p>The other time I’d suggest that you fire up Instruments is when you are working with some different pieces of the frameworks you are not as familiar with. With the amount of iOS frameworks and libraries constantly expanding, it’s likely you are going to work with some frameworks you aren’t as familiar with. Most developers will know when this is, and if you have that feeling, you should run some quick profiles to ensure your work is playing nice with the rest of the application. Bringing in 3rd party libraries can also be a good time to profile to ensure that the libraries you are adding are not causing any memory issues that might be out of your control.</p><h4><strong>Profiling in Xcode</strong></h4><p>Xcode has been expanding out the ‘Debug Navigator’ to include lots of information that used to be previously buried inside of Instruments. If you hit CMD-6, you can bring up the view that shows performance information about your application. Here you can see some quick summaries of CPU/Memory/Energy/Disk/Network activity and spot check to see if there are any immediate issues. From here you can even start up Instruments by clicking the ‘Profile in Instruments’ button at the top which will ask you transfer that debug session or start a new one in Instruments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T9y-NWljR754-CZZ." /></figure><h4><strong>CPU Profiling</strong></h4><p>The first thing we’ll take a look at is profiling your CPU usage. To start CPU profiling, we’ll choose to select ‘Profile’ product command and select the device as the target. You want to be sure to use an actual device when doing CPU profiling to get accurate information about the CPU usage. If you target a simulator, you’ll be getting CPU information off your machine and not how it’s running on an actual device which will be very different. Ideally you’ll want to use the slowest device you have to ensure it’ll work on that and anything faster.</p><p>CPU Profiling works by taking samples of processes running at set intervals. By default it samples every 1ms, but you can change this to customize the behavior if needed. By seeing what processes are still running between snapshots, it can determine how long things are running.</p><p>After the profile build is finished, Instruments will launch and ask you which profiling template to use. For CPU usage, we’ll use the ‘Time Profiler’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*HF1svjdQG5OjfJFXJQptzA.png" /></figure><p>This will give us the initial Instruments view with the Time Profiler view setup. Now to actually run the profiler, you’ll need to click the record button to start the profiling. If for some reason the record button is disabled, it should tell you why on the right hand side of the profiler track near the top. I’ve seen it get stuck in a state where it says the ‘device is offline’, and a device reboot usually fixes it. Once you’ve clicked the record button, it’ll start showing information about what’s happening in your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*455yL_eqEVPe5Mod." /></figure><p>You’ll see the top shows a chart of your CPU usage over time during the recording and the bottom will show the Call Tree of processes that have run. The initial dump of processes doesn’t really look very useful as it’s showing the top of the Call Tree and forces you to expand out the items to drill into the stuff that’s really happening. It is also showing you all kinds of system library activity that you may or may not be interested in. The majority of the time you are probably only interested in the code that you wrote. Luckily there are some quick settings you can change to get to the important information faster.</p><p>If you click the gear on the right side for ‘Display Settings’ (⌘2), there are a bunch of options for the ‘Call Tree’. By default most of these options are off and we’ll want to turn them on. Let’s look at what these options do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/0*03v_58mVkt7R1MXj." /></figure><ul><li>Separate by Thread — Shows the processes by thread to help diagnose overworked threads</li><li>Invert Call Tree — Reverses the stack to show the bottom portion first which is usually much more useful</li><li>Hide System Libraries — Removes system library processes allowing to focus only on your code</li><li>Flatten Recursion — Combines recursive calls into one single entry shown</li><li>Top Functions — Combines the time the function called used plus the time spent by functions called from that function. This helps find your more expensive methods to diagnose</li></ul><p>I typically find that it’s most useful to check all these boxes when profiling to quickly get to the information you want to see about your application. Once you check these, you’ll see the Call Tree become much more useful showing your application methods that are using up your CPU.</p><p>Now with your filtered list of expensive CPU methods you can begin to try to optimize certain spots in your application. There will likely be some things that you can’t do much about, but you might see some things that you can optimize. I’m not going to go into much detail about how you can optimize your application, but some things to consider would be:</p><ul><li>Offloading non UI processes to different threads</li><li>Caching images, data, or anything being used multiple times that don’t need to always be reloaded</li><li>Reducing the number of UI updates, you sometimes might be updating the UI unnecessarily</li></ul><p>One quick tip to mention is that you can use the ‘Extended Detail’ section ( the icon next to the Display Settings or ⌘3) on the right hand side of the ‘Call Tree’ section to see the specific stack trace for what you selected and then you can double click a line in that stack to have Instruments take you to that exact line in your code. From there you can click on the tiny little Xcode icon that will put you back into Xcode to work on that specific method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/0*KT2mKtWfVXKUSbbA." /></figure><p>After you make some updates to address any of your performance issues, run the same set of steps again with the profiler and check to see if your performance is better and continue this process until you are happy with the performance.</p><h4><strong>Memory Profiling</strong></h4><p>The next type of profiling we’ll look at is Memory profiling. This is often one of the most overlooked issues in developing iOS apps as it doesn’t cause any immediate issues. If you have memory leaks and users continue to use your app, memory will grow and grow until you reach an out of memory situation and the app will crash. Not only is this bad for your app, it’s also not being a good app citizen on that user’s device which might cause low memory situations for other apps. Let’s take a look at how we can use Instruments to make sure we’re not leaking memory and how we might be able to fix some of these situations.</p><p>When looking at your memory usage over time, you’ll want to make sure that it doesn’t keep increasing over time.</p><p>You don’t want to see growth like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3ADmr6QKpfpwugAh." /></figure><p>You should see something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n7o9T_O7SVV9RLuy." /></figure><p>The easiest way to take a look at memory usage is again in the ‘Debug Navigator’ when you run your app from Xcode. Here you can select the ‘Memory’ panel and watch memory usage over time. Scanning the chart here can help see any immediate memory issues like usage constantly growing and never going down.</p><p>To take a closer look at your memory usage, click the ‘Profile in Instruments’ button and it’ll ask you if you’d like to transfer this session or restart as a new one. Choose to restart the session with Instruments. I haven’t had good luck doing the transfer as some information seems to get lost. This will open Instruments and include the Allocations and Leaks templates that will help you see all the memory allocations and potential leaks that are occurring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7S6r4KwmrglUZgvw." /></figure><p>I’m not going to go into too much detail on the Leaks panel, but it will take snapshots for you at specified intervals to see if you have any memory that has been allocated but unable to deallocate. This often happens if you are working in Objective-C and using some of the C libraries where you are responsible for freeing any allocated memory. You can usually find most of these things with the ‘Analyze’ build option, but sometimes you might have a situation where the Analyze tool didn’t find anything, but Instruments caught the issue. If you are working in Swift, these leaks are less common as it takes care of some of the things you used to have to do in Objective-C.</p><p>With the memory profiler running, what I find useful to do is to perform a sequence of events multiple times and marking the generation of memory after each sequence. You can then analyze the memory growth between each snapshot. To take a snapshot of the memory you just click the ‘Mark Generation’ button on the ‘Display Settings’ section on the right hand side. If you forget to mark a generation during your sequence, you can always add a new one after the fact and then move it to the spot you want, you just click and hold on the flag near the top and then move it. Once you have a handful of generations, I’d sort them by growth, change the ‘Allocation Type’ to ‘All Heap Allocations’ which will sort them by raw size and remove some system things you may not have control over. Then you might see some things that stick out in terms of memory usage, but it may be hard to see the objects you have created versus some of the primitives that are just using up space.</p><p>Now that you have a list of memory allocations, it’s time to start looking to see that everything is in order, but the initial display of this data isn’t immediately useful. If you happen to be working in Swift, all of your Swift objects will get prefixed with the application name so you can just search for your application name in the filter to see all of the things in memory that are your objects. If you are working in Objective-C, it’s a little more tricky to get this information. You basically have to know the names of the things you are looking for. If you happened to have prefixed your files you could search on that prefix and see all your objects that way, or you could also search on some naming scheme you might have used like assuming you named all your view controllers *ViewController, you could search for ‘ViewController’ and see all those objects.</p><p>Here in my example screenshot, we can see that I made 4 snapshots and I’m filtering on objects with the name ViewController and I can see that I’m leaking a ServiceViewController between each generation snapshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N4BwB5Kpu0-Qps3G." /></figure><p>I happened to know exactly what the issue is here in my code here as I put something in the ViewController to cause a retain cycle for this article’s purpose, but for your code you’ll have to dig around and see what’s keeping some of your leaked objects from getting released. A retain cycle is when you have two objects that have strong references to each other and prevents them from being deallocated. I won’t go into all the details about what causes retain cycles, but I’d suggest looking at your delegates and blocks/closures first. They seem to cause the most drama. You’ll want to make sure your delegates are weak and that you are using weak ( or unowned in Swift ) references in your blocks/closures.</p><p>If you have trouble immediately seeing what’s holding on to some of your objects, you can use Instruments to give you more information on the allocation summary of the objects in question. If you click the little arrow next to the object, it’ll show you all the allocations of that object, and who is responsible for creating it. Then if you click the little arrow next to one of those allocations, you can see the detailed information about its retain and release count. If that number doesn’t reach 0, it won’t get deallocated. It sometimes takes some detective skills to see what’s causing some of the retains, but a quick tip is to look at anything where the ‘Responsible Library’ is your application or ‘libsystem_blocks’ and skip over anything ‘UIKit’. You can type those items in the search box to filter the list. Then be sure to have the ‘Extended Detail’ shown and you can see the stack trace of what’s going on with each of those.</p><h4><strong>Conclusion</strong></h4><p>This really just scratches the surface of all the things that Instruments does, but hopefully this information helps gets you past starting up Instruments and not immediately knowing what to do with it. Once you become more comfortable with the tooling, you’ll end up using it more, and the better your code will become. You’ll become more proactive about checking on things that you know might cause an issue and it’ll become part of your standard workflow.</p><p>If you want to learn more about using Instruments, I’d highly recommend watching this WWDC video from 2014 — <a href="https://developer.apple.com/videos/play/wwdc2014-418/">Improving your app with Instruments</a>. It’ll walk through some of the things discussed in this article with some additional tips and tricks. If you just want to read more about Instruments, check out the <a href="https://developer.apple.com/library/tvos/documentation/DeveloperTools/Conceptual/InstrumentsUserGuide/index.html">user guide</a> from Apple.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1661eeaf64f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smoking Meat with the Internet of Things]]></title>
            <link>https://medium.com/@kazmiekr/smoking-meat-with-the-internet-of-things-b047ecda94a0?source=rss-c7fa6524e952------2</link>
            <guid isPermaLink="false">https://medium.com/p/b047ecda94a0</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[iot]]></category>
            <dc:creator><![CDATA[Kevin Kazmierczak]]></dc:creator>
            <pubDate>Thu, 07 Jan 2016 15:01:26 GMT</pubDate>
            <atom:updated>2016-01-07T15:06:30.947Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1dsl18DuOc1qWPiWmgpcQw.jpeg" /></figure><h4>Background</h4><p>In the height of summer, I was getting into using my old Weber Kettle Grill as a smoker to do some low and slow cooking. I already had a remote grill thermometer and was using that to monitor the internal food temperature while I did other things around the house. After a few failed cooking attempts, I came to realize how important monitoring the internal grill temperature was. My thermometer didn’t do that, and I was about to order one from Amazon, when I asked myself, how hard could this be to build? Even better, could I build something that could tell me it was done? Or when it needed attention?</p><p>I’ve wanted to do an Arduino project ever since I heard about its capabilities, and now was the chance. I quickly validated that this was something that could actually be done, and as a software person, once I could get the data out of the temperature probes and into the Internet, I had a ton of options of what to do with it.</p><h4>Project Plan</h4><p>At a high level, my plan was to use two temperature probes — reusing one I had, and another from Amazon — connected to an Arduino. The Arduino would calculate the temperature readings and then send them up to <a href="http://www.parse.com/">Parse.com</a> where it would store and monitor the data. When the temperature hits a certain threshold, it would send a push notification to my devices. I’d also have an iOS app on the phone where I could check the current temperatures whenever I wanted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4IqXhztb-KpcHOooCHkfBg.png" /></figure><p>I’ve made all of the resources for this project available on <a href="https://github.com/kazmiekr/GrillLog">Github</a> and I’ll walk through how I’ve put all the pieces together in the following sections.</p><h4>Part List</h4><p>Here is a list of all the parts I used to put together the circuit.</p><ul><li>Breadboard</li><li>Misc jumper wires</li><li><a href="http://www.amazon.com/Arduino-Ultimate-Starter-page-Instruction/dp/B00BT0NDB8/ref=sr_1_5?ie=UTF8&amp;qid=1444243576&amp;sr=8-5&amp;keywords=arduino+uno">Arduino Uno</a></li><li><a href="https://www.sparkfun.com/products/13287">Sparkfun Wifi Shield</a></li><li><a href="http://www.amazon.com/gp/product/B006XLWL7K?psc=1&amp;redirect=true&amp;ref_=oh_aui_detailpage_o04_s00">Maverick ET732 Smoker Probe</a></li><li>Generic Remote BBQ Food Probe — I’m using one from <a href="http://www.amazon.com/Oregon-Scientific-AW129-Wireless-Thermometer/dp/B0006G2WYK/ref=sr_1_6?ie=UTF8&amp;qid=1444242131&amp;sr=8-6&amp;keywords=oregon+scientific+grill+thermometer">this</a>, but you could use any one you might have</li><li>10K Potentiometer</li><li>16×2 LCD Module with pin headers</li><li>220K Ohm Resistor</li><li>1M Ohm Resistor</li><li><a href="http://www.amazon.com/gp/product/B00AKWR59M?psc=1&amp;redirect=true&amp;ref_=oh_aui_detailpage_o06_s00">2x 2.5mm audio jack inputs</a></li></ul><h4>Circuit Design</h4><p>The central component to this device is the <a href="https://www.arduino.cc/en/Main/ArduinoBoardUno">Arduino UNO</a>. The UNO is a programmable microprocessor that can take in a number of digital and analog inputs. Using the Arduino IDE, we can write C code to control those inputs to read in signals or send out digital signals. For our example, the probes we’re going to use are analog inputs and will be plugged into the analog input pins 0 and 1.</p><p>The first thing that I needed to figure out was how to connect a BBQ temperature probe into the Arduino. It turns out that most BBQ thermometers are ‘<a href="https://learn.adafruit.com/thermistor/using-a-thermistor">thermistors</a>’. A thermistor is a component whose resistance will vary depending on the temperature. Assuming you have the specifications on the thermistor, you can convert that resistance into a temperature reading. In my case, these specifics were unknowns and I’ll talk through how I figured out how to get around that. Physically, all we need to connect the probe is a <a href="http://www.amazon.com/gp/product/B00AKWR59M?psc=1&amp;redirect=true&amp;ref_=oh_aui_detailpage_o06_s00">2.5mm audio jack input</a>. Attach some wire, either soldered, or alligator style clip wires to the jack input and wire that into the Arduino.</p><p>Just wiring them into the Arduino is not going to be sufficient. In order to get proper values into the Arduino, we’ll need to setup a ‘Voltage Divider’. You can read more about voltage dividers <a href="https://learn.sparkfun.com/tutorials/voltage-dividers">here</a>, but to set one up you need to choose a resistor to wire in the circuit that pairs with the resistance you want to measure. Because we don’t know the specific resistances required by the probes, we’ll have to get creative. For my setup, all that I did was use a multimeter to measure the resistance reported by the probe at room temperature and found a resistor that was closest to that value. In my case, it was 220K ohm for the food probe, and 1M ohm for the chamber probe. Place that resistor in between the Arduino and the Thermistor and we’ll be able to read some resistances that we can convert to temperatures.</p><p>Now that we can read in the resistances from the probes, we’ll need to figure out how to convert those values into temperatures. It turns out that there is a formula called the ‘Steinhart Hart Equation’ that will do that for you, granted you know all of the specifics. I won’t go into the detail of that equation nor do I really understand that portion, but you can go read about it <a href="https://en.wikipedia.org/wiki/Steinhart%E2%80%93Hart_equation">here</a>. I found some sample code on<a href="https://learn.adafruit.com/thermistor/using-a-thermistor">adafruit</a> that did exactly what I wanted, and I just used pieces of that in the Arduino code. The one tricky piece to that equation is that it requires something called a beta-coefficient of the thermistor, which was unknown for my probes. One way to calculate that coefficient is to measure the resistance of the thermistor at a handful of different temperatures in its supported range and then plug them into an<a href="http://www.thinksrs.com/downloads/programs/Therm%20Calc/NTCCalibrator/NTCcalculator.htm">online calculator</a>. I did that for my probes, and then tweaked that number a bit to get its converted temperature close to what I was using to compare it with. Not a perfect science, but was close enough for me.</p><p>Even though I wanted the temperatures to be sent into the cloud, I still wanted to be able to walk up to the device and see the current temperatures. For this, I plugged in a 2-line LCD screen and wired in a potentiometer to adjust the contrast. The LCD plugs into a number of the Arduino’s digital input pins to be able to set the text on the display.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZiXEKmanHosisDc5BeeHg.jpeg" /></figure><p>Here is a wiring diagram of what we’ve put together so far. It’ll read two temps and output the values on the LCD display. The next step is to get those readings posting to the internet so we can read those values from anywhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AMQHq5GXsFzfj4IE2G4DDA.jpeg" /></figure><h4>Connecting to Internet</h4><p>There are a number of options for getting an Arduino talking to the internet. Even Arduino has a network enabled board called the <a href="https://www.arduino.cc/en/Main/ArduinoBoardYun">YUN</a> that has wifi/ethernet built into it. The YUN sounds awesome, but it’s also much more expense than the UNO. I wanted to keep this as low-cost as possible, so I searched for some other options. I read a bunch about the <a href="https://www.sparkfun.com/products/13678">ESP8266</a> chip as a potential option. The ESP8266 is a programmable microcontroller with a wifi antenna built in. It even has it’s own GPIO pins and can be programmed via the Arduino IDE. But what makes this chip special is that it comes with a Serial-&gt;Wifi command set. Meaning I can send it commands from the Arduino using a serial interface to tell it to do things on the internet. You can read more about the AT commands <a href="https://cdn.sparkfun.com/assets/learn_tutorials/4/0/3/4A-ESP8266__AT_Instruction_Set__EN_v0.30.pdf">here</a>. The downside to using an ESP8266 is that it requires a bit of a more complicated setup as it requires 3.3v, whereas the Arduino usually powers 5v. Rather than mess around with voltage regulators, I found an option from<a href="https://www.sparkfun.com/products/13287">SparkFun</a>, where they took an ESP8266 and placed it onto a stackable Arduino board with built in voltage regulation, all for 15 bucks. Perfect.</p><p>You can go on <a href="https://github.com/sparkfun/SparkFun_ESP8266_AT_Arduino_Library">Github</a> and download a library that handles the ESP8266 communication layer specific to the wifi shield, but I wanted to dig in a bit further on how this device actually worked. It turns out that you can use the Arduino as a serial passthrough device to the ESP8266 chip. This means that you can place the shield onto the Arduino, and run some code ( named a sketch ) that passes through input from the Arduino IDE serial monitor into the ESP8266, and it’ll output the results from the ESP8266 to the serial monitor. From here, I can send my own AT commands to the device. For this project, the only thing I wanted to do was default the chip to connect to my home wifi when it started up. So all I had to do was enter ‘AT+CWJAP_DEF=”MY_SSID”,”MY_PASSWORD”’ into monitor, and the chip connected to my wifi and stored it into it’s memory so the next time it started up, it’ll automatically connect. You can see the complete passthrough sketch code <a href="https://github.com/kazmiekr/GrillLog/blob/master/Arduino/ESP8266_Programmer/ESP8266_Programmer.ino">here</a>.</p><p>With the wifi shield connecting to my home network, the next step was to get the Arduino code sending the temperature data to the internet. It turns out that to send data to the internet with the ESP8266, it’s just a sequence of AT commands: 1. open the session, 2. tell it how much data you are sending, 3. pass it the data you want to send. To handle sending the data, I’m going to construct an HTTP POST of the data and POST that to a server. I won’t go through the code in detail, but that’s the basic sequence of events.</p><p>Let’s see what that circuit looks like now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vF1qm02MBO-ftGxn-CqBMQ.jpeg" /></figure><p>Even though the wifi shield is a stackable Arduino shield, I actually had trouble with it being set in the stacked position. If you push it too far in, it ends up shorting something that causes intermittent wifi drops. I actually had better luck just wiring up the shield with only the wires it needed to operate. In this case it’s just power, ground, and the two pins 8/9 for the software serial transmission.</p><p>You can view the final Arduino code <a href="https://github.com/kazmiekr/GrillLog/tree/master/Arduino/GrillLog/GrillLog.ino">here</a>.</p><h4>Connecting to Parse</h4><p>Our circuit is now setup to send our temperature data somewhere. I’ve chosen to use <a href="http://www.parse.com/">Parse.com</a> as it’s super simple to setup and free for our purposes. Parse provides cloud storage of the data with the ability to do push notifications and has API’s available to access the data from pretty much anywhere. Parse will store the data we’re sending, and we’ll configure it to send a push notification when our food is ready. In order to get our device talking to Parse, we’ll specifically use their REST API to POST the data to.</p><p>The problem with using Parse is that it requires you to send the data over HTTPS and the ESP8266 does not support HTTPS. Not a problem, we’ll just create a Proxy server between the Arduino and Parse that will accept our HTTP data and forward it to Parse using HTTPS. For a more permanent solution, you could find an online service to do this, but we’ll just build our own using <a href="https://nodejs.org/en/">NodeJS</a> and <a href="http://expressjs.com/">Express</a>.</p><p>Express is a web application framework that will allow us to create a simple endpoint that will receive our POST request from the device, prepare the data for Parse, and then send it to Parse via https. When the request comes in, we’ll first convert our POST data into a JSON object. Next we’ll create a set of HTTP options to tell Node how to handle our request. Most importantly, we’ll need to add in the Application ID and Rest API key for Parse, so it knows where to process our data. We’ll construct a request to ‘/1/classes/TempData’ which means it’ll save the data into the TempData collection. Once we have our options setup, we can now use the https module from Node to send the data to Parse securely.</p><p>You can view the full proxy server code <a href="https://github.com/kazmiekr/GrillLog/blob/master/Server/server.js">here</a>.</p><h4>Reading the Data from Parse</h4><p>Now that we have our data stored, let’s make a simple application to read that data. One of the benefits of using Parse is that they have information on connecting up a ton of different clients to it, whether you want to use JavaScript, Android, iOS, etc. For my example, I wanted to build an iOS app and tie in push notifications. It’s worth noting that in order to do push notifications with iOS you need to have a paid Apple developer account ($100) to generate an application and certificate that Parse requires for setup. We’ll talk more about notifications a bit further down.</p><p>I’ve done a bunch of iOS development, but for this example I’m going to keep it simple and just download the QuickStart iOS app from Parse. The quick start application will setup the Xcode environment to handle their libraries for connecting to their services. The most important thing to do is update the section that wants to use your Parse id’s. You’ll want to plug in your Application ID and Client Key in your AppDelegate file <a href="https://github.com/kazmiekr/GrillLog/blob/master/iOS/GrillLog/AppDelegate.swift#L37">here</a>.</p><p>My application will show the two temperatures in the UI, with a date that shows the last updated time. I won’t go into all the detail of iOS development, but I’ve added my UI components to my storyboard, set up the appropriate outlets, and I’m ready to connect to Parse and update those outlets.</p><p>In iOS, when the app loads, it’ll call `viewDidLoad`. There we’ll setup a timer to run every 10 seconds that will query Parse and find the most recent entry recorded and update our UI with that information.</p><p>You can view the complete iOS code <a href="https://github.com/kazmiekr/GrillLog/tree/master/iOS">here</a>.</p><p>We now have everything connected where we can see the last record temperature from the Arduino on an iPhone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dTK6A6hsZr07D57psvQFMQ.jpeg" /></figure><h4>Push Notifications</h4><p>To finish this off, I wanted to be able to get a push notification when my food hit a certain temperature. Parse makes it pretty simple for you to enable push notifications for your application. You can just follow their <a href="https://parse.com/tutorials/ios-push-notifications">tutorial</a> to get things set up, but the general gist is that you have to use iTunes Connect to set up your application there and generate a certificate that will let Parse utilize the Apple push notification system.</p><p>Once you’ve set up Parse to do push notifications, you need to make sure in your iOS application that you add some code to enable receiving those notifications (registerForRemoteNotifications), and that when you run the app, you accept the dialog that asks if you’d like to receive notifications for this application. Once your device registers for notifications, Parse will know where to send the notification information.</p><h4>Temperature Trigger</h4><p>There are a few places in code that we could determine when a temperature hits a certain threshold, but the easiest place to put this logic is in a `beforeSave` trigger using the Parse cloud code. A trigger is a piece of code that runs at a specific points, in this case it’ll run before a record is saved.</p><p>We’ll define a threshold temperature in this trigger that we’ll use to check to see if our new temperature has crossed. It’ll be hard coded in the trigger for now, but you could easily move this into a value that gets configured elsewhere. Since we don’t want a notification every time the temperature is above the threshold, we’ll only send a message the first time it crosses that threshold. To do that we’ll query the last record saved, look at it’s temperature and check if that number is less than the threshold, and the new temperature we’re about to save is above that threshold. Once that happens, we’ll use the Cloud Push library to send a message to the global push channel.</p><p>If we’ve set everything up correctly, we should now be able to see temperatures being logged from the Arduino to Parse in the native iOS application. Once the food probe hits 165, it should send a push notification to the phone letting us know that it’s ready to eat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*wncc6OBZXsh9imamNECzrA.jpeg" /></figure><p>You can see the code for this <a href="https://github.com/kazmiekr/GrillLog/blob/master/Server/cloud/GrillLog/cloud/main.js">here</a>.</p><h4>Conclusion</h4><p>The beauty of making something like this is that you can swap out different components and change things for improvement. This is by no means the best way to do everything. It’s just a digest of what I did to build it. With the basics in place, you could eventually build this system to be more robust by doing things like: adding additional notifications for temperature changes alerts, adding charts of temperatures over time, or being able to look at previous times you’ve cooked.</p><p>Getting the Arduino hooked into the internet was a little tricky, but devices in this space are rapidly evolving and are becoming easier and easier to use. With new low cost powerful boards with built in wifi, like the Sparkfun Photon, this process could become even easier. Pair that with some of the new IoT services coming out with AWS, and you could try a different approach at handling the data/networking aspect.</p><p>Some may say that all this takes some of the fun out of barbecuing, but for me it was the perfect marriage of two hobbies I really enjoy, technology and barbecue. With the technology put in place, I took on more and more challenging recipes over the summer. The best thing I ended up making was hickory smoked pork spare ribs that I cooked following the <a href="http://bbq.about.com/od/ribs/a/aa122306a.htm">3–2–1 method</a>. I coated the ribs with my favorite dry rub and smoked them with hickory chunks for three hours, then wrapped them in foil with some apple juice for two hours, and then finished them on some higher heat with some sauce. With colder weather coming, I’ll likely not be using the grill as much, but when I do, at least I can check the temperature from inside the house.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b047ecda94a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>