Wednesday, July 25, 2012

Calling Lua From C

One of the most interesting features of Lua is that it was designed to be easily embedded into other languages. Here's an example of how to call Lua using the C API:
#include <stdlib.h>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>

int main(int argc, char **argv)
{
    /* create a new Lua state and 
       load the standard libraries */
    lua_State *lua_state = lua_open();
    luaL_openlibs(lua_state);

    /* push the function onto the stack*/
    lua_getglobal(lua_state, "print");

    /* push the arguments */
    lua_pushstring(lua_state, "Hello World!");

    /* call the print function*/
    lua_call(lua_state, 1, 0); /* nargs, nresults */

    /* close the Lua state */
    lua_close(lua_state);
    return 0;
}
Compile with
$ gcc main.c -llua5.1 -o luatest

Monday, July 23, 2012

Opaque Pointers in C

When designing a library, it is generally considered a good practice to hide the implementation details from the users, i.e encapsulation, this is how it's done in C:
mylib.h
/* The declaration of object_t */
struct object_t;
mylib.c
/* The definition of object_t */
struct object_t {
    int x;
    int y;
    ...
};

/* The compiler will consider object_t an incomplete type,
   so we need to allocate it internally and return a pointer */
struct object_handle_t *new_obj()
{
     return malloc(sizeof(struct object_t));
} 

Sunday, July 22, 2012

Sending a File With OBEX in Python

This example shows how to send a file to a Bluetooth device using OBEX and PyBluez, the OBEX implementation I used here is PyOBEX
#!/usr/bin/env python
from bluetooth import *
from PyOBEX.client import BrowserClient

# bluetooth device address
address = '50:56:63:4F:BF:4B'

# find OBEX port using SDP
svc = find_service(address=address, uuid=OBEX_FILETRANS_CLASS)
channel = svc[0]['port']

# send file
print 'sending file to %s...'%address
client = BrowserClient(address, channel)
client.connect()
client.put('test.txt', 'HelloWorld!')
client.disconnect()

Friday, July 13, 2012

Wrapping Static Member Functions in Cython

I was trying to wrap a static member function with Cython, after some digging, I figured out how to do it...First, declare the function in the definition file ".pxd" in the class namespace:
#handle.pxd
cdef extern from "Handle.h" namespace "Handle":
    int getHandleCount()
Next, in the ".pyx" file use a class method to expose the function to Python code:
#handle.pyx 
cdef class Handle:
    @classmethod
    def get_handle_count(cls):
        return getHandleCount()

Tuesday, July 10, 2012

Libutask a User-Level Threads Library

Libutask is a simple user-level threads library that is designed to be extensible for experimenting with scheduling algorithms in user space.The library has a simple API and provides two schedulers, a cooperative and a preemptive one that schedules tasks in a round robin fashion. This is an example of how to use the cooperative scheduler of the library:
#include "utask.h"
/* task callback function */
void task_func(void *arg)
{
    volatile int i,c,b;
    for (i=0; i<1000; i++) {
        /* do some work */
        for (c=0; c<1000; c++);
        /* yield */
        utask_yield();
    }
    utask_destroy();
}

int main(int argc, char **argv)
{    
    /* initialize the library using the 
       default cooperative scheduler*/
    utask_init(NULL);

    /* create two tasks */
    utask_create (
        task_func, /* task callback */
        NULL,      /* task arguments */
        16384      /* stack size 16k */
    );

    utask_create (
        task_func,/* task callback */
        NULL,     /* task arguments */
        16384     /* stack size 16k */
    );

    /* start the scheduler */
    utask_run();
    return 0;
}

Source code:
hg clone https://code.google.com/p/libutask

Monday, July 09, 2012

Scripting fdisk

As part of a larger script that installs a linux distro on SD card, I was trying automate the partitioning of the card, fortunately, that can easily be done with sfdisk(8) the format of each line fed to sfdisk is:
<start> <size> <id> <bootable> <c,h,s> <c,h,s>
Some fields are optional, like start or size, if left out sfdisk will use the defaults, i.e. the first cylinder or the remainder of the disk etc...  The following script creates two partitions a 16-cylinder/id(53) partition and the remaining of the disk in a partition of type 83:
echo "umounting device ${dev}..."
umount ${dev}*

echo "creating partitions on ${dev}..."
sfdisk ${dev} << EOF
,16,53,
,,83
EOF

Wednesday, July 04, 2012

Parse Command Line Options in Bash Script

This is an example of how to use getopts to parse command line options in bash
#!/usr/bin/env bash
LIST_FILE=0
RECURSIVE=0
# parse options from command line 
while getopts l:r: OPT; do
    case "$OPT" in
        r)  RECURSIVE="$OPTARG";;
        l)  LIST_FILE="$OPTARG";;
      [?])  echo "Usage: $0 [OPTION] [ARGS]">&2; exit 1;;
    esac
done
# shift parsed options
shift `expr $OPTIND - 1`
# process the arguments
for file in "$*"; do
    echo $file
done

Tuesday, July 03, 2012

How to Decompress jpeg Images Using libjpeg

This is a function I wrote to decompress jpeg images using libjpeg:
#include <jpeglib.h>

int decode_frame(const char *buffer, int length, void *samples)
{
    int n_samples;
    struct jpeg_error_mgr err;
    struct jpeg_decompress_struct cinfo = {0};

    /* create decompressor */
    jpeg_create_decompress(&cinfo);
    cinfo.err = jpeg_std_error(&err);
    cinfo.do_fancy_upsampling = FALSE;

    /* set source buffer */
    jpeg_mem_src(&cinfo, buffer, length);

    /* read jpeg header */
    jpeg_read_header(&cinfo, 1);

    /* decompress */
    jpeg_start_decompress(&cinfo);

    /* read scanlines */
    while (cinfo.output_scanline < cinfo.output_height) {
        n_samples = jpeg_read_scanlines(&cinfo, (JSAMPARRAY) &samples, 1);
        samples += n_samples * cinfo.image_width * cinfo.num_components;
    }   

    /* clean up */
    jpeg_finish_decompress(&cinfo);
    jpeg_destroy_decompress(&cinfo);
    return 0;
}

Monday, July 02, 2012

Python Class to Read/Write a Serial Port

This is a Python Class to read/write from a serial port:
import serial
class Serializer: 
    def __init__(self, port, baudrate=19200, timeout=5): 
        self.port = serial.Serial(port=port, baudrate=baudrate, 
        timeout=timeout, writeTimeout=timeout) 

    def open(self): 
        ''' Open the serial port.'''
        self.port.open()

    def close(self): 
        ''' Close the serial port.'''
        self.port.close() 
    
    def send(self, msg):
        self.prot.write(msg)

    def recv(self):
        return self.port.readline()

Monday, July 02, 2012

How to Copy/Paste from the Clipboard in vim

On Ubuntu 11.04, accessing the clipboard from vim is disabled by default, this is how to enable it:
Download the package source:
apt-get source vim
Edit vim/debian/rules
TINYFLAGS:=--with-features=normal
TINYFLAGS+=--enable-gui
Build and install the package:
dpkg-buildpackage
dpkg -i vim*.deb
Now you can copy and paste using:
"+y to copy to clipboard
"+p to paste from clipboard

Monday, July 02, 2012

How to Connect to a WPA2-PSK Wireless Network on Ubuntu

Network Manager (nm) may not always be there, this how you connect to a WPA2-PSK wireless network from the command line using wpa_supplicant on Ubnutu:

/etc/wireless-wpa.conf
ctrl_interface=/var/run/wpa_supplicant
network={
ssid="ssid"
scan_ssid=1
key_mgmt=WPA-PSK
psk="key"
}
config_wireless.sh
#!/bin/sh
iface=wlan0
ifdown $iface
ifup $iface
wpa_supplicant -B -Dwext -i $iface -c /etc/wireless-wpa.conf -dd
dhclient $iface

Sunday, July 01, 2012

Parsing C++ Headers With Python

cppheaderparser  is a very useful module that you can use to parse C/C++ headers with Python. The module allows you to walk through the classes, functions, parameters etc... I've been using this for a while now to generate bindings for a C shared library. This is an example of how you can use it:

#!/usr/bin/python
import CppHeaderParser

header = CppHeaderParser.CppHeader('MyClass.h')
for c in cpp_header.classes: #iterate over classes
    for f in cls['methods']['public']: #iterate over public functions
        print 'static:', f['static'], ' return type:', f['rtnType'],
        ' parameters:', f['parameters']

Sunday, July 01, 2012

How to Generate Random Nodes in NS2

I've been trying to get NS2 to generate random nodes, finally, this tcl code seems to work nicely:

set rng [new RNG]
$rng seed next-substream

for {set i 0} {$i < $val(nn)} {incr i} {
    set n($i) [$ns node]
    $n($i) set X_ [$rng uniform 0.0 500.0]
    $n($i) set Y_ [$rng uniform 0.0 500.0]
    $n($i) set Z_ 0.0 #flat ground
    $ns initial_node_pos $n($i) 20
}


Sunday, July 01, 2012

Openembedded Recipe for librtlsdr

DVB-T dongles based on the Realtek RTL2832U can be used as a cheap software-defined radio, or SDR. librtlsdr is a userspace USB driver for the RTL2832, it can initialize the receiver, tune to a given frequency and record the I/Q-samples to a file.The following is an Openembedded recipe for librtlsdr:
DESCRIPTION="DVB-T dongles based on the Realtek RTL2832U can be used as a cheap SDR, rtl-sdr is a commandline tool that can initialize the RTL2832, tune to a given frequency, and record the I/Q-samples to a file."
HOMEPAGE="http://sdr.osmocom.org"
LICENSE="GPLv2"
LIC_FILES_CHKSUM="file://COPYING;md5=751419260aa954499f7abaabaa882bbe"
SRC_URI="git://git.osmocom.org/rtl-sdr.git;branch=master"
SRCREV="${AUTOREV}"
DEPENDS="libusb"
PR="r0"  
S="${WORKDIR}/git"
inherit autotools pkgconfig

Sunday, July 01, 2012

Chroot Jail on Ubuntu and Debian

The following is an easy way to build a chroot jail on Debian based distros, it will download all the packages required for a functional chroot:

sudo debootstrap --arch <arch> <distro> debian_jail
sudo chroot debian_jail

Where arch is i386, x86_64 etc.. and distro is natty, hardy etc...