O'Reilly Hacks
oreilly.comO'Reilly NetworkSafari BookshelfConferences Sign In/My Account | View Cart   
Book List Learning Lab PDFs O'Reilly Gear Newsletters Press Room Jobs  


 
Buy the book!
Smart Home Hacks
By Gordon Meyer
October 2004
More Info

HACK
#97
Calculate Elapsed Time
If you want to know how much time has passed between events, such as how long it has been since the rain sensor was activated, or how many hours it has been since the motion detector in the library last sent a command, this technique will give you an answer in human-readable format.
The Code
[Discuss (0) | Link to this hack]

The Code

This script, inspired by a similar one from Jeffrey Laughter, provides a handy subroutine for converting from seconds to seconds, minutes, and days:

-- IntervalToString(numseconds)
-- Returns a text string decribing an interval in calendar format.
-- i.e. 791766 seconds returns " 9 days 3 hours 56 minutes"
-- left over seconds are dropped as being insignificant

on IntervalToString(numseconds)

set IntervalString to ""
set daysnum to numseconds div 86400 -- number of seconds in a day
set numseconds to numseconds mod 86400 -- save the remainder
if daysnum = 1 then set IntervalString to "1 day"
if daysnum > 1 then set IntervalString to " " & daysnum & " days"

set hoursnum to numseconds div 3600 -- seconds in an hour
set numseconds to numseconds mod 3600 -- save the remainder
if hoursnum = 1 then set IntervalString to IntervalString & " 1 hour"
if hoursnum > 1 then set IntervalString to IntervalString & " " & hoursnum
& " hours"

set minutesnum to numseconds div 60 -- left over minutes
if minutesnum = 1 then set IntervalString to IntervalString & " 1 minute"
if minutesnum > 1 then set IntervalString to IntervalString & " " &

minutesnum & " minutes"

if IntervalString = "" then set IntervalString to " less than a minute" --
occurs because we dropped the seconds remainder
  return IntervalString

end IntervalToString

In XTension, it's best to add to your attachment script . This enables you to call it as a function from any other script:

set goneTime to IntervalToString((time delta of "Nobody Home"))
say "Welcome Back. The house was empty " & goneTime

In this example, the elapsed time since the last time someone was home is announced so that the person returning home knows how long the pets have been without supervision or a bathroom break.

TIP

Although it's used in XTension here, this script should work with any AppleScript-enabled home automation software. Plus, it's simple enough to convert to just about any other language you need.


O'Reilly Home | Privacy Policy

© 2007 O'Reilly Media, Inc.
Website: | Customer Service: | Book issues:

All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.