Friday, January 31, 2014

OpenWRT for WEMO - Part 3 - Cross compilation and remote debug with Eclipse

Being able to compile and remotely debug applications on the WEMO is very useful in creating custom applications for remotely switching the power, or adding functionality to the WEMO. For remote debugging the WEMO must be connected to the wifi network that the cross compilation machine is on and the machine must be able to ssh into the WEMO. 

Here are some example settings to get the WEMO connected to a typical WPA-PSK wifi network. These settings can be modified over the serial terminal.
  • Edit /etc/config/network with vi and comment every line with # then add the follwing.
     
    config interface 'lan'
        option ifname 'wlan0'
        option proto 'dhcp'
        option hostname 'WEMO'

     
  • Edit /etc/config/wireless with vi and change it to the following, note change the SSID and password to that of your Wifi network.

    config wifi-iface
        option device 'radio0'
        option network 'lan'
        option mode 'sta'
        option ssid 'SSID'
        option encryption 'psk2'
        option key 'password'

     
  • Reboot the router and check over the serial terminal that the wlan0 interface has been assigned an ip address.

Using the custom compiled firmware from part 1 the required packages for remote debugging will be installed. If using the base image use the following command to install the required packages.  
opkg update
opkg install gdb-server openssh-sftp-server


The following steps setup Eclipse to cross compile a simple c project.
 

  1. Start Eclipse and navigate to "Help" menu and select "Install New Software...". In the install wizard select "--All Available Sites--" from the drop down menu next to "Work with:" at the top. This will load all available software packages that can be install in Eclipse and will take while.
     
  2. If your version of eclipse does not have CDT installed use the guide here to install it. Navigate to the "Mobile and Device Development" in the tree view and select "C/C++ GCC Cross Compiler Support", "Remote System Explorer End-User Runtime", and "C/C++ Remote Launch" as shown below.


    Click "Next >"  and follow the prompts in the wizard to install the packages. Eclipse may need to restart afterwards.
     
  3. In this example we will be creating a "C Project" that will cross compile C code only. Select "File" then "New" and finally "Project..." to bring up the "New Project" wizard. Choose the "C/C++" option in the tree view and then select "C Project" as shown below.


    Click "Next >" to proceed.
     
  4.  Select an "Empty Project" from "Executable" under "Project type:" and "Cross GCC" under "Toolchians:" as shown below.


    Choose a name for the project and enter it at the top then click "Next >" to proceed.
     
  5. In the final stage of the wizard (the "Finnish button" shown appear) click the "Advanced Settings" button. This will bring up a dialogue to edit the project settings, which can be accessed by right clicking on the project and selecting "Properties". The next steps deal with this dialogue and show the parameters that need to be added to configure the cross compiler.
  6. The staging directory in the openwrt folder contains the cross compiler and gdb for remote debugging. The first step is to configure the cross compiler, and this is under "C/C++ Build" then "Settings" on the left. Choose "Cross Settings" as shown in the image below.


    The toolchains directory depends on the architecture and gcc version. Locate the toolchain directory by looking in the staging directory of openwrt and set it to the path. The prefix is an appended string for the cross compilation tools such as gcc, this can be found by looking in the bin directory of the toolchain. Note all directories must be absolute and directories like "~/openwrt/..." will not work.
     
  7. The include directories can be specified to enable better code completion by selecting Includes as shown in the image below.


    Select the add button (upper right in the image) and locate the include directory in the toolchain directory.
     
  8. An environment variable "STAGING_DIR" is required by the cross compiler and can be set by navigating to "C/C++ Build" then "Environment" on the left as shown below.


    To add the environment variable click the "Add" and set the name as "STAGING_DIR" and the value as the path to the OpenWRT staging directory.
     
  9. Finnaly click "OK" to save the project settings and finally "Finish" to create the project.
  10. To test the cross compiler create a "main.c" file in the project by right clicking the project and selecting "New" then "File". Use the following code as a simple hello world.
     #include

    int main()
    {
        printf("hello world\r\n");
        return 0;
    }

     
  11. Save the main.c file then right click the project and select build. The output of the build (in the "Console" tab down the bottom) show a successful build, for example:

    **** Build of configuration Debug for project hello_world ****

    make all
    Building file: ../main.c
    Invoking: Cross GCC Compiler
    mipsel-openwrt-linux-gcc -I/home/sean/openwrt/openwrt/staging_dir/toolchain-mipsel_24kec+dsp_gcc-4.6-linaro_uClibc-0.9.33.2/include -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"main.d" -MT"main.d" -o "main.o" "../main.c"
    Finished building: ../main.c

    Building target: hello_world
    Invoking: Cross GCC Linker
    mipsel-openwrt-linux-gcc  -o "hello_world"  ./main.o  
    Finished building target: hello_world


    **** Build Finished ****


    If there are any problems with the build, check to ensure the paths to the tools are correct. If the path to the build tools requires changing then change the "PATH" environment variable, as changing the setting in step 6 will not update the environment variable.
