Flutter course in Swedish on YouTube

Last semester I gave a course on mobile app development using Flutter. The course was based around a series of video lectures, exercises, and supervision. Since the videos are recorded and there is not that much material on Flutter in Swedish, I decided to upload them to YouTube.

They are available here

The series of videos goes from introduction to Flutter, introduction to Dart programming, basic UI layouts, more advanced layouts, state management using StatefulWidget and Provider, and finally network communication.

Essentially it covers the basics of all aspects needed to build simple mobile applications.

 

Posted in Coding

Template for PoC using NodeJS, React, and Express

Quite often I need to try a simple idea for a new service or app. My weapon of choice is currently nodejs and react. It is fairly easy to quickly hash out a server backend. Using create-react-app or NextJS, it is also quite easy to write a react frontend for said backend.

This is all nice and well for a bit while you try out the idea for yourself. But no idea is really worth anything until it is shared with others. So now you need to host both the frontend and backend somehow, and point the frontend at the backend. This typically involves too many steps to make it feasible to try out the very simplest ideas.

What I typically want, is a single server that can run somewhere that hosts both the backend and the frontend. Ideally just a Dockerimage. And I want this to just work without bothering with builds and such. After having done this for a few projects recently I decided to create a template so that I can reuse it whenever I need to try out the next idea.

The result is in this GitHub repo.

To use it, copy the repo. Run npm install and then npm run dev. (I use node 10 and there is a .nvmrc in the repo.)

You now have a server on port 3000 that will restart when you change the server files, and will rebuild the client when you change the frontend. You are basically set to start materialising your idea.

Once you want to share it, you can either use ngrok, or build a Dockerimage using the Dockerfile in the repo and host where you typically host things. When the image starts it will build the frontend. I do it this way instead of when the dockerimage is built so that we can set environment variables on the hosting platform easier.

The repo sets up webpack 4, babel 7, react, express, and jest. The server runs in development mode or production mode. In development mode the server restarts when the backend code changes, and rebuilds the frontend using webpack on client code changes. In production mode the server builds the frontend on startup. It is called production mode, but I would not recommend this for actual production ready applications. But for a PoC this works very well.

Feel free to open issues or send PRs on the github repo.

 

Posted in Coding

Low power sensors using nRF24L01+ and ATTiny

Smart home devices are expensive. A simple temperature sensor costs quite a bit. If you want one in each room it quickly gets costly. If you want door sensors on all doors and windows it’s pricey.

Cost is not necessarily a problem. If you know what you need you can make a budget. But if you don’t know what you need then it stands in the way of experimentation. I want to be able to put up a bunch of stuff in the house and see what I can do with it. It’s hard to justify that cost for other than oneself.

So I’ve been on and off playing around with different ways to create cheap sensors. Not just to have these sensors, but because it is fun to learn.

This is something of a report on my latest adventures within this.

Hardware

I started out with Arduino pro minis as they are easy to program and test things with. And it all starts with communication. My thought of sensor network consists of nodes that are sensors and/or actuators (think lights and motors), and gateways that can receive sensor readings and send commands to actuators. Since cost has been an issue, I’ve come to fall in love with nRF24L01+ – super cheap and low power radio modules.

Arduinos are super convenient, but they are entire boards. You can do a bunch of stuff to get them power efficient. However my thought is that all I really need is the MCU. So instead I want my sensors to run on ATTiny84 chips. They are a little harder to flash, but you can use the same Arduino tools as for an Arduino. Libraries even come with attiny compatibility so it’s hardly any difference from a software standpoint. You have less memory but these sensors only read a value and send the value to the radio module so I don’t need much memory.

Getting radio to work

The nRF chip communicates using SPI. It requires no more than 3.6V. More and they break. It draws very little current when it is idle, like microamps. But when it wakes up to send data it quickly draws around 15mA. It means the power source must allow quick power draw without causing a massive voltage drop. A capacitor helps. (The capacitor acts as a low pass filter, smoothing out a potential voltage drop.) In my setup I power the sensors with either 5V from wall connected DC transformer, or by battery. I therefore use a 3.3V pull-down component, and a 0.1uF capacitor. I’m not sure I actually need this when powering with batteries and will test this out soon. I use two AA as batteries. I’ve been successful using CR2032 occasionally but it often fails. I think I need better capacitors. A CR2032 does not have a high peak power draw and can’t deliver enough power when sending without too much of a voltage drop (causing the radio to stop working). A bigger on like CR2450 should work but haven’t paid my hands on any yet.

Powering the device is the main thing. After that comes wiring and software, but they are easy. I use the RF24 library by TMRH20 for software. It details the wiring. Make sure you get the CE and CSN correct. I’ve flipped those at several occasions.

