Archive
Building a kiosk system with Smart Mobile Studio and ARM SoC

Kiosk systems comes in all shapes and sizes
Not sure how to define a kiosk system, but it would perhaps be something like “a multimedia driven information booth with user interaction allowed”? Most kiosk systems run your application in full-screen, have a touch capable display(some also have keypad or a full keyboard). Occationally you spot some mouse devices, but that is typically “homebrew”. We can do better.
You really want as little exposed hardware as possible. A mouse just screams “please cut me, cut me now!” to any teenager within miles, and it wouldn’t last an hour at a public library or museum. So touch screens – preferably with a secondary protective layer (an extra plate of thin plastic to protect the screen) is the way to go for public service machines.
Ok, lets look at the demographic for potential customers. This is something you should always do before starting a new (commercial) project. You should also check out the competition and find and angle where you have the advantage, where you can compete. It can sometimes be as simple as good service, better docs or a more friendly user interface. There are a ton of really bad software out there that survives and sells just because their service department does an outstanding job. So don’t limit your thinking to purely technical excellence (like we programmers typically do). Look at it from all angles. Under-do the competition is a catch phrase coined by 37signals in their book Rework (a great book by the way); it simply means: make sure the basic functionality is extremely well made and solid. Focus on the basic functionality rather than playing catch-up with every new “thing” on the market.
Ok, here are some examples of where you would offer your services and sell your kiosk systems:
- Ticket booths for public offices
- Ticket booths for pharmacies
- Information booths for physicians and hospitals
- City bicycle rental
- Airport information stalls
- Museum info booth
- Library inventory booth
- Paint color-mixers for hardware stores
I could go on forever, there are thousands of potential customers.
Hardware
The hardware I am using is the Raspberry PI 3 model b. This is probably one of the most affordable embedded platforms you can buy. And model 3 packs quite a punch to be honest. You could buy one of the clones like the Banana PI (there is also an orange pi or whatever it’s called) and save a buck or two – but seriously: at $35 a pop for the original I would honestly not bother risking it. There are subtle incompatibilities between the clones and the real deal – so you could end up “saving the pennies while wasting the bills” as they say. The way to save money on hardware is to buy in bulk. End of story.

The fantastic Raspberry PI 3
Next, you need a touch screen. The size is naturally only limited by the size of the booth and your budget. For this article series I will be using a small 10″ form-factor. I can recommend a visit to AliExpress.com, never had any problems ordering from them. But stay away from Wish and Geek – these websites will lie, steal and sell their own grandmother just to make a buck. I have nothing but bad experienced with them (like never getting what you ordered). So stick with AliExpress or even better RS components.

Touch screens have become ridicules cheap lately
If you have $5 to spare, please buy a remote control. Being able to stop, restart or display an “admin panel” purely by clicking a button on a remote (that only you or your client have access to) will save you so much razzle. You don’t want to mess about with
Besides. Once you know how to code your own set-top-box like I’m showing you now, why not go all out and create your own movie player? Chrome can play pretty much everything out there – and you can get plugins for VLC. Plex eay your heart out!
I have actually had my own NAS running for quite some time now, coded completely in Smart Pascal. And believe you me, its much better than many of the commercial products I see out there. If you are interested in contracting me for projects, contact Quartex Components.
Anyways, what you can do with a remote control is only limited by your imagination. But above all it just looks cool. In fact, buy it because it looks cool and always have sunglasses on when you click the admin button.

This set me back a whopping $4 from Banggood.com!
Linux for HTML5?
But now you are thinking: Smart compiles for JavaScript, how the hell are we going to display that full-screen? Do we have to first load the Linux desktop and then manually start a browser?
The answere is: nope!
Our operative system will be a modified version of Debian, one especially tailored for full-screen, HTML5 kiosk displays. And it so happens that there are quite a few such distributions on the market. Most of them completely free as well. JavaScript is after all the leading programming language of our time. As much as 50% of all software being written on this planet right now, is written in JavaScript. We didn’t set out to create Smart Mobile Studio just for the hell of it, but rather because we knew this was going to happen all the way back in 2010. It was inevitable and the factors in the market (and socially) all pointed to the same.
For our Smart Pascal kiosk system we will be using FullPageOS which basically skips the whole desktop thingy and boots directly into Chrome in full-screen. No desktop, no “oh damn the user just minimized the browser window“, just chromium rendering our awesome code directly to the frame-buffer. But you still have Linux ticking away beneath the hood with all the perks and power that represents.
So jump over to Github and download the latest binaries here: FullPageOS. I have also setup a mirror over at Quartex Components. So should for some reason github spontaneously burst into flames, I got you covered!
Next, we will be modifying the distribution slightly. We want to start node.js as a service when the device starts. The easiest way of doing that is to install something called PM2, which also gives you clustering capabilities and drill-down analysis at the same time.
PM2 is node.js equivalent to Microsoft windows service console. It gives you the ability to define if a node.js program should run as a service, if it should be re-started on a crash, logging, distribution – and much more.
We will just be using the automatic restart feature in this tutorial, but I have to tell you, PM2 is a powerful piece of engineering capable of a lot more than that. The most important being that it adds clustering capabilities to your node.js programs if you need it.
If you tell PM2 to run your Smart Pascal server in cluster mode, it will utilize all the cores your CPU has to offer. This is imperative since the JavaScript virtual machine is single threaded, event driven and async by nature.
You can also setup a traditional network cluster, with X number of physical devices dealing with your payload, while a central server act as a dispatcher delegating tasks in good old round-robin style. And the best part? You don’t even have to change a single line of your code to use this. PM2 takes care of everything for you, clustering mode is just a command-line switch. Now that is awesome if you ask me.