To remotely debug a cross compiled project use the steps below.
  1. Ensure the "main.c" file in cross compiled project is selected in the "Project Explorer" then open the debug configuration by clicking the arrow next to the debug button and then selection "Debug Configurations..." as shown below.


    This will open the Debug configuration dialouge.
     
  2. Create a new "C/C++ Remote Application" configuration by clicking the button shown in the image below.


    This will create a new debug configuration in the left pane.
  3. Set the "Remote Absolute File Path for C/C++ Application:" to a simple path such as /tmp/hello_world. It is better to use the tmp directory as it resides in ram making upload faster and decreases wear on the flash.
     
  4. Click the "New..." button next to the combo box for "Connection:" to add a connection to the WEMO. Select a "Linux" connection in the wizard as shown below, then click "Next".


  5. Give the the IP address of the WEMO on your WiFi network for the "Host Name:", and optionally a friendly "Connection name:" as shown below.


    Do not click "Finnish", instead click "Next".
     
  6. Select "ssh.files" from the "Configuration" check list as shown below.


    Proceed by clicking "Next".
     
  7. Select "processes.shell.linux" as shown below then click "Next".

     
  8. Select "ssh.shells" as shown below then "Finish" to complete the wizard.


    This creates a new option in the combo box next to "Connection:" for the WEMO in the debug configuration.
  9. Select the newly created connection from the "Connection:" comb box. Select "Enable auto build" to enable building before debugging.
  10. Navigate to the Debugger tab (at the top), click "Browse..." next to the "GDB debugger" option and select the cross compiled GDB debugger in the toolchains bin dierctory. The GDB debugger is cross compiled as a part of the toolchain, and is located in the bin folder of the toolchain directory used earlier. The GDB executable is prefixed like all the other tools.
  11. Click the "Debug" button in the right hand corner to intiate a remote debug session. A prompt for the ssh login will appear if the connection is successful. After logging in the executable will be uploaded and debugging session started. The program should stop on a break point on the first line of code.
The console tab provides access to the remote shell session but must be selected by clicking the arrow next to the console button and selecting the remote shell option as shown below.

If you step through the hello world program, hello world will appear in this console.

If an "Error during file upload" occurs this can mean an existing debug session has not terminated correctly. This requires the termination of the gdbserver process, which can be done in the "Remote Systems" tab. To enable the "Remote Systems" tab, open the "Window" menu and select "Show View" then "Other...". In the dialogue use the search button to find the "Remote Systems" tab. The gbdserver process can be terminated by selecting the connection to the WEMO in the "Remote Systems" tab, then selecting processes. Find the gdbserver process in the treeview, right click, and select "Kill..." as shown below.


That completes a guide to cross compiling and remote debugging in eclipse. Next I will show how to interface with the gpio pins to switch the relay in the WEMO.

OpenWRT for WEMO - Part 2 - Flashing Firmware

So the WEMO arrived, and the first thing I did was set it up with my iPhone. After checking it worked I voided the warranty to attach serial lines. The serial port is used to issue commands to flash firmware onto the WEMO and requires soldiering onto the board. There are pads for RX and TX, but the pad for ground proved tricky to heat sufficiently so I used the ground pin of the header in fear of damaging the board. There is also conveniently placed via to put the ground wire through, I refrained from soldering to the via for the same reason as the ground pad.


The location of the pads and various other information about the hardware can be found here and here. I attached the ground, rx, and tx to Sparkfun FTDI XBee explorer to give access to the serial terminal. Powering on the WEMO gave a very verbose boot log.

The flash memory partitioning on the WEMO can be determined from the boot messages.