I’ve had a lot of issues with getting Ack messages through. I think it has to do with power source and can possibly be fixed with capacitors. Still need to work on this. The data gets through, but it would be nice to know if data gets received or not. Especially for actuators. Most sensors will send it’s data again in a while so a drop of message is no biggie, except for door sensors that I’d like to resend every second until received by a gateway.

My setup consists of an Arduino pro mini communicating with a computer over serial. Essentially byte data received by the Arduino is sent in ASCII over the serial (simplifies debugging). Received data is published on mqtt to be subscribed on. The Arduino also reads from the serial and any data received is sent out over radio. It takes address and 32 bytes of data. There is very little logic on the gateway.

The idea is to be able to have several gateways around the house. Using raspberry pis would make them cheap. Using esp8266 or esp32 would make it even cheaper.

The gateway computer code is written in node.js.

Obviously I can connect the nRF chip directly to the gpio on an RPi, but this is simpler. I also have a bunch of computers laying around acting as gateways now.

Getting them to sleep

While power draw is low on the radio when idle, the MCU still draws power unless put to sleep. (Otherwise it just churns away at whatever clockspeed you’ve configured, looking for something to do. Delays are merely loops doing nothing but counting clockcycles.) So, we must tell it to go to sleep, getting it to use as little power as possible, and still be able to wake it up to occasionally do something useful.

When sleeping the sensors are barely using any current at all. Somewhere I read people saying that similar setups use less current than the battery looses by just laying around. This would mean that e.g. a door sensor on a window that never opens will work will function for the duration of the lifetime of the battery. That is quite impressive.

However, if this is the case, how will I know if the sensor is still working? To fix this I’m planning on also waking it up occasionally and send a heartbeat. That way I will be able to detect when a gateway haven’t heard from a sensor in a while and act accordingly.

Waking up

Getting it to sleep is fairly easy. Set some bits in some registers and off to sleep it goes. Getting it to wake up is done through interrupt. An interrupt is something that allows an MCU to halt it’s normal control flow to do something different for a while. It also happens to wake up a sleeping MCU.

I use two types of interrupts in my sensors so far. First one is a watch dog timer. It essentially let you specify a duration in which you want to be interrupted. It can be anything from a few milliseconds, to a few seconds (8s on the attiny). The second one is Pin Change interrupt that will alert the MCU that the logical value on a pin has changed. I use these in essentially the same way: I setup the interrupt I want to use, power down the radio, and go to sleep. When it wakes up I power up the radio, and continue the program which typically involves reading the value of an external sensor and send that to the radio module.

An important lesson I learned recently was to implement each ISR callback for each type of interrupt. E.g. there are two pin change interrupt handlers, PCINT0 and PCINT1, and one for WDT.

In the case of temperature sensor I ask the cpu to sleep for 8 seconds. I do that 6 times, and then send the temperature. The reason is that I don’t need to know the temperature every 8 seconds. Once a minute is fine. 6*8s is close enough.

On the door sensor I set the interrupt to react to the door pin – the pin that is high when the door is open and low when closed. This means that the sensor is basically sleeping almost all the time.

Summary

So far I’ve got very power efficient nodes for temperature and doors. They send data to a gateway that publish it over mqtt. I’ve implemented sending data to nodes, but have no nodes setup for it yet. Xmas lights might be a candidate as I have a bunch of WS2812B lights lying around.

I recommend anyone being interested to look at mysensors.org.

For the code for all this and more details, checkout my repos:

Nrf-gateway – nodejs server gayeway
Nrf-nodes – Arduino code for the nodes

Posted in Coding, Hardware

At home Tesla dashboard in Serverless

So at the weekend of my birthday I finally got the chance to sit down to work on a little project I’ve been wanting to do for a while. It was a gift for myself. Essentially I wanted to build a simple app to show on an iPad in the hallway of our house, where my wife could see where my car is and how long it would be for it to drive home in current traffic conditions. It would also allow me to make sure it was plugged in to charge over night, as well as let me turn on the AC in the morning if it was cold outside. (Obviously the last part could be automated but I don’t always drive in so it would be a waste of electricity to do it anyway. Plus it force me to check the temperature and dress appropriately.) I completed the first version on the Sunday and I’ve made some minor upgrades since, but the core functionality is done.

So how is it build? Well, my car is a Tesla Model S, and so it is essentially a computer on wheels. It has an accompanying app for my phone that let me control all kinds of things as well as give me its location so I can find it at a parking lot. Anything being controllable from a phone, means there is an API somewhere that can be used to do the same thing that the app can do. And Tesla is no exception. It is not official however, but fortunately it has already been documented by craftier people than myself and so far Tesla has made few attempts to prevent it being used so my hunch is that they kind of don’t mind.

The overall architecture of the system is essentially a React app as a frontend, talking to an API that serves the app with info about the car, an ETA for when I might be home, as well as controls for turning the AC on and off.

