<?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 Michael Marner on Medium]]></title>
        <description><![CDATA[Stories by Michael Marner on Medium]]></description>
        <link>https://medium.com/@MichaelMarner?source=rss-43a8de187db1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*dWFFmE7IOFgAIjOp.</url>
            <title>Stories by Michael Marner on Medium</title>
            <link>https://medium.com/@MichaelMarner?source=rss-43a8de187db1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:45:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@MichaelMarner/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[On Image Picker: A Flutter Debugging Story]]></title>
            <link>https://medium.com/careapp-engineering/on-image-picker-a-flutter-debugging-story-47ca092c513f?source=rss-43a8de187db1------2</link>
            <guid isPermaLink="false">https://medium.com/p/47ca092c513f</guid>
            <category><![CDATA[plugins]]></category>
            <category><![CDATA[bug-fixes]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Michael Marner]]></dc:creator>
            <pubDate>Fri, 19 Feb 2021 06:30:00 GMT</pubDate>
            <atom:updated>2021-02-19T11:17:59.439Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I3vaJuIYUOU9ywb7kUbYUQ.jpeg" /></figure><p>A journey into the Flutter source code… Again</p><p>CareApp uses Flutter to build our mobile app. I’m a fairly vocal supporter of Flutter; it has allowed us to develop a high-quality cross platform app super fast, with just 2 developers. That said, moving fast can mean sometimes things break. This post outlines a problem that unfortunately made its way to production. While the story is specific to us, hopefully the approach is useful to others trying to debug their Flutter apps.</p><h3>Part 1: The Report</h3><p>It’s Friday and everything is looking good. Then Jess, our customer support Legend posts this into Slack:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sSr-V4plzkCWycWj.png" /></figure><p>We had reports that the media attached to some messages shared through CareApp were not appearing for users. As one of CareApp’s primary uses is for sharing media with family, this was an issue.</p><h3>Part 2: Understanding The Symptoms</h3><p>Support requests from users usually are not good enough to jump to a quick fix. User’s don’t always know exactly what the problem is, and certainly don’t understand the technical issues that could lead to a problem. So the first step when investigating any report like this is to understand it as best as we can.</p><p><strong>The Report: Cannot see media attached to some messages</strong></p><p>To go further we needed to inspect the media. To begin, I tried to view the content and, sure enough, I see a placeholder graphic where an image should be. CareApp pre-processes images on the device (resize) before uploading, so this is strange.</p><p>Errors like this are often caused by network connectivity issues, but the file was being served just fine. How were these images corrupt?</p><p>Next step was to download and inspect one of the files. There were 2 things that immediately jumped out:</p><ol><li>No image editor or viewer could open the file</li><li>The file was unusually large</li></ol><p>As a last resort I tried opening the file in VLC and, BOOM! It wasn’t an image at all, but a video!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OPP2hAJddvn52bzf.png" /></figure><p>So we have a video file parading as an image file. This is much more useful, and leads the investigation further.</p><p>We store the filename and mimetype for all files uploaded to CareApp in our database. A look in our database verified that the filename of the file was a .jpg, and the mime type we recorded was image/jpg.</p><p>So we now had 2 possibilities:</p><ul><li>The user intended to select a photo, and was somehow able to select a video, or</li><li>The user intended to select a video, but the video was incorrectly uploaded as an image file</li></ul><p>Jess got on the phone to our customer and verified that they had tried to share a video, but it didn’t work. Now we knew where to go to fix this.</p><h3>Part 3: Jumping into source code</h3><p>At this point the following facts are relevant:</p><ul><li>We use the <a href="https://pub.dev/packages/image_picker">image_picker</a> Flutter plugin for accessing the device gallery</li><li>The user selected a video from the gallery to share in CareApp</li><li>While they selected a video file, we stored the file as an image</li><li>As our API didn’t think the file was a video, our video transcoding pipeline didn’t run</li></ul><p>It’s fairly obvious that the issue was somewhere inside image_picker. Running CareApp in a debugger confirmed that even when the user selected a video, the file had a .jpg extension. We could only replicate the issue on <em>some</em> Android devices, which indicated the problem was most likely in the Android implementation of image_picker.</p><h3>Part 4: Flutter Issues</h3><p>As a general principle, as soon as you are fairly confident the problem isn’t in <em>your</em> code, you should look to see if there’s a Flutter issue that matches your symptoms. At the time of writing, there were 8,289 of them. A quick search uncovered this issue from <strong>March 2020</strong>:</p><p><a href="https://github.com/flutter/flutter/issues/52419">image_picker returns .jpg extension when picking Video or GIF</a></p><p>There’s <a href="https://github.com/flutter/plugins/pull/2860">pull request</a> to fix this issue, opened in July 2020 and still open. We are already running our own <a href="https://github.com/flutter/flutter/issues/74014">image picker fork</a>, so we applied the PR to our fork and, sure enough, the bug went away.</p><p>We also added some conservative fallback code to ensure that, no matter what, a video wouldn’t be saved as an image:</p><pre>final video = await ImagePicker().getVideo(source: source);<br>    String mime = lookupMimeType(video.path);<br>    String name = basename(video.path);<br><br>    // getVideo should always return a video file, so force a mime type if we get back `.jpg`<br>    if (!mime.startsWith(&#39;video&#39;)) {<br>      mime = &#39;video/mp4&#39;;<br>      name = setExtension(video.path, &#39;mp4&#39;);<br>    }</pre><p>CareApp 2.16.1 released to the Play Store a short time later and the issue was resolved. We manually updated the metadata and triggered our video encoding pipeline for affected media, and the problem went away for our users. Importantly, they didn’t have to do anything — from their point of view the messages just started working.</p><p>So I guess to summarise:</p><ul><li>Learn as much as you can about the issue through data in the app. User reports aren’t good enough</li><li>Figure out how to replicate the issue</li><li>Look for existing bugs and pull requests before diving into the code yourself</li><li>Dive into the code if you need to</li></ul><h3>Part 5: Flutter _Issues_</h3><p>I understand that the Flutter team is fairly small and they’re trying to do a whole lot. Since I’ve been working with it, the mission has crept from wanting to build the best damn cross platform toolkit for mobile devices, to trying to build a universal toolkit for all platforms. This has a cost — and that is the less-sexy maintenance of existing plugins.</p><p>But for Flutter to truly be accepted the first party plugins need to be rock solid. They’re <a href="https://flutter.dev/jobs">starting </a>to solve this issue, which is great to see. Let’s hope the first party plugins see some significant improvements in the coming months. (Hey Google — maybe look beyond Mountain View for developers?)</p><p>The bug in question is labeled an <em>annoyance</em> — I reckon it’s a showstopper that makes the plugin unusable without workarounds. The PR has been open for 8 months, and is only un-merged because the (non-Google) author hasn’t had time to write unit tests. Meanwhile, the first party plugin is broken for everyone, without even a warning in the documentation.</p><p>Thankfully we identified and worked around the problem quickly. But if you’re evaluating Flutter, factor in plugin bugs into your cost-benefit. Use as few plugins as you can get away with, and pin the versions so you don’t accidentally ship a new problem.</p><p>Flutter still wins the cost-benefit analysis, but it ain’t all roses.</p><p><em>Originally published at </em><a href="https://engineering.careapp.com.au/post/52419-a-flutter-debugging-story/"><em>https://engineering.careapp.com.au</em></a><em> on February 19, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47ca092c513f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/careapp-engineering/on-image-picker-a-flutter-debugging-story-47ca092c513f">On Image Picker: A Flutter Debugging Story</a> was originally published in <a href="https://medium.com/careapp-engineering">CareApp Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving Flutter’s iOS build times on CI]]></title>
            <link>https://medium.com/careapp-engineering/improving-flutters-ios-build-times-on-ci-551dfec198ee?source=rss-43a8de187db1------2</link>
            <guid isPermaLink="false">https://medium.com/p/551dfec198ee</guid>
            <category><![CDATA[circleci]]></category>
            <category><![CDATA[ci]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Michael Marner]]></dc:creator>
            <pubDate>Fri, 13 Nov 2020 06:47:55 GMT</pubDate>
            <atom:updated>2020-11-15T23:52:28.988Z</atom:updated>
            <content:encoded><![CDATA[<p>We shave 12 minutes off our build &amp; deploy pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*UsykWgvpJ-icy5G7UQTs5Q.jpeg" /></figure><p>CareApp uses CI to test every commit of our mobile app, and build and deploy every merge to master, for iOS and Android. A few weeks ago I felt very <em>seen</em> by this tweet:</p><h3></h3><p>A build/deploy time of 2m50s (including infrastructure) makes me antsy as hell. I have no idea how people deal with builds that take double digit minutes and longer</p><p>This motivated me to do some digging and find out what we could do to improve our pipeline. What follows is a series of optimisations we made to speed up CI. We use <a href="https://circleci.com/">CircleCI</a>, but what follows should apply to any CI service.</p><h3>The starting point</h3><p>A merge to master triggers CI to run tests, build our Android and iOS apps, and deploy to TestFlight and Play Store internal testing. We use Fastlane to manage code signing and deployment.</p><p>The full pipeline was taking around 30 minutes, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hZmMk7azrNtOX2aj.png" /></figure><p>The graph shows the following critical path:</p><ul><li>Test (6:33)</li><li>Build iOS (15:08)</li><li>Deploy iOS (8:16)</li></ul><p>The android builds are fairly fast and, as we run iOS and Android builds in parallel, don’t contribute to the overall pipeline duration.</p><h3>Improvement 1: Stop building iOS twice!</h3><p>If you follow Flutter’s <a href="https://flutter.dev/docs/deployment/cd">documentation</a> for building iOS on CI, you will end up building the iOS app twice:</p><blockquote><em>On iOS an extra build is required since flutter build builds an .app rather than archiving .ipas for release</em></blockquote><p>So your CI script may look something like this:</p><pre># install deps<br>flutter pub get<br><br># build a non-signed .app<br>flutter build ios --release --no-codesign --build-number $BUILD_NUMBER<br><br># sign and deploy with fastlane<br>cd ios<br>chruby 2.7<br>gem install bundler:2.1.4<br>bundle install --path vendor/bundle<br><br># install certificates and profiles into CI&#39;s keychain<br>bundle exec fastlane ios match<br><br># build a signed app<br>bundle exec fastlane ios build</pre><p>The issue is that the iOS app will be build twice! Once during flutter build, and again by Fastlane to get a signed IPA.</p><p>Flutter recently introduced a new argument to build ios: --config-only. When run with this parameter, flutter build <em>configures</em> the XCode project, but does not actually build the .app. Putting that argument in place is trivial:</p><pre>flutter build ios --release --no-codesign --config-only --build-number $BUILD_NUMBER</pre><p>The rest of the script above stays the same.</p><p>Now, fastlane ios build is the only time the iOS app is actually compiled, greatly improving build times.</p><h3>Improvement 2: Caching rubygems for Fastlane</h3><p>CircleCI, like most CI services, allow you to <a href="https://circleci.com/docs/2.0/caching/">cache dependencies</a> between jobs. Usually this is project dependencies, but you should also consider caching your deployment tools.</p><p>In our case, Fastlane is required for both the build_ios and deploy_ios steps. If we could cache Fastlane and its dependencies, we should see an improvement to both build steps.</p><p>CircleCI allows you to create several caches, and so we add one for RubyGems:</p><pre>- restore_cache:<br>    keys:<br>      - gem-cache-v2-{{ arch }}-{{ .Branch }}-{{ checksum &quot;./ios/Gemfile.lock&quot; }}<br>      - gem-cache-v2-{{ arch }}-{{ .Branch }}<br>      - gem-cache-v1<br>- build_or_deploy<br>- save_cache:<br>    key: gem-cache-v2-{{ arch }}-{{ .Branch }}-{{ checksum &quot;./ios/Gemfile.lock&quot; }}<br>    paths:<br>      - ./ios/vendor/bundle</pre><p>As we’ll see, caching RubyGems makes a massive improvement to subsequent build times.</p><h3>Improvement 3: Persisting generated files between steps</h3><p>We use <a href="https://pub.dev/packages/json_serializable">json_serializable</a> to automatically generate toJson and fromJson methods on some of our data classes and Redux state. The one downside is we find running build_runner is slow (about 2:00 for us). This is compounded by the fact that the generated files are needed in every CI step.</p><p>The generated files are <em>dart</em> files, so they should be the same whether generated on Linux or macOS. Therefore, we can generate these once and safely reuse them in later CI steps.</p><p>On CircleCI we use Workspaces like so:</p><pre>- persist_to_workspace:<br>    root: .<br>    paths:<br>      - ./lib/store/*/*.g.dart<br>      - ./lib/store/*.g.dart</pre><p>CircleCI has a limitation that it can’t recursively glob files to persist. Therefore, we need to specify all the paths where generated files can be found. Thankfully for us, all our generated files are in a single place in our code.</p><p>In subsequent build steps we can restore the workspace. This puts the generated files into place, and our Flutter code will compile.</p><pre>- attach_workspace:<br>    at: .</pre><h3>12 Minutes Faster</h3><p>With those three changes in place, we’ve taken around 12 minutes off our full build pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1EXk2luSBwaowC2u.png" /></figure><p>As you can see, we get a massive speed increase in build and deploy steps for iOS. Caching the generated dart files also improves building for Android. While this wasn’t on the critical path and so doesn’t affect the overall time, it does mean that building for Android uses fewer CI credits, which is also good.</p><h3>Things we haven’t tried</h3><p>There is probably more we can do to improve this further, here are some things we haven’t tried.</p><ul><li><strong>Caching flutter packages</strong>. We still run flutter pub get in each step that needs it. It may be possible to cache the installed flutter packages, but we have not explored that yet.</li><li><strong>Using larger executors</strong>. The times above use medium class MacOS executors for building iOS, and medium class Docker executors for the test and Android steps. An easy win is to bump those up to large. Without further investigation though, it is unclear how much of a speed boost this would give, since there is still a lot of time waiting on network resources, rather than CPU. Also our non-master CI steps are simpler. Developers get test feedback in around 4 minutes, which is ok.</li></ul><p>Thanks for reading! Please share any neat tricks have you found for making Flutter builds faster.</p><p><em>Originally published at </em><a href="https://engineering.careapp.com.au/post/improving-flutter-ios-build-times/"><em>https://engineering.careapp.com.au</em></a><em> on November 13, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=551dfec198ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/careapp-engineering/improving-flutters-ios-build-times-on-ci-551dfec198ee">Improving Flutter’s iOS build times on CI</a> was originally published in <a href="https://medium.com/careapp-engineering">CareApp Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zxcvbn for Dart/Flutter]]></title>
            <link>https://medium.com/careapp-engineering/zxcvbn-for-dart-flutter-b9c4533afe49?source=rss-43a8de187db1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9c4533afe49</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[zxcvbn]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[passwords]]></category>
            <dc:creator><![CDATA[Michael Marner]]></dc:creator>
            <pubDate>Thu, 15 Oct 2020 11:47:55 GMT</pubDate>
            <atom:updated>2021-02-19T09:42:29.396Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBu8-p_0sI6y-PovTxTX-A.jpeg" /></figure><p><strong>Introducing our Dart port of DropBox’s Zxcvbn Password Strength Library. Available now on </strong><a href="https://pub.dev/packages/zxcvbn"><strong>pub.dev</strong></a><strong>!</strong></p><p>We want to help our users keep their account secure. One part of that is ensuring our users have good passwords that cannot easily be cracked. We wanted to give the users a simple rating of their password as they entered it, to encourage choosing a stronger password.</p><p>This isn’t a new problem — it’s one most web services grapple with. Thankfully, DropBox had already developed the very nice <a href="https://github.com/dropbox/zxcvbn">Zxcvbn</a> library. We put this to use in CareApp web quite easily. However, there was a problem: Zxcvbn did not exist for Dart, so we ported it ourselves.</p><p>Get it now from <a href="https://pub.dev/packages/zxcvbn">pub.dev</a> or <a href="https://github.com/careapp-inc/zxcvbn-dart">GitHub</a>. Pull requests welcome!</p><h3>Usage</h3><p>Zxcvbn accepts a password, with an optional dictionary of user-related words to include in dictionary attacks (eg their name, email). It returns a score between 0–4, as well as suggestions for making the password stronger.</p><p>Here’s an example:</p><pre>import &#39;package:zxcvbn/zxcvbn.dart&#39;;<br><br>void main() {<br>  final zxcvbn = Zxcvbn();<br><br>  final result = zxcvbn.evaluate(&#39;P@ssw0rd&#39;);<br><br>  print(&#39;Password: ${result.password}&#39;);<br>  print(&#39;Score: ${result.score}&#39;);<br>  print(result.feedback.warning);<br>  for (final suggestion in result.feedback.suggestions) {<br>    print(suggestion);<br>  }<br>}</pre><h3>Deciding to Port</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d1Ue9BnW7W0SPOxf.png" /><figcaption>CareApp gives visual feedback on password strength as the user types</figcaption></figure><p>Before we started this process, we did look for existing solutions. There is already an existing Dart implementation, <a href="https://pub.dev/packages/xcvbnm">Xcvbnm</a>. However, we found that Xcvbnm returned vastly different results compared to Zxcvbn official. Xcvbnm’s readme also makes it clear the library is incomplete:</p><blockquote><em>Please note, that library did not port all functionality but is already used in production.</em></blockquote><p>To press forward, we decided to port Zxcvbn to Dart from the original CoffeeScript. Our goals:</p><ul><li>Give exactly the same results for the same inputs as the CoffeeScript</li><li>Port all tests from CoffeeScript</li><li>Be as close to the original CoffeeScript as possible in order to aid implementing and debugging dart, as well as making it easier to bring upstream changes</li><li>Hide the coffee-like implementation from users of this library, so from the outside it feels like Dart</li></ul><p>As this is a close port of CoffeeScript, rather than a clean room implementation, the Dart code inside src is somewhat ugly and non-standard Dart in a lot of ways. However, keeping it close to CoffeeScript is seen as more important.</p><h3>The Process</h3><p>Once we had decided to keep the Dart port as close to the original CoffeeScript as possible, porting was slow, but fairly straight forward. Thankfully Zxcvbn has good automated tests. The work essentially involved translating a module from CoffeeScript to Dart, then translating the corresponding test file, and fixing things until all tests passed.</p><h3>Pitfalls</h3><p>I’m happy to go on the record and say that, when it comes to programming, I prefer languages that are statically typed, and are members of the curly-brace family. CoffeeScript is none of those things, and has some syntax that probably felt good in 2012 but my old 2020 brain just can’t handle.</p><h4>Numerical Limits</h4><p>One of the biggest causes of bugs during the port was numerical limits. Zxcvbn was written to run in a browser, and so all numbers are a Javascript number type - a float. However, Dart, when not running in a browser, has all kinds of different numerical types. Converting from Coffee to Dart required finding the right one. Zxcvbn generates <em>very</em> large numbers that overflow int. We use double to handle large numbers, as we don&#39;t need the precision of a BigInt.</p><p>And unfortunately you can’t just use dynamic everywhere. Dart will treat a number that looks like an int (eg 42) as an integer type - and not a float. So a number that starts off small, will eventually get very large and overflow the integer, even though you set it to dynamic.</p><h4>Trying to keep type safety</h4><p>The other big effort during the port was trying to retrofit type safety onto the code as it was being ported. This involved trial and error — running tests, seeing casting errors, change a variable type, try again. Eventually we got there.</p><p>Like the numerical limit issue, you can’t just throw dynamic in and call it a day. This is demonstrated below:</p><pre>dynamic x = 42;<br>dynamic y = 123.4;<br><br>dynamic z = x * y; // runtime error</pre><p>This example is trivial, but when it’s happening <em>somewhere</em> in <a href="https://github.com/careapp-inc/zxcvbn-dart/blob/master/lib/src/matching.dart">a thousand lines of very maths heavy code</a>, errors can be hard to spot.</p><h4>Discovering Properties</h4><p>While a Javascript object can have properties tacked on throughout its lifetime, this is not possible in Dart. The closest equivalent is using a Map&lt;String, dynamic&gt;, which has its own set of issues.</p><p>This was an issue, because Zxcvbn has several different strength estimation algorithms, all of which add new properties to the PasswordMatch object.</p><p>To work around this issue, we ended up adding all the properties to PasswordMatch, and also overriding operator[] to allow accessing by name. This feels a bit gross, but was the quickest way to getting the port complete. Here&#39;s an excerpt of PasswordMatch.</p><pre>class PasswordMatch {<br>  String pattern;<br>  int i;<br>  int j;<br>  String token;<br>  String matched_word;<br><br>  dynamic operator [](String arg) {<br>    switch (arg) {<br>      case &#39;pattern&#39;:<br>        return pattern;<br>      case &#39;i&#39;:<br>        return i;<br>      case &#39;j&#39;:<br>        return j;<br>      case &#39;token&#39;:<br>        return token;<br>      case &#39;matched_word&#39;:<br>        return matched_word;<br>    }<br>  }<br>}</pre><h3>The Future</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXzWAznWmBC7uK47m5C_Wg.png" /><figcaption>You chose… Poorly</figcaption></figure><p>Zxcvbn for Dart works and is in use in CareApp Mobile. In our testing, we get exactly the same output when compared to the official Zxcvbn code. However, the code is not very <em>Dart-like</em>. Future work really is to tidy up the API and make the ergonomics better. Again, PRs are welcome!</p><p><em>Originally published at </em><a href="https://engineering.careapp.com.au/post/zxcvbn-dart/"><em>https://engineering.careapp.com.au</em></a><em> on October 15, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9c4533afe49" width="1" height="1" alt=""><hr><p><a href="https://medium.com/careapp-engineering/zxcvbn-for-dart-flutter-b9c4533afe49">Zxcvbn for Dart/Flutter</a> was originally published in <a href="https://medium.com/careapp-engineering">CareApp Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remote Redux Debugging in Flutter]]></title>
            <link>https://medium.com/nextfaze/remote-redux-debugging-in-flutter-bf07343c0101?source=rss-43a8de187db1------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf07343c0101</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[remote-devtools]]></category>
            <dc:creator><![CDATA[Michael Marner]]></dc:creator>
            <pubDate>Tue, 09 Oct 2018 12:46:07 GMT</pubDate>
            <atom:updated>2018-10-09T13:13:27.319Z</atom:updated>
            <content:encoded><![CDATA[<p>Connect your Flutter app’s Redux Store to the Redux Devtools from the web!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bz-J49-_eBJWTVg2.jpg" /></figure><p>I really like Flutter, and I like using Redux when building mobile apps. There’s a great Redux implementation for Dart and Flutter, and a time travel capable debug store.</p><p>The Javascript world is spoilt with the fantastic <a href="http://extension.remotedev.io/">Redux DevTools plugin</a>. It allows you to inspect actions and application state in a web browser, time travel, and playback changes to your app’s state. There is an on screen time travel widget for <a href="https://pub.dartlang.org/packages/flutter_redux_dev_tools">Flutter</a>, but that means sacrificing screen space for the UI.</p><p>So why not combine the Redux DevTools from the Javascript world with Redux.dart? Now you can, with the <a href="https://github.com/MichaelMarner/dart-redux-remote-devtools">redux_remote_devtools</a> package!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B15zJjrIZyOpgnzZ.gif" /><figcaption>Debug your Redux Store with Flutter and Remote DevTools</figcaption></figure><p>This article gives a quick overview of how to get setup. The Git repository contains examples to help get you started.</p><h4>Getting Started</h4><p>Add the library to your app’s pubspec.yaml:</p><pre>dependencies:<br>  redux-remote-devtools: ^0.0.4</pre><p>And add the middleware to your app, and provide it a reference to your store so time travel actions from the remote can be dispatched:</p><pre>var remoteDevtools = RemoteDevToolsMiddleware(&#39;YOUR_HOST_IP:8000&#39;);<br>await remoteDevtools.connect();<br>final store = new DevToolsStore&lt;AppState&gt;(searchReducer,<br>  middleware: [<br>    remoteDevtools,<br>  ]);<br>remoteDevtools.store = store;</pre><p>Startup the remotedev server, and then run your Flutter app:</p><pre>npm install -g remotedev-server<br>remotedev --port 8000</pre><p>You can then browse to http://localhost:8000 and start using Remote DevTools to debug your Flutter app!</p><h4>Encoding Actions and State</h4><p>In the Javascript world, Redux follows a convention that your redux state is a plain Javascript Object, and actions are also Javascript objects that have a type property. The JS Redux Devtools expect this. However, Redux.dart tries to take advantage of the strong typing available in Dart. To make Redux.dart work with the JS devtools, we need to convert actions and state instances to JSON before sending.</p><p>Remember that the primary reason for using devtools is to allow the developer to reason about what the app is doing. Therefore, exact conversion is not strictly necessary — it’s more important for what appears in devtools to be meaningful to the developer.</p><p>To make your actions and state JSON encodable, you have two options. Either add a toJson method to all your classes, or using a package like <a href="https://pub.dartlang.org/packages/json_serializable">json_serializable</a> to generate the serialisation code at build time. The GitHub search example demonstrates both approaches.</p><p>If your store is simple then you may be using enums for actions. These encode just fine without any extra effort.</p><h4>Time Travel</h4><p>If you have configured your app to use the DevToolsStore from redux_devtools, then you can time travel through your app state using the UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7bRQuttqgcvfmor5.gif" /><figcaption>Time Travel through your app</figcaption></figure><p>Remember that there are limitations to time travel, especially if you are using epics or other asynchronous processing with your Redux store.</p><p>Being a new library there are still things to work out. PRs are welcome if you’re up for helping out.</p><p>Now go build something cool with Flutter!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf07343c0101" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nextfaze/remote-redux-debugging-in-flutter-bf07343c0101">Remote Redux Debugging in Flutter</a> was originally published in <a href="https://medium.com/nextfaze">NextFaze</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Production Error Handling in Ionic]]></title>
            <link>https://medium.com/nextfaze/production-error-handling-in-ionic-eb2cc7308867?source=rss-43a8de187db1------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb2cc7308867</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[ionic]]></category>
            <dc:creator><![CDATA[Michael Marner]]></dc:creator>
            <pubDate>Mon, 26 Feb 2018 10:39:24 GMT</pubDate>
            <atom:updated>2018-02-26T10:39:24.006Z</atom:updated>
            <content:encoded><![CDATA[<p>How to deal with errors in production and keep your users on side</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z4y1lGGmZ5kKxQJuA-6kiQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/eUFZOFHJrdY?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kris Mikael Krister</a> on <a href="https://unsplash.com/search/photos/nudibranch?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Nobody likes apps that crash or stop working properly. Handling and recovering from errors is obviously an important task for any developer; we should not assume that everything will run smoothly.</p><p>In this post we’re talking about what to do <em>on top</em> of your regular error handling — the last resort.</p><h4>Ionic and Unhandled Errors</h4><p>Ionic’s production error handling is, well, lacking. An unhandled exception or promise rejection in your JS code leaves your application in an undefined state. It may still look ok, but your users will experience very strange behaviour and errors that simply don’t make sense.</p><h3>Implement an ErrorHandler</h3><p>The best way to implement last-resort error handling in Ionic and Angular is to implement your own <a href="https://angular.io/api/core/ErrorHandler">ErrorHandler</a> class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fed48157bfd19ced4f68e3867a84b8f6/href">https://medium.com/media/fed48157bfd19ced4f68e3867a84b8f6/href</a></iframe><p>Angular will automatically call handleError whenever an exception is thrown.</p><p>Hooking up the custom error handler to Angular simply requires providing it at boot time. You probably want to keep Ionic’s default error handler in development, and switch the error handler in for production.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc16a7de6882046814b7fc92c6bb9e91/href">https://medium.com/media/cc16a7de6882046814b7fc92c6bb9e91/href</a></iframe><h4>What should we do?</h4><p>The exact requirements will depend on your application, but a good starting point is to pop up an alert to the user, apologising, and asking them to reload the app. We also pop up the Ionic splash screen while the app is reloading.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71a78f0bbcd376f90f2755a5141a716d/href">https://medium.com/media/71a78f0bbcd376f90f2755a5141a716d/href</a></iframe><p>Reloading the app is drastic, but remember this is a last resort, <em>on top</em> of our regular error handling.</p><h3>Log to a 3rd party service</h3><p>Handling the error is only the first step in the process. What we really want is to fix the error. There’s no need to wait for your user to complain — we can log the error to a 3rd party service. You’ll get a much nicer error report, with a stack trace and logs, making finding and fixing the error much easier.</p><p>For this example we’re going to log to <a href="http://rollbar.com/">Rollbar</a>*, but there are lots of other services available. You could even write your own.</p><h4>Angular Rollbar</h4><p>For this example we’ll use <a href="https://github.com/NextFaze/angular-rollbar">angular-rollba</a>r to simplify the process. First up we’ll add the module to our project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/995c90beb5b92f9f9be1080a9a6b1c80/href">https://medium.com/media/995c90beb5b92f9f9be1080a9a6b1c80/href</a></iframe><p>Next up we’ll set up the RollbarService to be injected into our ErrorHandler and and log the error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c867ee7ac1f7506c82128e7374108de/href">https://medium.com/media/4c867ee7ac1f7506c82128e7374108de/href</a></iframe><p>Now our error will be logged for future debugging, and we’ve presented an error to the user. They probably still aren’t happy about the error, but at least you’re honest with them.</p><h3>Conclusion</h3><p>We can now catch unhandled errors in production, log them to a 3rd party service, and notify the user that something’s gone wrong. The app will restart and will never be left in an undefined state. This is a last resort, and should compliment proper, fine grained error handling, but is an absolute must for production apps.</p><p>*I have no vested interest or relationship with Rollbar, but we do use their service from time to time.</p><p><em>Originally published at </em><a href="https://nextfaze.com/blog/production-error-handling-in-ionic/"><em>www.nextfaze.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb2cc7308867" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nextfaze/production-error-handling-in-ionic-eb2cc7308867">Production Error Handling in Ionic</a> was originally published in <a href="https://medium.com/nextfaze">NextFaze</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mandatory Update for your apps]]></title>
            <link>https://medium.com/nextfaze/mandatory-update-for-your-apps-b99b0d4c36d6?source=rss-43a8de187db1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b99b0d4c36d6</guid>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[ionic]]></category>
            <dc:creator><![CDATA[Michael Marner]]></dc:creator>
            <pubDate>Fri, 24 Nov 2017 06:13:55 GMT</pubDate>
            <atom:updated>2017-11-24T06:13:55.489Z</atom:updated>
            <content:encoded><![CDATA[<p>Sometimes you really just need your users to update their app!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q9PLY9QAb-h10v5P_JfI3A.jpeg" /><figcaption>Unrelated sting ray photo by <a href="https://unsplash.com/photos/79YoQ2edaZc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jakob Owens</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Publishing app updates can be a chaotic experience. You hit that publish button and it’s out of your hands. You’re at the mercy of your users, relying on them to stay up to date and get that latest version onto their devices.</p><p>And sometimes those updates are important. A critical bugfix or a new feature essential to the business. Sometimes things can’t wait.</p><p>Mandatory Update (ManUp) is a technique we recommend in all our apps, and have open source libraries for <a href="https://github.com/NextFaze/ionic-manup">Ionic</a>, <a href="https://github.com/NextFaze/ManUp">iOS</a>, and <a href="https://github.com/NextFaze/unity-manup">Unity3D</a> for you to use in yours. It’s simple, but can make a huge difference to the user experience of your app. (Our Android implementation is not generalised enough to provide as a standalone library at this time.)</p><p>On startup, your app checks a small file containing release metadata, including the latest release version, the minimum required version, and a maintenance mode switch. The app compares itself to the metadata, and presents alerts as appropriate.</p><p>The user has the latest version? No problem, just load the app like normal!</p><p>If the installed version is less than the minimum, the app presents an alert telling the user an update is required, with a link to the relevant app store. The alert cannot be dismissed, effectively making the app unusable until an update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*7hH9RrSbTGOYrVDLnt4Y1w.png" /></figure><p>If there’s a newer version, but the app still satisfies the minimum, an alert can be shown suggesting the user upgrades. However they can still use the app as normal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Nbtyp0rKqOcahFMySBrwxg.png" /></figure><p>Finally, we also include a maintenance mode switch. This is most useful if your backend API has issues and you just need time to fix things. In this case the app presents an alert telling the user to check back later. This is of course a last resort, but it’s a life saver in a dire situation.</p><h4>Tricks to remember</h4><ul><li>Be forgiving! If the metadata could not be downloaded (no network, server down) let the app run</li><li>App updates take time to propagate through the store. Don’t frustrate your users by telling them to update when the store says they have the latest version</li><li>Show optional update alerts sparingly. Nobody likes a nag!</li><li>Don’t store your metadata in your backend API, because ManUp needs to survive API failures. A separate static file hosted on S3 or similar is a safer option.</li></ul><p>We recommend ManUp in all the apps we build. It does not excuse more fine grained error handling but is hard to beat when the situation requires it. We have developed open source libraries for some of the platforms we build for. Links below, and pull requests are welcome.</p><ul><li><a href="https://github.com/NextFaze/ionic-manup">Ionic</a></li><li><a href="https://github.com/NextFaze/ManUp">iOS</a></li><li><a href="https://github.com/NextFaze/unity-manup">Unity3D</a></li></ul><p>ManUp, and take back control over your app updates!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b99b0d4c36d6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nextfaze/mandatory-update-for-your-apps-b99b0d4c36d6">Mandatory Update for your apps</a> was originally published in <a href="https://medium.com/nextfaze">NextFaze</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary responses with Serverless Framework and API Gateway]]></title>
            <link>https://medium.com/nextfaze/binary-responses-with-serverless-framework-and-api-gateway-5fde91376b76?source=rss-43a8de187db1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fde91376b76</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[binary]]></category>
            <dc:creator><![CDATA[Michael Marner]]></dc:creator>
            <pubDate>Fri, 03 Nov 2017 02:06:22 GMT</pubDate>
            <atom:updated>2017-11-03T03:06:26.297Z</atom:updated>
            <content:encoded><![CDATA[<p>Today we’re looking at how to send binary data to clients using Serverless Framework and AWS API Gateway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3cYN2Wx1zonPCf9_LhJvsQ.jpeg" /><figcaption>Jellyfish are cool. Photo by <a href="https://unsplash.com/photos/bviex5lwf3s?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">贝莉儿 NG</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>We’re big fans of serverless technologies and the Serverless Framework if the use case supports it. While API Gateway <a href="http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings.html">supports binary data</a>, there’s a bit of work involved to configure Serverless.</p><h4>An example: Lambda based on-the-fly image processing</h4><p>Suppose you want to build an image resizing service using Lambda. You’d have an API endpoint that accepts an image source url, and the desired width and height as url query parameters. The lambda would process the image and return it in the response body.</p><p>The lambda function is actually pretty simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fc3d50505bb80ce605de10b7095c797/href">https://medium.com/media/3fc3d50505bb80ce605de10b7095c797/href</a></iframe><p>This example is using Typescript, error checking is omitted for brevity, and we’re using <a href="https://github.com/oliver-moran/jimp">Jimp</a> to do the image processing. Important parts:</p><ul><li>Output the binary data as a base64 encoded string in the response body</li><li>Set the Content-Type header appropriately.</li></ul><p>Unfortunately if you deploy this you won’t get the desired result. You’ll get the base64 encoded string, when what you really want is the binary data. There are two parts to the solution: allowing binary data for our content type, and telling Lambda to convert the base64 string to raw binary.</p><h4>Enabling Binary Output for your content-type</h4><p>We’ll use a <a href="https://github.com/maciejtreder/serverless-apigw-binary">plugin</a> for configuring binary output for specificContent-Types.</p><pre>npm install --save-dev serverless-apigw-binary</pre><p>We then need to modify our serverless.yml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0137a7f81cf6db0631bd37bf83dff94/href">https://medium.com/media/c0137a7f81cf6db0631bd37bf83dff94/href</a></iframe><p>As you can see, we just list the mime types that should be allowed as binary. You can also use wildcards such as */* . After a deployment you can see in the AWS console that the binary type is enabled:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*voGYI0qXE3d_Z8rrBvI_wQ.png" /></figure><h4>Convert the base64 output to binary</h4><p>That’s half the work done. We now need to tell AWS to convert the base64 string into raw binary data before sending it through to the client. We do this with another, painfully similarly named <a href="https://github.com/ryanmurakami/serverless-apigwy-binary">plugin</a>.</p><pre>npm install --save-dev serverless-apigwy-binary</pre><p>And configure serverless.yml , it will end up looking something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c806ee3ea9cf60646c4b05fa7c4a89f/href">https://medium.com/media/4c806ee3ea9cf60646c4b05fa7c4a89f/href</a></iframe><p>The key changes are:</p><ul><li>Add the second plugin</li><li>Set contentHandling: CONVERT_TO_BINARY in our event configuration</li></ul><p>And that’s it. This technique works with any binary data format, you just need to enable binary for that mime type.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fde91376b76" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nextfaze/binary-responses-with-serverless-framework-and-api-gateway-5fde91376b76">Binary responses with Serverless Framework and API Gateway</a> was originally published in <a href="https://medium.com/nextfaze">NextFaze</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sending & Receiving SMS on Linux]]></title>
            <link>https://medium.com/@MichaelMarner/sending-receiving-sms-on-linux-acf7610e2d2?source=rss-43a8de187db1------2</link>
            <guid isPermaLink="false">https://medium.com/p/acf7610e2d2</guid>
            <category><![CDATA[sms]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Michael Marner]]></dc:creator>
            <pubDate>Thu, 23 Apr 2015 04:01:32 GMT</pubDate>
            <atom:updated>2018-08-10T04:29:38.662Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C5r7c1ok9QdYKU5m.jpg" /></figure><p>tl;dr: Use an SMS gateway service. Unless you don’t have internet access because you’re in the middle of nowhere.</p><p>A little while ago I worked on a mixed media theatre production called <a href="http://illuminart.com.au/project/if-there-was-a-colour-darker-than-black-id-wear-it/">If There Was A Colour Darker Than Black I’d Wear It</a>. As part of this production I needed to build a system that could send and receive SMS messages from audience members. Today we’re looking at the technical aspects of how to do that using <a href="http://smstools3.kekekasvi.com/">SMS Server Tools</a>.</p><p>There are actually a couple of ways to obtain incoming text messages:</p><ul><li>Using an SMS gateway and software API</li><li>Using a GSM modem plugged into the computer, and a prepaid SIM</li></ul><p>The API route is the easiest way to go from a programming aspect. It costs money, but most gateways provide a nice API to interface with, and you’ll be able to send larger volumes of messages.</p><p>BLACK had a few specific requirements that made the gateway unsuitable.</p><ol><li>We were projecting out of a van in regional South Australia. We had terrible phone reception, and mobile data was really flakey.</li><li>We were going to be sending text messages to audience members later, and needed to have the same phone number.</li></ol><p>So, we got hold of a USB GSM modem and used a prepaid phone SIM. This allowed us to receive unlimited messages for free. However, we couldn’t send messages as quickly as we would have liked.</p><h3>Modem Selection</h3><p>There are quite a few GSM modems to choose from. You are looking for one with a USB interface and a removable SIM. GSM modems that use wifi to connect to computers won’t work. You need to be able to remove the SIM because most mobile data SIMs won’t allow you to send or receive SMS messages. The other big requirement is Linux drivers, and Google is really your friend here. The main thing to watch out for is manufacturers changing the chipsets in minor product revisions.</p><p>We ended up going with an old Vodafone modem using a Huawei chipset. The exact model I used is <strong>HUAWEi Mobile Connect Model E169</strong> It shows up in Linux like this:</p><pre>ID 12d1:1001 Huawei Technologies Co., Ltd. E169/E620/E800 HSDPA Modem</pre><h3>SMS Tools</h3><p>SMS Tools is an open source software package for interfacing with GSM modems on Linux. It includes a daemon, SMSD, which receives messages. SMSD is configured to run your own scripts when messages are received, allowing you to do pretty much anything you want with them.</p><p>Installation is straight forward on Ubuntu et al:</p><pre>sudo apt-get install smstools</pre><p>Next you’ll need to configure the software for your modem and scripts.</p><h3>Configuration File</h3><p>The configuration file is a bit <a href="http://smstools3.kekekasvi.com/index.php?p=configure">unwieldy</a>, but thankfully it comes with some sane default settings. Edit the file in your favourite text editor:</p><h4>Modem Configuration</h4><p>First up you will need to configure your modem. The modem configuration is at the end of the config file, and the exact parameters will vary depending on what modem you have. Let’s have a look at what I needed:</p><pre>[GSM1] device = /dev/ttyUSB0 init = AT^CURC=0 incoming = yes baudrate = 115200</pre><p><em>device</em> is where you specify the file descriptor for your modem. If you’re using a USB modem, this will almost allways be /dev/ttyUSB0.</p><p><em>init</em> specifies <a href="http://en.wikipedia.org/wiki/Hayes_command_set">AT commands</a> needed for your modem. Some modems require initialisation commands before they start doing anything. There are two strategies here, either find the manual for your modem, or take advantage of the SMSTools <a href="http://smstools3.kekekasvi.com/forum.php?id=6">Forums</a> to find a working configuration from someone else.</p><p><em>incoming</em> is there to tell SMSTools you want to use this device to receive messages.</p><p><em>baudrate</em> is, well, the baud rate needed for talking to the device.</p><p>Like I said, there are many options to pick from, but this is the bare minimum I needed. Check the SMSTools website and forum for help!</p><h4>Event Handler</h4><p>The other big important part of the config file is the event handler. Here you can specify a script/program that is run every time a message is sent or received. From this script you can do any processing you need, and could even reply to incoming messages.</p><pre>eventhandler = /home/michael/smstools/sql_insert</pre><p>My script is some simple Bash which inserts a message into a database, but more on that in a moment.</p><h3>Sending Messages</h3><p>Sending SMS messages is super easy. Smsd looks in a folder, specified in the config file, for outgoing messages. Any files that appear in this folder get sent automatically. By default this folder is /var/spool/sms/outgoing.</p><p>An SMS file contains a phone number to send to (including country code, but with out the +) and the body of the message. For example:</p><p>To: 61412345678 This is a text message sent by smstools. Awesome!</p><p>This is a text message sent by smstools. Awesome!</p><p>Easy! Just put files that look like this into the folder and you’re sending messages.</p><h3>Receiving Messages</h3><p>Let’s have a better look at the event handler. Remember, this script is called every time a message is sent or received. The information about the message is given to your program as command line arguments:</p><ol><li>The event type. This will be either SENT, RECEIVED, FAILED, REPORT, or CALL. We’re only interested in RECEIVED here.</li><li>The path to the SMS file. You read this file to do whatever you need with the message</li></ol><p>You can use any programming language to work with the message. However, it is very easy to use <a href="http://linux.die.net/man/1/formail">formail</a> and Bash. For example:</p><pre>#!/bin/bash</pre><pre>#run this script only when a message was received.<br>if [ “$1” != “RECEIVED” ]; then exit; fi;<br>#Extract data from the SMS file<br>SENDER=`formail -zx From: &amp;lt; $2`<br>TEXT=`formail -I “” &amp;lt;$2 | sed -e”1d”`</pre><p>From there you can do whatever you want. I put the message into a MySQL database.</p><h3>Troubleshooting</h3><p>That’s all you need to write programs that can send and receive SMS messages on Linux. Once you have smsd actually talking to your modem it’s pretty easy. However, in practice it’s also fragile.</p><p>The smsd log file is <em>incredibly</em> useful here. It lives in /var/log/smstools/smsd.log</p><p>Here are some of the errors I encountered and what to do about them:</p><h3>Modem Not Registered</h3><p>You’ll see an error that looks like this:</p><pre>GSM1: MODEM IS NOT REGISTERED, WAITING 1 SEC. BEFORE RETRYING</pre><p>This means the modem has lost reception, and is trying to re-establish a connection. Unfortunately there is nothing you can do here but wait or, using a USB extension cable, trying to find a spot with better reception.</p><h3>Write To Modem Error</h3><p>An error like this:</p><pre>GSM1: write_to_modem: error 5: Input/output error</pre><p>means the software can no longer communicate with the modem. This is usually caused by the modem being accidentally unplugged, the modem being plugged in after the system has powered up, or by an intermittent glitch in the USB driver. To fix this, do the following:</p><ol><li>Stop smsd (sudo service smstools stop)</li><li>Unplug the modem</li><li>Wait 10 seconds or so</li><li>Plug the modem back in</li><li>Start smsd (sudo service smstools start)</li></ol><h3>Cannot Open Serial Port</h3><p>You may see this error:</p><pre>Couldn’t open serial port /dev/ttyUSB0, error: No such file or directory</pre><p>This occurs if you started the computer (and therefore smsd) before plugging in the modem. Follow the steps above to fix it.</p><p>So there you have it. Follow these steps and you can send and receive SMS messages on Linux, using a cheap prepaid SIM and GSM modem.</p><p>In the next post we’ll be looking at exactly what I used this setup for.</p><p><em>Originally published at </em><a href="http://www.20papercups.net/programming/sending-receiving-sms-on-linux/"><em>www.20papercups.net</em></a><em> on April 23, 2015.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acf7610e2d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>