Creating 10 MTD partitions on "raspi":
0x00000000-0x00050000 : "uboot"
0x00050000-0x007c0000 : "A - Kernel and Rootfs"
0x00150000-0x007c0000 : "A - Rootfs"
0x007c0000-0x00f30000 : "B - Kernel and Rootfs"
0x008c0000-0x00f30000 : "B - Rootfs"
0x00fe0000-0x00ff0000 : "Nvram"
0x00ff0000-0x01000000 : "User_Factory"
0x00040000-0x00050000 : "Factory"
0x00f30000-0x00fd0000 : "Belkin_settings"
0x00030000-0x00040000 : "Uboot_env"

The stock firmware allows for updating from Belkin, so to increase reliability there are actually 2 firmware images stored in flash. From the partitions above you can see where they reside in flash. Uboot uses the environment variables "bootstate" and "check_boot" for switching between which images to boot from (more info can be found on the OpenWRT site).

When I first uploaded the firmware onto the WEMO I assumed that OpenWRT would either override this or nicely work with their redundancy scheme. Unfortunately it didn't quite work out because the partitions OpenWRT expected to see weren't there as it was put into the "B - Kerenel and Rootfs" partition.

Using the fwupgrade tool in the stock firmware I flashed my compiled firmware image in, but at boot it would not mount the rootfs partition. Setting the uboot "bootarg" variable with different mtdblock numbers did not remedy the situation. So I booted back into the stock firmware (changed "bootstate" to 0) and dd'ed the stock firmware to overwrite openwrt using:

dd if=/dev/mtdblock1 of=/dev/mtdblock3
 
This overwrites the kernel and rootfs. The intial state of the flash memory appears to have identical contents of a and b firmware partitions. To flash the OpenWRT firmware requires that a stock firmware version of less than WeMo_WW_2.00.2176.PVT. To find the firmware version use this command in the serial terminal

cat /etc/ver.txt

The contents of my ver.txt is:
 

02/19/2012 06:35:50 AM
WeMo_WW_1.01.1105.PVT

If you have an upgraded WEMO it may be possible to still boot into the stock firmware, you can check if the stock firmware is in the b partition by using step 4 and 5 below.

To write the OpenWRT firmware to the WEMO use the following steps:

  1. Ensure the WEMO is connected to your WIFI network by setting it up, DO NOT UPGRADE THE FIRMWARE if prompted.

  2. This step is optional - if you want to used a custom compiled image. Install apache or any other web server. This is needed to download the firmware image. Place the compiled firmware image in the in root web server directory and ensure it is accessible.

  3. Open a terminal for the serial port, I used PuTTy, the buad rate is 57600.
     
  4. While in the terminal hold down "4" and then boot the WEMO, uboot only has a 1 second wait time.
     
  5. In the uboot command line set it to boot from the b firmware image using:
     
    set bootstate 2
    set boot_check 0
    set bootargs 'console=ttys1,57600n root=/dev/mtdblock4'
    saveenv
    boot
     
    After the boot command the WEMO will reboot into the stock firmware image from the b firmware partition.
     
  6. Wait for about 10 seconds for a prompt, the serial terminal is the default output for some of the log messages so messages will appear sporadically. To stop these log messages use:
     

    killall sh
    killall wemoAPP

    This kills the Belkin applications that enable remote switching and log to the serial port.
     
  7. Now we can download the firmware image into the tmp (this is for a firmware image from openwrt.org, change the url accordingly):
     

    cd /tmp
    wget http://downloads.openwrt.org/snapshots/trunk/ramips/openwrt-ramips-rt305x-belkinf7c027-squashfs-sysupgrade.bin

    The tmp directory resides in RAM, all other directories are in flash so the image will not fit. I have given the URL to the trunk snapshot on openwrt.org, if you are using a custom image give the url to webserver that has the image.
     
  8. The image is now in the tmp directory and it can be flashed using:
     

    fwupgrade openwrt-ramips-rt305x-belkinf7c027-squashfs-sysupgrade.bin
     
  9. Reboot the router using the "reboot" command and then hold "4" to enter the uboot command menu. The "bootstate" and "boot_check" variable need to be set in order to prevent uboot reverting back to the stock firmware.
     
    set bootstate 0 
    set boot_check 0
    saveenv
    boot

    The WEMO will now reboot and hopefully boot into OpenWRT. The nice thing is that the stock firmware can be reverted to by changing the boot variables using step 5.