PM2 makes clustering and process monitoring a snap. You can even check out the state of your back-end node processes remotely via a secondary fancy HTML5 dashboard
You can check out PM2 here: http://pm2.keymetrics.io/. We will be installing that after we have prototyped our server -because during development you want errors to surface so they can be fixed.
Smart Mobile Studio
Needless to say you are not in Kansas any more and Delphi is not really suited for this line of work. Object Pascal and C++ is great for a lot of things, from desktop applications to large-scale eco-systems. But for IOT the full might of Delphi or C++ builder is quite frankly overkill. In this part of the IT forest, python, node.js and bash rule supreme.
So whip out your trusty copy of Smart Mobile Studio and get ready to make those ARM cpu cores purr like a kitten!
The code thing
Since I work on the Smart Pascal RTL, we often have this problem where I blog about or demonstrate code that is not yet publicly available. The reason I blog about new features is naturally to show people what is going on, what they can expect from the next update and so forth.
For this project I will try to avoid non-released features as much as possible so everyone can execute and work with the code. But I will also include code from the new RTL whenever there are no options.
Just keep in mind that any RTL code is copyright. You are not allowed to use it without owning a proper license.
When this tutorial is done you will have a working kiosk system. What media or features you want to deliver is up to you, I’m just here to get you going 🙂
The architecture
Right! With the Linux distribution, node.js and PM2 taken care of, let’s look at the software architecture. What we are going to do is to divide our kiosk system into two parts. Two applications.
- A node.js server
- database access
- image and media serving
- filesystem access
- A visual smart mobile user interface
- Menu system
- User interaction
- Displaying information
- Fancy CSS3 effects
Node.js is very different from the browser JSVM. First of all it executes with the same level of access to the filesystem, network, pipes, threading etc. as a normal executable. It basically gives you the same features Freepascal or Delphi would give you. Node.js is not sandboxed like the browser’s JSVM is. There are no restriction on database size, file size or anything like that.
This means that by dividing our application architecture into two parts, we get to enjoy the best of both worlds. We will isolate any low-level stuff in our node.js server (and more importantly: access to the content our booth is going to display). So our visual application needs only care about presenting information and keeping a dialog going with the node.js backend.
By using Chromium as our browser we ensure that the rendering process makes use of the GPU, which is quite important for embedded devices. HTML5 is demanding and rendering it all via the CPU alone would, well, suck.
But our simple architecture allows us to put our application logic in the front-end, and then reduce our node.js backend to a simple command server, almost like a DLL or library. But with perks. Loads of perks.
This model also helps us to abstract the display from changes or updates to the back-end server. The display interface could not care less if you are using sqlite as your database or a $200.000 a month Oracle monster. It doesn’t need to know where the server obtains images, music or files. All it needs to know is the commands and response codes.
It also means we can fragment and do clustering. If you have, say, between 50-100 booths operating on the same network, we could in fact push the node.js server to a dedicated server machine. The clients running on the Raspberry PI wont know the difference. Nor would they care as long as they can connect and get the response they need.
Developing on Windows
Before we start assembling the parts and jousting with Linux, I want to teach you a little trick. When people get a Raspberry PI they tend to do changes to their in the worst possible way: Namely to either use a second USB stick to move files between their PC and the RPI, or (better) install samba so they can copy files over the network.

