Sunday, 27 February 2011

Arduino two way comunication over DC

So the reason that I have gotten an Arduino is so that I can build a sensor/control network primarily targeted at sprinkler systems.
The idea is that I can have the following

PSC05 <=> arduino controller <=> station 1 <=> station 2 <=> ......

At the moment I have the PSC05 and controller work, now onto the fun bit.

My thoughts are to use the zero crossing signal as a master clock for all comms and to transpose the tx/rx signal onto the same line. Then use LC coupling onto the DC supply.
I am hoping that this will allow for easy reuse of the X10 Lib that the controller is using.

Monday, 21 February 2011

I hate scammers

So tonight I received a phone call from some who said that my computer was producing spam. They promised that they were not a scammer and ask me to do stuff.
So here's a transcript of the call

Caller: your computer is producing spam and we would like you to help you fix it
Me: huh, ok
Caller: can you go to your computer and turn it on
Me: ok it is
Caller: let me know when you can see the icons
Me: ok i can see them
Called: ok, if you look at your keyboard the bottom left should be CTRL
Me: no, its got CONTROL on it
Caller: ok,next to that should be a windows logo
Me: no its got ALT/OPTION
Caller:[puzzled voice] ok, lets try the desktop. there should be a windows logo on the bottem left
Me: No just a blue box with a K
Caller: ok click on that and it should say windows
Me: no just KDE DESKTOP
Call: [more puzzled noises]
Me: So you just want me to install your key logger then?
Caller: it should say windows
Me: So you just want me to install your key logger then?
Caller: uh, no we dont installer key loggers
Me: I am in IT know the scam
Caller:uh [ beep,beep,beep]

I always love that noise, the beeping of the phone line as they realise that I know what I am on about and the scam isnt going to work.

I thought that the give aways would have worked
1. it's not a windows keyboard but one from a Mac
2. no start button, but one for KDE

Bet I will get another call tomorrow :)

The Twitter feeds

So here is the archive of the twitter feed scripts i spoke of earlier.

Sunday, 20 February 2011

Sharing files

I think I have it now. Sharing files is easy with Dropbox.

Just upload files to my public area and past the link :)

So here is the x10 code for arduino

Computer Backups

Got to say that I am impressed with the ease of setup with BackupPC
I just works with Linux/Windows and Mac.
All I need to do now is setup the last computer (Mac) and I'm done :)

Arduino X10 temperature library

Time to release the temperature library I have been working on... ( there has to be a better way )

It turns out that what is required is a response to a status request to send back the temperature using preset dim commands. The results are a rcs type sensor

  x10.cpp - X10 transmission library for Arduino version 0.3
  Original library                              (0.1) by Tom Igoe.
  Timing bug fixes                              (0.2) "   "   "
  #include bug fixes for 0012                   (0.3) "   "   "
  Temperature Sensing                           (0.4) by Jason Cox

  Zero crossing algorithms borrowed from David Mellis' shiftOut command
  for Arduino.
  The circuits can be found at


#include "WProgram.h"
#include "x10.h"
#include "x10constants.h"


 Sets the pins and sets their I/O modes.

x10::x10(int zeroCrossingPin, int dataPin)
  this->zeroCrossingPin = zeroCrossingPin;      // the zero crossing pin
  this->dataPin = dataPin;                                      // the output data pin
  // Set I/O modes:
  pinMode(this->zeroCrossingPin, INPUT);
  pinMode(this->dataPin, OUTPUT);

        Writes an X10 command out to the X10 modem
void x10::write(byte houseCode, byte numberCode, int numRepeats) {
  byte startCode = B1110;               // every X10 command starts with this

        // repeat as many times as requested:
        for (int i = 0; i < numRepeats; i++) {
                // send the three parts of the command:
                sendBits(startCode, 4, true);
                sendBits(houseCode, 4, false);
                sendBits(numberCode, 5, false);
        // if this isn't a bright or dim command, it should be followed by
        // a delay of 3 power cycles (or 6 zero crossings):
        if ((numberCode != BRIGHT) && (numberCode != DIM)) {
                waitForZeroCross(this->zeroCrossingPin, 6);
        Writes a sequence of bits out.  If the sequence is not a start code,
        it repeats the bits, inverting them.

void x10::sendBits(byte cmd, byte numBits, byte isStartCode) {
  byte thisBit;         // copy of command so we can shift bits
        // iterate the number of bits to be shifted:
        for(int i=1; i<=numBits; i++) {
                // wait for a zero crossing change:
                waitForZeroCross(this->zeroCrossingPin, 1);
                // shift off the last bit of the command:
                thisBit = !!(cmd & (1 << (numBits - i)));

                // repeat once for each phase:
                for (int phase = 0; phase < 3; phase++) {
                        // set the data Pin:
                        digitalWrite(this->dataPin, thisBit);
                        // clear the data pin:
                        digitalWrite(this->dataPin, LOW);

                // if this command is a start code, don't
                // send its complement.  Otherwise do:
                if(!isStartCode) {
                        // wait for zero crossing:
                        waitForZeroCross(zeroCrossingPin, 1);
                        for (int phase = 0; phase < 3; phase++) {
                                // set the data pin:
                                digitalWrite(this->dataPin, !thisBit);
                                // clear the data pin:
                                digitalWrite(dataPin, LOW);

  waits for a the zero crossing pin to cross zero

void x10::waitForZeroCross(int pin, int howManyTimes) {
        unsigned long cycleTime = 0;

        // cache the port and bit of the pin in order to speed up the
        // pulse width measuring loop and achieve finer resolution.  calling
        // digitalRead() instead yields much coarser resolution.
        uint8_t bit = digitalPinToBitMask(pin);
        uint8_t port = digitalPinToPort(pin);

        for (int i = 0; i < howManyTimes; i++) {
                // wait for pin to change:
        if((*portInputRegister(port) & bit))
                while((*portInputRegister(port) & bit))
                while(!(*portInputRegister(port) & bit))

  version() returns the version of the library:
int x10::version(void)
  return 3;

void x10::x10temp (byte temp_houseCode, byte tmep_Unit, int count, int RPT_SEND){
        detachInterrupt(0);                  // must detach interrupt before sending
          x10::write(temp_houseCode ,tmep_Unit ,RPT_SEND); 
          x10::write(temp_houseCode ,UNIT_13 ,RPT_SEND);
          switch (count) {
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
            case 10:
            case 11:
            case 12:
            case 13:
            case 14:
            case 15:
            case 16:
            case 17:
            case 18:
            case 19:
            case 20:
            case 21:
            case 22:
            case 23:
            case 24:
            case 25:
            case 26:
            case 27:
            case 28:
            case 29:
            case 30:
            case 31:

and x10.h
  Original library              (0.1) by Tom Igoe.
  Timing bug fixes              (0.2) "   "   "
  Temperature                   (0.3) by Jason Cox
        Sends X10 commands.


// ensure this library description is only included once
#ifndef x10_h
#define x10_h

// include types & constants of Wiring core API
#include "WProgram.h"
#include "pins_arduino.h"

// library interface description
class x10 {
    // constructors:
    x10(int zeroCrossingPin, int dataPin);

    // write command method:
        void write(byte houseCode, byte numberCode, int numRepeats);
    // returns the version number:
    int version(void);
    void x10temp(byte tmep_houseCode, byte temp_Unit , int count, int RPT_SEND);

        int zeroCrossingPin;    // AC zero crossing pin
        int dataPin;                    // data out pin
        // sends the individual bits of the commands:
    void sendBits(byte cmd, byte numBits, byte isStartCode);
    // checks for AC zero crossing
    void waitForZeroCross(int pin, int howManyTimes);


Lastly the constants file (added preset dim2)

#define HIGH 0x1
#define LOW  0x0
#define BIT_DELAY 2133          // 1778 us between bit repeats in a half-cycle
#define BIT_LENGTH 900          // each bit is slightly less than 1ms long

#define A       B0110
#define B       B1110
#define C       B0010
#define D       B1010
#define E       B0001
#define F       B1001
#define G       B0101
#define H       B1101
#define I       B0111
#define J       B1111
#define K       B0011
#define L       B1011
#define M       B0000
#define N       B1000
#define O       B0100
#define P       B1100

#define UNIT_1  B01100
#define UNIT_2  B11100
#define UNIT_3  B00100
#define UNIT_4  B10100
#define UNIT_5  B00010
#define UNIT_6  B10010
#define UNIT_7  B01010
#define UNIT_8  B11010
#define UNIT_9  B01110
#define UNIT_10 B11110
#define UNIT_11 B00110
#define UNIT_12 B10110
#define UNIT_13 B00000
#define UNIT_14 B10000
#define UNIT_15 B01000
#define UNIT_16 B11000

#define ALL_UNITS_OFF                   B00001
#define ALL_LIGHTS_ON                   B00011
#define ON                              B00101
#define OFF                             B00111
#define DIM                             B01001
#define BRIGHT                          B01011
#define ALL_LIGHTS_OFF                  B01101
#define EXTENDED_CODE                   B01111
#define HAIL_REQUEST                    B10001
#define HAIL_ACKNOWLEDGE                B10011
#define PRE_SET_DIM                     B10101
#define PRE_SET_DIM2                    B10111
#define EXTENDED_DATA                   B11001
#define STATUS_ON                       B11011
#define STATUS_OFF                      B11101
#define STATUS_REQUEST                  B11111

How I log the hacking on my computer

One day I decided that I had had enough of script kiddies and the like trying to hack my computer and so I was thinking how can I shame them....
Having never used twitter before and needing more challenges, I came up with the idea of sending out an automated stream in real time to twitter and so was born

This has worked out well so far.

I have been asked "how did I do it?" and so here goes.......

I installed rsyslog on to my computer and setup a new rule for auth logging.

The rule is as follows,
auth,authpriv.*                 ^/root/

This executes the wrapper ( on each auth event in the logger sending the data to it.

Next its that does the work sending information to a Perl twitter agent
echo ${message} >> /tw.log
filter1=`echo ${message}|grep -i invalid |grep user`
if [ $? -eq 0 ]
        echo " Invalid User" >> /tw.log
        datetime=`echo $filter1 |awk -F"localhost" '{print $1}'`
        field=`echo $filter1 |awk -F"]:" '{print $2}'`
        output=`echo $datetime $field`
        /root/ "${output}"

filter1=`echo ${message}|grep  "Did not receive identification string from" `
if [ $? -eq 0 ]
        echo "No Identification" >> /tw.log
       datetime=`echo $filter1 |awk -F"localhost" '{print $1}'`
        field=`echo $filter1 |awk -F"]:" '{print $2}'`
        output=`echo $datetime $field`
        /root/ "${output}"

filter1=`echo ${message}|grep  "Authentication failure for"`
if [ $? -eq 0 ]
        echo "Auth Failed" >> /tw.log
        datetime=`echo $filter1 |awk -F"localhost" '{print $1}'`
        field=`echo $filter1 |awk -F"PAM:" '{print $2}'`
        output=`echo $datetime $field`
        /root/ "${output}"

Last on the list is the which sends the filtered output to twitter (need to register to get consumer key and secret). The following was found on the net a long time ago and unfortunately it is not mine nor can I remember whose it is .

# Net::Twitter::Lite - OAuth desktop app example
# From what I can figure out, this code can only perform one operation
# ie, you can get a timeline or update but not both.
# Trying multiple actions results in "503 Bad Gateway" error.

use warnings;
use strict;

# You need to install all of these from CPAN
# along with dependencies (and having
# Bundle::CPAN installed will help)
# Data::Dumper is just for debugging.
# >sudo cpan
# cpan> install Net::Twitter::Lite
use Net::Twitter::Lite;
use File::Spec;
use File::HomeDir;
use Storable;
use Data::Dumper;

# You need to register for key and secret at
# They are private-ish, don't share.  Anyone using these values
# will show up as using your code.
my %consumer_tokens = (
  consumer_key    => 'consumer_key',
  consumer_secret => 'consumer_secret',

# $datafile = oauth_desktop.dat ($0 is program name)
# This will place the dat file in users HOME dir (/home/$user/.net_twitter_example.dat)
# each user needs a .dat file to authenticate.
my (undef, undef, $datafile) = File::Spec->splitpath($0);
my $home = File::HomeDir->my_data;
$datafile = File::Spec->catfile($home,".$datafile.dat");

my $nt = Net::Twitter::Lite->new(%consumer_tokens);
my $access_tokens = eval { retrieve($datafile) } || [];

if ( @$access_tokens ) {
else {
  my $auth_url = $nt->get_authorization_url;
  print " Authorize this application at: $auth_url\nThen, enter the PIN# provided to continue: ";
  my $pin = ; # wait for input
  chomp $pin;
  # request_access_token stores the tokens in $nt AND returns them
  my @access_tokens = $nt->request_access_token(verifier => $pin);
  # save the access tokens
  store \@access_tokens, $datafile;

# Authentication done, now process requests
# if nothing was supplied on the command line, get timeline
if (!@ARGV) {
  eval {
    my $statuses = $nt->friends_timeline();
    for my $status ( @$statuses ) {
      #                 dayofweek,month,day,time,  offset, year
      my (undef, $month, $day,undef, undef, $year) = split(' ',"$status->{created_at}");
      print "$month/$day/$year <$status->{user}{screen_name}> $status->{text}\n";
      warn "$@\n" if $@;
      # otherwise, post the string that was supplied
      # this should probably be sanatized at some point
      else {
    my $message = shift(@ARGV);
    eval {
      my $twit = $nt->update($message);
    warn "$@\n" if $@;


Name and shame

My computer sits on the net full time in the DMZ of my network. For years its been setup this way and of course I have a LOT of attempts to hack in.
I eventually thought I would setup a new way of logging these attempts but wanted a more public listing of them. Thats when I came up with my twitter idea.
The plan, collect all these attempts and send them to a feed on twitter in real-time. Once the feed is working correctly, write a daemon to monitor the feed and plug it back into /etc/host.deny......
So my initial work is done and via a few Perl scripts I send it out to It is now very surprising how many hacking attempts are made on my computer, 9602 since the beginning of the year. Also surprising is that I have maintained 10 followers (turn over is about 10/month) for the 6 months of the project so far.
People will follow anything, even auto generated logging.....
So where to now?  Writing the client side scripts to watch the feed :)

Cheap Atmeg328

I wanted to start using Arduino after talking to a co-worker about his experiences with it.
I sourced the processor and resonator from an ebay seller (why can I get it this way for less than Jaycar?).
So once the parts arrived it was onto my plan to make a X10 garden sprinkler control.
First it was onto finding a library for X10 control. After much research I found on at BroHogan.
This covered the basics of send and receive but I also decided that I wanted temperature sensors. The solution came whilst reading one of the manuals for Heyu. This showed the basic algorithm for temperature sensing. I extended the library to include it and also responding to status requests.

And so it begins......

So here I am just past 40, in IT and thought it about time I started to setup a blog.

I have been involved in Linux since it was on 0.95 and before the dawn of the distro. I have been suppling feed back to the wonderful FOSS community and just think its time to get out there on some of my work.

I really should have started this a fews ago when I had the good fortune of helping with port of Rockbox onto the GigaBeat F60. From this project I discovered that I like embedded devices and micro-controllers.
I have also been working on EMC for a home made PCB mill.
So there you have it, time for this adventure to start and take me to who knows where.