Keeping an Application Alive

I recently was working on a project in which, among other things, there needed to be a process that would restart the application should it ever be terminated for no reason. This isn’t unusual for kiosk applications where the only UI that the user will be able to get to is a single application running on the system. This isn’t an unusual need and something for which we had a utility that could do this; we generally refer to these as “Kiosk Application Monitors.”  But I decided not to use it. Why not? Because when developing it is a pain to deal with an app that isn’t easily killed. If I manually terminated the application it would almost immediately restart; this was a behaviour that was by design. When I really wanted the application to terminate and stay that way things were more challenging. This had to be done from the task manager and the task manager wasn’t easily accessible since the KIOSK app ran as always on top. To see the task manager I would first have to kill the app. But if the app were killed it would just restart.

Not wanting to deal with the difficulty of this I made a new a Kiosk Application Monitor (hereon referred to as KAM). While I would generally prefer to make utilities in C# I used C for this; I was going to be using Win32 APIs and it is easier to have direct access to them instead of  writing P/Invoking declarations for them.

The key difference in this KAM and the other ones that we had used was that this KAM could be terminated through keystrokes. It adds a keyboard hook that receives every keystroke that a user makes no matter what application.

Termination on Detecting Safe Word

I’ve got a variable named SafeWord that contains the word that when typed will kill all of the child processes and shut down the KAM. To better insulate the app from an accidental activation I’ve mandated that the escape key be pressed before the safe word and the enter key be pressed immediately after the safe word.  The keyboard hook receives the virtual key codes for the keys pressed. The code for escape (0x1b) and enter (0x0d) are both used directly within the source code.   Any other key press will be will be ignored until the escape key has been pressed, and will be checked for a match to the safe word. At the first mismatch the procedure will stop comparing until the escape key is pressed again. When the enter key is pressed the routine checks if the end of the safe word has been reached. If it has then the user has typed the same word; the routine to terminate the child processes is called.

keyboardHook

They keyboard routine is a small part in what this does, but a real time saver for me.

Allowing Only One Instance

I didn’t want more than one instance of this program ever running on the same machine. The way I managed that is pretty usual for Win32 programs; I used a named event to ensure there is a single instance. Named events are shared across programs. After creating one (with CreateEvent ) calling the GetLastError() function afterwords indicates whether or not this is the only instance of an application that has access to the event or if another program already has an instance of an event by the same name. When another instance has already created one GetLastError returns ERROR_ALREADY_EXISTS.

SingleInstance

Process Description and Start-Up

Moving from the ancillary functionality to the core functionality, I decided to use JSON for specifying information on the processes that should be started and watched. The C++ libraries do no intrinsically support JSON data handling. I used a third party library for this. The data in the JSON is used to populate a structure that gives very basic information on the process to be monitored.

Structure

Most of these values are passed directly to the Win32 function CreateFunction. Ignore is there so that I could disable a process without completely removing it from my configuration file. For each process that I’m going to start I create a new thread to monitor it.

CreateThreads

Most of the code within the CreateWatchedProcess function will run within an infinite loop. The process is created and information about it is populated into a PROCESS_INFORMATION variable (which I have named pi). The value of interest for the KAM is pi.hProcess. This is the process handle. The wait functions in the Win32 API can accept handles processes. In the case of WaitForSingleObject passing a process handle will block the calling thread until the process terminates.  There is nothing that my program has to do for detecting the termination of the process. When the next line after WaitForSingleObject executes we know the process has been terminated. The only question is if it was terminated because there was a request for the KAM to shut down or if this were an unexpected .

processLoop

How Did it Perform

In testing things worked fine. I’d intentionally put a bug in the program of interest that would cause it to crash and the KAM restarted it. The app I was using it with also remembered it’s state and could restore the UI to what it was before. From the perspective of the user the screen flashed but was otherwise normal. When I tried the same utility in the production environment I’m happy to say that its full functionality was not exercised; the program it was monitoring never crashed.

I’ve found the program to be useful and see some opportunities to increase it’s utility. I plan to make updates to it to support things such as starting processes in a specific order, monitoring the message pump of another process to detect lock conditions, and allowing the utility to accept or transmit process information over a network connection.

Advertisements

Raspberry Pi 4 Announced

Raspberry Pi 4
Raspberry Pi 4

