Embedded Experience

This is a backup copy of my professional blog at Google Blogger.
For latest postings and comments, please take a look at the original site:

http://embeddedexperience.blogspot.com/

WebSocket experimentation with BeagleBone [2013-08-14]

I really like the concept of BeagleBone and Cloud9 IDE. I have my board connected directly to my local intranet with Ethernet cable, so I can access the IDE and my saved project, and continue working at any PC in my household, no matter whether it’s the ChromeBook, my company Windows Ultrabook, or my wife's MacBook. The very same user experience available with zero-installation needed. And my project is secured, as it is stored locally at the mass memory of the board itself. No one can access it from outside of my intranet. Of course, in case of professional software development, version control, collaboration, backups, etc. needs to be considered separately.

The default Ångström Linux image installed on BeagleBone, does not have the WebSocket Javascript library socket.io installed by default. At GitHub BoneScript Socket.IO page there are instructions how to install socket.io. The whole project was initially committed only two weeks ago. There is also a nice, but rather complex example of using WebSocket to remote control LEDs, which needs to be externally attached to the BeagleBone board. NB! Some hardware hacking required.

I wrote a canonical code example demonstrating how to control an onboard LED at BeagleBone. So, no hardware hacking is needed to test the code. JavaScript uses JSON (JavaScript Object Notation) to exchange data. In this example, very simple JSON messages are delivered over the WebSocket connection to control and confirm the LED state. BoneScript functions are used for hardware access.

JSON messages in this example have the following simple syntax:

{“name”:“led”,“args”:[“on”]}

The demo consists of two files located in sockserv folder. Socketserver.js, which is the Node.JS executed at BeagleBone, and socketclient.html which is the web page delivered to web browser upon request, containing HTML and JavaScript code for communication with the Beagle. The architecture equals to the scenario #1, presented in my previous posting.

Let’s take a closer look at few key functions.

Server side This is how the “web server” is implemented. Whenever a client is connected and sends any GET command, the static socketclient.html file is read from local the flash disk at beagle, and send to the browser.

function httpserver (req, res) {
  fs.readFile('sockserv/socketclient.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    } 
    res.writeHead(200);
    res.end(data);
  });
}

When WebSocket connection is established, and some data received, the following callback will parse the message, whether the LED should be switched ON or OFF. As an acknowledgement, the same message is transmitted back to the client.

io.sockets.on('connection', function (socket) {
  socket.on('led', function (data) {
    console.log(data);
    if (data == 'on'){
        b.digitalWrite(led, b.HIGH);
        socket.emit('led', 'on');
    }else{
        b.digitalWrite(led, b.LOW);
        socket.emit('led', 'off');
    }
  });
});

Client side At the socketclient.html page, there is one button to toggle the state of the LED. When the button is clicked, this function transmits JSON message over WebSocket to server.

   
function toggleLed(){
  if ( document.getElementById("ledButton").value == "Switch On" ) {
      socket.emit('led', 'on');
  } else {
      socket.emit('led', 'off');
  }      
}

If acknowledgement is received, it it processed by this callback function, which changes the state of the button, confirming successful operation to user. If you see the label of the button changed, you know the message has travelled back and forth.

socket.on('led', function (data) {
  console.log(data);
  if (data == 'on'){
      document.getElementById("ledButton").value= "Switch Off";
  } else {
      document.getElementById("ledButton").value= "Switch On";
  }
});

There is one flaw in beauty in this code. Once the page is loaded, the button is not initially synchronized with the actual state of the physical LED. Only after clicking the button for the first time, the UI and the LED are in sync. I made this decision by purpose, as I want to keep the example as simple as possible.


Web UI of the demo.

Disclaimer: I’m not a professional JavaScript programmer, actual this was my first Node.JS code written ever, and only few times tried JavaScript before. Thus, the code may not be optimal, and something I may have understood wrong. I warmly welcome any feedback to correct faults, and to make it pedagogically more correct. Well, it just looks like working OK.

WebSocket connectivity for Embedded [2013-08-14]

WebSocket is not only for web pages, but is good for embedded M2M connectivity as well.

