Wednesday, December 17, 2014

Alternative Power Setup for Load Schedding (or "Power Blackouts") in South Africa

Disclaimer: I am a programmer, not an electrician. It works though, so maybe I did something right ... use at your own risk!

So lately we have had this problem in South Africa, where you are busy with something, and then suddenly the power dies. This got annoying to the point where I decided to get myself an alternative power setup involving an inverter and a deep cycle battery.

The obvious solution is to go out and buy a petrol/diesel power generator, however this approach suffers from a few problems that I cannot live with. The first is that it is noisy. If you live in a townhouse complex, the neighbours may complain, causing all kinds of hate mail/legal fees. One solution would be to look for a quiet generator, but now you have the problem of "how quiet is it really?" before you buy it. Also: "Quiet" inverter generators like this one is expensive. It also has to be refueled. It is not that much effort to drive to the petrol station, but this is not as convenient as recharging a battery from a wall socket. And then there is the problem with fumes which may prevent indoor use.

My solution (Which I heard about from a colleague with an engineering degree ...)

I decided to get a giant rechargeable battery instead of a generator. This has the benefit of being completely quiet. You can also "refuel" if from the wall socket when the power is available, and it has extra potential in the sense that you can buy more batteries when you "run out of capacity" or load shedding gets worse. It also has the potential of being used in a solar power scenario in case the wall socket goes dead or becomes too expensive. (The expensiveness of electricity in South Africa is a topic for another time, more about it can be found with a quick Google search ... ex. see this link)

My current power setup. I may add more batteries if load shedding (power blackouts) gets worse. 
I followed these steps to get to this point:

1. Calculate projected use in Watt-Hours and choosing an inverter

Electricity use is measured in Watt-Hours, abbreviated Wh. So it you want to run a 250 Watt Play Station 4 for 2 hours, you will use 500 Watt-Hours. But it gets more complicated. The first thing I bought was an inverter.

An inverter converts the direct current electricity to alternating current used by home appliances.

A 600W pure sine wave inverter that I bought from Communica (
There are a few things to take into account when buying an inverter:

  • How much electricity are you going to use? The general approach is to add up the watts of the appliances that will run at the same time. The tricky part though is that your energy setup between the battery, the inverter and your appliances will also use electricity, so you cannot buy a 600W inverter if you want to consume 600W.
  • How much do you want to spend on a battery This is where the interconnectedness of everything comes into the picture. When I opened my inverter manual, I got a surprise when I saw that the inverter has a minimum recommended battery size. I guess this should have been expected though, seeing that it is probably ill-advised to run a large inverter off a small battery.
  • Modified vs. Pure sine wave inverters There are two kinds of inverters to my knowledge: Modified and Pure Sine Wave inverters. Modified sine wave inverters are noticeably cheaper but there is a catch. You cannot run certain kinds of equipment from modified sine wave generators. For example: My one colleague's cellphone charger worked for a few minutes and died.
  • Cabling The cables connecting the inverter to the battery has Amp ratings. Obviously you do not want to exceed these ratings when drawing power through the inverter.
  • Safety mechanisms Some inverters comes with protection mechanisms like fuses and a cutoff mechanism for when the battery is discharged too far. A battery can be ruined this way, so it is a good idea to have this. The fuses are apparently there to blow when the battery is connected incorrectly. (IE. the polarity is revered) According to the booklet this will void my warranty.
  • Startup load Some devices could use a lot more watts on start-up. Inverters has an overload rating for this. So it is possible to run the inverter in the picture for 2 seconds at 2 times the rated load.
2. Choosing the battery size and "how long will it last?"

Battery size if rated in Amp-Hours or Ah. This is very confusing, considering that power usage is measured in Watt-Hours. In order to choose a battery, I followed my inverter manual guideline of 100 Ah, though it turns about that it is sufficient for my purposes. When I measured the discharge rate, it matched my requirements. 

It seems that it is very difficult to calculate how long a battery will last because it is based on a large number of unknown factors. To make matters worse, batteries to not discharge at a constant rate and does not discharge to 0 Volts. To get an idea of the factors involved, I refer the reader to this link:

These are my sums, I leave the reader to draw their own conclusions:
  1. Get projected use. From section 1 above, it is 300 Watts for 2 hours (this is how long load shedding lasts at the moment ...). This gives you 600 Watt-hours.
  2. Multiply the battery volts by the Amp-Hours. I have a 96 Ah 12V battery, so this is around 1200 Watt Hours.
  3. Therefore I should have 4 hours of battery life (ie, 1200 Wh divided by 300 watts). But this is not really the case, because deep cycle batteries should not be discharged past a certain point. According to online reading (see this should not go past 50%. So that gives me 2 hours of battery.
A deep cycle battery I bought from Communica.
I decided to get a deep cycle battery, seeing that these batteries are designed to be discharged more "deeply" than car batteries, and it designed for repeated charging/discharging. The battery is unfortunately the most expensive part of this setup, and you have to carefully calculate how much battery you need. In comparison for generators, you get far less power from a battery, however it has the benefits I listed in the introduction. There are also safety considerations, seeing that batteries contain sulphuric acid and emits explosive gasses.

In order to measure the battery discharge level, I used a voltmeter which I connected to the battery after switching off all appliances. I checked the measured voltage on a lookup table that I found at It discharged to 12.15V after 2 hours, so my calculation seem sound.

3. Buying a battery charger

When I bought my battery charger, I went for a smart charger. It seems that you cannot just buy any charger to charge deep-cycle batteries. Batteries undergoes a process called Sulfation, which reduces their lifespan. Seeing that the batteries are the most expensive part of this setup, it is a good idea to try to keep them in good shape. Some battery chargers have a "maintenance mode" which apparently helps to prevent this.

Also: something else to consider is the charger rate of charge vs. the size of the battery. I see that battery chargers have Amp ratings. There is a nice article on chargers here:

Also: I saw that my battery charger had a minimum recommended battery size in Ah, which I exceeded purely by accident, so this is another thing to take into account.


I am happy with my setup as it currently is. I do not miss buying a generator, purely because the generator is not a flexible in terms of future expansion as a battery based setup. In total it cost about R 6000, which is more than you would pay for a generator. I guess what you buy is dependent on your needs.

Thursday, September 25, 2014

How to: Tokenize a string with Typescript and Regular Expressions

Source Code:

Sometimes you have a string, and you want to identify sub-strings in this string by matching them with regular expressions. I wrote this small program to do that: (see full source code here)

Step 1: Specify the regular expressions and sub-strings

(Note: Tokenizer is not a build-in class, I wrote it. See step 2. See above link for the rest.)

var tokenizer = new Tokenizer();      
tokenizer.addTokenDefinition(TokenType.Variable, /\:\w+/);
tokenizer.addTokenDefinition(TokenType.Identifier, /[a-zA-Z_]\w*/);
tokenizer.addTokenDefinition(TokenType.String, /"[^"]*"/);
tokenizer.addTokenDefinition(TokenType.Number, /[+-]?[0-9]+[\.]?[0-9]*/);
tokenizer.addTokenDefinition(TokenType.Whitespace, /[\s]+/);

Step 2: Tokenize

class Tokenizer {

  private definitions: Array;

  constructor() {
    this.definitions = new Array();

  addTokenDefinition(type: TokenType, regex: RegExp) {
    var tokenDef = new TokenDefinition();
    tokenDef.type = type;
    tokenDef.regex = regex;

  tokenize(strIn: string): TokenizationResult {
    var retVal = new TokenizationResult();
    var sourceString = strIn;
    if (!strIn || (strIn.match(/^[\s]*$/) != null)) {
      retVal.succeed = false;
      retVal.message = "Error: Empty input given."
      return retVal;
    var nextParsePosition = 0;
    var matchedType = TokenType.None;
    retVal.result = new Array();
    do {
      matchedType = TokenType.None;
      this.definitions.forEach(def => {
        var match = def.regex.exec(sourceString);
        if (match != null && match.index == 0 && match.length >= 1) {
          // Use the string indexOf member to skip the unwanted characters
          var token = new Token(strIn, nextParsePosition, match[0].length, def.type);
          // Note: It is neccesary to skip by the amount adding in non-matched characters from the first group.
          nextParsePosition += match[0].length;          
          sourceString = sourceString.substr(match[0].length);
          // Continue to next token 
          matchedType = def.type;
    while (nextParsePosition < strIn.length && matchedType != TokenType.None);
    retVal.succeed = nextParsePosition == strIn.length;
    if (!retVal.succeed) retVal.message = "Unexpected characters at position " + nextParsePosition;    
    return retVal;

Points of interest

Wednesday, September 24, 2014

How to: Setup a Github repository and do an initial upload on Windows

This guide is a quick how-to for creating a new Github repository, and uploading new files via the command prompt. The Windows interface was too confusing for me, so I ran back to the command line :-) Note that this is a guide assumes that you are new to Github and does everything in the master branch. Therefore I do not do forking etc.

Step 1: Create a Github account if you don't have one

This can be done by visiting and signing up. For this guide you will need a Github username and password.

Step 2: Create a repository

Create a repository by clicking on the button in the screenshot:

The Github repository creation button
Follow the instructions on the screen until you have a repository.

Step 3: Download Github for Windows

Get it here:

Step 4: Open Github for Windows, and browse to the Github shell

Where to find the Github shell in Github for Windows
This will open Powershell with the Github extentions: (it will be blank at this point)

The Github for Windows Powershell extensions in action
Step 5: Initialize the repository locally

Change directory to the parent of the directory where you want to host your code. The directory must not exist yet:

cd D:\Github

Now get the new repository that you created in step 2: First copy the repository HTTPS URL: You can copy and paste it from the website in the location in this screenshot.

Where to find your repository HTTPS URL
Now the repository can be initialized by cloning it to your hard-drive. Go back to Powershell and run this command:

D:\Github> git clone

Note that is what I copied and pasted. This command will create a subdirectory, in this case D:\Github\RandomUsefulCode

Step 6: Create your content and copy it to the local directory

The local directory here is D:\Github\RandomUsefulCode. If you have existing old content in the local directory, overwrite it with the new content.

Step 7: Upload your code to Github

First change to the directory containing the code:

D:\Github> cd .\RandomUsefulCode

Now add the new files. You can always run this step, just to be sure nothing goes missing:

git add -A

Now commit all changes:

git commit -a -m "Upload tokenizer version 1"

The part in quotes is the description of the changes. Please note that these changes have only been "locally committed". Therefore it is not uploaded to Github on the Internet yet. In order to upload it, you will need to copy the HTTPS URL from step 5 again. With the URL, run this command:

git push master

This will ask you your Github username and password from step 1.

Step 8: Check your upload

You can check that your files have been uploaded by browsing to your repository after you logged in. The files usually appears immediately.