#!/usr/bin/tclsh
#
# switch Relais connected to DS2406
#
# $Id: ds2406relais.tcl 1 2007-06-17 12:56:18Z sven $
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
#

proc getDS2406devices {} {
  if {[catch {set all [::OW::get uncached -list]}]} {
    puts stderr "unable to read 1-wire bus"
    exit 1
  }

  # scan for DS2406 devices
  foreach device $all {
    if {[regexp {^[0-9A-F]{2}\.[0-9A-F]{12}} $device]} {
      if {[catch {
	if {[::OW::get /${device}type]=="DS2406"} {
	  lappend deviceList [string trim $device /]
	}
      }
	  ]} {
	puts stderr "unable to read 1-wire bus"
	exit 1
      }      
    }
  }
  return $deviceList
}

proc printDS2406devices {} {
  foreach device [getDS2406devices] {
    puts $device
  }
}

proc setDS2406relais {id state} {
  if {[catch {::OW::put /$id/PIO.A $state}]} {
    puts stderr "error switching DS2406 relais: id $id"
    exit 1
  }

}

package require ow

set PROGRAM [file tail [lindex $argv0]]

# parse commandline
if {$argc == 0} {
  puts stderr "usage: $PROGRAM --id ?--list? ?--init? on|off"
  exit 1
}

# default init
set init "u"

set list 0
set i 0
set idok 0
foreach arg $argv {
  if {$arg == "--list"} {
    set list 1
  }

  if {$arg == "--id"} {
    set id [lindex $argv [expr $i+1]]
    set idok 1
  }

  if {$arg == "--init"} {
    set init [lindex $argv [expr $i+1]]
  }

  incr i
}
incr i -1
set cmd [lindex $argv $i]

if {!$idok && !$list} {
  puts stderr "$PROGRAM --id is a mandatory parameter"
  exit 1
}

if {[catch {::OW::init $init}]} {
  puts stderr "error in owfs init"
  exit 1
}

if {$list} {
  puts "DS2406 devices on bus:"
  printDS2406devices  
} else {
  if {$cmd == "on"} {
    setDS2406relais $id 1
  } else {
    if {$cmd == "off"} {
      setDS2406relais $id 0
    } else {
      puts stderr "usage: $PROGRAM --id ?--list? ?--init? on|off"
      exit 1
    }
  }
}

#printDS2406devices
#setDS2406relais


::OW::finish

