Saturday, April 01, 2017

This is how birds enjoy water ...

This is how much the sunbirds in my garden enjoy even with the little water you share with them this summer. They are pretty cool :)

Musings on Nature around Gandhkosh

Some of shots of nature taken around DSK Gandhkosh, my work home over a period of few months. Hope you like it :)

Friday, February 24, 2017

A "Generic Component" in Angular 2

I am generally a lazy person. Especially so when it comes to writing some UI code (although I can have endless comments and critiques on someone else's UI and UX ;-)) . I find it repetitive. And any form of repetitive behaviour is ripe for automation. One such activity which I recently encountered in a project I was doing was creating forms - a lot of them - with Angular 2 front end. I remember in good old MS Access days these were just a click away - although I disliked it, this is what I did in my first paying job in summer break of my school.
I am not sure we have something equivalent here - more so when Angular is so rapidly changing and keeps breaking every other month.

However, it is rather easy to write a "generic component" that can be simply configured using a JSON and you can have a new form without writing any of the usual code. This has two main advantages: 1) You have a single place to fix when Angular changes something in its structure 2) You have a super reusable form engine which can be configured on the fly, allowing you to do cool things like storing form info in a backend service, and automatically update the Angular 2 app on the fly.

To start off, you will need to define a JSON which can be used to construct the UI on the fly.

this.componentJSON = {};
this.componentJSON['title'] = "Trials";