WebSocket is often called as the TCP socket of the Web. And that’s pretty much correct. WebSocket provides full-duplex communication channel in between WS client and WS server. Roles of client and server are relevant only when establishing connection, when communicating it’s irrelevant, as both sides can transmit independently, just like in traditional TCP/IP sockets.

What’s the added value of WebSocket over conventional TCP socket then? It’s the browser integration. With WebSocket, browser can open a socket connection easily as instructed by JavaScript code. Opening traditional TCP socket at client side is not trivial at all. Secondly, WebSocket supports TSL/SSL security by nature, no separate security function needs to be implemented.

What makes WebSocket good for Embedded M2M? Well, first of all, it’s standardized, free, and open. It reduces your code size, in case of having both human interface and machine interface, as the same communication module can be utilized for purposes. Most importantly, it gives new freedom in constellation of functionality.

In the old school web architecture, specific application logic was only accessible to client through web server. This means the server must be capable enough to handle that kind of communication, and provide an interface of some sort for application logic integration. Generally speaking, in order to run such a capable web server, a proper CPU w/MMU and a real operating system is needed. We’re talking about something like Espotel Jhumar platform or similar, a device with ARM9 CPU running Linux. Traditional web architecture.


Traditional web architecture

Thanks to WebSocket, web server and application logic can be totally separated from each other. No need for any interfacing, and they can be located in separate hardware even. In this scenario, web server only needs to provide static HTML/JavaScript code when requested, which makes server implementation super lightweight. One can implement such a server from scratch in matter of hours, with minimal memory footprint. By instructions given in JavaScript code, the client can then establish WebSocket connection directly to application logic only, for application specific data exchange.

Our engineers have demonstrated running web server and an application logic with WebSocket support in a Cortex-M0 MCU. I have done that same by myself with Arduino platform. That’s the proof of simplicity. Even the most low-end hardware can do Internet-of-Things, with help of HTML5 technology. If strong authentication and security is needed, then HW requirement is upgradedup to Cortex-M4 or higher, depending on availability of cryptographic subsystem.

I have recognized 4 different scenarios how to distribute web server and application logic, illustrated in the picture below. Different WebSocket architecture options


Different WebSocket architecture options

1. Integrated - Both server and application logic resides in the same hardware. Stand-alone all-in-one solution.
2. Pre-loaded – HTML/JS code is pre-loaded in client side, sort of Apps approach. Most lightweight.
3. Cloud wed – Web service is located in cloud, and data is exchanged directly with embedded device. Easy deployment of new UI features.
4. Cloud hub – All traffic is routed through cloud. Access through firewalls, and in case of mobile and non-static IP end-points.

Let's get started with Embedded JavaScript [2013-08-13]

BeagleBone provides super simple way of getting started with embedded JavaScript programming. BoneScript Node.JS library provides Arduino style function calls for interfacing with hardware. Together with Cloud9 IDE, all the pieces of embedded development are in place.

Cloud9 is an open source IDE dedicated for JavaScript development. It is by itself written in JavaScript and uses Node.JS. C9 provides easy deployment to several cloud services, like Azure and Heroku. In case of BeagleBone, one can save and execute JavaScript code directly in the target hardware, without a separate deployment phase.

Start of Javascript programming requires just a few steps:

1. Connect USB cable in between BeagleBone and your PC
2. Install Ethernet-over-USB drivers, according to instructions
3. Open URL http://192.168.7.2:3000 to start C9 IDE
4. Start coding, and run your code in target hardware by a single click

Later on, you can skip step #2, and if your BeagleBone is connected to Ethernet, you can skip the step #1 as well. Hard to make it more simple than that. I remember the good old days when embedded programming required first to construct a programming device and an UV erase chamber…


Cloud9 IDE with BoneScript example code, connected to my BeagleBone.

Paradigm shift towards Web programming [2013-08-13]

There is an interesting article The Quiet Revolution in Programming published by Dr.Dobb's (Apr.2013), which confirms the trend of rising web technologies. There are two important findings of changes occurred in between 2010 and 2012.

1. Relative proportion of software developers using one programming language only has decreased significantly. 2. Rise of HTML/JavaScript languages. Basicly every designer uses them in some extend.

Not every programmer does implement web pages, which implies web programming is used for other purposes as well. Chrome OS style web apps philosophy increases the importance of web technologies in implementation of general purpose software as well.

