Saturday, August 29, 2015

Finite State Machine in Java

If you want an in-depth explanation of the Finite State Machine concept, there are plenty of good resources out there, so I'll skip past that. I'm a fan of FSMs because of the ability to condense large amounts of logic into a tidy package. Recently I found myself needing to implement a FSM in Java, and decided to share my implementation.

The demo code is located here. To compile and run the code:

javac StateMachineDemo.java
java StateMachineDemo

The output should look like this:

Transition from 'Idle' -> 'Building Widget' results in action 'Build Widget'
Error! Transition from 'Packing Widget' -> 'Idle' is invalid!
In state 'Packing Widget', action 'Ship Widget' results in new state 'Shipping Widget'
Error! Action 'Build Widget' while in state 'Canceled' is invalid!

This example includes a state map that simulates a factory building widgets. A few points of explanation are in order.

  • The FiniteStateMachine class is static, and I did that purposefully, because I wanted to ensure that I was not needlessly creating and destroying instances of the FSM in my application.
  • The state map looks like this:
private static Map<List<state>, action> stateMap = new HashMap<>();
It is a hashmap of lists of states to an action. By using a list of states (as opposed to a hashmap of states), we can have the same starting state mapping to several different ending states depending on the action. This ability is required for non-deterministic FSMs.

  • Depending on your application, you may know the starting and ending state, but not the resulting action. Or, you may know the starting state and the action, but not the ending state. The example code contains two Transition methods, one for each case.
  • If Transition() is called with an invalid combination of states or state and action, it will throw a StateTransitionException.
This example class could be grown or extended into a more fully featured library, but I kind of enjoy the KISS approach. Anyway, hope you find it useful, enjoy.

Monday, August 24, 2015

Android Notifications Without an App

What if you have a pile of Android devices and want to send some kind of notification to them? Android supports GCM - Google Could Messaging - but you must write an app to receive these messages. That's fine and works great, but what I wanted was the convenience of pushing messages to my devices, without the inconvenience of having to write a custom app, and keep that app running to receive the notifications.

The idea that I hit upon was to create a "dummy" Gmail account and send XMPP chat messages from the dummy account to my "real" Gmail account, which is connected to my Android devices. This results in a native notification popping up on all connected devices.

Unfortunately for us, Google has masked our Gmail accounts such that you cannot just send XMPP messages directly to your Gmail address. This mask is a unique 26-character string at the domain public.talk.google.com (shown in the green box below). The reason for the mask is to make it more difficult for people to spam you with chat messages. What is needed is a way to discover the masked address so we can send XMPP messages to it.


To discover the masked address, I created a Python script that logs into the dummy account. While that script is running, send a chat from your main account to the dummy account (using the Gmail web interface). The Python script will catch the message and dump the "from" address, which is exactly what we need.

Here is the Python script to do it. Make sure to follow the directions closely. You may also find that it works best on Linux.


Once you have the masked account, you can send your main Gmail account notifications using XMPP libraries in a variety of different languages. Shown above, I have been using this technique to send notifications for a home automation system.

Sunday, August 16, 2015

Adventures in Low Power PIR Sensors



As part of a larger project to be discussed later, I have been working on coming up with a very low power wireless motion sensor. PIR (passive infrared) sensors are normally used for these kinds of applications. The problem is that they are very thirsty, usually consuming something in the neighborhood of 80-100 uA while sensing, and 200+ uA once motion has been detected.

Looking at most cheap PIR sensors available from China, we can see that there are usually one or two active items on the PIR module: a voltage regulator and/or op amp. I reasoned that these components would be responsible for a good chunk of the power consumption, and started looking for alternatives.

I stumbled on this small PIR sensor which appeared to have no active components like regulators or op amps, and bought a couple. I measured the current consumption at 3V and was impressed to see that it was indeed roughly 27-28 uA.

The image you see above is a Moteino with the ATmega328 put into power down, the RFM69 radio module is in power down, and the PIR sensor providing an interrupt to wake the ATmega328. The only trick was to swap out the 3.3V regulator for a 3V variant, because I found that the PIR sensor consumed significantly more power at 3.3V compared to 3V. As you can see, this achieves an overall power consumption of about 29uA.

I decided to pop the white plastic lens off the PIR sensor and see if I could find the manufacturer's part number - rather than just the "SimplyTronics ST-00082" part number.




It appears to be an AM322, manufactured by Nanyang Senba. They could probably be purchased for pennies in large quantities.

While 29uA for the entire wireless motion sensor was pretty good, I wasn't done yet. I wanted to see how low I could go. I poked around on Digikey and was intrigued to find a bunch of PIR sensors from Panasonic that claimed to consume a miserly 1uA of current while sensing. I picked up an EKMB1101111 from Digikey. Unfortunately I think the 1uA figure is bogus. It appears to hover much closer to 100uA, which is more realistic. Perhaps there were other factors influencing my measurement, but I doubt it. For now, the AM322 is the best part I have found for this device.

