#!/usr/bin/python
# -*- coding: utf-8 -*-
# jack.py - An application to read jack
#
# Version 0.1
#
# Authors: Francois TOURDE <fr-om@tourde.org>
#
# Copyright (c) 2008 François TOURDE
#
# jack.py is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 3 of the License, or (at your
# option) any later version.
#
# jack.py is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# TODO
#
# Change List
#
# 2008-09-03: First release

import os
import sys

# Hexdump of /dev/input/event0
# When jack inserted
#     9131 48be a594 0001 0005 0002 0001 0000
#     9131 48be a5f9 0001 0000 0000 0000 0000
# When jack removed
#     9131 48be a594 0001 0005 0002 0000 0000
#     9131 48be a5f9 0001 0000 0000 0000 0000

# Where files are stored
p="/usr/share/openmoko/scenarios/"
ps="saved/"

# Open the jack sensor
f = open("/dev/input/event0", "r")

while 1:
  block = f.read(16)
  if block[8] == "\x05":
    if block[10] == "\x02":
      if block[12] == "\x01":
        # Moving to headset mechanism:
        # point stereoout to headset
        # point gmshandset to gsmheadset
        os.system("ln -sf %s%s%s %s%s" % (p, ps, "headset.state", p, "stereoout.state"))
        os.system("ln -sf %s%s%s %s%s" % (p, ps, "gsmheadset.state", p, "gmshandset.state"))
        os.system("alsactl -f %sstereoout.state restore" % p)
      if block[12] == "\x00":
        # Moving to handset mechanism
        # point stereoout to stereoout
        # point gsmhandset to gsmhandset
        os.system("ln -sf %s%s%s %s%s" % (p, ps, "stereoout.state", p, "stereoout.state"))
        os.system("ln -sf %s%s%s %s%s" % (p, ps, "gsmhandset.state", p, "gmshandset.state"))
        os.system("alsactl -f %sstereoout.state restore" % p)

# Close the jack
f.close()