this.componentJSON['formItems'] = [
 { "type": "text", "id": "trial", "name": "Trial Name", "description": "Name of trial", "theValue": "", "param_name": "trial_name" },
 { "type": "text", "id": "sponsorer", "name": "Sponsorer", "description": "Sponsorer of the trial", "theValue": "", "param_name": "sponsorer_name" },
 { "type": "button", "id": "submit", "name": "Submit", "description": "Submit the form", "api_call": this.createTrial },

The above JSON is intended to create a simple form with a title, two text fields and a button. The api_call parameter of the button is a Service object used to make an API call.  This JSON should be used in any parent component that intends to use this component, typically being initialised in ngOnInit() method.

Next we define generic.component.ts and generic.component.html as follows

import { Component, OnInit, Input } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';

   selector: 'generic-cmp',
   templateUrl: 'generic.component.html'
export class GenericComponent implements OnInit {

   componentJSON: any;

   constructor() { }

   ngOnInit() {

   callAPI(item: any) {
     item.api_call.api_call(this.processInput(this.componentJSON)).subscribe((res:any) => {      
if (res.status == 0) {
} else {

   processInput(componentJSON: any) {
     var formItems = componentJSON['formItems'];

     var params: any;
     params = {};
     for(var frmItm in formItems) {
if (formItems[frmItm].type != 'button') {
        params[formItems[frmItm].param_name] = formItems[frmItm].theValue;

     return params;

The trick as always is to generalise the JSON and then the generic component generator above to take care of different input forms as well as adding validations. The callAPI function above for instance, basically generalises an API call, where as the processInput method creates the parameter payload for API call from the JSON we created earlier. Advantage again being that simply changing the JSON pretty much re-creates the whole of the HTML. Creating a different form just requires one to define a new JSON.

Since this component needs to be used in multiple places it would be wise to declare the directives associated with this component in a shared.module.ts file:

import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';

import { NameListService } from './name-list/index';
import { GenericComponent } from './generic-component/generic.component';

    imports: [CommonModule, RouterModule, FormsModule],
    declarations: [GenericComponent],
    exports: [CommonModule, FormsModule, RouterModule, BrowserModule, GenericComponent],    

export class SharedModule {
    static forRoot(): ModuleWithProviders {
        return {
            ngModule: SharedModule,
            providers: [NameListService]

Now a third component can embed this reusable, configurable component as using:

Thats it! You should have a fairly reusable forms module, that you can fully configure using the JSON, without the need to keep writing the HTML and related Component code every time. 

A similar pattern may also be used for creating a generic service call. This is again useful as you code can remain independent of the changes that may occur in basic underlying syntax of say actually calling the HTTP post method. 

Wednesday, January 04, 2017

My tech wish list - 2017

1. MacBook with inbuilt cellular connectivity
2. iPhone with no ports - not even lightning - with wireless charging. For a truly courageous furture.
3. If I can just use my phone for every thing - where is that elusive Surface Phone ?
4. On demand apps on iOS - so that I can save on my precious local storage
5. Driver less cars - where are they ?
6. Super personalised medicines
7. AI assistant for myself - without a cloud connected device
8. Battery that lasts for 1 month on 15 min charge and doesn't explode. 

Saturday, October 15, 2016

A memory corruption bug as result of 'single character'

It has been a quite a few months since I saw or have written some serious algorithmic code involving C++ (read computing surfaces or doing numerical computation). So when a weird bug was reported for a program I work with, I though it must be fun. The case was for a particular feature in the program that would plot a surface based on some input parameters. The bug was strange because it made the program crash on Windows but on Linux it plotted the surface correctly.

Good then, let us fire gdb and figure out where it was faulting. But for some reason, on the build system I was using for Windows, I couldn't get gdb to work properly. So was left with old way: read the code and put a lot of printf(). Now since this was Windows, printf() wouldn't work either! The program however had a logging API, that would log text to a window. The problem however was that there was no text in the window (or the window was not refreshed) just before the program used to crash. So the next technique was to use the logging and commenting one line at a time, with a premature return from the affected function, which is usually very tricky to do when there are nested loops. And this was exactly the case here. Finally, the real culprit was one line that read:

if (k+l < numberOfXPoints) {
 x[i][j][k+l] = ...

There you have it. The code ought to be:

if (k+l < numberOfZPoints) {
 x[i][j][k+l] = ...

Apparently this error was never observed, and looking back at the history of the source code, I found that it was this way ever since it was written, a couple of years ago! This error didn't probably produce any visible output errors and apparently went past all the test cases as well, because for none of those, the points along z-direction exceeded the points along x-direction.

Two things to learn:
1) Never name two variables such that they differ in only one character. If you indeed need to then ideally have the differing character towards the beginning of the word as in the case above a better way to name would have been using: xPts and yPts.
2) If an error is occurring on one platform but not on another, it is most likely a memory corruption issue. Hunt down all the code dealing with arrays. 

Thursday, May 12, 2016

Experiments with super capacitors and solar panel

Towards the end of 2012, I started experimenting with powering devices directly using solar panel and an pretty expensive super capacitor. For this I bought a couple of solar calculators from a nearby mall, disassembled the tiny solar panels and tried to run a small mp3 player using the same. The project kind of got shelved, towards the beginning of 2013 due to loss of my mother.

Later on in 2014, I got some pretty inexpensive but good quality super capacitors from eBay. And then repeated the experiments. I tried two things:
1) Powering the calculator fully on solar and super capacitor
2) Powering an MP3 player using a super capacitor and a slightly larger solar panel (again ripped off from a solar power bank)

While the fully solar calculator (supported by the super capacitor) works wonderfully well (even today), the MP3 did work pretty well too. The only issue with the MP3 player being that the 1F super capacitor I had only lasted for about a minute if I got it away from direct sun light. The calculator on the other hand, requiring pretty low power didn't have issue with even ambient room light.

I believe super capacitors combined with solar panels have interesting applications. Especially in wearable world. It is only a matter of time that these things become common place.

Friday, April 01, 2016

A Thousand Times

I must have talked a thousand times .. to myself
Where are you ? Where you?

I must have walked a thousand times
To see you. Where you ?

I must have heard a thousand times
About you. Where you?

I must have walked a thousand miles
Still here 
Wondering what am I doing still, again and again and again ..


Saturday, February 13, 2016

Printing on a white label BLE thermal printer from iOS - a quick story

Over at, we are building tools to help small merchants better connect with their customers. Check to see what we do, and do not forget to watch that video, we are sure you would love it :-)

While one of the core principles at OneGreenDiary is to be as paper less as possible, there are still places where a printed paper bill may be required. We avoided print support for our merchant apps, till one of our early adopters specifically asked for it. Since we are kind of cash strapped, and can not afford to spend on a damn printer that is iOS certified, we went over to and ordered this cheap Bluetooth enabled thermal printer that claimed to work with iOS :

Great. After the printer arrived, we though that it would magically connect to out iOS device and we did start printing instantly. Bummer. Ok, how about Android ? No luck. Apparently neither iOS nor Android provide native support for BLE printers. I tried to install the outdated Windows driver, and Linux cups drivers with no luck. Not even able to print on desktop. 

But then, Abhay C, a wanderer with us, found an iOS app called printer-x, that was a demo app to print on bluetooth enabled thermal printers. He printed this:  "hello, world!"

At this point we knew, it could be done. But how? All communications with the vendor didn't go anywhere. They send some sample iOS (Objective C) code, and some Android code, both of which didn't compile, and neither we could understand what was going on in the code. There were a few comments in Chinese that tried to be helpful. Chinese, not Swift. The programmers manual that came with printer reminded me of good old DOS assembly days. There was something, but didn't know where to start.

Next we tried to venture into programming our own BLE layer for printer communication. Instead of using the CoreBluetooth library we zeroed in on using BluetoothKit, which is Swift wrapper over CoreBluetooth library ( So basically it is this: BLE frameworks try to give you two interfaces: Peripherals and Central. Peripheral refers to a device which can be discovered, asked for data, or can receive data. Central on the other hand scans for Peripherals, discovers characteristics offered by Peripheral, receive / send data to the Peripheral. One of the important thing to enable discovery is the UUID of the Bluetooth device, this can be easily obtained by using a discovery code, or a number of BLE query apps available on the App store/ Play store. I used the LightBlue app from the App store for this purpose. Once this device was discovered, we needed to connect to the device. The BluetoothKit provides a elegant interface to connect. But the issue started after this: apparently BluetoothKit's connect call back returns an instance of BKRemotePeripheral class, and this class exposes API to only receive data, not send! Apparently the class was more designed for bluetooth sensors, that only transmit data, not receive anything. Digging into the BKRemotePeripheral class, I found out a way to expose the embedded CBPeripheral object along with capturing CBCharasteristic objects. These are the objects of CoreBluetooth iOS library that allow lower level controls.

Next is when the DOS assembly like programmer's manual, which came with the printer, came up for help. After this I could easily figure out the code to issue a line feed to the printer device:

let lineFeed = self.hexToNSData("0A")
let printer = self.connectedDevice!.getPeripheral()!
printer.writeValue(lineFeed, forCharacteristic: self.connectedDevice!.getCharacteristic()!, type: CBCharacteristicWriteType.WithResponse)
At this point, I knew, things were pretty much in control. The above code basically writes the hex code "0A" to the discovered characteristic. This initiates a line feed operation on the printer. Once this is done, it was a wow moment to print this:

and then this:

Since all of this code (written in Swift) was majorly based on BluetoothKit, we felt it was best to open up this part of the code, which is now hosted on GitHub:

Hope this is of some help, especially if you are trying to programatically access these kind of printers with iOS.

Note: Before you ask, I am still connected with VLife for all official (and practical) purposes. Once an officer at immigration and citizenship department in Oz told me, it is always good to be in love with two countries, you are contributing to both with your heart. Fits well here.