I have recently been working with Serverless and serverless architectures so I wanted to use that here. In short it means you write very small pieces of software that is invoked for a short period of time and then dies. It is run on servers somewhere, but you don’t have to care about where or how they are setup, just trust that your code will run when something triggers it. (There are books written on this and this is probably the shortest explanation I can manage so YMMV).

The react app is nothing special. It fetches the last state of the car every 60s and that’s about it. I built it using next.js that I use to export it to an s3 bucket where it is served from as a static site. It looks something like this:

Tesla home dashboard

Tesla home dashboard

The backend part is where the fun begins. There are essentially three components (although there are some support components as well). The first component is a function for getting the car state from the Tesla API. There are 5 routes used, that are aggregated and populated into a state object. This object is then put on a message queue in AWS SQS. Another function for saving this state in a dynamodb database is set to be triggered on a new message on the same queue. The update function is set to trigger every 1 minute using AWS scheduled events. 1 minute it she smalled time frame for schedules events. It is enough for now but I might need to change this in the future.

Once the data is in the database the last piece is a HTTP GET route for fetching the last state to display in the dashboard. Once this was done, it was simple to add two routes for turing the climate on and off. I later added a route for fetching the last locations of the previous hour, to show on the map plotting the route I’ve taken so far which gives additional cues for my wife as to where I might be heading.

Using the serverless framework, all components are neatly described in a serverless.yml file. Each component is dead simple, and easy to test. Having the state published to the queue, rather than save directly, means I can now write another function that also listens to the queue, and emit new events for particular state changes. This could allow e.g. me to write a function that spots when I park in other places than at home or at work and send me a push notification that open up the correct parking app for the location. (Or ideally, get the parking meter companies to open up their APIs so I can have my car pay for me automatically.)

In all this, I never had to touch a server configuration. I could focus on the code doing its thing.

Btw, here’s the code on github.

Posted in Coding

Valentine’s IoT mirror

I have for the longest time wanted to get into electronics. While I have been tinkering with connecting lights and motors to batteries since a very low age, taken several electronics courses both in highschool and at university, I’ve never done anything practical. Recently however I started using my now-of-age reserves of money towards DIY-electronic stuff in order to try and finally do something. In the last couple of weeks I’ve learned how easy it really is once you actually have the components you need, and how the DIY culture, especially around Arduino, have made these things incredibly accessible. It’s safe to say that we’ve come a long way since the days of holding a small toy lightbulb against a 4.5V battery (which I did as a kid).

Since when I get into something I tend to immerse myself quite deeply. Therefore, for this valentines day I quite readily jumped to the idea of building something with my newfound skills and toys. I therefore decided to connect a few LEDs in the shape of a heart that could flash in interesting ways to give to my girlfriend. As you can see in the video, it eventually turned into a mirror with hidden heart-shaped LEDs that can be controlled through a web interface on the local network.

I had at this point built up a sensor network at home using nRF24L01+ for wireless communication (which is an incredibly cheap but easy to use RF-module), and both Arduino Pro Minis as well as ATtiny85s as brains. Therefore I already had one of the radio modules connected to an Arduino communicating serially with a small server in the house. All I had to do was to figure out how I could control and drive a bunch of LEDs (ended up using 14) from the Arduino, and then try and package it nicely to be a suitable gift.

The mirror is built using an Arduino Pro Mini 5V, a nRF24L01+, driven using a 12V power adapter. Pretty sure 12V is overkill, but it’s what I had lying around. The nRF24L01+ must be run on 3.3V so it’s also using a voltage regulator that I put on the control board for the LEDs. The LED control is two 547 transistors and the LEDs are current limited using 470ohm. I figured that I couldn’t run the current for all 14 LEDs through one transistor (they would consume about 150mA, and I didn’t have any other transistors lying around) and therefore split them over two. Also ended up connecting the base of the transistors to two different pins on the Arduino, and could theoretically control the upper and lower part of the heart individually. Just ended up not doing that.

The mirror is continuously listening to radio traffic. When a control message arrives, it changes the mode of the LEDs. The software on the mirror is therefore incredibly simple. The server however had to be slightly modified. To this point the server was only listening to sensor nodes, and not transmitting any information back. I therefore had to change both the Arduino program to listen to serial communication and forward the data to the radio, and the software running on the server. The current server software was in Python, but decided to change to NodeJS. Since I also wanted to be able to control from a web interface, I took the time to also build a simple rest-api for sending the command to the mirror using HTTP. Thus the server software now listens to the serial for sensor readings from my sensors in the house and stores that in a database, as well as receives HTTP requests for sending out data packets to listening nodes.

Finally I created a super simple web page with four buttons for selecting one of the four settings on the mirror: heart-beat, off, on, and smooth pulse.

It was a fun project, girlfriend was happy, and I can now move on to the next projects. The project gave me experience in designing and soldering a PCB (using vero board), cutting such board using a drill, how simple it can be to put things together in not too shabby ways.

Posted in Coding, Hardware

ProtoDB as an ORM – ProtoORM?

I believe coding should be seen as a craft, and as such there has to be as little between your creativity and executing on the creativity as possible. One such obstacle when it comes to most development of web applications, is the need to create a database structure. For years now I have been using different iterations of my own set of help functions in PHP. It started with some getters for fetching an array of rows from a MySQL query in one go, and later it evolved into what I called ProtoDB, which is available on GitHub. The core point of ProtoDB is that it creates the database structure as you code it. Setting some value for a column in a table will create that column if it does not exist, and will create the table if the table does not exists. This allows you to stay in the code editor and still work with a database. (Optimizing can always be done later.)

However, sometimes it can be nice to use a simple ORM, in order to group model functions together in an object oriented way. Most ORMs however (that I have seen), still require the database structure to be in place. The tables need to exist, and have the columns needed for the ORM to map to this structure. I have therefore started to expand on ProtoDB to create a basic ORM on top of it, which gives you the flexibility of ProtoDB and the benefits of an object oriented architecture of an ORM.

For now there is only one class Model that is the base of everything else.

namespace ProtoORM;
use \DB;

class Model {
 public static function create($row); // row is an associated array of values for columns given by the keys
 public static function find($id); // gets the model object with the given id
 public static function all(); // gives you an array of all objects in the table
 public function save(); // updates the table or inserts a new row
}

From this it is easy to create a new model, for instance a User:

class User extends ProtoORM\Model {
 protected $table = "users"; // sets the table name
}

// create a new user
$user = User::create("name"=>Mattias);
$user->save();

// later we can set some more info
$user->age = 31;
$user->role = 'dev';
$user->save();

$user = User::find($user_id);

The points of this is that the table ‘users’ does not need to exist before running this code. Everything will be added to the database structure as need. This is obviously only the beginning, and I aim to expand on it as I keep using it in some of my current projects.

I am also thinking about also implementing some kind of automation of migration files, in order for groups of people to work together in early stages of design.

 

Posted in Coding

Developer Options on Android 4.2

If you just updated an Android device to 4.2, and try to develop for it, you may have noticed that there are no Developer Options anymore. They used to be in the settings, just above “About phone”, but since 4.2 they are gone. This can make it difficult (impossible) to enable USB debugging. However there is a fix for it that once you know it is simple enough.

All you have to do to enable it is to go to Settings->About phone. Then go down to Build number, and tap it 7 times. After the first three times there will be a count down towards the hidden option. Just go back to the settings menu, and the Developer options will have appeared.

I found this from this forum thread.

Posted in Coding | Leave a reply

ProtoDB on GitHub

I wrote a simple database library for rapid prototyping some time back, and decided to put it on github for anyone to use. It mainly takes away the need to setup a database structure before being able to save data on a server when writing simple web apps or other client apps.

It is both a PHP library, a server backend, and a javascript library in one. Use it for prototyping only, as it is not made to be neither secure nor efficient. However, once you got your app up and running, it should be easy to exchange those parts, or just make the library more secure.

Feel free to use and feel free to comment or send pull requests. The repo is here.

Posted in Coding | Leave a reply

Fitvids

Embedding video in a responsive web design can be a hassle. With FitVids.js (via Think Vitamin) it is now a piece of cake. Check video below.

Posted in Coding | Tagged , , , | Leave a reply

Responsive IMGs

My friend Viktor at We Made You Look pointed me to this article at Cloud Four on Responsive IMGs. The article makes a case for what is the problem with IMG tags when doing responsive web design. What you want in a truly responsive web design when it comes to images, is to only load images of the size needed for the viewing display. Using IMG tags one can set the src attribute to the smallest possible image, and then through scripting change the src attribute to what ever is appropriate once the display size is known. For small screens this works well, however for bigger devices this slows the loading down as it has to do two requests (and loads) for each image (unless the script manages to change the src before the browser starts fetching the image). There are of course other techniques for responsive images, by for instance using CSS and media queries, but the article deals with the problems with the IMG tag specifically not other techniques. I prefer using media queries which to me makes most sense from a technology standpoint, but I agree it is far from ideal. However it is what is available now, and should therefore be used!

He goes on to start a discussion about what would be appropriate to future proof the IMG tag – i.e. what is needed in order to make sure responsive web designs also work for devices, screen sizes, and resolutions, that we do not know of yet. He makes his own list of what he believe is needed and encourage readers to add to it.

Cloud Four is an excellent blog on web and mobile development and design, and is definitely worth a visit!

Posted in Coding, Design | Tagged , , | Leave a reply