The fourth generation of the Raspberry Pi has been announced. Each generation of the Raspberry Pi is primarily identified by its specifications. (Not including the Raspberry Pi Compute module because it generally is not used by hobbyist). With the Raspberry Pi 4, this isn’t the case. There are three variations available. The new Raspberry Pi 4 comes with a 1.5 GHz ARM Cortex-A72 quad-core processor.  With that processor the Raspberry Pi 4 can decode 4K video at 60 FPS or two 4K videos at 30 FPS. The amount of RAM available to the unit depends on the version. The smallest amount of RAM, 1 gig, is available for $35 USD. The next size, 2 gigs, can be purchased for $45 USD. The largest unit, 4 gigs, is $55 USD.

At first glance, the unit will be recognized as a Raspberry PI but a closer look at the ports will show some immediate differences. The Pi has converted from a micro-USB port to USB-C. The full sized HDMI port is gone and has been replaced with two micro-HDMI ports. The unit can drive two displays at once.  A couple of the 4 USB ports have been upgraded to USB 3 while the other two are still USB 2. The wireless capabilities are upgraded to use USB 5.0 and dual-band 802.11ac Wi-Fi.

 

The unit is available for purchase from Raspberry Pi’s site now.  A new case for the Pi 4 and a USB-C power supply of appropriate wattage are both available through the site as well.

 

https://www.raspberrypi.org/products/raspberry-pi-4-model-b/

 

Rotation Notations

I was writing some code to perform some celestial calculations.  A lot of it handled changes in positions from certain rotations (orbits, revolutions).  There are also instances where time is treated as a rotation (ex: 1 hour of rotation is 15 degrees).  The best notation for the rotation depends on what is being done.  Here are the rotation notations that might be used.

  • Radians
  • Degrees
    • Decimal Degrees
    • Degrees, Minutes, Seconds
  • Hours
    • Decimal Hours
    • Hours, Minutes, Seconds

Conversion from one to another is easy.  What I did find challenging is ensuring that the right conversion had been performed before working with it.  The trig functions expect to always receive radians.  More than once I made the mistake of converting to the wrong unit before performing a calculation.  Rather then continue forward on a path that has many opportunities for mistakes I made a single class to represent rotations that can be used in various scenarios.  It will always internally represent rotations in degrees.  If I want to explicitly convert the class to a specific type there are methods to explicitly convert to any of the other rotation types.

Instances of this custom type also can be assigned a preferred notation. This preferred notation is used when printing it to the output stream. This allows a preferred format to be assigned without risking making any conversion mistakes.

The interface for the class and the support class follows.

#include <stdio.h>
#include <cmath>
#include <iostream>

typedef double Degree;
typedef double  Hour;
typedef double Minute;
typedef double Second;
typedef double Radian;

enum RotationNotation {
    NOTATION_DEGREES, 
    NOTATION_DMS, 
    NOTATION_HOURS, 
    NOTATION_HMS, 
    NOTATION_RADIANS
};

class Rotation;

struct HMS {
    Hour H;
    Minute M;
    Second S;
};


struct DMS {
    Degree D;
    Minute M;
    Second S;
} ;

std::ostream& operator << (std::ostream& o, const HMS& h);
std::ostream& operator << (std::ostream& o, const DMS& d);
std::ostream& operator << (std::ostream& o, const Rotation a);


double sin(const Rotation& source);
double cos(const Rotation& source);

Hour RadToHour(const Radian );
Hour HMSToHour(const HMS& hms);
Hour DMSToHour(const DMS&);
Hour DegToHour(const Degree degrees);

DMS RadToDMS(const Radian);
DMS DegToDMS(const Degree degrees);
DMS HourToDMS(const Hour hour);
DMS HMSToDMS(const HMS&);

HMS RadToHMS(const Radian);
HMS DegToHMS(const Degree degrees);
HMS DMSToHMS(const DMS&);
HMS HourToHMS(const Hour);

Degree RadToDeg(const Radian);
Degree DMSToDeg(const DMS& );
Degree HMSToDeg(const HMS&);
Degree HourToDeg(const Hour hour);

Radian HourToRad(const Hour);
Radian HMSToRad(const HMS& );
Radian DMSToRad(const DMS& );
Radian DegToRad(const Degree);


class Rotation { 
    private:
        Degree _degrees;
        RotationNotation _notation;
    public:
        Rotation();
        Rotation(const Rotation& source);
        
        RotationNotation getNotation() const;
        void setNotation(RotationNotation);

        const Degree getDegrees() const;
        const Hour getHours() const ;
        const Minute getRadians() const ;
        const DMS getDMS() const ;
        const HMS getHMS() const ;


        void setDegrees(const Degree degree) ;
        void setHours(const Hour hour)  ;
        void setRadians(const Radian rad)  ;
        void setDMS(const DMS& dms)  ;
        void setHMS(const HMS& hms)  ;
};

Download Code 2.0 KB

-30-

What’s In My Bag? Windows To Go: Windows on USB