QEmu makes it a bit easier developing for the PI
Both solutions are “ok”, but they are time-consuming. And after having copied your Smart Mobile Studio compiled code over for the 78’th time, odds are your frustration level will be through the roof (yes we have all made this mistake at some point).
The trick is to run Raspbian on Windows through qemu. Just like you would run Windows or Linux through VMWare or similar products, you can actually do the same with Raspberry PI (although only model 2b is supported to my knowledge).
You can download the whole system image from Sourceforge here:
https://sourceforge.net/projects/rpiqemuwindows/
Alternatively, I did a mirror of the distribution and you can download that from Quartex Components, right here (but please use Sourceforge first, this link is only for emergencies like if the owner is kidnapped by aliens or moves to Tibet where he intends to live as a goat or something): QuartexHub-Public
Once downloaded, just unzip to whatever location you like.
Notice the run.bat file? This simply starts qemu for ARM and loads the operative system disk image. The disk image is stored inside the qemu folder, cleverly disguised as:
2012-07-15-wheezy-raspbian.img
Here is the full file-list inside the folder. You don’t have to understand or know what this is to use it. Once inside Raspbian you can install Samba (google it, its out of scope for this article to explain) so you can share files between your Windows host and the QEMU Linux installation.
Homework

No I didnt see you playing with your websockets again SIR!
In the next installment of this article series we will create a websocket server for nodejs and a then use the websocket client in the VJL (the Smart Pascal run-time library) to communicate with it.
We will be sending whole objects over the wire, which sounds very complex and hard, but it’s almost a one-liner under Smart. All JavaScript objects can be serialized to JSON and un-serialized back to an instance on the other side, so this is a piece of cake.
The main job will be to establish a simple, fast, lightweight ASYNC protocol that ensures a snappy and responsive user-interface.
We will also dig into TFileStream which is exclusive for node.js and last but not least, use SQLite for our database needs (Raspberry PI is an embedded system after all, so resources are sparse).
When the coding is done we will perform the required changes to the Linux distribution, hook up the hardware and feel the thrill of having constructed our very own remote-controlled kiosk system!
Your homework assignment is to install node.js on your Windows PC, create a new node.js project in Smart Mobile Studio and look at the API units. You will find the node.js API units under $RTL\NodeJS\ (check links created by our installer in the start-menu program group).
In the next update of Smart Mobile Studio you will have plenty of high-level classes dealing with all that low-level stuff. But getting to know the classes and datastructures node.js expose beneath it all is very useful. It will help you build better node.js servers later on.
Have a good weekend!
Apparently I am the devil
This has been quite a week for me. Apparently my post on C# hit a nerve and I have so far gotten around 34 hate-mails. That’s a first even for me. I have been out a rainy day before as we say in Norway, but hate mail over programming? If facts hurt you that much then please seek professional help. With great haste I might add.
Jon is the devil
But the biggest shock was getting a phone-call today. From a friend of mine who runs a Delphi company. They have recently started to use Smart Mobile Studio for some light mobile clients, projects where Delphi would be overkill or to demanding.
A while back he hired a guy from the FPC / Lazarus team (both products that I love by the way!). When this coder, who shall remain anonymous, found out I was a personal friend on Facebook — he bloody went and quit his job!

Just way to go! Group-hug, starbucks on the house and pat on the back
Apparently he could not find it in his heart to work for a company that regarded me as a friend. Because, in his words, I was lucifer himself. Why? Because I pose (in this deranged individual’s mind) a threat to Freepascal and all the work they had done.
I’m not sure what to even respond to this. My natural instinct is to lay down on the floor and laugh until I cant feel my legs, but at the same time I feel a bit sad. Sad that grown men, adults, people who probably pretend to be role models for their kids, can even do shit like this.
That FPC forum again
The freepascal community is widely known as the most unfriendly community in the history of mankind, but this particular case really is the mother-load of insanity. We are bordering on fundamentalism here. You are one AK-47 away from being the first hands on pascal terrorist. With a manifest written in pascal of course. Death to the JavaScript infidels! Node.js must die! Did you see the fangs when Jon smiled? He’s a witch!
Sadly, my involvement with Freepascal and Lazarus is insignificant at best. But they dont like people who hit back when bullied, and this has festered into the conspiracy nutters they represent today.
I once had plans to help freepascal by writing an alternative IDE. Something roughly 100+ other developers also wanted by the way. I also helped out by submitting code to get special folders on Windows, Linux and Unix through a common set of functions. And that’s about the extent to my involvement with their codebase.

Quartex IDE uses both smsc and fpc as its compiler. I never finished it because the fpc guys were utter nutballs about it. But it works, and it works very well!
I also warned them, together with two others, both respected members of the Delphi community, that a popular fork of Lazarus was breaking every possible GPL rule known to mankind (!) — And I did this in order to protect Lazarus/fpc from getting caught in the middle of a potential lawsuit.
If protecting Lazarus from harm is a diabolical, hellish act of evil – then I guess am guilty as charged. And I would do it again because Freepascal and Lazarus deserves to be protected. It is a cornerstone of the pascal community. It’s only so damn sad that many of its representatives (especially the self-proclaimed ones who couldn’t code a compiler if their life depended on it) practically molest and insult new users for no good reason. So much so that people avoid FPC and Lazarus because of it.

