Accessing Blockchain on ESP8266 Using the NodeMCU Board


Blockchains claim to be public, distributed, effectively immutable ledgers. Unfortunately, they also tend to get a little bit huge – presently the Bitcoin blockchain is 194GB and Ethereum weighs in at 444GB. That poses quite an inconvenience for me, as I was looking at making some fun ‘Ethereum blockchain aware’ gadgets and that’s several orders of magnitude too much data to deal with on a microcontroller, not to mention the bandwidth cost if using 3G.

Having imagined a thin device that I could integrate into my mobile phone cover (or perhaps… a wallet?) dealing with the whole blockchain was clearly not a possibility. I could use a VPS or router to efficiently download the necessary data and respond to queries, but even that seemed like a lot of overhead, so I investigated available APIs.

As it turns out, several blockchain explorers offer APIs that do what I want. My efforts get an ESP8266 involved with the blockchain began with two of the available APIs: Ethplorer and Etherscan.

Where Blockchain and Microcontroller Collide

To start with something simple, I set out to build a small gadget that contains a hardcoded Ethereum address, retrieves the Eth balance at that address over Wi-Fi using the Etherscan API, and displays it on a small OLED screen (without requiring any of your security keys of course).

In a few days I’ll expand on this with an application of the websockets protocol to create a simple automated service controller. Imagine for example a conference room that you can rent with Ethereum, where power to the room is supplied for a period of time depending on how much Eth is sent to an address. In other words, an Ethereum-controlled switch with a timer!

As usual I’ll be using a NodeMCU board (I really did order a lot of them) which uses an ESP8266, but there’s no reason this would be difficult to achieve on an Arduino-based device. I chose a 128×32 pixel OLED screen based on the SSD1306 controller. I really like this line of screens because they are high contrast and easy to read, come in a number of form factors, are inexpensive, and are easy to use as long as you choose the right NodeMCU compile options.

Pros and Cons of the API Options

Ethplorer (Github) responds with data to HTTP GET requests. Some key features are that it allows you to retrieve trading data like pricing and volume for both coins and tokens. Price tracking gadgets have been done before, and this looks like a great way to implement it.

Etherscan on the other hand focuses on more things that I’m interested in. It has some basic smart contract features like checking execution status, and in addition to HTTP GET requests it supports websockets for something approaching real-time alerting.

Both services are presently free to use and can check Eth balances, transactions histories, and the other features you’d expect in this type of blockchain explorer. I chose Etherscan for this project because I wasn’t interested in price data and I thought of some fun things websockets would allow. Both services provide data in JSON format, which is quite convenient as we’ll see later.

Preparing the Firmware is Easy with NodeMCU-build

NodeMCU-build tool makes adding module support very simple.

For my application, I needed to compile support in NodeMCU for a few more features than usual, so let’s over that in detail. The excellent NodeMCU-build tool will make this easy

Besides the default modules, I needed at least I2C, SPI, HTTP, websocket and SJSON. I also recommend adding MQTT and end user setup as well for a little flexibility.

There are a couple of optional graphics libraries to deal with LCD screens. Most of the screens available to me have fallen under the U8G module (or occasionally under the UCG module). When you select one of them, this tool provides options for fonts, as well as I2C and SPI display drivers. Fonts take up valuable space. My personal preference is to remove the two default choices (press the little ‘select’ link to open a menu) and choose u8g.font_profont17r and u8g.font_profont15r as both of those are easy to read and leave me two font size choices with a decent character set.

Finally, I selected display drivers from the dropdown listed as chipset/screensize/protocol and clicked the build button. I needed the float firmware and not the integer version — I don’t enough Ethereum to without decimal point values!

While waiting for it to build, I went to Etherscan and register for an API key. Once the firmware was built, I flashed it and we’re ready to go.

The Program

With hardware figured out, and modules added to the firmware, it’s time to write the code. I only needed four basic parts to make this happen: a network connection, some API calls, a way to show the data on the screen, and a timing mechanism to update at regular intervals.

WiFi:

We’ll start by connecting to Wi-Fi:


wifi.setmode(wifi.STATION)
wifi.setphymode(wifi.PHYMODE_B)
station_cfg={}
station_cfg.ssid="my_ssid"
station_cfg.pwd="my_password"
station_cfg.save=true
wifi.sta.config(station_cfg)

I’ve set PHYMODE_B to improve the range at the expense of power. I’m not using a battery, so figured I may as well have decent wireless range.

Retrieving Wallet Balance:

Next, we’ll define a function to retrieve the account balance of a specific wallet address. This will return the balance in Wei (1 Eth = 1,000,000,000,000,000,000 Wei). Replace ‘target address’ and ‘API key’ with your values.


function amount()
http.get("http://api.etherscan.io/api?module=account&action=balance&address=target address&tag=latest&apikey=API key", nil, function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(code, data)
t = sjson.decode(data)
wei = (t["result"])
eth = wei/1000000000000000000
print (eth)
end)
end

Above, we see how neat the sjson library is. If you look at the raw JSON data the NodeMCU receives, it looks something like this:

Above, sjson.decode converts the received data into a table. Running t[“result”] returns the value associated with the field named ‘result’ (and we convert it from Wei to Eth). This is a very clean and easy way to deal with the many APIs that return JSON data!

Pushing Data to the OLED Display:

Next, we extend the function to display data on the screen.


function amount()
http.get("http://api.etherscan.io/api?module=account&action=balance&address=target address&tag=latest&apikey=API key", nil, function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(code, data)
t = sjson.decode(data)
wei = (t["result"])
eth = wei/1000000000000000000
print (eth)
-- Setup screen
sda = 1
scl = 2
sla = 0x3C
i2c.setup(0, sda, scl, i2c.SLOW)
disp = u8g.ssd1306_128x32_i2c(sla)
disp:setFontRefHeightExtendedText()
disp:setDefaultForegroundColor()
disp:setFontPosTop()
disp:firstPage()
repeat
-- choose font
disp:setFont(u8g.font_profont17r)
-- display balance
disp:drawStr(2, 22, eth)

until disp:nextPage() == false

end
end)
end

The Waiting Games:

Finally, we add a timer so Wi-Fi has time to connect before the function tries to retrieve your Eth balance, and then update every 10 seconds. There are more elegant ways to do this (e.g. run only once connected) but this works very well for the moment. Once I decide whether it will use a static Wi-Fi configuration or the end user configuration tool, I’ll likely change it to the latter method.


--wait 10 seconds for wifi to connect before trying to 
access the Eth balance

tmr.alarm(0,10000,tmr.ALARM_AUTO,amount)

 

Build… Code… Profit!

There we have it! A simple device that retrieves and displays an Eth balance fresh from the blockchain. No, this is not my account, I used one from the API docs to see how it would actually handle large numbers.

There are many avenues this could be extended with new functionality, both frivolous and useful. Keep your eye on Hackaday as I’ll soon have a follow-up that implements something like that conference room rental concept. But I could totally make a screen that lets you pay Eth to rickroll me at work! What’s your best and worst idea for microcontrollers that interact with the blockchain?



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *