Wednesday 10 December 2014

Disable Screen Auto Rotation on Unity3D

Disable screen auto-rotation in a game in Unity. 

Option 1


Create a script that disables auto rotate to portrait and sets the orientation to landscape.

using UnityEngine;

public class CameraScript : MonoBehaviour {

    void Start() {
        DisableAutoRotation ();
    }

    public void DisableAutoRotation() {
        Screen.autorotateToPortrait = false;
        Screen.autorotateToPortraitUpsideDown = false;
        Screen.orientation = ScreenOrientation.Landscape;
    }
}



Create a game object to attach the script to. This can be any game object. You could also attach the script to the main camera in the scene either. When the game is run on hand held devices, the autorotation will be disabled.

Option 2


Another solution to this problem is to change this setting when building the project. 
Go to 
File -> Build Settings...




Click on Player Settings...


Click on Resolution and Presentations panel in the inspector. This will then expand and present more options.




In the Resolution and Presentation panel there are options for configuring the orientation.
First select the default Orientation. This is the orientation that the game will start in. 
You can configure what orientations are allowed when the game is being run. To do this, check or uncheck the required boxes for "Allowed Orientations for Auto Rotation".



Monday 13 October 2014

Setting up Minidlna on Linux Mint

Minidlna is useful for broadcasting media around your home network. Multimedia can be streamed from the minidlna server to different upnp enabled devices such as computers/smartphones/game consoles.

Install the Pre-requisites
sudo apt-get install software-properties-common python-software-properties


Add the repository to get minidlna
sudo add-apt-repository ppa:djart/mindlna


update the repo
sudo apt-get update


Install minidlna
sudo apt-get install minidlna


Change the configuration file
sudo vim /etc/minidlna.conf


Change the user in the file to whatever user you want to use
Comment out the media_dir
Add an Audio directory, Video directory, Pictures directory. Also add the location that the Log files will be kept and where the database file will be kept
media_dir=A,/home/myuser/Music
media_dir=P,/home/myuser/Pictures
media_dir=V,/home/myuser/Videos
db_dir=/home/myuser/Cache
log_dir=/home/myuser/Log

Change the name of the DLNA server
friendly_name=myServerName


Restart the minidlna server
sudo service minidlna restart


If you see this error, Cannot connect to server, make sure to reload the server with the new content,
minidlnad -R

Thursday 12 June 2014

Allow Remote Connections to MySQL Database on Raspberry Pi

This article shows how to set up a MySQL database to allow remote client connections. This will allow other programs on remote computers to access the database.
The first step is to allow machines to connect. This is done by removing the bind-address line from the configuration file /etc/mysql/my.cnf

Once this is done restart the database to pick up the changes
/etc/init.d/mysql restart

Once the database is restarted, we need to create database user for the remote clients. We create a user called remoteuser.
CREATE USER 'remoteuser'@'%' IDENTIFIED BY 'remoteuser';

Next, we grant all permissions to remoteuser for our database, mydatabase
GRANT ALL ON mydatabase.* TO 'remoteuser'@'%';

Finally, we set the password for the user to 'remotepassword'.
SET PASSWORD FOR 'remoteuser'@'%'=password('remotepassword');

Now external clients can connect remotely to the database and should be able to execute commands against it.

Thursday 20 March 2014

Create a Simple Kernel Module on Ubuntu

Create a file, hello.c, that prints "Hello, world" when the module is loaded and prints "Goodbye, cruel world" when the module is unloaded
#include 
#include 
MODULE_LICENSE("Dual BSD/GPL");

static int hello_init(void) {
        printk(KERN_ALERT "Hello, world\n");
        return 0;
}

static void hello_exit(void) {
        printk(KERN_ALERT "Goodbye, cruel world\n");
}

module_init(hello_init);
module_exit(hello_exit);

Create a Makefile
ifneq ($(KERNELRELEASE),)
        obj-m := hello.o

else
        KERNELDIR ?= /lib/modules/$(shell uname -r)/build
        PWD := $(shell pwd)

default:
        $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
endif

Running make will create the kernel module named hello.ko
make

load the module by using the following command
sudo insmod hello.ko
View the messages by entering the dmesg command.
dmesg

unload the module by using the following command
sudo rmmod hello

Sunday 16 March 2014

Playing Internet Radio Stations on Raspberry Pi

Install mpd and mpc. MPD is the music player and MPC is a client to control the music player
sudo apt-get install mpc mpd

Once these are installed, you just need to have a stream to play from. I found this site useful for getting streams: http://www.listenlive.eu/index.html
Add the stream to the playlist
mpc add http://stream.hoerradar.de:80/deltaradio-alternative128
Play the station using the following command.
mpc play
Use the following command to stop the player.
mpc stop
Once the station is added, you will only need to use mpc play or mpc stop to control the player.

Add Syntax Highlighting in Vim

Syntax highlighting is extremely helpful when editing code. Vim has syntax highlighting built in to it but it is not enabled by default. To enable syntax highlighting, edit the Vim configuration file, /etc/vim/vimrc, and add "syntax on" to the file and then restart Vim.

Show line numbers in Vim

Adding line numbers in Vim is very simple. To add line numbers in Vim, edit the vim configuration file, /etc/vim/vimrc and add "set number" to the file and then restart Vim.

Connect to Wifi network with Raspberry Pi

Edit the /etc/network/interfaces file. You will need to use sudo when editing the file.

sudo vim /etc/network/interfaces


The contents of the file should have the following, where you have to substitute your_network and network_password are the ssid and the password of your network:
auto lo

iface lo inet loopback
iface eth0 inet dhcp

allow-hotplug wlan0
auto wlan0

iface wlan0 inet dhcp
        wpa-ssid "your_network"
        wpa-psk "network_password"


Restart networking to pick up the changes
sudo /etc/init.d/networking restart

Setting up VNC on Raspberry Pi

Setting up a VNC server on Raspberry Pi will allow you to access the desktop remotely, similar to Windows Remote Desktop Connection (RPC). Unlike RPC, multiple VNC sessions can be run concurrently, allowing multiple users to use the same machine at once.

To set up a VNC server on Raspberry Pi, install tightvncserver

sudo apt-get install tightvncserver

Get the resolution of your screen in Windows
Right click on the desktop and click on "Screen Resolution"

Then see what the resolution of your screen is. Mine is 1600 x 900


Start a VNC session on the Raspberry Pi with the following command
vncserver -geometry 1600x900

This will ask for a password, enter the password.

Once this is done, the session will be displayed
New 'X' desktop is raspberrypi:1

The session number is 1. You can now view the desktop remotely.

To do this you will need to download a VNC viewer. I use RealVNC http://www.realvnc.com/download/viewer/

Now you will need the IP Address of your Raspberry Pi. Use the following command to get the IP Address
ifconfig | grep inet

pi@raspberrypi ~ $ ifconfig | grep inet
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet addr:192.168.1.37  Bcast:192.168.1.255  Mask:255.255.255.0

You will need to the inet addr. There will be two addresses. 127.0.0.1 and some other address. In my case, it is 192.168.1.37

Open the VNC viewer and type in the IP Address, colon, VNC session in the VNC Server field. <ipaddr>:<sessionnum>
Select the "Let VNC Server choose" option for Encryption and then click "Connect".



A warning message will be shown saying the connection is unencrypted.  Click the "Do not warn me about this for <vnc session> again" and click the continue button.


You will then be prompted for your password. Enter the password that you used when you installed tightnvc and click OK.

You will now be able to use the desktop


Thursday 6 March 2014

Link Apache Web Server Root Directory to Home Directory on Raspberry Pi

When Apache2 is installed on Raspberry Pi, the www directory (the root directory of the web server), is configured as /var/www

You need to use sudo to write to files in this directory. You can configure another directory to be the root directory of the web server by modifying the Apache configuration files but I used a quick and dirty way to link it to my home directory

first install apache2
sudo apt-get install apache2

stop apache
sudo /etc/init.d/apache2 stop

delete the apache www directory
sudo rm -rf /var/www

create the www directory in /home/pi
mkdir /home/pi/www

create the symbolic link to /home/pi
sudo ln -s /home/pi/www/ /var/www

Create an index.html file in /home/pi/www
vim /home/pi/www/index.html

<html>
</body>
test
</body>
</html>

Start Apache
sudo /etc/init.d/apache2 start

Check that the webserver works in the browser

Tuesday 4 March 2014

Windows API C++ Hello World Application

#define WIN32_LEAN_AND_MEAN
#include 

int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int);
bool CreateMainWindow(HINSTANCE, int);
LRESULT WINAPI WinProc(HWND, UINT, WPARAM, LPARAM);

HINSTANCE hinst;

const char CLASS_NAME[] = "WinMain";
const char APP_TITLE[] = "Hello World";
const int WINDOW_WIDTH = 400;
const int WINDOW_HEIGHT = 400;

int WINAPI WinMain(HINSTANCE hInstance,
       HINSTANCE hPrevInstance,
       LPSTR lpCmdLine,
       int nCmdShow) {
  
  MSG msg;

  if(!CreateMainWindow(hInstance, nCmdShow)) {
   return false;
  }

  int done = 0;
  while(!done) {
   if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
    if(msg.message == WM_QUIT) {
     done = 1;
    }

    TranslateMessage(&msg);
    DispatchMessage(&msg);
   }
  }

  return msg.wParam;
}

LRESULT WINAPI WinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
 switch(msg) {
  case WM_DESTROY:
   PostQuitMessage(0);
   return 0;
 }
 return DefWindowProc(hWnd, msg, wParam, lParam);
}

bool CreateMainWindow(HINSTANCE hInstance, int nCmdShow) {
 WNDCLASSEX wcx;
 HWND hwnd;

 wcx.cbSize = sizeof(wcx);
 wcx.style = CS_HREDRAW | CS_VREDRAW;
 wcx.lpfnWndProc = WinProc;
 wcx.cbClsExtra = 0;
 wcx.cbWndExtra = 0;
 wcx.hInstance = hInstance;
 wcx.hIcon = NULL;
 wcx.hCursor = LoadCursor(NULL, IDC_ARROW);

 wcx.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
 wcx.lpszMenuName = NULL;
 wcx.lpszClassName = CLASS_NAME;
 wcx.hIconSm = NULL;

 if(RegisterClassEx(&wcx) == 0) {
  return false;
 }

 hwnd = CreateWindow(CLASS_NAME,
       APP_TITLE,
       WS_OVERLAPPEDWINDOW,
       CW_USEDEFAULT,
       CW_USEDEFAULT,
       WINDOW_WIDTH,
       WINDOW_HEIGHT,
       (HWND) NULL,
       (HMENU) NULL,
       hInstance,
       (LPVOID) NULL);
 if(!hwnd) {
  return false;
 }

 ShowWindow(hwnd, nCmdShow);
 UpdateWindow(hwnd);
 return true;
}

Saturday 22 February 2014

JavaFX Create a button

Create a simple JavaFX application which displays a button.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;


public class TestApp extends Application {

 @Override
 public void start(Stage primaryStage) throws Exception {
  primaryStage.setWidth(600);
  primaryStage.setHeight(400);
  
  Button playButton = new Button("Button");
  Group group = new Group();
  group.getChildren().add(playButton);
  BorderPane root = new BorderPane();
  root.setCenter(group);
  Scene scene = new Scene(root);
  primaryStage.setScene(scene);
  
  primaryStage.show();
 }
 
 public static void main(String[] args) {
  launch(args);
 }

}

Friday 21 February 2014

Java - Check if X509Certificate is a CA certificate

How to check in Java if an X509Certificate is a Certificate Authority trust certificate
 public boolean isCA(X509Certificate x509Cert) {
  if(x509Cert.getBasicConstraints() != -1) {
   return true;
  }
  return false;
 }

Saturday 8 February 2014

Create Simple Soap Messages with JAXB

I want to create a SOAP Message with Java. I will use JAXB to construct the SOAP message.



  ...
  ...



  ...
  ...
 


We'll start with creating the soap envelope. First we will create two packages, tutorial, and tutorial.soap. tutorial will contain the main file. tutorial.soap will contain the JAXB files that will be used to construct the SOAP messages. We will start by creating a skeleton for the SOAP Envelope. tutorial.soap.SoapEnvelope.java
package tutorial.soap;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="envelope")
public class SoapEnvelope {

}
We'll create the class which creates the SoapEnvelope using JAXB and converts it to a string. tutorial.Test.java
package tutorial;

import java.io.StringWriter;

import tutorial.soap.SoapEnvelope;

public class Test {

 public static void main(String[] args) {
  SoapEnvelope envelope = new SoapEnvelope();
  
  try {            
            javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(envelope.getClass().getPackage().getName());
            javax.xml.bind.Marshaller marshaller = jaxbCtx.createMarshaller();
            marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8"); 
            marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            
            StringWriter writer = new StringWriter();
            
            marshaller.marshal(envelope, writer);
            
            System.out.println(writer.toString());
  }
  catch(Exception e) {
   e.printStackTrace();
  }
 }
}
This creates the following SOAP Message



Now we will create the namespace, xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope". To do this, create a new Java file in the tutorial.soap package called package-info.java
@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.w3.org/2001/12/soap-envelope", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED,
        xmlns={@XmlNs(prefix="soap-env", namespaceURI="http://www.w3.org/2001/12/soap-envelope")})

package tutorial.soap;

import javax.xml.bind.annotation.XmlNs;
This will create the following XML


Next we will create the SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding" attribute. To do this, add an XmlAttribute to the SoapEnvelope class.
package tutorial.soap;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="envelope")
public class SoapEnvelope {
 @XmlAttribute(name="SOAP-ENV:encodingStyle")
 private String soapEnvEncodingStyle;
 
 public SoapEnvelope() {
  soapEnvEncodingStyle = "http://www.w3.org/2001/12/soap-encoding";
 }
}
That will create the following SOAP Message




Now we will create the Soap Header and the SoapBody. For this we will add two Strings to the SoapEnvelope, soapHeader and soapBody. Will initialize the strings in the constructor.
package tutorial.soap;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="envelope")
public class SoapEnvelope {
 @XmlAttribute(name="SOAP-ENV:encodingStyle")
 private String soapEnvEncodingStyle;
 
 @XmlElement(name="header")
 private String soapHeader;
 
 @XmlElement(name="body")
 private String soapBody;
 
 public SoapEnvelope() {
  soapEnvEncodingStyle = "http://www.w3.org/2001/12/soap-encoding";
  soapHeader = new String();
  soapBody = new String();
 }
}
This creates the following SOAP Message.


    
    

Thursday 6 February 2014

Using ANT on Raspberry Pi

Install the Java Runtime
pi@raspberrypi ~/testProject $ sudo apt-get install openjdk-7-jre
Install the Java Development Kit
pi@raspberrypi ~/testProject $ sudo apt-get install openjdk-7-jdk

Check where Java is installed
pi@raspberrypi ~/testProject $ which java
It was installed in /usr/bin/java on my Pi
Set up the JAVA_HOME environment variable
pi@raspberrypi ~/testProject $ export JAVA_HOME=/usr 
Install ANT
pi@raspberrypi ~/testProject $ sudo apt-get install ant
Make a directory for the Java project
pi@raspberrypi ~/testProject $ mkdir ~/testProject 
Change to the testProject directory
pi@raspberrypi ~/testProject $ cd ~/testProject 
Create a simple Java file Test.java. This just prints a message saying "Test.java is running".
public class Test {
        public static void main(String[] args) {
                System.out.println("Test.java is running");
        }
}

Create an ANT build file, build.xml

        
                
        

There is just one target in the build file to compile the source code. You can run the build file with ant by just running ant
pi@raspberrypi ~/testProject $ ant
After this finishes building, check the contents of the directory for the java class file
pi@raspberrypi ~/testProject $ ls
build.xml Test.class Test.java
Run the Java program
pi@raspberrypi ~/testProject $ java Test
Test.java is running

Java Web Services on Raspberry Pi

These are the steps for setting up a Simple Java Web Service on the Raspberry Pi.
The Raspberry Pi might not be the most suitable device for hosting a web service but it is suitable for educational purposes.

http://www.javatutoronline.com/webservice/Axis2-Web-Service.jsp
http://axis.apache.org/axis2/java/core/docs/quickstartguide.html

Install Java
Install the java run time environment and the java development kit
sudo apt-get install openjdk-7-jre
sudo apt-get install openjdk-7-jdk

Check where java is installed
pi@raspberrypi:~/webService$ which java
/usr/bin/java

Then set up the JAVA_HOME environment variable
export JAVA_HOME=/usr

Install Tomcat
sudo apt-get install tomcat7

Install ANT
sudo apt-get install ant

Install AXIS2
Download the axis2 file (attached to this page) and unzip the axis2 to /home/pi

Set up the AXIS2_HOME environment variable
export AXIS2_HOME=/home/pi/axis2-1.6.2

Go to $AXIS2_HOME/webapp and run ant create.war
cd $AXIS2_HOME/webapp
ant create.war

Copy the axis2.war file to tomcat directory
sudo cp $AXIS2_HOME/dist/axis2.war /var/lib/tomcat7/webapps

Restart tomcat to pick up the axis2 war file
sudo /etc/init.d/tomcat7 restart

Go to the axis2 webpage
go to http://<ipaddress>:8080/axis2

You should see the axis webpage. click on the validate link. This will show you if the system is configured correctly

Create the Web Service

First, create a directory META-INF and create a services.xml file with the following contents.
<service name="GetDate" scope="application">
        <description>
                Get the date
        </description>
        <parameter name="ServiceClass" locked="false">
                test.GetDate
        </parameter>
        <operation name="getDate">
                <messageReceiver class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
        </operation>
</service>

Create a directory, test and create the java file, GetDate.java in it
package test;

import java.util.Calendar;

public class GetDate {
        public String getDate() {
                Calendar cal = Calendar.getInstance();
                int year = cal.get(Calendar.YEAR);
                int month = cal.get(Calendar.MONTH) + 1;
                int day = cal.get(Calendar.DAY_OF_MONTH);

                String date = String.format("%02d", day) + "/" +
                                String.format("%02d", month) + "/" + year;
                return date;
        }
}

Compile the java file
javac test/GetDate.java

If you need any external jars, make sure to place the jar files in a lib directory

Create the aar file
jar -cvf GetDate.aar *

Copy the aar file to the AXIS2 services directory
sudo cp GetDate.aar /var/lib/tomcat7/webapps/axis2/WEB-INF/services

There is no need to restart Tomcat, AXIS2 will pick up the changes automatically.
Go to the the following URL
http://<ip address of Pi>:8080/axis2/services/listServices

You should see the GetDate service. If you click on the GetDate link, you will be redirected to the WSDL.
http://<ip address of Pi>:8080/axis2/services/GetDate?wsdl

Creating the client

Import the WSDL
wsimport -keep -s src http://192.168.2.4:8080/axis2/services/GetDate?wsdl

With the generated files, create the following client that queries the web service
import test.GetDate_Service;

public class TestGetDateWebService {


public static void main(String[] args) {
GetDate_Service service = new GetDate_Service();
String response = service.getGetDateHttpSoap11Endpoint().getDate();
System.out.println("the date is = " + response);
}
}
If you import the WSDL into SOAPUI, you can see the SOAP messages that are sent and received by the webservice
Request
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:test="http://test">
   <soapenv:Header/>
   <soapenv:Body>
      <test:getDate/>
   </soapenv:Body>
</soapenv:Envelope>

Response
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <ns:getDateResponse xmlns:ns="http://test">
         <ns:return>31/08/2013</ns:return>
      </ns:getDateResponse>
   </soapenv:Body>
</soapenv:Envelope>

Echo Service
Now that we can use basic functionality of a WebService, we will use the webservice to echo what we send it

echo/EchoService.java
package echo;


public class EchoService {
public String getMessage(String msg) {
return "You sent: " + msg;
}
}

META-INF/services.xml
<service name="EchoService" scope="application">
        <description>
                This service echos whatever is sent into it
        </description>
        <parameter name="ServiceClass" locked="false">
                echo.EchoService
        </parameter>
        <operation name="getMessage">
                <messageReceiver class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
        </operation>
</service>

Create and copy the aar file to the tomcat axis2 services directory.

Import the wsdl and generate the source code using wsimport. Create an Echo Client using the generated code.

EchoClient
import echo.EchoService;

public class EchoClient {

 /**
  * @param args
  */
 public static void main(String[] args) {
 EchoService echoService = new EchoService();
 String response = echoService.getEchoServiceHttpSoap11Endpoint().getMessage("Hello from the client");
 System.out.println(response);
 }

}

These are the SOAP requests and responses

SOAP request
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:echo="http://echo">
   <soapenv:Header/>
   <soapenv:Body>
      <echo:getMessage>
         <!--Optional:-->
         <echo:args0>test</echo:args0>
      </echo:getMessage>
   </soapenv:Body>
</soapenv:Envelope>

SOAP response
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <ns:getMessageResponse xmlns:ns="http://echo">
         <ns:return>You sent: test</ns:return>
      </ns:getMessageResponse>
   </soapenv:Body>
</soapenv:Envelope>

Setting up SVN on Raspberry Pi

Notes from http://www.jeremymorgan.com/tutorials/raspberry-pi/raspberry-pi-how-to-svn-server/

Install Subversion
sudo apt-get install subversion

Create a directory to hold the repositories
mkdir -p /home/pi/repos

Create a new repository
svnadmin create /home/pi/repos/<repo name>

Import a project to svn repository
sudo svn import /home/pi/projects/<project to import> file://localhost/home/pi/repos/<repo name>

Install apache
sudo apt-get install apache2 libapache2-svn


Modify the file /etc/apache2/mods-available/dav_svn.conf
add the following to the file

<Location /svn>
DAV svn
SVNParentPath /home/pi/repos
AuthType Basic
AuthName "Subversion Repo"
AuthUserFile /etc/apache2/dav_svn.passwd
<LimitExcept GET PROPFIND OPTIONS REPORT>
Require valid-user
</LimitExcept>
</Location>


Restart Apache to pick up the config
sudo /etc/init.d/apache2 restart


Change the permissions of the repos directory
sudo chown -R www-data:www-data /home/pi/repos


Set up an svn user
sudo htpasswd -c /etc/apache2/dav_svn.passwd <username>

go to http://<ip of pi>/svn/<project name> and you should be able to see the revision of the project in the browser

Create a new repository
svnadmin create /home/pi/repos/<repo name>
Import the new project into the repo
sudo svn import /home/pi/<new project> file://localhost/home/pi/repos/<new repo>
Change the permissions of the repo
sudo chown -R www-data:www-data /home/pi/repos
Check out the project
svn co --username <username> http://localhost/svn/<project name>

Raspberry Pi Wifi Disconnects after an arbitrary amount of time

Raspberry Pi Wifi Disconnects after an arbitrary amount of time

I was working with my Raspberry Pi and I often noticed that it would disconnect from the network after an arbitrary amount of time. I had to either reboot or manually restart networking to get it going again. It turns out that the power management is switched on.
You can see if power management is on or off by using the following command. The iwconfig command configures a wireless network interface.
iwconfig
wlan0     IEEE 802.11bgn  ESSID:"ssid"
          Mode:Managed  Frequency:2.437 GHz  Access Point: FF:FF:FF:FF:FF:FF
          Bit Rate=52 Mb/s   Tx-Power=20 dBm
          Retry  long limit:7   RTS thr:off   Fragment thr:off
          Power Management:on          Link Quality=41/70  Signal level=-69 dBm
          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
          Tx excessive retries:50  Invalid misc:26   Missed beacon:0


I then disabled power management for the by editing the wireless interface section in /etc/network/interfaces file. I did this by adding "wireless-power off"
iface wlan0 inet dhcp
    wpa-ssid "ssid"
    wpa-psk "password"
    wireless-power off

Once this is done, I restarted networking to pick up the power management changes.
sudo /etc/init.d/networking restart
If you run iwconfig again, you should see "Power Management: off"