Embedded JavaScript programming [2013-08-12]

First there was client side JavaScript, then we got server side JavaScript, called Node.JS. Next step is embedded side JavaScript programming.

As you know, JavaScript is not Java. JS has many characteristics that makes it behave much unlike Java. First of all, in JS external function calls are asynchronous, non-blocking. This means when you request for certain resource, your call returns immediately, and your request is served later. Then, callback function you provided may be invoked or not. This approach makes JavaScript ideal for distributed computing, as the same phenomena occurs over there. You request something, and you may or may not get the response.

Second, server sessions are stateless, as session management is typically off-loaded to the client side as well. In Java implementation, memory consumption and CPU load is increased proportionally to number of concurrent sessions. In JS, all calls are served in a single-threaded event loop. Thus no new context is created for each new session, which reduces memory consumption dramatically. These same features, which make JavaScript superscalar in heavy load server systems, makes it suitable for low-end embedded systems as well. Client side session management and asynchronous calls both makes your embedded implementation more lightweight.

Of course, JavaScript is not suitable for the most time-critical sections of your code, help of other languages is needed for that. However, real-time requirements typically covers only small fraction of the whole code base. Integrating external native functions calls is much easier with JavaScript than in Java. Last but not least, JavaScript integrates with your web UI by nature, yet another reason why to choose JS over Java.

My recommendation; implement real-time and performance critical parts of your embedded code with just plain C, and do the rest with JavaScript. This way you get both the performance and productivity at once.

BeagleBone - Industrial grade hacking platform [2013-08-10]

I just got my first BeagleBone Black, the latest variant of Beagleboard open-hardware single-board embedded computers, released at spring 2013. One can say that BeagleBone is just a one alternative in the long list of credit card size development boards. What makes BeagleBone special, is the industrial grade components selection, especially the TI Sitara AM335x CPU with ARM Cortex-A8 core.

Most of the other development boards I have got, are based on CPUs dedicated for consumer electronics or mobile phone industry. BeagleBone is the first one that I know having similar long life-cycle CPU that my company uses in professional embedded designs. Actually, Espotel Industrial Computer platform has a CPU from the same Sitara Cortex-A8 family.

BeagleBone provides very good performance per buck –ratio. Running at 1 GHz, the Black is pretty powerful, at the price of $45 (36€). 512 MB RAM and 2GB integrated flash enables use of many advanced software. uSD slot provides more storage space if needed. BeagleBone is very well supported by different Linux distributions. In addition to the factory loaded Ångström, number of different Linux distros are ported for the device, including Debian, Ubuntu, Fedora, Gentoo, and more. Even Android support exists. Some non-Linux OS ports exists as well, like QNX and FreeBSD.

How about RaspberryPi?


RaspberryPi vs. BeagleBone Black

RaspberryPi is also nice, I’m running several RPi’s for home automation and entertainment (set-top-box). However, RPi was originally intended for educational purposes. You get that at the price of limited connectivity. RPi provides only limited set of IO through single 26 pin expansion header, and the form-factor of RPi does not make it ideal for mechanical mounting. RPi has two ZIF-connectors for flexible flat cable, providing camera and display connectivity. Need for special FFC makes it more difficult and expensive to integrate RPi as a part of any bigger embedded system.

BeagleBone, in contrast, is designed having connectivity in mind. It has two 46 pin extension headers, located symmetrically on both edges of the board. With help of the software controlled pin mux at the processor, it is possible to access almost every IO-line of the CPU. There are 4 symmetrically located holes in corners of the board for screw towers, providing sturdy mechanical attachment. BeagleBoard may be considered as a CPU-module as a such for small scale production.

There is a nice video comparison of the two boards in Youtube http://youtu.be/Tbk_Z_8macI detailing differences.

I conclude the same way as TheRaspberryPiGuy says on the video; if you do anything serious, I’d select the Black.

Mobile Linux [2013-08-09]

In the previous posting I told about Chrome OS.

Why yet another Linux based OS?

How about Android, that's also Linux based and provided by Google too. Why two competing solutions from the same vendor? Well, first of all, Android uses Java, which intellectual property is owned by another company. Second reason is that Google does not have 100% control over Android. Device vendors are free to modify their Android flavors, and that has led to a situation where Google's brand value is diminishing, while device manufacturers are taken more role; that's a Samsung Android, or Acer Android, or Lenovo Android, not just plain Android.