(Article originally published 11 February 2015, and appears to have been mistakenly deleted somehow.)

Saturday, August 15, 2015

Simulating "Rolljam" wireless attacks

A Wired article recently exposed an attack which is capable of attacking many different makes and models of vehicles currently on the market. This attack steals the "rolling code" which is used to authenticate the unlock command, and then replays the stolen code at a later time to gain access to the vehicle.

I simulate this by creating a TCP socket server (the vehicle) and TCP clients (the victim and attacker). I generate rolling codes with a simple scheme: SHA1(salt + n) where 'salt' is a passphrase, and 'n' is a counter that is synchronized both on the client and server. The lower 8 bytes of the hashed phrase are used as the rolling code. When the server receives a message, it increments its 'n' counter, takes the SHA1 hash, and checks if the codes match. In case they do not match, it keeps incrementing 'n' and generating new hashes until the codes match.

In order to prevent the rolljam attack, any code which has been generated by the server and did not match the received code is added to a list of permanently invalid codes. The server assumes any code in the list of invalid codes has been stolen.

Because I am using an 8 byte rolling code, it would be quite some time until an invalid code was legitimately reused by the client, so I feel like this is an acceptable solution.

Another key difference between my simulation and the real world is that my simulation encrypts the entire message being transmitted, while real vehicle systems appear to only encrypt part of the message.

The code is available on my github.

Saturday, August 8, 2015

LPCXpresso11U37 board with FatFs


NXP makes a bunch of really interesting ARM microcontrollers. One distinguishing feature is that much of the USB device functionality is contained in ROM, which makes for a very slim USB stack. There is also a USB mass storage bootloader contained in ROM, which makes flashing firmware easy. Combine that with low power operation, and I have been pretty interested in these devices. I first started tinkering with the Cortex M3 LPC1343, and the board pictured above has a Cortex M0 LPC11u37, which is pin compatible with the earlier devices.

A fellow named Kevin Townsend has built several software frameworks for these chips, and maintains them on Github. I like the fact that the ARM GCC toolchain works perfectly with these frameworks, but I noticed that the repository for the LPC11uX devices has not been updated in a while, and lacks support for the LPCXpressso11U37 board, pictured above.  So I forked his repository, and I have been in the process of adding a few changes and corrections to get the FatFs file system up and running.

I have the board enumerating as a composite USB device, with both mass storage (provided by the SD card) and serial port working. Unfortunately, the read and write performance is so far pretty bad. I am getting roughly 70-80 kB/s write and 200 kB/s read for large files. This is well below what should be possible. Debugging will continue...

Sunday, February 8, 2015

Kinetis L Series


Looking for the cheapest ARM microcontroller I could find with built-in USB, I eventually settled on the Kinetis L series. The MKL26Z32 has 32k flash, 4k RAM, built-in USB and is available for less than $3 in singles from big distributors like Digikey. Besides the low cost, the other major appeal of the Kinetis L series is the extremely low power operation. According to the datasheet, it can achieve "static" power consumption down to 2uA and offers 9 different low power modes. Considering that this includes a built-in linear voltage regulator, it is really impressive.

I designed the little dev board shown above, which breaks out nearly every pin of the chip and has an RGB LED as well. I wanted to use the GCC ARM toolchain which proved to be somewhat challenging. I managed to find this Github repository belonging to Martin Kojtal which includes the very trickiest bits (the startup and linker scripts) for the KL26 and a few others in L family. This allowed me to build simple applications, but without a USB stack, it is nearly pointless.

Now I am starting to think I may have been approaching the software from the wrong direction. Freescale now offers an IDE for Windows called Kinetis Design Studio. Apparently this IDE is built on top of GCC, so it is possible that a GPL'd USB stack (and other goodies) is available.

At any rate, the KL26 is now old news. A new series of devices - the KL17, KL27, KL33 and KL43 - have just been released. The main attraction of the newer devices is that they include a ROM USB bootloader. This feature is incredibly handy, making the device appear as a USB storage device when plugged in to a computer, allowing for firmware updates just by dragging and dropping the firmware binary. While the KL27 is slightly more expensive ($4.40 in singles from Digikey), it includes much more flash and RAM (256k and 32k respectively) while maintaining the vanishingly low power consumption.

Monday, January 26, 2015

OSH Park Solder Mask Quality


If you are into hardware projects at all, you have probably used OSH Park by now to fabricate some PCBs. They are very cheap, pretty speedy, and fabricate what I consider to be excellent quality boards for hobby use. However, it seems the formula for the solder mask has changed. In the image above, the PCB on the right has the older, matte textured formula. The PCB on the left has the newer, shiny formula. The old formula seems to be higher quality, and just generally looks smoother and more consistent. The shiny formula flaked just a bit in some small areas after soldering. Like most things, the reason was probably cost. Just curious if anyone else has any clue what's going on.