In the next part I will show how to use Eclipse to compile and remotely debug software for the WEMO using the toolchain compiled in part 1.

Thursday, January 30, 2014

OpenWRT for WEMO - Part 1 - Compiling firmware

While waiting for a Belkin WEMO to arrive in the mail, I decided to at least get the firmware and development tools ready for its arrival. The Belkin WEMO is a power socket switch that can be turned on and off via the internet. It runs an embedded form of linux, with 16 Mb of storage and 32 Mb of ram. The embedded processor it uses (RT5350F) is part of the ralink mips embedded processor line for networking devices such as routers. OpenWRT is embedded linux for routers and many ARM and MIPS based devices. The ralink MIPS processor is supported by OpenWRT, so I will show how to install OpenWRT on the router and develop software for it.  This will enable development of custom applications to run on the device for switching appliances not restricted to Belkins proprietary software. Alternatively you could use the uPnP protocol with the stock firmware to control the unit (here), but that's a messy solution that requires a computer!

There are some prerequisites for putting OpenWRT on the WEMO, which are:

  • You must have Linux, preferably Ubuntu
  • The WEMO must be running stock firmware (pre 2.00.2176), due to an exploit Belkin locked access to the device (see here).

The following steps show how to create the toolchain for cross compilation, create tools for remote debugging, and create the firmware image for the WEMO.

  1. Install the latest build tools for linux.

    sudo apt-get install subversion build-essential libncurses5-dev
    sudo apt-get install git-core python2.7-dev
     
  2. Checkout the latest OpenWRT.
     
    mkdir ~/openwrt
    cd ~/openwrt
    git clone git://git.openwrt.org/openwrt.git
     
  3. Update and download the feeds, the feeds are source code for building packages to install in the firmware image.
     

    cd ~/openwrt/openwrt
    ./scripts/feeds update -a
    ./scripts/feeds install -a
     
  4. Start the menu configuration for OpenWRT, this will check for dependencies required for cross compilation.
     

    make menuconfig
     
  5. The menu configuration configures which cross compilation tools are to be compiled for creating a firmware image for a specific platform. For the Belking WEMO select the Target System as "Ralink RT288x/RT3xxx" and select the Subtarget as "RT3x5x/RT5350 based boards"
     
  6. This step enables options to build a toolchain for cross compiling and tools for remote debugging in eclipse (tutorial how to do this here). To build a toolchain and remote debugging tools select the following options:
     
    • Enable "Advanced configuration options (for developers)" (press space  bar), and from this menu (press enter to open once enabled) select "Toolchain Options --->" and ensure "Build gdb (NEW)" is enabled.
    • Back in the main menu, enable "Build the OpenWRT based Toolchain"
    • Select the "Development --->" menu and enable the "gdbserver" option, To select the option press space bar twice until an * appears next to the option, when M appears next to an option the package will be built but not installed in the firmware image.
    • Back to the main menu, then select "Network --->", "SSH --->" and enable the package "openssh-sftp-server"
     
    These options will allow for compilation and remote debugging using Eclipse, guide will be [here]
     
  7. Exit menu configuration and when prompted save the configuration.
     
  8. Begin the build processing with:
     
    make 
    
     
    This can take several hours, if there are problems use the option V=99 to get a more verbrose output. 

This completes the build of the firmware image, which can be found in:
  

~/openwrt/openwrt/bin/ramips/openwrt-ramips-rt305x-belkinf7c027-squashfs-sysupgrade.bin

The next step (here) is to connect serial lines to the Wemo, prepare the uboot environment, and finally flash the firmware image.

Tuesday, September 10, 2013

OpenWRT based Video Recording System - Part 2 - Software setup for OpenWRT

Fromatting SD card with EXT2

In order to use the SD card with OpenWRT it must be formatted with the EXT2 filesystem. For flash based storage devices EXT2 is preferred as it reduces the amount of writes performed, as it is not a journaled filesystem. Flash devices have a limited number of write cycles, and while this is limit is very high (millions or more) reducing the number of writes will increase the lifespan of the device. A non journaled filesystem essentially means that it does not track changes to files, which results in less writes performed.

