Wednesday, March 13, 2013

Using Pyinotify to Monitor a Directory

This example uses python and pyinotify to monitor a mount point

import os
import pyinotify as inotify

class EventHandler(inotify.ProcessEvent):
    def process_IN_CREATE(self, event):
        print "Create: %s" %  os.path.join(event.path, event.name)

    def process_IN_DELETE(self, event):
        print "Remove: %s" %  os.path.join(event.path, event.name)

wm = inotify.WatchManager()
notifier = inotify.Notifier(wm, EventHandler())
wm.add_watch('/media', inotify.IN_DELETE | inotify.IN_CREATE, rec=False)

try:
    while True:
        # process the queue of events
        notifier.process_events()
        if notifier.check_events():
            #read notified events and enqeue them
             notifier.read_events()
except KeyboardInterrupt:
    notifier.stop()

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