I heard he said that she said that maybe he meant that .. oh for the love of god pick up the phone and get the facts!
But people quitting their job because I supposedly am Lucifer incarnate, that’s a new high. Or low, or whatever comes natural. Coming face to face with mental illness on this scale is new to me, so I need some time to digest this.
But dude, seek help. Professional help. Call your doctor and get a huge glass of Valium, take two pills and contemplate every possible meaning of the phrase “social refactoring“.
You need to set some serious break points in your reasoning. Because quitting your day job over a misunderstanding on a web-forum, that my friend is reason in ruin.
You see, if I was full of shit; If I produced crap code, or indeed – if my predictions and analysis of trends were wrong (which they rarely are) – then you could sink me quite easily. But when that is not the case, when in fact I write pretty good code, when I share my knowledge and help people the best I can, when I keep up to date and invest back in the community I love so much; then the situation is very different.
You will discover that I can bite back and be just as nasty as you. But I choose not to, because you don’t treat people like that. If growing up has a perk it’s that you understand the value of kindness and companionship, of community and helping each other.
So why not solve this like a civilized, normal human being? just ask. Give me a call, get the facts. Dont sit there like a 14-year-old girl and base your assumptions on rumors. If in doubt, just call me up and ask. Then we can put whatever misunderstanding there may be to rest. You might even discover that I’m actually a nice guy!
Now back to the Delphi community where people are friendly, positive, creative and easy going!
require.js for Smart Pascal
I guess it had to happen. And why not? If you don’t know what require.js is then you can read up on it here: http://requirejs.org/ and also check out their repo on github. I’ll show you how to get this going for Smart Mobile Studio.
Require.js
Ever looked at a node.js program? Notice how they always start with require? It’s just all over the place. Well fret ye not, it’s basically node’s equivalent of pascal’s uses. Except, it also deals with code modularization, resolving dependencies and file-loading at the same time.
I don’t know what’s up with these JS developers. Brilliant coders and I love them for it, but they have this tendency to just stuff everything under the sun including the kitchen sink into a single package. This is what happens when they replace C and Pascal at universities around the world 🙂
require.js can be divided into 4 aspects:
- Defining dependencies that must be in place before a piece of code executes
- Loading JavaScript files en-mass and getting a nice callback when the files are ready
- Loading of code modules, ala DLL files in a clever way
- Support for plugins, there is a whole bunch available (check the website)
Loading JavaScript files en-mass
To be honest the VJL already have this. It’s been a part of our RTL for ages now. If you look at the unit SmartCL.FileUtils.pas you will find a class called TW3Storage sporting routines for loading not just scripts -but images, text-files, sound files, XML and even CSS. So in your face require.js! Ha!
It has the following interface:
TW3Storage = static class public class procedure LoadXML(aFilename:String; const OnComplete:TW3XMLDataReadyEvent); class procedure LoadFile(aFilename:String; const OnComplete:TW3TextDataReadyEvent);overload; class procedure LoadFile(aFilename:String; const OnComplete:TW3StreamDataReadyEvent);overload; class function LoadCSS(const aRel,aHref:String; const OnComplete:TProcedureRef):THandle;overload; class function LoadCSS(const aRel,aHref:String):THandle;overload; class Procedure LoadScript(aFilename:String; const OnComplete:TProcedureRef);overload; class procedure LoadScript(aFilename:String);overload; class function LoadImage(aFilename:String; const OnComplete:TProcedureRef):THandle;overload; class function LoadImage(aFilename:String):THandle;overload; (* This function is for batch-loading an array of images. The callback will be invoked when all images are successfully loaded *) class Procedure BatchLoadImages(aFileNames:TStrArray; const OnComplete:TProcedureRef); End;
So we have little need for require.js when it comes to loading files. There is actually very little require.js (on the surface) has to offer the Smart RTL. Having said that – require.js is not just about loading files. It also deals with module declarations and dependencies when loading these – which is what a Delphi programmer would call a DLL file.
So I think it’s wise to include it for the future, because pure JS libraries is something we will be adding to the codegen later. I wont set a date for it, but I have already added quite a bit to the codegen.
As a bonus, the keyword “require” is already marked as a reserved keyword for node.js, so the syntax highlighter in Smart Mobile Studio (im testing this on version 2.2.1.4542 which is older than the current release) will highlight the keyword as an intrinsic procedure in SmartCL based projects as well. Neat and fits like a glove!