These are the steps to format an SD card using Ubuntu:
  1. Check to see where SD card is mounted.

    root@ubuntu:~# mount
    ...
    /dev/sdb1 on /media/sean/9016-4EF8 type vfat
     
  2. Unmount the SD card.

    root@ubuntu:~# umount /dev/sdb1
     
  3. Run fdisk to remove existing partition and create new partition for EXT2.

    root@ubuntu:~# fdisk /dev/sdb

    Command (m for help): d
    Selected partition 1

    Command (m for help): n

    Partition type:
       p   primary (0 primary, 0 extended, 4 free)
       e   extended
    Select (default p): p
    Partition number (1-4, default 1): 1
    First sector (2048-15407103, default 2048):
    Using default value 2048
    Last sector, +sectors or +size{K,M,G} (2048-15407103, default 15407103):
    Using default value 15407103

    Command (m for help): p

    Disk /dev/sdb: 7888 MB, 7888437248 bytes
    13 heads, 13 sectors/track, 91166 cylinders, total 15407104 sectors
    Units = sectors of 1 * 512 = 512 bytes
    Sector size (logical/physical): 512 bytes / 512 bytes
    I/O size (minimum/optimal): 512 bytes / 512 bytes
    Disk identifier: 0x00000000

       Device Boot      Start         End      Blocks   Id  System
    /dev/sdb1            2048    15407103     7702528   83  Linux

    Command (m for help): w
    The partition table has been altered!

    Calling ioctl() to re-read partition table.
    Syncing disks.
     
  4. Finally create the EXT2 file-system on the new partition.

    root@ubuntu:~# mkfs.ext2 /dev/sdb1
    ...
    Allocating group tables: done                          
    Writing inode tables: done                          
    Writing superblocks and filesystem accounting information: done
     
The SD Card is now ready for use in OpenWRT. The next steps are to install OpenWRT on the router, and then transfer the OpenWRT filesystem from the internal flash memory to the SD card. Finally we can install the packages needed to capture video from the USB webcam.

OpenWRT configuration on MR3020

The firmware used on the MR3020 can be obtained from:

MR3020 OpenWRT 12.09 r36088 for sysupgrade
MR3020 OpenWRT 12.09 r36088 for factory upgrade

The first link is the firmware image for a sysupgrade using OpenWRT, and the second link is the firmware image that can be used with the factory firmware update.

The following steps will configure OpenWRT to use the SD card as the overlay. The overlay is where any changes to the file system are stored, as the original file system is read only.
  1. Update opkg repositories.
     
    opkg update
     
  2. Install the kmod-usb-storage, kmod-fs-ext4 and block-mount packages to enabled usb flash drive support.
     
    opkg install kmod-usb-storage kmod-fs-ext4 block-mount

     
  3. Create a directory to mount the USB drive on, and mount it.yes
    mkdir /mnt/sda1
    mount /dev/sda1 /mnt/sda1

     
  4. Copy the contents of the existing overlay to the flash drive. 
         
    tar -C /overlay -cvf - . | tar -C /mnt/sda1 -xf -

     
  5. Edit the file /etc/config/fstab and add the following.

    config mount
            option target   /overlay
            option device   /dev/sda1
            option fstype   ext2
            option options  rw,sync
            option enabled  1
            option enabled_fsck 0
     
  6. Reboot.
  7. Check to see if it has mounted correctly by looking at the free space on the root.
     
    OpenWrt:~# df -h
    Filesystem                Size      Used Available Use% Mounted on
    rootfs                    7.2G      3.3M      6.8G   0% /
    /dev/root                 2.0M      2.0M         0 100% /rom
    tmpfs                    14.3M     72.0K     14.2M   0% /tmp
    tmpfs                   512.0K         0    512.0K   0% /dev
    /dev/sda1                 7.2G      3.3M      6.8G   0% /overlay
    overlayfs:/overlay        7.2G      3.3M      6.8G   0% /
     