When I’m travelling for work there are a number of items that I make sure are in my travel bag.  These include a USB-C charger (almost all of my electronics can charge over USB-C now); a copy of any recent projects I’ve worked on (sometimes I need to hop in to help a team member); and a computer.

The operating system on that computer may vary.  Sometimes I travel with a Windows machine, sometimes a Linux machine, and other times a Mac.  Regardless of the operating system, I usually always have a Windows To Go drive.

The last item is something that is probably a little more obscure.  Since Windows 8, there have been a special type of USB drives that are different in one aspect: they appear as a fixed drive to the computer, even though they are connected to a USB port.  These drives were specifically made for making a portable Windows experience on a USB drive.

It is possible to make bootable Windows environments on other USB drive, but there are some differences.  If you have a Windows ISO you can make a bootable Windows USB drive with a number of tools.  I recommend using Rufus to make the drive.  Though there are other options (including one that is a part of Windows Enterprise Edition), Rufus doesn’t care much about the drive properties.  It will just write the data to the drive in a bootable format.

With any type of USB drive you’ll be able to boot up with little to no trouble and do initial setup on the drive.  The difference will show up when you start installing programs.  Some programs will only install to a fixed drive.  Visual Studio is one such program.  If you have a USB drive that isn’t Windows To Go certified, then chances are that it will appear as a removable drive to the computer.  Visual Studio will not install to a removable drive.

With a non-certified drive it will generally refuse to install.  If you know that the programs of interest to you don’t care about the drive type, there’s a couple of other reasons why you still may want to consider a Windows To Go certified drive.  One is performance. There was a minimum performance requirement that these drives had to achieve as a part of their certification.  However, now there are other solid state drives available that are much faster than the available Windows To Go drive (such as the Thunderbolt 3 only Samsung X5 drives).  Another consideration is security.  Some of the Windows To Go drives have hardware implemented encryption and include the option of voiding the contents of the drive under some conditions that you can define (such as the wrong password being entered at bootup too many times).

The best practice, if you plan to work with any sensitive data, is to not store it on a portable drive, if possible. But if you must, then encryption is an uncompromising need. Whether or not a Windows To Go drive is necessary for you may only be known after you review your needs.

One significant drawback of Windows To Go drives is you cannot perform a major Windows Update on it. The installation can receive Windows security updates though.  When there is a major Windows Update if you want to install it, it’s necessary to format the entire drive and start from scratch.

For my needs, I have a Super Talent 128 GB USB 3.0 drive (for speed) and a Western Digital 500 GB mechanical drive (much slower, but I can work with larger projects using it).  If you choose to do this with a certified drive, make sure you read the drive’s instructions, before you begin writing your Windows Image to it.  Some drives come with their own software that must be used for making the image and if you start off formatting the drive then you’ve already destroyed the software that you need (and it may not be readily available for download from the company’s website).

If your project needs call for a Windows To Go certified drive, I’ve found 4 available on Amazon.  Here are the links to them (affiliate links).

//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=qf_sp_asin_til&ad_type=product_link&tracking_id=j2inet-20&marketplace=amazon&region=US&placement=B00CFI402O&asins=B00CFI402O&linkId=bc4f9901d4fa29a7092cb52f6eb0ea41&show_border=false&link_opens_in_new_window=false&price_color=333333&title_color=0066C0&bg_color=FFFFFF //ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=j2inet-20&marketplace=amazon&region=US&placement=B00A48LB6K&asins=B00A48LB6K&linkId=669d2905a2a87f408df07b5c89e7cfec&show_border=false&link_opens_in_new_window=false&price_color=333333&title_color=0066c0&bg_color=ffffff //ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=j2inet-20&marketplace=amazon&region=US&placement=B00DWCPDHS&asins=B00DWCPDHS&linkId=0e21eefd6195691755311fa96a5ddc4c&show_border=false&link_opens_in_new_window=false&price_color=333333&title_color=0066c0&bg_color=ffffff //ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=j2inet-20&marketplace=amazon&region=US&placement=B015GGR14A&asins=B015GGR14A&linkId=9f8fb3d7f7a3bb009fda0934eaf181e1&show_border=false&link_opens_in_new_window=false&price_color=333333&title_color=0066c0&bg_color=ffffff

-30-

NodeJS on BrightSign

When I left off I was trying to achieve data persistence on a BrightSign  (model XT1144) using the typical APIs that one would expect to be available in an HTML application. To summarize the results, I found that using typical methods of checking localStorage and indexedDB show as being available; but indexedDB isn’t actually available; and localStorage appears to work, but doesn’t survive a device reset.

