#!/usr/bin/python

import hal
import sys
import time
import os

class StoredValue:
    def __init__(self, c, name):
	self.c = c

        if name.startswith('f:'):
            convert = float
            haltype = hal.HAL_FLOAT
            name = name[2:]
        elif name.startswith('u:'):
            convert = int
            haltype = hal.HAL_U32
            name = name[2:]
        else:
            convert = int
            haltype = hal.HAL_S32

	self.n = name
        self.fn = '%s.state' % name
	c.newpin(name + '.stored-value', haltype, hal.HAL_OUT)
	c.newpin(name + '.new-value', haltype, hal.HAL_IN)
	c.newpin(name + '.store', hal.HAL_BIT, hal.HAL_IN)
	c.newpin(name + '.stored', hal.HAL_BIT, hal.HAL_OUT)

        if os.path.exists(self.fn):
            value = convert(open(self.fn).read())
            self['stored-value'] = value

    def __setitem__(self, k, v): self.c[self.n + '.' + k] = v
    def __getitem__(self, k): return self.c[self.n + '.' + k]

    def iterate(self):
        store = self['store']
        if store and not self.old_store:
            value = self['new-value']
            tfn = self.fn + ".tmp"
	    open(tfn, 'w').write('%s\n' % value)
            os.rename(tfn, self.fn)
	    self['stored-value'] = value
	    self['stored'] = 1
        elif not store:
            self['stored'] = 0
        self.old_store = store

if len(sys.argv) < 2:
    raise SystemExit, "specify at least one value to store"

c = hal.component('remember')
values = [StoredValue(c, n) for n in sys.argv[1:]]
c.ready()

try:
    while 1:
        for v in values: v.iterate()
	time.sleep(.01)
except KeyboardInterrupt:
    pass

#    Copyright 2009 Jeff Epler <jepler@unpythonic.net>
#
#    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-1307  USA

# vim:sw=4:sts=4:et