Creating a swap file increases the stability of the system as capturing video is memory intensive and may exhaust the limited RAM. Also log files may become large if the system isn't rebooted for long periods, they are stored in a temporary directory which is in RAM. The following steps setup a swap file.
  1. Create the swap file using dd, the count is the number of kilobyes as the blocksize (bs) is a kilobyte (1024 bytes). For a count of 65536 a 64 MB swap will be created. Note this will take some time.

    dd if=/dev/zero of=/swapfile bs=1024 count=65536
     
  2. The file needs to be formatted as a swap file using mkswap.

    mkswap /swapfile
     
  3. The swapfile needs to be mounted by the fstab, so edit /etc/config/fstab and add the following.

    config swap
            option device   /swapfile
            option enabled  1

     
  4. Restart fstab to mount and enable the swap file.

    /etc/init.d/fstab restart
     
  5. Check the swap is working using free. You should see 65532 under the total column for the Swap row.

    # free
                 total         used         free       shared      buffers
    Mem:         29212        27856         1356            0         1216
    -/+ buffers:              26640         2572
    Swap:        65532            0        65532

     
The USB flash drive has now been configured as the overlay and with a swapfile.

Logitech C170 Webcam configuration for OpenWRT


The next stage is installing packages and configuring the Webcam, which is as following.
  1. Install the packages ffmpeg, and kmod-video-uvc, the Logitech C170 webcam uses the usb video class (uvc) drivers and ffmpeg is used to encode videos.
         
    opkg update
    opkg install ffmpeg kmod-video-uvc

     
  2. Plug the C170 in and check that the drivers work by looking at the dev directory, it should contain video0.
  3. "Motion" is a software package that will capture videos or images when motion has been detected from a video source (the webcam in our case). The standard motion package that was compiled for OpenWRT does not have ffmpeg support, so I compiled a custom version. This version can be obtained here. To install it on the MR3020 do the following.
         

    wget http://228899seankelly.googlecode.com/svn/trunk/ar71xx/motion/motion_20120605-224837-2_ar71xx.ipk
    opkg install motion_20120605-224837-2_ar71xx.ipk

     
  4. Motion has a configuration file in /etc/motion.conf, to capture video from the C170 webcam the following options were set.

    The pixel format of the C170 webcam is MJPEG which corresponds to a value of 8 for the v4l2_palette option:

    v4l2_palette 8

    The size of the image to be captured is 320x240 so this is given by width and height. 320x240 lowers the strain of motion detection.

    width 320
    height 240


    Decreasing the frame rate to less than 5 fps will also reduce the processing required. For my setup I found 3 fps was adequate to detect and record motion, I set it using the following.

    framerate 3

    To detect motion a threshold is required, this is the number of pixels that must change in the picture for motion to be present. For the 320x240 image size and a wide angle camera about 500 to 1000 pixels should be adequate. To set the number of pixels the threshold is set as following.

    threshold 1000

    De-speckling of the motion to produce better defined bounds for the motion can be turned off to further reduce the processing required. To turn of the filters that do this comment out the line below using ";"

    ;despeckle_filter EedDl

    In order to filter out some noise the minimum number of consecutive frames with motion can be set. This stops random noise from cause a motion event. The minimum number of frames is set as following, I used 2 frames as at 3 fps this is 0.6 of second of motion is required to start a motion event.

    minimum_motion_frames 2

    In order to create better video captures a number of frames after and before the motion event can be saved as well to create a more fluid video. The pre_capture and post_capture variables specify the number of frames to capture before and after and event. I set both to 2 frames, as following.

    pre_capture 2
    post_capture 2


    The goal is to use ffmpeg to encode videos so we need to disable image output by setting the following.

    output_pictures off

    The default bitrate for ffmpeg is high for lower resolutions so lowering it to between 200000 bps to 300000 bps should be ok, to do this change the following.

    ffmpeg_bps 200000

    To enable playback in a browser, ffmpeg must encode videos in a compatible format such as a flash swf. To use the swf format set the following.

    ffmpeg_video_codec swf

    The last setting is the directory to store the videos in, to give access to the videos from the inbuilt http server they can be stored in the /www folder using the variable as following.

    target_dir /www/cam
This completes the setup for motion to capture video from the C170 webcam. The files will be output to to the cam directory in the uhttp deamons www directory, which gives access to them from the web. 

Friday, September 6, 2013

OpenWRT based Video Recording System - Part 1 - Hardware

An OpenWRT router can be used to capture video with a usb webcam in order to record movements in a room. The internal flash storage for the MR3020 is only 4 Mb which isn't sufficient for storing video. So additional storage is required, which can be provided by a USB flash device. However the MR3020 Router only has a single USB port, so it needs to be expanded with a usb hub. The usb hub in the images below is small enough to fit inside the MR3020, and has a built in micro SD card reader. The SD card reader is essentially a usb SD card reader connected to the 4th USB port of the hub. Removing the casing and de-soldering the usb jacks are the first steps.


The USB port on the MR3020 needs to be removed to connect the USB hub. Short small gauge wires are suitable for connecting the hub. The ground wire needs to have a short amount of wire exposed above the board, the reason for this will become clear later. The USB port can be put back onto the MR3020 board but first the power and data lines must be connected to the pins. This will restore the functionality of the USB port however it will be internal connected to the USB hub so it adds the benefit of an internal SD carder reader.



The USB port can be reattached using only the mounting tabs, and the pins that go into the board can be bent outwards. This allows the wires attached to them to be routed along the board and attached to a free port on the USB hub. The ground pin of the USB port can be directly attached the short length of ground wire that was exposed from earlier. This saves having to run an additional line. The power wire should be run back to the hub in case the hub has the capability to shut off power to the ports.


This completes the required modifications to the interal hardware of the MR3020 router. An SD card can now be used to store videos, but OpenWRT needs packages to be installed and configuration to use the SD card reader and webcam, details will be given in part 2.

The logitech C170 webcam has a very narrow field of view, probably around 45 degrees. This is problematic when trying to monitor a room as some of the room is outside the field of view of the webcam. To increase the viewing angle of the camera lenses designed for smart phones can be used. These come with a metallic ring that a magnet on the lense sticks to in order to hold the lense in place. This can be used on the logitech webcam to hold these types of lenses in place. The two vertical bezels above and below the sensor need to be cut so that the lenses sit flush.


There are two types of lenses available, a wide angle lense and a fish eye lense. The wide angle lense gives about 120 degrees of viewing angle, while the fish eye gives 180 degrees. The downside of these lenses is that they distort the image.



The fish eye lense is to the right, and the wide angle is to the left.

I installed the two cameras in the lounge and kitchen, which you can see below.

Configuring the MR3020 routers to capture video is here.

Monday, February 25, 2013

Sparkfuns' Open Logic Sniffer