Require is a reserved word in node.js
Right. Loading files is well and dandy, but what about the modules? I havent really bothered with that just yet. It’s there, and it shouldnt be to hard for a crafty Smart coder to complete it, but I want it to remain dormant until we have time to make it an integral part of Smart. No point in adding something super-cool and just expose it in the IDE. And we have our work cut out for us as it is (!) So let’s finish the backlog before we start with the DLL standard.
Also, Smart is package based just like Delphi and Lazarus, so the whole JavaScript “module” system is a bit of a mess really. It works, but elegant is not a word I’ll use to describe some of the JavaScript solutions out there.
You want it now? Ok, here you go!
Yes, this time you can actually get it now. I have written the wrapper in such a way that you can just download require.js, stuff it in a library, then add a unit to your RTL folder. I know I have irritated you with all these previews. Since this unit have no special dependencies you can assemble it in 10 minutes or less.
Click here to download both the test project and the library files if you don’t want to follow the tutorial.
First, download require.js and put that in the $root\libraries folder. like this ([D] = Directory, [F] = file):
- [D] Libraries
- [D] Require.js
- [F] require.js
- [D] Require.js

You want the minified version so click that
For simplicity just rename the JavaScript file “require.js”, then create a text file in the same folder with the download url and the version number. That way you can keep track of the version when you update in the future.
Now let’s write some pascal to make this puppy conform to our way of doing things! But always remember, this file works with the document object model (DOM) and must never be used in a node.js application. Node has its own version of require(). So this belongs in SmartCL namespace and visual applications only (!).
Note: Normally I would urge you to save this file to the RTL folder, but that is quite risky. The RTL folder is under the control of our automatic update program (see license) and as such it can be deleted or replaced without further notice.
To avoid any changes you make being erased, place it side-by-side with the pascal file in $Libraries\require.js\SmartCL.Require.pas. Just saying.
Note: This file is copyright, but if you own Smart Mobile Studio you have the right to use it in your projects. If not, visit www.smartmobilestudio.com for licensing options.
{ **************************************************************************** } { } { Smart Mobile Studio - Runtime Library } { } { Copyright (c) The Smart Company AS. All rights reserved. } { } { **************************************************************************** } unit SmartCL.Require; interface uses W3C.DOM, System.Types, system.reader; type EW3RequireJS = class(EW3Exception); TW3RequireError = class external (JDomError) public property columnNumber: integer; property lineNumber: integer; property fileName: string; property message: string; property name: string; property stack: TStrArray; property requireType: string; property requireModules: TStrArray; end; TW3RequireErrHandler = procedure (err: TW3RequireError); TW3RequireJSConfig = class external "requirejs.config" property enforceDefine: boolean; property baseUrl: string; property paths[name: string]: variant; property waitSeconds: integer; end; TW3RequireJS = class external "requirejs" property config: TW3RequireJSConfig; property onError: TW3RequireErrHandler; end; function Require: TW3RequireJS; overload; procedure Require(Files: TStrArray); overload; procedure Require(Files: TStrArray; const Success: TProcedureRef); overload; procedure Require(Files: TStrArray; const Success: TProcedureRef; const Failure: TW3RequireErrHandler); overload; implementation {$R "require.js"} function Require: TW3RequireJS; begin try asm @result = require; end; except on e: exception do raise EW3RequireJS.Create({$I %FUNCTION%}, nil, e.message); end; end; procedure Require(Files: Array of string); begin try asm require(@files); end; except on e: exception do raise EW3RequireJS.Create({$I %FUNCTION%}, nil, e.message); end; end; procedure Require(Files: TStrArray; const Success: TProcedureRef); begin try asm require(@Files, @Success); end; except on e: exception do raise EW3RequireJS.Create({$I %FUNCTION%}, nil, e.message); end; end; procedure Require(Files: TStrArray; const Success: TProcedureRef; const Failure: TW3RequireErrHandler); begin try asm require(@Files, @Success, @Failure); end; except on e: exception do raise EW3RequireJS.Create({$I %FUNCTION%}, nil, e.message); end; end; initialization begin // When you compile a smart program, it will copy all files imported with // the $R compiler define, these will be stored in the $AppName/Res folder // and are loaded automatically. // Since that is the place you want to store other scripts as well, we // create an alias for the location. So $scripts will always point to // that path. You can add as many aliases you wish require.config.enforceDefine := false; require.config.paths['$scripts'] := '/res/'; end; end.
Now save this as described above and give it a testdrive!
Start a new visual project, save the project before you start coding (important!)
Add a button, save once more (I know, I know.. this is being fixed now. I hate that bug so much). Double click the button in the designer, then add this:
procedure TForm1.W3Button1Click(Sender: TObject); begin require(["https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"], procedure () begin showmessage("JQuery loaded"); end); end;
The above code will load jQuery (latest build) from google’s public API server. To make sure that everything went ok, click the “devtools” button in the Smart display browser and investigate:
Note: JQuery is here just used as an example. You have absolutely no need for it under Smart, because the way visual controls work in the VJL a control always knows it’s childrens handles. So searching (hence the “query” in jquery) for tags and groups of elements have little meaning for object pascal in the browser. It already knows its children and have direct access to them. So no querying required.
Well — enjoy!
Smart codecs, a draft
When you hear the word codec, what comes to your mind? For me I get flashbacks to early 2000’s when I worked in visual C++ and Visual Basic on a huge media project. ActiveX was a total cluster fu**, with a proverbial vipers nest of interfaces, vague explanations and more blue-screens than i care to remember.
Working on the RTL for Smart Mobile Studio has forced me to learn a lot of topics that I would, had I chosen not to go down the JavaScript rabbit hole, never have given a second thought. And I have now reached the point where codecs is starting to make more and more sense for the RTL. Let me explain why.
Codec is just short for “encode decode”, and a codec represents just an isolated ability to encode or decode a piece of data. If you have followed the evolution of Smart Mobile Studio and know your way around the RTL – you must have noticed that we have a fair bit of duplicate code hanging around. So far I have found two wildly different CRC implementations, a sexy and fast RC4 encryption routine, RLE compression, URL encoding, Base64 encoding, UTF8 encoding .. the list goes on.
All of these routines, no matter how small or large they may be, does the exact same thing: they encode or decode a piece of data. So you input one type of data and you get something else back.
Part of our RTL update is not just about adding cool new features, it’s also about order, cleaning up and getting the RTL into a form that is better suited for the future. I have already blogged about namespaces and the important role they play in the next version of Smart Mobile Studio. Well, I think its time to put our encoding/decoding capabilities into order as well.
Smart codecs
The first challenge that comes to mind when you sit down to create a codec framework, is the data formats you have to deal with. I mean, what is the point of a codec class if its only capable of processing strings right? And since Smart has all these cool mediums to play with, like streams, buffers and untyped arrays, we want each codec to support as many such input and output types as possible.
This is where things get’s complicated and the critique I dished out to Microsoft ages ago comes back to haunt me. Because I now see why their codec system had to be so elaborate.
I mean, lets say you have a URL codec. It exists to take strings and replace characters that could be filtered out by the locale on another pc – so all it does is to replace these characters with a %charcode representation. That way the text can be re-mapped on the other side safely.
For a codec designed to process this type of data, you would have to define an input channel that can deal with text – as well as an output channel of the same type. But what if you want the output as a stream or memory buffer? Suddenly input and output gates become more complex, more fluid and data-dependent.
IBinaryTransport to the rescue
In the last update I did something magical. So magical in fact that I was oblivious to the fact that that I had just solved the problem of data mitigation. It was a 2 second mistake that turned out to be a stroke of genius (which I can’t take credit for, because I had no idea I was being genius at the time).
IBinaryTransport is just a super simple interface that gives you info about how much data is available, a reading method and a writing method, and finally the position of the read/write cursor. It’s stupendously simple, yet solves so many problems:
IBinaryTransport = Interface function DataOffset: integer; function DataGetSize: integer; function DataRead(const Offset: integer; const ByteCount: integer): TByteArray; procedure DataWrite(const Offset: integer; const Bytes: TByteArray); end;
What I did was to add this interface to both TStream, TAllocation and TBinaryData. I figured it would be handy when calling ToStream() and similar helper functions. But it turned out that with this interface in place – I could throw out TStreamReader, TStreamWriter, TBufferReader, TBufferwriter – and just write a single reader/writer class. TStreamReader actually doesnt have a clue what a stream is, because it speaks to the target via IBinaryTransport.
Same with TReader and TWriter for TBinaryData (memory buffer). They don’t know anything about memory at all, they just know how to communicate with the target through IBinaryTransport.
So how does this affect codecs? It means we can throw out the older model completely. Instead of having to define a whole list of input/output channels, add support for dealing with each of them — all we have to do is make the input and output channels IBinaryTransport (!)
This reduces the basic codec class to this:
TCustomCodec = class(TObject, ICodecBinding, ICodecProcess ) private FBindings: TCodecBindingList; FCodecInfo: TCodecInfo; protected /* IMPLEMENTS :: ICodecBinding */ procedure RegisterBinding(const Binding: TCodecBinding); procedure UnRegisterBinding(const Binding: TCodecBinding); protected /* IMPLEMENTS :: ICodecBinding */ procedure Encode(const Source: IBinaryTransport; const Target: IBinaryTransport); virtual; abstract; procedure Decode(const Source: IBinaryTransport; const Target: IBinaryTransport); virtual; abstract; protected function MakeCodecInfo: TCodecInfo; virtual; public property Info: TCodecInfo read FCodecInfo; constructor Create;virtual; destructor Destroy;Override; end;
And the work you have to do implementing a new codec to this:
TURLCodec = class(TCustomCodec) protected (* IMPLEMENTS :: ICodecProcess *) procedure Encode(const Source: IBinaryTransport; const Target: IBinaryTransport); override; procedure Decode(const Source: IBinaryTransport; const Target: IBinaryTransport); override; protected function MakeCodecInfo: TCodecInfo; override; end;
Using a codec
A codec should never be used directly, but via proxy. This gives the framework a chance to create instances on demand, and also makes sure you don’t compile in codecs you never use. A few basic codec classes will be registered when your application starts – but these have always been compiled with your Smart application so there is little or no difference with regards to size or speed.
The benefits however are great: all codecs register with a central manager, they also register their mime-type (the format they work on), making it possible for you to query the codec-manager if it supports a specific encoding/decoding mechanism.
And naturally, it gives us uniformity with regards to data processing.
Here is an example of using the codec-api to URL encode a string:
var LBinding: TCodecBinding; LList: TCodecList; LSource: TStream; LTarget: TStream; LReader: TReader; LWriter: TWriter; begin if CodecManager.QueryByName('url', LList) then begin LSource := TMemoryStream.Create; try LTarget := TMemoryStream.Create; try LWriter := TWriter.Create(LSource as IBinaryTransport); try LWriter.Options := [woEmulateCursor, woFlexibleBoundaries]; LWriter.write( TDataType.StringToBytes("This is a string ready for URL-encoding!") ); finally LWriter.free; end; LSource.position := 0; LBinding := TCodecBinding.Create(LList[0]); try LBinding.Input := LSource as IBinaryTransport; LBinding.Output := LTarget as IBinaryTransport; LBinding.Encode(); finally LBinding.free; end; LTarget.position := 0; LReader := TReader.Create(LTarget as IBinaryTransport); try var LBytes := LReader.Read(LTarget.Size); writeln( TDataType.bytesToString(LBytes) ); finally LReader.free; end; finally LTarget.free; end; finally LSource.free; end; end;
The cool part here is that the data can be anything. The source can be a stream, a buffer, a memory allocation – even a socket (!) Same with the target. As long as the target object implements IBinaryTransport the codecs will do their bussiness regardless of medium.
URL, Base64, UTF8, UTF16 .. and encryption ciphers naturally .. all these processes can now be represented under a single, efficient and small framework. And yes, there will naturally be top-level functions for these, same as before. I don’t expect people to write all of this every time they need to URL encode a string.
The point here is depth, and that Smart Mobile Studio applications can now do more and more of what you would expect from a native compiled system.
Websocket, WebSocket.io and Socket.io
Wow. Thats is a mouthfull isn’t it? Websocket, websocket.io and socket.io. So what is that all about?
In short, im finishing off the server units for Smart Mobile Studio! And I think people are going to be super pleased and happy about this one.
As you may know, node.js gives your JavaScript more or less the same functionality as classical programming languages. You get to work with sockets, talk to databases, implement protocols – all of it in JavaScript and all of it capable of doing exactly what we are doing in Delphi. That is pretty neat!
But that also means someone has to expose the node.js functionality in pascal form and then write thin wrappers around that. This is where Smart Mobile Studio really shines, because after six years of constant development – we have built up a very powerful codebase. Smart mobile studio is not just about compiling to JavaScript. There are 10-20 compilers out there doing that. Nope, the power of smart mobile studio is in the infrastructure we have painstakingly constructed for our customers. Hundreds of hand-written classes, units and library files. Add to that our cosy little IDE which is very nice to work with and the advantages starts piling up.
Servers, glorious node.js servers
So whats on the menu? A lot! More than I actually thought we would add in the next update. Here is a list of the server types you will be getting:
- http server
- websocket server
- tcp/ip server
- socket.io server
- websocket.io server
To explain the differences:
Websocket is a full-duplex communication stack that allows both client and server to talk; at the same time. It also contains fancy commands for emitting messages to all connected clients, and likewise a client can commit messages to other clients (if the server allows it). You can send both text messages and binary messages. And the cool part is that the websocket engine will collect the data, deal with net-frames and spare you all the razzle you would otherwise have to do.
On top of this we have something called socket.io. This takes the whole thing one step further, allowing you to define a set of commands on the server (by name), and associate that with the code to execute when such a command is received. Socket.io also come in client-form for both browser and node.js itself. And just like the server edition you can define a set of commands for the client as well. This moves websocket into the realm of real-time messaging, where rather than wasting days and weeks coding your own protocol, you can kick back and flesh out your command-set much in the way RemObjects SDK does. Socket.io also contains clustering mechanics, but I wont cover that just yet.
Websocket.io is sort of third option. It’s basically websocket and socket.io glued together. You don’t have to upgrade the http socket (read up on websocket if you have no clue what that means) if you don’t want to. Websocket.io gives you pretty much exactly the same as websocket + socket.io, but from a unified API. And to be honest this is the library I use the most myself.
So long story short: you get 3 websocket based server classes to play with, all of them inheriting from TNJCustomServer, so you use the same code to work with all servers. And the speed is phenomenal! I have to pinch myself sometimes just to remember that this is kick-ass javascript running the show.
If you think websocket is “communication with training wheels” (I don’t, I frikkin love it) then a raw TCP server is probably your cup of tea. This is a perfect class to use if you need to port over some old Delphi code, if you for some reason hate XML or JSON – or perhaps you just want to dump over raw binary data as quickly as possible. Either way: it’s there, and it works brilliantly.
As you would expect I’m also doing the client side of things. We have supported websocket out of the box for a while now, and I just added a socket.io client to the codebase. I have a few alternatives to try out on the raw tcp stuff, but ultimately tcp is now allowed for HTML5. But a client and server for node.js is ofcourse on the menu.
Benefits
It’s when I sit and work with the codebase like I do now that I see just how much cool stuff we have. When doing research on a library, how to best wrap or implement it in our RTL, I naturally come across hundreds of comments by JavaScript programmers. Things like allocating memory, copying data from one buffer to the next, working with bytes and bits — a lot of these guys are having a really hard time doing classical programming.
But for Smart Pascal that’s not even an issue. We have supported memory allocation, blue-pointers and even a threading model for quite some time now. Yes, threading. Check your RTL folder and you will find it 🙂 It goes without saying that when you have memory streams, file streams, raw buffer classes, stacks, queues and proper inheritance that smart pascal gives you more than just a head-start. The benefits are astronomical in places.
And no, im not just blowing my own horn here — I use Smart Mobile Studio to create services and mobile applications on a daily basis. So I am painfully aware of what we did wrong, but also what we did right. And thankfully we got more right than wrong.
Try out HexLicense in your browser
If you head over to HexLicense.com you will find both the roadmap for 2016 and beyond – but also that you can now testdrive HexLicense in your browser (!) That is pretty cool if I say so myself.
In the browser?
Hexlicense consists of two parts: the first is the generation process where you mint license numbers. These numbers have some nifty criteria attached to them, like being able to verify that they have indeed been minted using a root-key, that they evolve and mutate in a non-linear fashion and naturally: they should obfuscate as much as possible.
The second part is the validation process. This is where the customer inputs the serial number he received when he bought your software. Under Delphi you validate such keys inside your Delphi program via the THexLicense component. In the future you will be able to do this via the HexLicense server system as well, which makes is going to make your life as a developer a lot easier.
HexLicense for Smart Mobile Studio covers both aspects, so you can perform the minting and validation. The code is so universal that it will run on your node.js server, in your visual applications – most of the code is actually shared between Delphi and Smart Mobile Studio.
Note: The demo of HexLicense running in your browser is just for educational purposes. It demonstrates that Smart Mobile Studio is capable of some very nifty things. And it also demonstrates the speed and flexibility of HexLicense.
Hexlicense 1.0.1 for VCL is shipping
HexLicense v1.0.1 has now started shipping to customers! And hot on the heels of the VCL implementation comes the FMX version (due shortly).
![HexLicense test running on Android [FMX]](https://jonlennartaasenden.files.wordpress.com/2016/10/hex_03.png?w=319&h=340)
HexLicense test running on Android [FMX]
Head over to www.hexlicense.com and grab your copy while the 40% discount is on!
What up next?
While focus is on finalizing the FMX platform, the server edition is also being worked on.
You will be happy to know that it’s going to be a low-latency websocket client/server solution. This means your products can validate their licenses from HTML5, node.js, Delphi, FPC, C#, C++ or any language that supports ordinary websocket.
Two servers
Two versions of the server is planned: one native win32/64, and one node.js server written in Smart Mobile Studio. The native version uses the ZeosDB library giving you a rich set of options for what database you want to use. By default it uses sqlite which is more than enough for handling <500.000 licenses. However the pro edition will use mysql embedded for maximum performance.

The websocket prototype is already in the making
The node.js edition enoys the full onslaught of node modules for data storage. Be it clound managed through Amazon or Azure – or a more humble, local sqlite database. You pick what is best for you and your product.
More ciphers, more encryption and more tools! Head over to hexlicense and check it out
You must be logged in to post a comment.