Monday, 6 July 2015

Hacking a Solar Security Light

Introduction

I've got a few LED lights around my home with infrared motion detectors. They provide soft light at night in the hall, stairs and inside cupboards, and another provides a surprisingly bright light over the back door. So no more fumbling in the dark for light switches or keys on cold dark nights. But the one thing that's been bugging me is the light in the garage.

I replaced the single light fitting with a 6 foot fluorescent tube last year. It does a good job lighting the space, but the kids sometimes leave it on, and the second or so delay is annoying if you're repeatedly going in an out of the side door.

Having been impressed by the light over the back door I decided to get another for inside the garage. Not only will this provide some convenience, but solar = free power.

Problems With the New Light

Solar LED Light
I picked up this 36 LED light from Maplin which provides 150 lumens and has a sensor range of 8 metres. Not bright enough to do any work by, but enough to stop miscellaneous clutter from being a tripping hazard.

It was different from the previous one I'd bought, being a bit cheaper, and the on-line reviews showed that some had problems with water getting in. But as I'd planned to install it inside my garage, I disregarded that as a problem, and purchased the light.

It wasn't until testing that I realised the light wouldn't come on in daylight. (this is determined by measuring the voltage coming from the solar cell). I found I had to cover the solar panel with my hand, or disconnect it to get the light to come on.

This was NOT good!

Hacking the Light

I mused that perhaps the circuit could be altered so that the solar panel only charges the battery and doesn't factor into the sensor circuit. I grabbed my screw driver and started to investigate.

After removing the screws from the main case I found a 3 cell battery pack and a small circuit board.

The light's casing open showing circuit board.

You don't get wiring diagrams these days so I had to trace the circuit and sketch it out on scrap paper.

1. The voltage from the solar cell passes through the blocker diode D1, which then feeds onto the battery connected to the (slightly blurred) white connector.

2. The white return wire from the IR sensor connects to the OUT pad on the circuit board, which feeds the base of larger transistor on the far left. This turns the light on when the sensor is triggered.

3. The smaller transistor Q2 shorts the base to 0v if the voltage through R4 (from solar cell) is high. This stops the light coming on in the day.

Remove R4 from the circuit.

So,.. I grabbed my soldiering iron and desoldered this resistor.

The removed resistor on my finger

Bingo, the light comes on, and this time I didn't have to cover the solar panel.

Tuesday, 24 March 2015

Unicode data extracts using Oracle SQL*Plus in Unix

Introduction

The normal data spooling method using Oracle SQL*Plus will use the locale setting to determine the output file encoding method. Typically we are only interested in data extracts using just ASCII characters, but if you need (for example) to use a unicode character as a data separator, then things tend to go wrong.

Consider the following SQL statement which uses the double dagger unicode character as a separator:-

SELECT 'FIRST_NAME'||unistr('\2021')||'SURNAME' from dual;
 
If we run this in an SQLPlus session we get the following..

FIRST_NAMEĆ¢¡SURNAME 
 