Chrome OS is fully controlled by Google, and device vendors are not allowed to modify it. Google pushes software updates to all devices simultaneously, and user experience across different device brands remains the same, rising Google’s positions and diminishing device vendors. Just what happened in PC industry decades ago, when Microsoft Windows managed to gain the controlling position of the industry, and hardware brands lost the importance.

Chrome OS and it's applications are based on web technologies, which enables easy integration to any other web based services provided by Google and other vendors. Due to this, it's obvious that Google will push Chrome OS instead of Android. Now we're just waiting for Google to launch a Chrome OS based phone of its own. Remember, Google acquired Motorola's Mobile Devices division last year. But why to have a hardware of your own? Well, Apple makes majority of the profit of the mobile industry, with help of its own hardware.

ARM, Linux and HTML5, the winning combination

Let's take a look at some of the most known brand consumer electronics devices of the day: Samsung Galaxy, Apple iPhon, Apple iPad, Nokia Lumia, and finally my Samsung Chromebook, what's in common? Well, they are all having ARM CPU, not Intel inside.


IDC study, Aug. 2013

At the day, Android is dominating mobile phones, having stunning 80% market share, according to IDC market study (Aug. 2013). Fur sure, Android will not disappear in the near future, instead I believe the rise of Chrome OS together with other variants like Jolla and Bada/Tizen will even increase the market share of devices based on Linux technology.

Chrome OS is just an example of the megatrend of transition towards the use of web technologies for more generic purposes. Remember, Adobe abandoned Flash in favor of HTML5. Today, even the most conservative embedded industry is adopting HTML5. Not only in remote user interface, but I have seen even application logic embedded systems implemented using web technologies.

I conclude my post by stating that ARM, Linux and HTML5 are the winning combination of the day, and the right choice for the embedded systems as well, whether in consumer of industrial segment.

Chromebook - ARM, Linux and HTML5 [2013-08-09]

Recently I purchased a Samsung Chromebook with Google Chrome OS. At a local retailer, it costs 399€ with 3G data modem option. Cheapest models are sold for less than $200 in the U.S. and various web stores.


Samsung Series 3 Chromebook running Ubuntu Unity.

What an amazing piece of technology! I'm mostly fascinated by it's totally fan-less design. The book is running Samsung Exynos 5 series CPU, with dual-core Cortex-A15. The chip was originally intended for smart phones like Samsung Galaxy, etc, but is proven to be equally good for lightweight computation as well. In continuous use, I haven't noticed heat of any significance.

Chrome OS is sort of a new rise of dummy terminals. With web-apps philosophy, applications implemented with HTML5 and Javascript are intended to be executed from the cloud at run-time, and files are expected to be stored at cloud storage as well, as the integrated 16 GB Flash disk does not allow much local store. Out of the 16GB, six gigabytes are already taken by the Chrome OS base installation.

Concerned for confidentiality issues of cloud computing?

There is option to replace the original Google operating system by another Linux variant. There are at least two projects, Crouton and ChrUbuntu providing alternatives. Google OS is based on Linux, thus it is easy to replace by another Linux. Crouton actually does not replace the original kernel and drivers, only installs an new windowing environment and middleware, reusing lower layers of the Linux OS. Chrubuntu is a Ubuntu port dedicated for Chromebooks, and it replaces the whole software stack.

Crouton is originally developed by Google engineers, thus it is very easy to install a top of existing Chrome OS. Here it is explained how:

http://www.howtogeek.com/162120/how-to-install-ubuntu-linux-on-your-chromebook-with-crouton/

I'm now a happy user of Ubuntu Unity, which enables me all the software there exists for Ubuntu, with easiness of apt-get. Now the book is a really a tool for software development and other purposes. An SD card increases local storage space for my files and programs. Now, it’s really not only for consuming web content, like many considers the Chrome OS. And, I can always switch back to the original Chrome OS just with a key press, as both environments are running simultaneously side by side.

blog.txt · Last modified: 2013/08/15 00:45 by jap
Recent changes RSS feed CC Attribution-Share Alike 4.0 International Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki