Showing posts with label Home Automation Project Series. Show all posts
Showing posts with label Home Automation Project Series. Show all posts

Sunday, September 20, 2015

5 Ways to Secure Your Raspberry Pi's Websocket Server.



Websocket's are a great way to transmit real time data.  I use them quite often from transfering picam to the web, controlling lights, controlling a raspberry pi picture frame, and controlling my sprinklers(pending post).  ALL with the Raspberry Pi.  But if it's done without security someone somewhere can tap in and take control.  Things could end up pretty bad if it's used to stream video and control lighting.

1. WSS (WebSockets over SSL/TLS).

First I strongly strongly recommend SSL/TLS encryption.  Just like https it encrypts the traffic between the client and server.  Nothing should be transmitted in plain text to a client. Anyone smart enough to be listening on the connection can probably find out how your websocket protocol is working and take control.  For examples on how to create a wss capable server refer to:
Some problems arise when using self-signed certificates with some clients/browsers. See here.


2.  Query String Authentication

Creating a connection connection to your websocket server by your connection parameters (sometimes a username/password) and appending it as a Query String to the end of the connection:

    var websocket = new Websocket("wss://rpi?user=Eben&password=Upton");

I don't recommend doing it that way especially if you don't have a secure SSL/TLS connection.

3. CHAP Authentication (Challenge Response Authentication)

I was not liking the query string method and knowing that just securing the channel using SSL/TLS wasn't enough I tried implementing a CHAP authentication routine for my Autobahn WS server on my Pi.
CHAP explained on wikipedia.  CHAP is a 3 way handshake:

  1. Client Connects to the websocket server, server then sends a challenge string (random characters of random or set length) to client.  
  2. Client responds with the hash of the challenge+'shared secret' 
  3. Server calculates the challenge it sent and the 'shared secret' it has locally and compares the client's hash to it's own and either authenticates (adds it to approved clients) or drops the client.
I went a bit further in my code and if the client was dropped I added him to a blocked list with a timestamp.  If the client tries to connect I check if he is in the blocked list and if his timestamp is old enough. Then continue with the CHAP auth for the client again.  I use a SHA256 one-way hash in my example.  Since I don't use nodejs I only have an autobahn example:

The javascript library I used for SHA256 is found here

4. Basic/Digest/Forms Authentication

Basic/Digest is a common way the web authenticates it's clients.  Uses a username and password authentication and there several APIs that support it.  Explanation of Digest Auth 

This can be done before a connection to the websocket server is made using a post to the server.  The server can then add the client to the list of accepted connections. 

5. Auth Header

*This only works if the client is NOT a webpage.  Just like basic/digest authentication some websocket servers can read custom headers.  Through the current web api for websockets you are not able to modify the headers in any way.  But your client may able to change his auth header through nodejs, autobahn, and socketrocket

Bonus. Using A Third Party Authentication

One way to authenticate it use a third party authentication service.  
With websockets becoming more and more popular for a easy-to-make realtime feed for your Raspberry pi projects it's important to keep your pi safe from all sides.  It's possible to layer these options to improve security.  I strongly suggest using websocket SSL/TLS always and at least one of the authentication methods.  

Please share

Sunday, September 6, 2015

Raspberry Pi: How to create your own WebSocket API - Part 2

Part 1: Setup xcode project

Now that I've set up the server to handle request from the client we can set up the iOS client. Either you can start with a blank project or fork/clone my github example.




  • Now install the SocketRocket websocket client library.  There are a couple ways to do it.  I used cocoapods, follow the directions for installation here.   I setup a basic uitableview within my viewcontroller.  
  • Link your tableview to your viewcontroller and call it tableView. 
  • Setup your viewDidLoad

static NSString *cellIdent = @"cellIdent";
NSMutableArray *outputs; //global array of our outputs for the piface 
NSMutableArray *inputs;  //global array of our inputs
- (void)viewDidLoad {
    [super viewDidLoad];
    _webSocket = [[SRWebSocket alloc] initWithURL:[NSURL URLWithString:@"wss://192.168.5.21:9000" ]];
    _webSocket.delegate = self;
    outputs = [@[@0,@0,@0,@0,@0,@0,@0,@0] mutableCopy];//pre populate our array with zeros
    inputs  = [@[@0,@0,@0,@0,@0,@0,@0,@0] mutableCopy];// "
    self.tableView.dataSource = self; //don't forget to set your delegate for your datasource
//we have a custom xib for our tableview cell.  register it here
    [self.tableView registerNib:[UINib nibWithNibName:@"OutputTableViewCell" bundle:nil] forCellReuseIdentifier:cellIdent];
    [self.webSocket open]; //open our websocket
}


We need to set our socket rocket delegate so we can handle messages from the server:


-(void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean{
    [self performSelector:@selector(connectWS) withObject:nil afterDelay:5];
}
-(void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error{
    [self performSelector:@selector(connectWS) withObject:nil afterDelay:5];

}
-(void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message{
    NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
                                                         options:NSJSONReadingMutableContainers
                                                           error:nil];
    [self parseJSON:json];
}
-(void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload{
    
}
-(void)webSocketDidOpen:(SRWebSocket *)webSocket{
    
}
-(void)parseJSON:(NSDictionary*)jsonObj{
    if([jsonObj isKindOfClass:[NSArray class]]){
        for (NSDictionary *dict in jsonObj) {
            if([dict objectForKey:@"Outputs"]) [self parseOutputs:[dict objectForKey:@"Outputs"]];
            if([dict objectForKey:@"Inputs"]) [self parseInputs:[dict objectForKey:@"Inputs"]];
        }
    }
    else{
        if([jsonObj objectForKey:@"Outputs"]) [self parseOutputs:[jsonObj objectForKey:@"Outputs"]];
        if([jsonObj objectForKey:@"Inputs"]) [self parseInputs:[jsonObj objectForKey:@"Inputs"]];
    }
}
-(void)parseOutputs:(NSString*)outputStr{
    for(int index=0; index < outputStr.length; index++){
        NSString *val = [outputStr substringWithRange:NSMakeRange(index, 1)];
        [outputs setObject:@([val boolValue]) atIndexedSubscript:index];
    }
    [self.tableView reloadData];
}
-(void)parseInputs:(NSString*)inputStr{
    for(int index=0; index < inputStr.length; index++){
        NSString *val = [inputStr substringWithRange:NSMakeRange(index, 1)];
        [inputs setObject:@([val boolValue]) atIndexedSubscript:index];
    }
    [self.tableView reloadData];
}

Note what we just did here:

  1. Set up the delegates
    •  webSocketDidOpen
    • didRecieveMessage
    • didCloseWithCode
    • didFailWithError
  2. Created code to handle the JSON message
    • Convert our JSON msg into NSData and then into a NSDictionary
    • Parsing Inputs and Outputs and modifying our global arrays for each
Now we set up the table a bit more:

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    OutputTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdent forIndexPath:indexPath];
    if(indexPath.section==0){
        int output_num = [@(indexPath.item) intValue];
        [cell setLabelText:[NSString stringWithFormat:@"Output: %d",output_num]];
        [cell setOutputStatus:[outputs[indexPath.item] boolValue]];
        [cell setOutput:output_num];
        [cell setCmd:^(int output) {
            [self.webSocket send:[NSString stringWithFormat:@"{\"Output\":\"%d\"}",output]];
        }];
    }
    else{
        int input_num = [@(indexPath.item) intValue];
        [cell setLabelText:[NSString stringWithFormat:@"Input: %d",input_num]];
        [cell setOutputStatus:[inputs[indexPath.item] boolValue]];
        [cell setCmd:nil];
    }
    return cell;
}
-(void)connectWS{
    _webSocket = [[SRWebSocket alloc] initWithURL:[NSURL URLWithString:@"wss://10.10.55.21:9000" ]];
     _webSocket.delegate = self;
    [self.webSocket open];
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section==0)
        return outputs.count;
    if(section ==1)
        return inputs.count;
    else
        return 0;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

When we set the table up we use our custom cell class:

  1. Cell count/ Section count.  We have two types of cells. One we don't have a reaction to button presses (inputs we are reading). And the other we have the outputs we want to control and see status.    
    • return 2 in our numberOfSectionsInTableView
    • return our output/input row count depending on the section number in numberOfRowsInSection
  2. Connect our cells up to the status stored in the global input/output array
    • If it is an output we set up the callback to send a custom message to our WebSocket Server.  If you recall we set our server to respond to JSON messages formatted as {"Output",pinNumber}.  So we use the IndexPath.Item to determine our position in the inputs/outputs.
    • If it is an input we do not set the "setCmd" callback from our button press.  
  3. We also set up a connectWS method to have it attempt to re-connect after 5 if the websocket connection drops. (usually happens when you lose connection to wifi/cellular or if you restart the websocket server.
In this iOS app I won't connect my custom plug code since you haven't set up the server to respond to anything but output commands.  We could set it up to be {"Plug":plugNum} in the server if we needed.  

Now we only color our output and input buttons ONLY when we know the status.  Don't set the color just because you tapped the button, let the server reply with it's status.  


For simplistic purposes I didn't decorate it anymore than this in this example.  You can be creative and set up your UI however it seems easiest.  Note that iOS does not keep this connection open when you close your app.  I don't handle it elegantly in my example code.  If you wish to have your phone get updates on your sensors while off you will need to set it up as a background service and have it poll a REST-like service you can set up on your Pi with-in the same server app.  


Custom API and modules for WebSockets

WebSocket communication is one of the best ways to get realtime data to your client device.  Creating custom class modules for each sensor type connected to device can make your code and  organized and and your project expandable.  

Raspberry Pi: How to create your own WebSocket API - Part 1



A while I posted my very first raspberry pi home automation project (LightSwitchPi) and since then I've learned a lot more python and circuitry.  I, being one of many, achieving exactly what the Raspberry Pi Foundation wanted, Education.

Here's a quick tutorial on how to create and form your own home automation api for expansion.  I am going to use Autobahn Python for the WebSocket backend and in Part 2 going to build a simple iOS app to communicate with the Pi via WebSockets (SocketRocket).

Part 1: Custom Sensor/Control Modules:

Install the following if you don't have it:

  • For WebSockets, Autobahn Python :
    • sudo apt-get install python-twisted python-pip 
    • sudo pip install autobahn
    • github example
In the github example there are several files to note:
  • websocket.py
    • The autobahn python based websocket broadcast server with ssl encryption.
  • ButtonListener.py
    • The lightswitch (module) using the first gen PiFace Relay Board.  
  • PlugPoller.py
    • A wifi plug I built (link here, forgive the sloppy design :-P ) with a uart-to-wifi interface.
  • web folder
    • simple webpage showing the broadcasts from the websocket server for testing.
First we need to set up our modules.  I'm using the term modules to clarify that you can at anytime add to your websocket server "things" your Raspberry pi can do (I.E temperature sensing, motion, etc...).  In each module you set it up as a separate thread.  

For example ButtonListener is as Follows:

import threading
import os
import pifacedigitalio
from sys import exit
from time import sleep
import time

class Buttons(threading.Thread):
    cmd = None
    loop = True
    button1Callback = None
    button2Callback = None #set up a callback for each button
    button2LongPressCallback = None #set up custom stuff if needed

We start by importing our needed libraries and creating a class of the "threading.Thread) type. I am creating several callback variables so that when we instantiate our class in the websocket server we can assign those callbacks to broadcast to our clients the status of the button presses.  We continue with the init and the run.  Take note that when input[x] is pressed it sets a variable to true and then doesn't react till you release the button. A way to programmatically set a rising/falling edge detection for button presses.  

def __init__(self):
        threading.Thread.__init__(self)
        self.cmd = pifacedigitalio.PiFaceDigital()
        self.loop = True

    def run(self):
        time_pushed = 0
        pushed_1 = False
        pushed_2 = False
        inputs = None
        # toggle button turn relay 1 on
        while self.loop:
            sleep(0.05)
            inputs = self.input_status()
            outputs = self.output_status()
            # print inputs, ' ', outputs
            if inputs[0] == '1' and pushed_1 is not True:
                pushed_1 = True
                if self.button1Callback:  # json callback for button press
                    self.button1Callback('{"Inputs":"' + self.input_status() + '"}')
            if inputs[0] == '0' and pushed_1:
                pushed_1 = False
                self.cmd.relays[0].toggle() 
                if self.button1Callback:  # json callback for button press
                    self.button1Callback('{"Outputs":"' + self.output_status() + '"}')
                    self.button1Callback('{"Inputs":"' + self.input_status() + '"}')
            if inputs[1] == '1' and pushed_2 is not True:
                pushed_2 = True
                time_pushed = time.time()
                if self.button2Callback:
                    self.button2Callback('{"Inputs":"' + self.input_status() + '"}')
            if inputs[1] == '0' and pushed_2:
                time_taken = time.time() - time_pushed
                pushed_2 = False
                if(self.button2Callback):
                    self.button2Callback('{"Inputs":"' + self.input_status() + '"}')
                if time_taken < .5:
                    self.cmd.relays[1].toggle()
                    if self.button2Callback:
                        self.button2Callback('{"Outputs":"' + self.output_status() + '"}')
                    time_pushed = 0
                if (time_taken > .5):
                    try:
                        if self.button2LongPressCallback:
                            self.button2LongPressCallback()
                    except:
                        pass
                time_pushed = 0

We also need to create a stop function so we can exit cleanly from the thread if needed. "def output_status" and "def input_status" are reading the inputs and outputs of the PiFace board and outputting them to a string for our JSON broadcast. "def output_cmd" is a quick method for changing outputs along with outputting the result to the callbacks.

    def stop(self):
        self.loop = False

    def output_status(self):
        list1 = self.cmd.output_port.value
        status = '{0:08b}'.format(list1)[::-1]
        return status

    def output_cmd(self, pin, value, local=True):
        self.cmd.leds[pin].value=value
        if self.button2Callback and not local:
            self.button2Callback('{"Outputs":"' + self.output_status() + '"}')
        return self.output_status()

    def input_status(self):
        list1 = self.cmd.input_port.value
        status = '{0:08b}'.format(list1)[::-1]
        return status


Part 2: WebSocket Broadcast Server Broadcasting

*(For the complete github code see here)
In a broadcast server you need to keep track of the following:
  • Registering clients
  • UnRegistering clients
  • Broadcasting to clients
  • When to broadcast
In my previous post I usually have a polling timer in my websocket server having the server check status of each item and sending it out on change. In this example the "modules" are doing that anyway so we will only need to assign what the callback methods do.
We will put the light switch button module in the init part of the broadcast portion of the server:

class BroadcastServerFactory(WebSocketServerFactory):

    def __init__(self, url, debug=False, debugCodePaths=False):
        WebSocketServerFactory.__init__(self, url, debug=debug, debugCodePaths=debugCodePaths)
        self.clients = []
        self.lighting = Buttons()
        self.lighting.button1Callback = self.broadcast
        self.lighting.button2Callback = self.broadcast
        self.lighting.start()
        self.plugs = PlugPoller(plugIp, 8080)
        self.plugs.statusChangeCallback = self.broadcast
        self.lighting.button2LongPressCallback = self.plugs.toggleAll

Note what we did: 

  1.  We instantiate our Button class and assign the two regular button press callbacks.  Since self.broadcast only takes one argument self.broadcast(msg) it works great for how we set it up in the button class. 
  2. Set up the plugs module along with it's callbacks. 
  3.  We also set up the long button press callback to toggle some plugs.
With those we will broadcast to our clients status changes for inputs and outputs in a JSON format. {"Outputs":"00000000"},{"Inputs":"00000000"}

Since we are not polling periodically we need to let the clients know the status of all the modules when they are registered as a client:

    def register(self, client):
        if client not in self.clients:
            client.sendMessage(json.dumps([{"Outputs":self.lighting.output_status()},
                                {"Inputs":self.lighting.input_status()},
                                {"Lamps":self.plugs.getstatus()}]))
            print("registered client {}".format(client.peer))
            self.clients.append(client)

Part 3: WebSocket Commands from clients:

When our server receives a message from a client we need to handle it if is supposed to control something.  In mine I decided since it's an output I'm toggling I just send a JSON string {"Output",pinNum}.  If it was an analog device you'd need to send a bit more.  With python you can convert json to a dictionary using json.loads(json_string).

    def onMessage(self, payload, isBinary):
        if not isBinary:
            data = json.loads(payload)
            if(data["Output"]):
                output = data["Output"]
                #get current status to toggle the output. 
                current = factory.lighting.output_status()[int(output)]
                newval = not int(current)
                #print(output,' ',current,' ',newval)
                factory.lighting.output_cmd(int(output), newval, False)
                
Remember we put a status change callback whenever we call the output_cmd.  That way all clients get the new status change.


For the iOS portion continue here

Friday, April 17, 2015

Raspberry Pi Digital Picture Frame: Part 2 Adding an Accelerometer and some more!

UPDATE (4-17-2015): 

To see "Part 1" of this project please go here
So we have few new features!!

  • Ability to hide/show clock and temperature via phone webapp 
  • Change time between image transitions via webapp
  • Uploading multiple images from the web interface now works.
  • Deleting Images now works.
  • Lazy loading of images when looking through them on the webapp. (loads as you scroll)
  •  I just added a 3-axis sensor to the 7" frame and have it broadcast to the HTML side the angle of rotation.

TODO(Coming Soon)

  • Weather feed option in the config. (see weather every 10 slides, and or outside temperature in right hand corner)
  • DNLA Support for those who have NAS servers with millions of images.
  • Option to only show images of the same aspect ratio as your picture frame rotation.(if you frame is vertical show vertical taken images and visa vera)
  • piframe image for download so no setup is required (except hardware)

Details on the new webapp features

To make it more handy to have a IoT picture frame I've added some handy configurations that load when the frame starts up. 



Details on the Acceleromter

I updated the git repository with a class to communicate via i2c to a MMA7455 accelerometer.
https://github.com/SimplyAutomationized/piframe/blob/master/MMA7455.py
The class has a callback method within it so it can broadcast a tilt change to whomever instantiates the class. Which I'm calling it within the websocket code and broadcasting to the client(the frame) the correct angle.

#I check the config file to see if you have enabled the tilt sensor
if(config['tiltsensor']):
 self.tiltSensor=tilt.TiltSensor(self.rotateFrame)
 self.tiltSensor.start()
#...later in the code we define the callback rotateFrame when rotation changes.
#(when the X axis inverts)
def rotateFrame(self,data):
 rotation=data*270
 self.frameconfig.changeKey('rotation',rotation)
 self.sendNewConfig(self,all=True)
#the code then broadcasts it's new rotation, the CSS on the frame then rotate's the images based off of the new rotation :-) win!




And rotation:

Tuesday, August 26, 2014

Raspberry Pi, Parse.com, and Temperature Logging



As part of a future project I may be working on(details coming soon). I wanted to get some logging done with some temperature sensors to the online cloud database called Parse.com
If you want your data stored on the cloud to be able to access anywhere this is what you will need to do:
  • install the DS18b20 temperature probes

Parse App Setup

 copy the application id and the rest api key to your python script

Get the ParsePy library:

install on your pi using the command

git clone https://github.com/dgrtwo/ParsePy
cd ParsePy
sudo python setup.py install

Getting my Logging Library:

download here:
https://github.com/SimplyAutomationized/raspberrypi/raw/master/ParseTempLogging/ParseTemperature.py
usage:
from ParseTemperature import *
logger = TempLogger(appkey='yourappkey',apikey='yourapikey')
logger.start()#will create the class in your app and start appending temperature data to it whenever the temperature changes. 

Now the two sensors started populating my online db. 

for reference here's the logging libarary:

from parse_rest.connection import register
from parse_rest.datatypes import Object

from threading import Thread
from time import sleep
import os
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
class Temperature(Object):
 pass


class TempLogger(Thread):
 """
 A class for getting the current temp of a DS18B20
 """
 def __init__(self, fileName='',debug=False,appkey='',apikey=''):
  Thread.__init__(self)
  register(appkey,apikey)#put your api key and app id here
  self.debug = debug
  self.probes = {}
  self.tempDir = '/sys/bus/w1/devices/'
  self.currentTemp = -999
  self.correctionFactor = 1;
  self.enabled = True
  self.repopulateprobes()
 def repopulateprobes(self):
  list = os.listdir(self.tempDir)#here we create a dictionary with the probe id's
  for item in list:
   if(item[:2]=="28"):
   if(self.debug):
    print item
   if(self.probes.has_key(item)==False):
    self.probes[item]=0

 def getTempForFile(self,file):
  try:
   f = open(self.tempDir + file + "/w1_slave", 'r')
  except IOError as e:
   print "Error: File " + self.tempDir + file + "/w1_slave" + " doesn't exist"
   return;
  lines=f.readlines()
  crcLine=lines[0]
  tempLine=lines[1]
  result_list = tempLine.split("=")
  temp = float(result_list[-1])/1000 # temp in Celcius
  temp = temp + self.correctionFactor # correction factor
  #if you want to convert to Celcius, comment this line
  temp = (9.0/5.0)*temp + 32
  if crcLine.find("NO") > -1:
   temp = -999
  if(self.debug):
   print "Current: " + str(temp) + " " + str(file)
  return float(int(temp*100))/100    
 def run(self):
  while self.enabled:
   for item in self.probes.items(): #we iterate through our probes we scanned for earlier and save temperatures to the dictionary
    temp = self.getTempForFile(item[0])
    if(item[1]!=temp):#if there is a change in the temperature we send it to parse
     parseDBObject=Temperature()
     parseDBObject.Probe=item[0]
     parseDBObject.Temperature=temp
     try:
      parseDBObject.save()
     except:
      pass
     self.probes[item[0]]=temp
 def stop(self):
  self.enabled=False
    #returns the current temp for the probe
 def getCurrentTemp(self,file):
  return self.probes[file]

Sunday, August 10, 2014

A Simple Interface for the Internet of Things with my Raspberry Pi

A Simple Interface for the Internet of Things

Awhile back I bought the Adafruit starter kit for the LPC810.
LPC811  on a TSSOP-16 breakout board

With much trial and error I was able to get a simple serial communication with it through a ttl usb cable.  I then wanted to control the I/O remotely. This device can be polled for status and controlled through tcp messages from your Android/iOS device and Raspberry Pi

My Remote Control portable plug
Parts:

  • 1 - LPC810
  • 1 - HLK-RM04
  • 1 - ULN2803APG
  • 3 - 1k ohm Resistors
  • 1 - 120v to 5v 500mA converter module (ebay)
  • 1 - 2Ch relay module
  • 1 - prototyping board

and connected it all up:


simple code for controlling my plugs in python:

import socket
class PlugPoller(threading.Thread):
 def __init__(self,ip,port):
  threading.Thread.__init__(self)
  self.ip=ip
  self.port=port
  self.connect(ip,port)
  self.status='0000'
  self.command='!getstat\r'
 def connect(self,ip,port):
  try:
   self.s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
   self.s.settimeout(1)
   self.s.connect((ip,port))
  except:
   pass
 def run(self):
  while True:
   try:
    sleep(.1)
    self.s.send(self.command)
    self.status=str(self.s.recv(4))
    #print "data:{"+self.command,self.status+"}"
   except:
    print 'error'
    sleep(5.0)
    self.connect(self.ip,self.port)
    pass
   if(self.command!='!getstat\r'):
    #print self.command
    self.command='!getstat\r'
 def getstatus(self):
  return self.status
 def sendcmd(self,c):
  try:
   self.s.send(c)
  except:
   pass
  return self.s.recv(4)
def main():
 plug=PlugPoller("192.168.16.254",8080)
 plug.start()#start the async status poller
 plug.sendcmd('!turnon1') #turns on relay 1
 plug.sendcmd('!trnoff1') #turns off relay 1
 plug.getstatus() #returns a status of 0001, first two binary numbers are the button inputs the last two are the relays
 plug.sendcmd('!talloff')#turns off all relays
Whenever these inputs are pressed it will toggle the relays locally. The pushbuttons  would be connected to the right side of the Wifi Module.   Giving you remote and local control of your device without having to put an Arduino or Raspberry Pi in that enclosure.
For me I like knowing instantly whether my light is on while looking at it remotely. The PlugPoller python script is polling statuses every tenth of a second.  The MCU and the module talk at 115k baud so you can get your results pretty quickly.

Since that looked pretty ugly (prototype), i'm currently working with the LPC811 which has more I/O.  14 configurable pins, 2 of which I will use for UART communication (12 for I/O pins) which will let you sense more inputs and turn on more outputs.  These chips can have some of these pins configured for i2c and spi that can connect you to 100s of sensors that you can have through wifi.


Please Comment if you wish to see this as a kit you could buy
Or if you have questions

Monday, February 24, 2014

Home Automation Project #4 1-Wire I/O Performance Test

Dallas has a couple 1-Wire I/O chips out there.  I decided to test the one that seemed practical to replace a light switch or plug. The DS2413 was almost perfect.  It has 2 I/O, gets power from the data line, and Adafruit made it easy for me to test by making the breakout board.

Here's what I used for my test:


With these I created a demo to see the read and write speeds through the 1-wire data line.
Source code for benchmark:

As you can see the performance dropped more than half every time I pressed the button.  Not bad if all I care about is whether the light turns on right when I press the button, and it would.
I then ran the loop to see how fast it would go at turning on and off the relay and saw an average of 20.833 requests per second. (Don't worry, the relay wasn't able to click on and off that fast)

Adding a DS18B20 Temperature sensor and requesting it every second I found that when the temperature was requested the requests per second dropped down to 1.950 requests per second and then jumped back up to the 42.27 range until the next second came along.

Requesting the temperature every loop cycle was unworkable.  I had to hold my finger on the button far longer than desired to get the relay to turn on.  I tuned it up by requesting the lesser accurate temperature value "fasttemp".  I also requested it less often (every other second).

t=ow.Sensor('/28.B0A534050000')
t.useCache(False)
print t.fasttemp

The DS2413 datasheet mentions the ability for Overdrive (~10x the communication speed) but I was unsuccessful on getting it to work.  The communication would seize when I tried enabling it on the bus.

Conclusion:
Controlling your lights with the DS2413 is possible, but you are limited on the quantity of chips on the same bus line. If you are able to get the chip's Overdrive feature working then I would suggest getting the 8-port i2c to 1-wire add-on board if you have plans for your whole house.

I'm going to test the DS2408 (8 port 1-Wire I/O chip) soon and am a little more hopeful since you can control multiple rooms and/or lights with one chip.

(Pictures coming soon.)

Tuesday, September 24, 2013

Home Automation Project #3 Light Switch Cont. - WebUI-Source with WebSockets!

For the best and quickest response times with my webgui I decided to go with websockets. This was my first websocket experiment and it took many, many tutorials and websocket engines for me to finally come to this conclusion. I went with autobahn websockets because of its ease of use and ability to do reactor.callLater() which is the equivelent of a setTimout in javascript from what I understand. With that I used it to constantly check the outputs of my PiFace and send the socket message to the client webapp based off of its changes. So if anyone else in your house turns the lights on or off physically, you can instantly see it change on your phone. Now the only problem is older devices (like my wife's phone) are not all html5 websocket compatible. You may have to create a python cgi script to use as a fallback.

If you are kinda lost and need to recap on the lightswitch series here are the links and summaries:
Setting up the Piface communication listener and the button listener scripts HERE
Pics and description of the WebUI HERE

Setup:
Need to install Twisted, AutoBahnPython, and for the static pages I use lighttpd.

sudo apt-get install python-pip
sudo easy_install autobahn
sudo apt-get install twisted lighttpd


Websocket Server Code:

needs to run on boot after out PifaceListener script (source found here) has started.

Webpage Code:

I copied to my /var/www/ directory:

Sunday, September 22, 2013

Home Automation Project #3 - WebApp

I posted last week about the Raspberry Pi Light Switch (link here) and wanted to share the web pages I've developed to controlling these home automation devices. Starting with the Lighting:



As you see in the pics the status light changed on the Lamps button.  It happened when I pushed the Lamps button on the web app which then turned the Lamps on and indicated they were on the web app.  If I were to physically press the button the webapp would indicate the change within a second of the light coming on (thanks to html5 server push and AJAX).  I've made my router a vpn server so I can securely do this from anywhere I have an internet connection or cell service.  (And now the wife's asking me why I keep playing with the lights....I am writing this at work, oops. )

If you have questions or comments don't be afraid to ask.



 Here's a sneak peak of what's coming up in the series:



Tuesday, September 17, 2013

Home Automation Project #2 Rpi Light Switch

Lightswitch Replacement

Parts: PiFace $30,
Rpi Model A $25,
Wifi Adapter $10,
120v to 5vdc adapter $5ish,
Low voltage 2 gange wall box $5
Blank wall plate $2
2x low profile sanwa arcade buttons $4

This was one of my first pi projects in my home automation endeavor. I wanted something simple and that wasn't too expensive. I decided to go with the PiFace add-on board.  
One really important thing I wanted was to be able to control the light switch via the web. I ran into a problem with the webapp though. Every time I opened it up it would reset the piface card. I found it was reinitializing the card every time it opened my cgi script. I then decided I needed a python program that would run on boot that would listen for commands to execute against the piface card. I then came upon Pyro, which came in very handy.

Source for my pyro piface

import Pyro.core
import piface.pfio as cmd
import os
from time import sleep
from sys import exit
from os import fork,chdir,setsid,umask


class Command(Pyro.core.ObjBase):
        def __init__(self):
          Pyro.core.ObjBase.__init__(self)
        def outputStatus(self):
          list1=cmd.read_output()
          status = '{0:08b}'.format(list1)[::-1]
          return status
 #output command for piface outputs
        def outputCmd(self,pin,value):
             cmd.digital_write(pin,value)
             return self.outputStatus()
#command to return input statuses
        def inputStatus(self):
          list1 = cmd.read_input()
          status = '{0:08b}'.format(list1)[::-1]
          return status
#read cpu temperature
        def pitemperature(self):
          return open('/sys/class/thermal/thermal_zone0/temp','r').read()
def main():
        Pyro.core.initServer()
        cmd.init()
        daemon = Pyro.core.Daemon()
        uri = daemon.connect(Command(),"cmd")
        print "cmd port: ", daemon.port
        print "cmd uri:", uri
        daemon.requestLoop()

if __name__ == "__main__":
  try:
    pid = fork()
    if pid > 0:
      exit(0)
  except OSError, e:
    exit(1)

  chdir("/")
  setsid()
  umask(0)

  try:
    pid = fork()
    if pid > 0:
      exit(0)
  except OSError, e:
    exit(1)
  main()


I then have either my button listener script(which runs as a daemon on boot) or the web cgi script. Here's the lightswitch.py daemon code:

import sys
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
from os import fork,chdir,setsid,umask
from sys import exit
from time import sleep
import time
import os
import Pyro.core

def main():
        loop=True
#connect to the piface pyro daemon we created earlier
        cmd = Pyro.core.getProxyForURI("PYROLOC://localhost:7766/cmd")
        time_pushed=0
        pushed_1=False
        pushed_2=False
        longpush_2=False
        count=0
        client = ModbusClient('ip_address_of_modbus_IO')
        client.close()
        while loop:
                sleep(.05)
                status = cmd.outputStatus()
                inputstatus = cmd.inputStatus()
#toggle button turn relay 1 on
                if inputstatus[0]=='1' and pushed_1 != True:
                        if status[0]=='0':
                           cmd.outputCmd(0,1)
                        else:
                           cmd.outputCmd(0,0)
                        pushed_1=True
                if inputstatus[0]=='0' and pushed_1:
                        pushed_1=False
#toggle button turn relay 2 on
                      if inputstatus[1]=='1' and pushed_2 !=True:
                        pushed_2=True
                        longpush_2=False
                        time_pushed=time.time()
#if both buttons are pressed for 10 second the reboot the pi
                      while inputstatus[0]=='1' and inputstatus[1]=='1':
                        sleep(1)
                        count=count+1
                        if(count==10):
                          os.system("sudo reboot")


#button released
                     if inputstatus[1]=='0' and pushed_2:
#calculate the time the button was pressed to determine what to do
                        time_taken = time.time()-time_pushed
                        pushed_2=False
                        if(time_taken<.5):
                         if status[1]=='0':
                           cmd.outputCmd(1,1)
                         else:
                           cmd.outputCmd(1,0)
#send command to remote i/o using modbus to turn on some lamps if you hold the button longer than 1/2 second
                        if (time_taken>.5):
                         try:
                          if(client.connect()):
                           if(client.read_discrete_inputs(200,1).bits[0]==True):
                             client.write_coil(0,True)
                           else:
                             client.write_coil(2,True)
                           client.close()
                         except:
                           e = sys.exc_info()[0]
                           f=open('error.log','w+')
                           f.write(e+'\n')
                           f.close()
                        time_pushed=0
#turn off light at certain time
                        hour=time.localtime(time.time())[3]
                        minute=time.localtime(time.time())[4]
                        second=time.localtime(time.time())[5]

                if(hour==5 and minute == 0 and second == 0 and status[0]=='1'):
                  cmd.outputCmd(1,0)


#useful daemon-like code:
if __name__ == "__main__":
  try:
    pid = fork()
    if pid > 0:
      exit(0)
  except OSError, e:
    exit(1)

  chdir("/")
  setsid()
  umask(0)

  try:
    pid = fork()
    if pid > 0:
      exit(0)
  except OSError, e:
    exit(1)
  main()



I threw in a bit of modbus to talk to some of my remote i/o to control some lamps throughout the room. The web code is similar to the lightswitch code (without listening for button presses of course). It response to AJAX requests to give the statuses of the outputs. If desired I can post the web code later.

Pics





see part one to this series here:Sprinkler Control

Saturday, September 1, 2012

Home Automation Project #1 (Sprinklers)

Home Automation Project #1 (Sprinklers)

I finally got out of the apartment business and decided as my first project for "actual" home automation would be to get my sprinkler controlled by the Koyo DL06.  I know I wanted to be able to manually turn them on and have them on a schedule at the same time. 

Part 1:
using jQuery Mobile, Asp.net forms w/ C#, and a PLC I get to turn on my sprinklers on manually.  With html5 server side event pushing live updates every couple seconds to my web app.  Now when some unexpected victim walks near my front yard. ZAP! Squirt!!

Part 2 (4hrs later): After coding all day (at work hehe) I made it so i can access and change the scheduling of the sprinkling system. Changing the PLC's schedule based on the ladder program i built. works like a charm!