(nb. I'm going to assume that you are using Putty as your terminal client)

 Setting your Locale in Putty

The data returned by the select looks like it's become mangled, but it's not. Your Putty session needs it's Window/Translation setting to be changed to UTF-8 before it can be displayed correctly.

Select UTF-8 translation in Putty


Now if we run this SQL again we get..

FIRST_NAME‡SURNAME

Similarly we can run the following SQL script using SQL*Plus to produce the file output.csv:-

set feedback off
set heading off
set term off
set echo off
spool output.csv SELECT 'FIRST_NAME'||unistr('\2021')||'SURNAME' from dual;
spool off
exit

The contents of output.csv will also display correctly using 'cat', but only because your locale settings in Putty are UTF-8.

NB. You can also copy the file back to your PC and open it using notepad (which handles UTF8 files correctly).

Scheduling with Cron

The spool script works OK when run interactively, but now let's schedule it from the cron. The script will be run using the machine's locale settings (probably ISO8859), and so SQLPlus will replace the unicode characters with question marks to keep it a valid ASCII format.

FIRST_NAME?SURNAME

But we can fix this by adding the following line near the start of our shell script:-

export NLS_LANG=.AL32UTF8

Tuesday, 3 March 2015

Oracle APEX - Soft Validation using Dynamic Actions

Introduction

It's often a good idea to have validation on your forms in APEX, especially when you have business rules that govern how data can be entered. On a recent system enhancement we wanted to add a 'target bonus' flag to a page, but only allow it to be set to 'Yes' if the 'rebate level' was not set to 'None'.

This is simple enough to do..

Create a Page Validation, with a validation type of 'PL/SQL', 'Function Returning Boolean', then enter code as follows:-

BEGIN
  IF :P4_TARGET_BONUS = 'Yes' AND :P4_REBATE_LEVEL = 'None' THEN
     RETURN false;
  ELSE
    RETURN true;
   END IF;
END;

But it turns out that it's not quite what the customer wanted. There may be instances were it's OK to break these rules, so in that case can we just warn the user by showing a pop-up confirmation box instead.

Confirmation boxes are a UI thing which needs to happen before the page is submitted, so this sounds like a job for a dynamic action.


Using Dynamic Actions For Validation

I deleted the page validation (above) and set about using jQuery and a Dynamic Action to perform the same field comparison, but this time at the browser level.

Adding a Confirm action for soft validation.

1. Create a dynamic action against your submit button and set the following details in the When section.

Event: Click
Selection Type: Button
Condition: Javascript expression
Value: ($v('P4_TARGET_BONUS') == 'Yes' && $v('P4_REBATE_LEVEL') == 'None');

2. Next add a True action for when validation fails..
 
Action: Confirm
Fire When Event Result is: True
Text: Target Bonus is not allowed while Rebate Level is 'None', continue?
 

3. Add another True action which will be used if OK is clicked on the confirm action..
 
Action: Submit Page
Fire When Event Result is: True
Request/Button Name: UPDATE
 
4. Finally add a False Action to perform a simple submit if validation passes..

Action: Submit Page
Fire When Event Result is: True
Request/Button Name: UPDATE

That's it!... you can make your own validation tests more complex in the dynamic actions javascript box using the standard comparison and logic operators.

Thursday, 19 February 2015

Nintendo DSi - Resetting Parental Control

The Problem

If you've ever watched kids use computer devices then you'll be aware of their preoccupation with the menus (or screwing around with the settings). I've gotta admit the worst incident of this was when I had to reset the language on an MP3 player from Chinese back to English.

Anyway my son (let's call him Dick to retain his anonymity) has wasted countless hours exploring all of the menu options and settings on his Nintendo DSi. At some stage we think he set the parental lock and then forgot the four digit code.

He'd been complaining for some time about how we need to ring up Nintendo's Technical Support and get a reset key. And we've done our best to ignore the request, keen to show him that there's a real world impact to "buggering about with things in a hap-hazard way".

The net result of this problem: he can't access the web (fine by me), and can't access the Nintendo Shop (again fine). The latter generally forces a firmware update, which in the past has stopped their R4 cartridge from working.

But after replacing his brother Harry's DSi at the weekend, Dick became very upset that the new machine had DSiWare on it that his didn't have. Specifically Flipnote Studio!


Flipnote Studio - Finally a constructive use for the DS


He initially tried to copy the app over using an SD card, but it refused to copy back to his DSi. (Nice try but it's restricted to that console during the download. Copying to an SD card should be viewed as a backup only.)

I think it's a pretty good program, so I waited until they were in bed and then attempted to access the Nintendo Store.


Parentally Locked

My first problem was unlocking internet access. The old four digit code (we'd set when the DSi had belonged to Tom) wouldn't work, so I was then asked to enter the town were I was born. I tapped it in but - no go!,  then tried my wife's - also no! (and various other places we'd lived - all to no avail)

Eventually I was presented with an eight digit enquiry number and advised to contact Customer Support to obtain a master key. I fired off an email, but in the mean time carried on looking for an alternative.

I got a standard reply from Nintendo stating they were busy and would respond soon, and then I found the following page..

http://wii.marcan.st/parental

Obviously it's meant for the Nintendo Wii, but it also works for the DSi.

Enter your enquiry number and click on the button to receive your 5 digit master key.

If it doesn't work check the date is set in-correctly on your DS.

Tuesday, 10 February 2015

Raspberry Pi Diary - Scratch GPIO and 7 Segment Displays

Installing Scratch GPIO

The standard version of scratch can't control the GPIO, so you need to install ScratchGPIO7 before you can play with LED's and switches. I googled the install instructions but here they are if you need them:-

wget http://bit.ly/1wxrqdp -O isgh7.sh

sudo bash isgh7.sh

If you need to add the desktop icons to other users you can specify user name on that last command:-

sudo bash isgh7.sh fred

(nb. make sure you have an internet connection first!)

Use the new desktop icons to start scratch and it will ensure a background python task is running that enables the GPIO control.

There's a simple code example that toggles pin 11 between low and high. We attached an LED to this pin, (using a 470R resistor) and connected the other end to one of the ground pins. (doesn't matter which)

Success - a flashing LED!


Moving on from Basics

The plan was that I'd set my 8 year old a task of driving one of his 7 segment displays using the Raspberry Pi, and maybe get it counting 0 to 9.

It seemed like a suitable jump of of complexity both in software and breadboard wiring. (perhaps it was a jump too far) Here's what happened!


Circuit Debugging

My son disappeared for half an hour and returned with breadboard, 7 segment display, and T-Cobbler carefully connected with jumper wires. He plugged it in to the RPi, loaded up the pin 11 demo program and clicked the green flag icon to run the program. The scratch variable was clearly cycling on and off on the screen, but none of the segments lit. We ended up tearing the circuit down trying to get it to work and along the way discovered a few problems..

1. The T-Cobbler board has 40 pins that need to be inserted into the breadboard. That takes more insertion force than you'd think.

2. The LED display was of the common anode variety. This means that all the anodes are connected together and the segments lit by pulling the individual cathodes down to ground.

(So he had connected the LED segments the wrong way round.)

A quick flick through the Maplin catalog confirmed you can get common cathode versions.

Driving Common Anode Displays

My initial thought was we'd have to use a transistor inverter to drive each segment, but that's a fair bit of extra complexity and not strictly necessary.

A simple inverter circuit is not necessary.

Each GPIO output actively pulls high or low, so if you connect the common anode to 3.3v then any low pins connected to the cathodes will turn the display segment on.

Connecting a common anode display to a Raspberry Pi

The only hitch is the logic is the other way around! (pin low = segment on)

But it's only just occurred to me that we could do this after reading the Raspberry Pi GPIO Documentation and seeing an LED connected this way. (Must try this tonight!!)

Wednesday, 4 February 2015

Raspberry Pi Diary - Breakout Boards

Interfacing 101

One of the main reasons why I bought the Raspberry Pi was to bring together the two worlds of electronics and computing for my two youngest sons. The oldest of the two already has various components and breadboard to play about with, and he's already been experimenting with scratch for a while now.

The great thing about the Raspberry Pi is that it has those GPIO pins just waiting to connected to LEDs, switches, sensors or the wide variety of add-ons that you can buy these days. I thought I'd start by getting a simple breakout board from Maplin.

GPIO Breakout Board
I got one, but lets just say I made a few mistakes!

Mistake #1

It comes in kit form, requiring the ribbon socket and header pins to be soldered together before you can use it. There's a simple diagram that suggests how the ribbon connector should connect to the GPIO pins and which way it should fasten into the breakout board. Seemed simple enough but it wasn't obvious which way up the board should go.

One end of the breakout board
One end was labelled 'GPIO HEADER' (see diagram), so I concluded that it belongs this way up and started soldering the socket. After I'd done about eight I started to get the niggling feeling that it wasn't correct. I stopped and traced the wiring only to find I actually had the board upside down!!!

Now unsoldering a double-sided board is a nightmare, and my desoldering pump just wasn't doing the job. In the end, I levered the socket away from the board leaving the soldered pins still attached. These were then individually removed with a hot soldering iron and a pair of pliers.

Botched breakout board with removed socket pins.
Now I'll have to drill out the remaining solder before I can start again. (This wasn't going well!)

Mistake #2

It wasn't until my son came through to check how I was getting on that I realised my next mistake. I was explaining to him about how the ribbon plug would fit into the GPIO. When I went to demonstrate this I spotted my next mistake. (this one pretty fatal)

This was a 26 pin breakout board for the original Raspberry Pi, but I'd bought the newer RPi B+ model, which has a 40 pin GPIO. The ribbon plug won't fit and if you try to force it you'll end up bending some of the pins. (darn!)

Let's do it Right

All I can say is "Cobblers" - or to be more exact Adafruit's T-Cobbler Plus. As soon as I opened the bag I was immediately impressed by the improved quality and the neat screen printing showing (without doubt) which way the socket should be soldered.

You can bet I still checked it carefully before I started, but within about 10 minutes it was done.

The assembled Adafruit T-Cobbler Plus
My son quickly relieved me of it and started building a circuit to light his 7 segment LED display.

(More about that another day)

Oracle APEX - Advanced Tabular Form Validation

Introduction

In my previous APEX post I took you through a method of adding click-able column help to your tabular forms. I also needed to add validation between my columns, and initially it wasn't clear how I might do this. You can validate against static values, normal item values, or just check for nulls, but nowhere can you validate against a value from another column on the same row.


Tabular Form Requirement

Just to recap from before, I have a table of measures with three columns to hold the weighting, cap and uplift values for each. (shown below)


My Tabular Form
The validation I wanted to add was to ensure that if a Cap value is added then it must be greater than the Weighting value.

One way of performing this type of validation is to use some jQuery code which runs on the browser, but generally its not recommended for security reasons. Instead we'll use a method that replies on the inherent use of collections for tabular tables and write our validation using PL/SQL.

Creating the Validation

1. Run the page containing your tabular form and inspect the input fields from the columns your need to validate to get their id's.

The HTML for the first Weighting field is:-
<input id="f03_0001" type="text" value="0" maxlength="2000" size="2" name="f03"
autocomplete="off">

The HTML for the first Cap field is:-
<input id="f04_0001" type="text" value="0" maxlength="2000" size="2" name="f04"
autocomplete="off">

So the two pieces of information we need here is f03 and f04.

2. Create a page level validation and give it a suitable name. (I'm going to call mine "Check Cap Values Exceed Weighting")

3. Select 'PL/SQL' as the validation type.

4. Then select 'Function Returning Boolean'.

5. Here's the code I entered:-

BEGIN
  FOR i in 1..apex_application.g_f03.count
  LOOP
  IF apex_application.g_f04(i) IS NOT NULL
    THEN IF apex_application.g_f03(i) IS NOT NULL 
      THEN IF TO_NUMBER(apex_application.g_f04(i)) <= TO_NUMBER(apex_application.g_f03(i))
        THEN RETURN false;
      END IF; 
    END IF; 
  END IF; 
  END LOOP;
END;

NB. APEX automatically creates a collection for each column in a tabular form ("apex_application.g_f01", "apex_application.g_f02" etc...) This function loops through the values in columns 3 and 4 comparing the values. 

It's reasonably simple, just don't forget to turn these values into numbers before you do your comparison, or you'll find that 8 is greater than 10 and your validation won't work as you intended!

6. Enter the following for Error Message:-

Cap values must be greater than Weighting, or left empty.

7. Finally set the condition to When Button Pressed 'SUBMIT'.

That's it!