Monday, October 6, 2014

My Tiny Timer Class

Just yesterday I posted about creating a new way of controlling and monitoring my Wemo light switches.  In the post I talked about having to develop a way of timing operations.  It was pretty simple and has worked well overnight, so I decided to put it in a python class and use it in the other parts of my system.

So you understand, I hate classes.  When c++ came around, and object oriented programming was all the rage, I resisted.  No, it wasn't that I couldn't accept change, it was that the crap they produced was incredibly hard to read.  Four pages of class definitions and sixteen lines of code may have been cool, but just try and debug it.  Especially with the tools available back then.  Well, it's been some years and objects have matured as well as the folk that created the mess back then.  Now, they're not as big a mess, maybe I should join the 21st century.  Sure, I use classes all the time; I just avoid writing them if at all possible; this is an exception.

So, here's my basic timer class.  Simple right?  Remember, the reason I did this was to keep control within a single thread thus avoiding deadlocks in code and locked up databases.

import time

class timer:
 _things = []
 
 def __init__(self, callback, seconds=1, minutes=0, hours=0):
  interval = (hours*60*60) + (minutes*60) + seconds
  actionTime = time.time() + interval
  self._things.append({"callback":callback,"interval":interval,"actionTime":actionTime})

 def tick(self):
  now = time.time()
  for i in self._things:
   if i["callback"] == None:
    continue
   if now >= i["actionTime"]:
    i["callback"]()
    i["actionTime"] += i["interval"]

checkTimer = timer(None)

''' This is code to test and illustrate the usage '''
def printSecond():
 print "second"
 
def printTwoSeconds():
 print "twoseconds"

def printMinute():
 print "minute"

if __name__ == "__main__":
 # First create any timers you need
 oneSecond = timer(printSecond, seconds=1)
 twoSeconds = timer(printTwoSeconds, seconds=2)
 minute = timer(printMinute, minutes=1)
 
 # now once in a while call tick to let them happen
 while True:
  checkTimer.tick()
  # a sleep lets the cpu have a rest to do other things.
  time.sleep(0.5)
It just keeps a list of the various timers I create to do things and steps through them to see if something needs to be done.  I included an instance by default so, when I use it, I don't have to create one.  It's easy to use and I may be extending it to handle other things that may need to be timed differently like: Every day at 3:00pm, feed the fish.  That takes more work parsing various parameters and such, but it's easy to extend.

Within the module is an example of how to use it.  This can be directly run under python, to see how it works, and how to use it.

I've already modified my module for the Wemo switches to use it, now I'm looking at the other modules to see if this would be appropriate there as well.  

6 comments:

  1. Glad to see you're back in the saddle, so to speak. Sad to hear about the weather issues. You obviously had more rain than we had here in the desert of Southern California. Regardless, I'm glad someone is discussing the Wemo stuff, but not being reliable and having to check on the Wemo devices constantly seems a definite "no-go". Out of curiosity, have you/why did you change from the Iris/XBee products?

    ReplyDelete
    Replies
    1. Actually I didn't switch. I started with the Wemo because it was a cool device ... and a lightswitch that mounted in the wall. Then I saw the Iris Smart Switch and wanted it because it could monitor power. Two different purposes. On the one hand I wanted to control the lights with a switch in the wall and on the other I wanted to monitor the power on some appliances. Besides, have you looked at Zigbee in-wall light switches? I think there's one or two and they're expensive.

      Go down to Lowe's and look at the rack. You'll see a couple of Zigbee devices and a ton of z-wave. If you go to Home Depot, you'll see Wemo. I'm just covering my bases.

      And besides, it's fun to play with new little devices.

      Delete
    2. I'm pretty sure that Einstein, in addition to coming up with e=mc^2, also came up with HA=$^12. As far as reliability (or lack of), I started with commercial HA in the late 70s/early 80's with X10. Prior to that, it was AC relays, switches and ladder diagrams.

      Speaking of new, fun little devices, have you checked out ESP8266? The little IoT modules are about $5/ea from China. The software is still immature but coming along nicely. I got two of the units but haven't found time to explore them.

      Delete
    3. Those little things are pretty good for taking the serial output of something and sending it over wifi to something that can work with it. I have a device I use for that. The problem is always that relying on wifi is a path to a nervous breakdown.

      Delete
  2. have you heard of the raspberry picrowave. the guy ripped out the controller of a microwave and then used a RPi to interface it with the internet as well as voice control and several other things. It might be of interest as his voice command system was actually working fairly well. Also just finished reading your blog and am very impressed.

    ReplyDelete
    Replies
    1. Thanks for the pointer. That is a really nice project. I've got one of those super microwaves that has menus and everything else on it. However, the washing machine and dryer are old style simple devices. One day ...

      Delete