Sparkfun sells a Logic sniffer which is a low cost OLS (Open Logic Sniffer) platform that supports the sump logic analyser software. It uses a FPGA connected to a usb to serial adapater, and this is where the problem lies. The drivers required for the usb to serial adapter do not work with Windows 8 as they are not signed. The following procedure will sign the drivers:

  1. Obtain the driver to sign by downloading the ols software, found here. Either version (expert or full) contains the driver.
     
  2. Modifications to the inf file are needed in order to use the usbser.sys driver provided by windows. Extract the archive and find the driver directory. Locate mchpcdc.inf and copy it to another directory (for example C:\drivers). Edit the copied version and make the following changes:
     
    [DestinationDirs]
    FakeModemCopyFileSection=12 //add
    DefaultDestDir=12
    ...
    [DriverInstall.nt]
    include=mdmcpq.inf
    CopyFiles=DriverCopyFiles.nt  //remove
    CopyFiles=FakeModemCopyFileSection //add
    AddReg=DriverInstall.nt.AddReg
    ...
    [DriverCopyFiles.nt]  //remove
    usbser.sys,,,0x20     //remove

    ...
    [DriverInstall.NTamd64]
    include=mdmcpq.inf
    CopyFiles=DriverCopyFiles.NTamd64 //remove
    CopyFiles=FakeModemCopyFileSection //add
    AddReg=DriverInstall.NTamd64.AddReg
     
     
  3. The next steps sign the driver and require the Windows Driver Kit, found here.
     
  4. If you have Visual Studio 2012, open a Developer Command Prompt as an administrator. Otherwise open a command prompt as an administrator and use the following if you are running 64 bit windows:

    set PATH=PATH;C:\Program Files (x86)\Windows Kits\8.0\bin\x64
      

    or if you are running 32 bit windows:

    set PATH=PATH;C:\Program Files\Windows Kits\8.0\bin\x86
     

    This adds the path of the tools needed for the driver signing. The Developer Command Prompt already has these paths setup.
     
  5. The directory of the inf used in the following steps is in C:\drivers. The first step is to change the date of the driver in the inf using the following:

    C:\drivers>stampinf -f mchpcdc.inf -d 09/09/2012 -v 9.0.9999.0
    Stamping .\mchpcdc.inf [Version] section with
    DriverVer=09/09/2012,9.0.9999.0
     

    This sets the date of the driver so that it can be signed. The date needs to be newer than 21/04/2012 as we cannot sign software created before windows 8.
     
  6. Next create a catalog file for the driver:
     
    C:\drivers>inf2cat /driver:. /os:8_X86,8_X64
    ....................
    Signability test complete.
    Errors:
    None
    Warnings:
    None
    Catalog generation complete.
     
  7. A certificate is needed to sign the driver catalog, to create a certificate use:
     
    C:\drivers>Makecert -r -pe -ss PrivateCertStore -n "CN=TestCertforWDK" TestCert.cer
    Succeeded
     

    This creates the certificate to sign the driver catalog, it must now be added to the trusted certificates on the computer. This is what allows the driver to be installed as the certificate to sign the driver is also part of the trusted certificates on the computer. The following commands add the certificate to the root and to the trusted publishers:
     
    C:\drivers>certmgr.exe /add TestCert.cer /s /r localMachine root
    CertMgr Succeeded
    C:\drivers>certmgr.exe /add TestCert.cer /s /r localMachine trustedpublisher
    CertMgr Succeeded
     
  8. The driver catalog can now be signed with the certificate created in the previous step, using the following:
     
    C:\drivers>Signtool sign /v /s PrivateCertStore /n TestCertForWDK /t http://timestamp.verisign.com/scripts/timestamp.dll mchpcdc.cat
    The following certificate was selected:
        Issued to: TestCertforWDK
        Issued by: TestCertforWDK
        Expires:   Sun Jan 01 12:59:59 2040
        SHA1 hash: ...
    Done Adding Additional Store
    Successfully signed and timestamped: mchpcdc.cat
    Number of files successfully Signed: 1
    Number of warnings: 0
    Number of errors: 0

     
  9. The final step in signing the driver is to verify the driver catalog and associated inf, this is done using:
     
    C:\drivers>Signtool sign /v /s PrivateCertStore /n TestCertForWDK /t http://timestamp.verisign.com/scripts/timestamp.dll mchpcdc.cat
    The following certificate was selected:
        Issued to: TestCertforWDK
        Issued by: TestCertforWDK
        Expires:   Sun Jan 01 12:59:59 2040
        SHA1 hash: ...
    Done Adding Additional Store
    Successfully signed and timestamped: mchpcdc.cat
    Number of files successfully Signed: 1
    Number of warnings: 0
    Number of errors: 0
    C:\drivers>Signtool verify /pa /v /c mchpcdc.cat mchpcdc.inf
    Verifying: mchpcdc.inf
    File is signed in catalog: mchpcdc.cat
    Hash of file (sha1): ...
    Signing Certificate Chain:
        Issued to: TestCertforWDK
        Issued by: TestCertforWDK
        Expires:   Sun Jan 01 12:59:59 2040
        SHA1 hash: ...
    The signature is timestamped: Mon Feb 25 09:07:48 2013
    Timestamp Verified by:
        Issued to: Thawte Timestamping CA
        Issued by: Thawte Timestamping CA
        Expires:   Fri Jan 01 12:59:59 2021
        SHA1 hash: ...
            Issued to: Symantec Time Stamping Services CA - G2
            Issued by: Thawte Timestamping CA
            Expires:   Thu Dec 31 12:59:59 2020
            SHA1 hash: ...
                Issued to: Symantec Time Stamping Services Signer - G4
                Issued by: Symantec Time Stamping Services CA - G2
                Expires:   Wed Dec 30 12:59:59 2020
                SHA1 hash: ...
    Successfully verified: mchpcdc.inf
    Number of files successfully Verified: 1
    Number of warnings: 0
    Number of errors: 0
     
  10. The driver is now signed. Right click on the mchpcdc.inf and click install. Next time the Open Logic sniffer is plugged in it should be detected and the correct driver installed.
This guide was based on these links:

http://www.microchip.com/forums/m488342.aspx

http://msdn.microsoft.com/en-nz/library/windows/hardware/ff547089(v=vs.85).aspx

http://stackoverflow.com/questions/10832499/workaround-to-skip-driver-signing-in-64bit-windows