Logitech, Inc. Webcam C270 on Raspberry Pi

Just a small note. I tried to get my Logitech, Inc. Webcam C270 running on an raspberry pi v1 running raspbian wheezy and ran into some problems.

The webcam can be used on linux with the uvcvideo kernel module but using uvccapture did not work for me.

$ dmesg
uvcvideo: Found UVC 1.00 device <unnamed> (046d:0825)
input: UVC Camera (046d:0825) as /devices/.../input/input0
usbcore: registered new interface driver uvcvideo

Running uvccapture:

$ uvccapture
ERROR opening V4L interface
: No such file or directory

Mplayer didn’t work either with various settings – producing green only images.

mplayer tv:// -tv driver=v4l2:device=/dev/video0 -vo png -frames 1

Then I found out there is a limited set of formats your camera can deliver and how to display:

$  v4l2-ctl --list-formats -d /dev/video0
ioctl: VIDIOC_ENUM_FMT
        Index       : 0
        Type        : Video Capture
        Pixel Format: 'YUYV'
        Name        : YUV 4:2:2 (YUYV)

        Index       : 1
        Type        : Video Capture
        Pixel Format: 'MJPG' (compressed)
        Name        : MJPEG

Seems like I can capture images in YUYV Format and MJPEG directly. This led me to vgrabbj which seems to be a highly flexible image grabber. The following command works for me:

$  vgrabbj -q 100 -i vga -o jpg -f /tmp/snap.jpg -e -d /dev/video0

So, give vgrabbj a try.

Simple caldav4j example in java and clojure

I was trying to access a caldav calendar through java and clojure to build a small application. But it wasn’t too easy.

caldav4j seemed to be very confusing and not so well maintained. There is no quick start guide and you are directed to have a look at the unit tests. But they are a compilation of interconnected classes and their hierarchies including a lot of deprecated classes being used – pretty confusing for a newcomer.

I had also problems using the alternative ical4j and it’s caldav connector. After some debugging it seemed incompatible with zimbra because of some strange filter constraints.

This might all be due to the fact that caldav is a complex protocol and I accepted to dig deeper into caldav4j.

Enough of the yacking, I traced down the necessary wire to build a basic example and hope it’ll help others looking for a quick start.

Java: https://github.com/dedeibel/list-events-caldav4j-example

Clojure: https://github.com/dedeibel/list-events-caldav4j-example-clojure

I tested it with zimbra. For google calendar a little more work might be required. The key might be in the GoogleCalDavDialect.java class.

 
Java:
 

    HttpClient httpClient = new HttpClient();
    // I tried it with zimbra - but I had no luck using google calendar
    httpClient.getHostConfiguration().setHost("CALDAVHOST", 443, "https");
    String username = "username";
    UsernamePasswordCredentials httpCredentials = new UsernamePasswordCredentials(username, "secret");
    httpClient.getState().setCredentials(AuthScope.ANY, httpCredentials);
    httpClient.getParams().setAuthenticationPreemptive(true);
    // Need a proxy?
    //httpClient.getHostConfiguration().setProxy("phost", 8080);

    CalDAVCollection collection = new CalDAVCollection(
        "/dav/"+ username +"/Calendar",
        (HostConfiguration) httpClient.getHostConfiguration().clone(),
        new CalDAV4JMethodFactory(),
        CalDAVConstants.PROC_ID_DEFAULT
        );

    GenerateQuery gq=new GenerateQuery();
    // TODO you might want to adjust the date
    gq.setFilter("VEVENT [20131001T000000Z;20131010T000000Z] : STATUS!=CANCELLED");
    // Get the raw caldav query
    // System.out.println("Query: "+ gq.prettyPrint());
    CalendarQuery calendarQuery = gq.generate();
    List<Calendar>calendars = collection.queryCalendars(httpClient, calendarQuery);

    for (Calendar calendar : calendars) {
      ComponentList componentList = calendar.getComponents().getComponents(Component.VEVENT);
      Iterator<VEvent> eventIterator = componentList.iterator();
      while (eventIterator.hasNext()) {
        VEvent ve = eventIterator.next();
        System.out.println("Event: "+ ve.toString());
        System.out.println("\n\n");
      }
    }

 
Clojure:
 

defn- create-query []
  (let [gq (GenerateQuery.)]
    ; Date Format yyyyMMdd
    (.setFilter gq "VEVENT [20131001T000000Z;20131010T000000Z] : STATUS!=CANCELLED")
    (.generate gq)))

(defn -main []
  (let [http-client (initialize-http-client)
        collection-path (:collection-path configuration)
        host-configuration (.clone (.getHostConfiguration http-client))
        method-factory (CalDAV4JMethodFactory.)
        collection (CalDAVCollection. collection-path host-configuration method-factory CalDAVConstants/PROC_ID_DEFAULT)
        calendars (.queryCalendars collection http-client (create-query))
        ]
    (doseq [cal calendars
            event (-> cal (.getComponents) (.getComponents Component/VEVENT))]
      (println "Event: " event)
      (println "\n\n"))))

Clojure core.logic cheatsheets

I am currently having a look at clojure core.logic and was missing some kind of reference documentation. There are a lot of examples and tutorials but I never had an overview about what’s available.

In a google groups discussion the idea of a reference documentation like clojure cheat sheets came up. https://groups.google.com/forum/#!topic/clojure/ScJa_o4lP2k

So I decided to create one, view it directly: cheatsheet on github

Have a look at the github project: https://github.com/dedeibel/clojure-core-logic-cheatsheets

Thanks to the original author of the cheatsheet generator Michael Fogus and Andy Fingerhut.

Thanks goes to xavriley who created a cool version of clojuredocs for core.logic which is where the cheatsheet entries link to.

How to install oracle java 7 update 11 (jdk-7u11) on debian linux

Currently you can’t install the new java sdk 7 update 11 from oracle using java_package. Usually you can simply follow this instruction: Installing oracle jre / sdk on debian.

Unfortunately the error is: No matching plugin was found.

But you can modify the script /usr/share/java-package/oracle-j2sdk.sh to accept the new package:

15,16c15,16
<       "jdk-7u"[0-9]"-linux-i586.tar.gz") # SUPPORTED
<           j2se_version=1.7.0+update${archive_name:6:1}${revision}
---
>       "jdk-7u"[0-9][0-9]"-linux-i586.tar.gz") # SUPPORTED
>           j2se_version=1.7.0+update${archive_name:6:2}${revision}
31,32c31,32
<       "jdk-7u"[0-9]"-linux-x64.tar.gz") # SUPPORTED
<           j2se_version=1.7.0+update${archive_name:6:1}${revision}
---
>       "jdk-7u"[0-9][0-9]"-linux-x64.tar.gz") # SUPPORTED
>           j2se_version=1.7.0+update${archive_name:6:2}${revision}

Worked for me:

The Debian package has been created in the current directory. You can
install the package as root (e.g. dpkg -i oracle-j2sdk1.7_1.7.0+update11_amd64.deb).

(#:/tmp)- dpkg -i oracle-j2sdk1.7_1.7.0+update11_amd64.deb
(Reading database … 225711 files and directories currently installed.)
Preparing to replace oracle-j2sdk1.7 1.7.0+update7 (using oracle-j2sdk1.7_1.7.0+update11_amd64.deb) …
Unpacking replacement oracle-j2sdk1.7 …
Setting up oracle-j2sdk1.7 (1.7.0+update11) …

(#:/tmp)- java -version
java version „1.7.0_11“
Java(TM) SE Runtime Environment (build 1.7.0_11-b21)
Java HotSpot(TM) 64-Bit Server VM (build 23.6-b04, mixed mode)

There is also a bug report: Bug#698108: jdk7u11 not supported

Edit: also works for java 7 update 12 (jdk-7u12), java 7 update 13 (jdk-7u13), java 7 update 14 (jdk-7u14) and java 7 update 15 (jdk-7u15)

Edit: Oh boy, too many updates recently.

Created a shortcut cheat sheet for the clojure foreplay vim plugin

In Meikel Brandmeyer’s post „On the state of VimClojure“ he mentioned the alternative „foreplay“ to his vimclojure repl solution which is using ng-server.

I tried the plugin and liked it. It has a more robust feel and very easy setup – none required to be precise. You can simply start your nrepl using lein repl and the plugin automagically talks to it.

There are quite some useful shortcuts you should know, therefore I created a foreplay-cheat-sheet (PDF) which might be helpful at the beginning.

Maybe the more often required commands should be on top, but I guess you’ll learn those quite fast anyway.

I created it manually from the foreplay vim documentation, so the content is actually from Tim Pope. The office document is available here foreplay-cheat-sheet.odt

hth

Simple xmpp standup meeting notification for the team

I guess you all know it – when it is standup time some notice it immediately while others are still on the phone or some still digging in the code. It does help to have a calendar notification but everyone has to enable it etc.

At my work we are all using the company wide jabber service and it’s a great tool I think. With these few steps you can build a simple notifier for your team.

First you’ll have to install sendxmpp. For debian:
% apt-get install sendxmpp

The usage is easy and you can write a simple script file and place it in your PATH.
% cat bin/standupnote
#!/bin/sh

MEMBERS="
fred@jabber.example.com
barney@jabber.example.com
pebbles@jabber.example.com
"

echo "Reminder: Standup Meeting! :-)" | sendxmpp $MEMBERS

Your credentials have to be added to added to the ~/.sendxmpprc file. Don’t forget to chmod 600 it!
echo "user@jabber.example.com password componentname" > ~/.sendxmpprc && chmod 600 ~/.sendxmpprc

And finally you should install a cronjob to run the script at standup time. Simply run as user and edit the config file:
% crontab -e
# m h dom mon dow command
45 10 * * 1,2,3,4,5 /home/fred/bin/standupnote

Yes, our meeting is not until 10:45 … :-\

Clojure store persistent data structures gotcha – load-file size limit

In clojure – the data structure and their default representation are suited as readable and portable format to persist data. But there is a small pitfall in using it.

Data Structure example:

{
  :request-time 2636,
  :status 200,
  :headers
  {
    "server" "Server",
    "content-encoding" "gzip",
  }
}

Be aware that this function is intended to load code only. If your data structures or a string in them grow bigger than around 65,535 it crashes.

Exception similar to:

java.lang.ClassFormatError: Unknown constant tag 49 in class file parse$eval13

Please use read-string instead.

Example: (read-string (slurp "data.clj"))

Source: Rich Hickey on google groups Google Groups

XBMC windowed mode calibration (overscan) settings not remembered

I love XBMC, it is a great free media center, controllable via android phone with lot’s of cool plugins and even blue ray support.

But there was this bug annoying me. I am using two monitors and want to keep the mouse non captured, therefore using xbmc in maximized windowed mode instead of fullscreen. This works great but the overscan settings get lost on every restart, hiding great parts of the GUI.

The settings are written correctly to the „resolution“ node in guisettings.xml with the description „Windowed“ but are not loaded. After the next start the default settings are used and the config overwritten.

These forum posts or some posts of them might be related:
http://forum.xbmc.org/showthread.php?tid=104735
http://forum.xbmc.org/showthread.php?tid=132776

I tried to fix the problem myself and got up with a patch. There were a couple of problems preventing the settings from being loaded and applied – see pull request for details. It also seems like it makes sense to reset the overscan settings when the window is resized but upon initial start they should be loaded from the config.

See Ticket http://trac.xbmc.org/ticket/11861
Pull Request https://github.com/xbmc/xbmc/pull/1246

Edit:

Well, the xbmc folks answered quite fast, see below. Too bad but until then I got my patch.

FernetMenta commented
check out #1231
There are (and should) no calibration settings for windowed mode. Your original problem mentioned in the ticket 11861 will be fixed by not grabbing the mouse.

Clojure Game Of Life App on Heroku

A while ago I created a heroku account to try it out. They allow you to host clojure web apps in the cloud. One worker is for free and there are also quite more languages supported.

In order to practice some clojure I implemented game of life and packaged it into a lib. Here does leiningen help you a lot, it is the maven of the clojure world and also creates maven compatible jar files.

My app was originally printing out the game of life world to the CLI but now outputs it as text/plain.

I won’t repeat the steps to setup heroku since they are explained very well on heroku: http://devcenter.heroku.com/articles/clojure

The result can be accessed here: http://gentle-journey-9851.herokuapp.com/

The state is globally shared through all requests. So don’t be surprised if there are some generations missing.

The code and library is available on github. The game of life source code is included in the jar, in case some is interested. I might have a different post about this later.

https://github.com/dedeibel/herokus_game_of_clojure_life

To start the app:

Prerequisites: leiningen

To run locally, simple run

$ lein run -m herokutest.web 5000

or

$ foreman start

And visit http://localhost:5000

(ns herokutest.web
  (:use [game_of_life.cell :only (new_cell)])
  (:use [game_of_life.world_printer :only (to_string)])
  (:use [game_of_life.world_builder :only (from_string)])
  (:use [game_of_life.game :only (next_generation)])
  (:use ring.adapter.jetty)
)

(def twentyfour_and_more
"xx
,xx
,
,
,
,                                   x x  xxx
,                                   x x    x
,                                   xxx  xxx
,                                     x  x
,                                     x  xxx
,                                                                                                   xx  
,                                                                                                  x  x
,                                                                                                 x    x
,                                                                                                x      x
,                                                                                                x      x
,                                                                                                 x    x
,                                                                                                  x  x
,                                                                                                   xx"
)

(def counter (atom 0))
(def world (atom (from_string twentyfour_and_more new_cell)))

(defn app [req]
  (let [current @world]
    (swap! counter inc)
    (swap! world next_generation)
    {:status 200
     :headers {"Content-Type" "text/plain"}
     :body 
       (str "Game Of Life (Step " @counter "):\n" (to_string current))
    }
  )
)

(defn -main [port]
  (run-jetty app {:port (Integer. port)}))

Android phone as webcam to capture binary clock patterns

A while ago I got a binary clock for my birthday by some college friends (thank you again at this point). When you watch it from the sofa, you can sometimes see it creating some interesting or funny shapes and I wondered how many of them are there.

Sure, you could write a program to generate all combinations but I wanted to make a photo for each of the clock’s states. Since I don’t have a webcam or something more advanced – the idea was to use my android phone.

Searching for an app, I found this really great and easy one IP Webcam which allows you to take shots via HTTP or and directly grab an image from the video buffer. Luckily this was fast enough to make a picture every second. This was not the case when I tried using the auto focus and normal photo mode.

I wrote a little C program to print out seconds and microseconds to analyze the camera’s delay by taking a shot of the screen. The result surprised me a little since the picture was actually from before it was triggered and not after.
The explanation is at hand, the picture from the camera is buffered on the phone or the app and you simple get a snapshot of what is ready at that time.

I’ll just dump the source code of the program to take a shot every second here and with some interesting pictures I found after recording about ten hours. one to ten o’clock.

/* makeshots.c */

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <string.h>
#include <unistd.h>
#include <time.h>

#define MSSLEEP "./mssleep"
#define CAMERA_LATENCY "350000"
#define CAMERA_URL "\"http://192.168.1.112:8080/shot.jpg\""
// printf
#define TIMEFORMAT "%010ld,%06ld"
// strftime
#define OUTTIMEFORMAT "%H_%M_%S"

#define MINUTE 60l
#define HOUR (60l * MINUTE)
// 86_400 pictures per 24 hours
#define RUNTIME (10l * HOUR + MINUTE)
#define LOOPWAIT_MS 2000

void shoot() {
  char shoot_cmd[256];
  char timestamp[128];
  struct tm tmine;
  time_t rawtime;

  time (&rawtime);
  localtime_r(&rawtime, &tmine);

  strftime(timestamp, 128, OUTTIMEFORMAT, &tmine);
  snprintf(
    shoot_cmd,
    256,
    "("MSSLEEP" "CAMERA_LATENCY"; curl -s -S "CAMERA_URL" -o out/%s.jpg 2>> curl.log) &",
    timestamp
  );
  system(shoot_cmd); // returns immediately
}

int main(int argc, char **argv) {
  struct timeval t;
  struct timezone tz;

  // init
  if (gettimeofday(&t, &tz)) {
    perror("gettimeofday in init failed");
  }
  time_t start_sec = t.tv_sec;
  time_t lastsec   = t.tv_sec;

  while (t.tv_sec - start_sec < RUNTIME) {
    if (gettimeofday(&t, &tz)) {
      perror("gettimeofday in loop failed");
    }
    printf(TIMEFORMAT, (long) t.tv_sec, (long) t.tv_usec);

    // Shoot every second
    if (t.tv_sec - lastsec > 0) {
      lastsec = t.tv_sec;
      shoot();
    }

    usleep(LOOPWAIT_MS);
    // Must be as long as TIMEFORMAT
    printf("\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r");
  }
  printf("\n");
  return EXIT_SUCCESS;
}
/* mssleep.c */

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char **argv) {
  if (argc != 2) {
    fprintf(stderr, "%s: <milliseconds>\n", argv[0]);
    return EXIT_FAILURE;
  }

  long ms = atol(argv[1]);
  usleep((useconds_t) ms);
  return EXIT_SUCCESS;
}

I was using C to get a good performance but mostly since it has been a while and I wanted to get my hands on it again. The code runs on mac osx leopard using gcc. curl must be installed.