The next method to try is NodeJS.  The BrightSign devices support NodeJS, but the entry point is different than a standard entry point of a NodeJS project. A typical NodeJS project will have its entry point defined in a JavaScript file. For BrightSign, the entry point is an HTML file. NodeJS is disabled on the BrightSign by default. There is nothing in BrightAuthor that will enable it. There is a file written to the memory card (that one might otherwise ignore when using BrightAuthor) that must be manually modified. For your future deployments using BrightAuthor, take note that you will want to have the file modification described in this article saved to a back-up device so that it can be restored if a mistake is made.

The file, AUTORUN.BRS, is the first point of execution on the memory card. You can look at the usual function of this file as being like a boot loader; it will get your BrightSign project loaded and transfer execution to it. For BrightSign projects that use an HTML window the HTML window is actually created by the execution of this file. I am not going to cover the BrightScript language. For those that were ever familiar with the language, it looks very much like a variant of the B.A.S.I.C. language. When an HTML window is being created it is done with a call to the CreateObject method with “roHtmlWidget” as the first parameter to the function. The second parameter to this call is a “rectangle” object that indicates the coordinates at which the HTML window will be created. The third (optional) parameter is the one that is of interest. The third parameter is an object that defines options that can be applied to the HTML window.  The options that we want to specify are those that enable NodeJS, set a storage quota, and define the root of the file system that we will be accessing.

The exact layout of your Autorun.js may differ, but in the one that I am currently working with, I have modified the “config” object by adding the necessary parameters. It is possible that in your AutoRun.brs that the third parameter is not being passed at all. If this is the case, you can create your own “config” object to be passed as a third parameter. The additions I have made are in bold in the following.

is = {
    port: 3999
}    
security = {
        websecurity: false,
        camera_enabled: true
}
    
config = {
    nodejs_enabled: true,
    inspector_server: is,
    brightsign_js_objects_enabled: true,
    javascript_enabled: true,
    mouse_enabled: true,
    port: m.msgPort,
    storage_path: "SD:"
    storage_quota: 1073741824            
    security_params: {
        websecurity: false,
        camera_enabled: true
    },
    url: nodeUrl$
}
    
htmlWidget = CreateObject("roHtmlWidget", rect, config)

Once node is enabled the JavaScript for your page will run with the capabilities that you would generally expect to have in a NodeJS project. For my scenario, this means that I now have acces to the FS object for reading and writing to the file system.

fs = require('fs');
var writer = fs.createWriteStream('/storage/sd/myFile.mp4',{defaultEncoding:'utf16le'});
writer.write("Hello World!\r\n");
writer.end()

I put this code in an HTML page and ran it on a BrightSign. After inspecting the SD card after the device booted up and was on for a few moments I saw that my file was still there (Success!).  Now I have a direction in which to move for file persistence.

One of the nice things about using the ServiceWorker object for caching files is that you can treat a file as either successfully cached or failed. When using a file system writer there are other states that I will have to consider. A file could have partially downloaded, but not finished (due to a power outage; network outage; timeout; or someone pressing the reset button; etc.). I’m inclined to be pessimistic when it comes to guaging the reliability of external factors to a system. I find it necessary to plan with the anticipation of them failing.

With that pessimism in mind, there are a couple of approaches that I can immediately think to apply to downloading and caching files.  One is to download files with a temporary name and change the name of the file from its temporary to permanent name only after the download is successful. The other (which is a variation of that solution) is to download the file structure to a temporary location. Once all of the files are downloaded, I could move the folder to its final place (or simply change the path at which the HTML project looks to load its files). Both methods could work.

I am going to try some variations of the solutions I have in mind and will write back with the results of one of the solutions.

-30-

NEWS:Linux on Dex Coming to More Devices

LoD

Samsung has announced that Linux on Dex is coming to more devices. Previously it was only available on non-LTE models of the Galaxy Tab S4 and on the Galaxy Note 9. Per an email that Samsung sent on Monday support is coming to the Android Pie builds of the  S9, S9+, S10e, S10+, Tab S4, and Tab S5e.

Based on interaction with others (and also being my own personal story) there are owners of the TAB S4 that haven’t yet received Linux on Dex support that wait with anticipation for support to come. I’ve not been able to confirm compatibility yet as the Pie build of Android isn’t yet available for my device. The Linux on Dex page had previously stated that none of the LTE Tab S4 models were supported. The page now only states that the Verizon LTE tablets are not supported.  I hope that this means that support for my device is coming. For now the only option is to wait.

Update (2019-April 30): Today I received the Android Pie update for the Galaxy Tab S4. It does indeed have support for Linux on Dex (finally!).