Showing posts with label AppleScript. Show all posts
Showing posts with label AppleScript. Show all posts

Friday, July 3, 2020

1-wire Temperature Sensors and Lightning (and other sources of interference)

I use a lot of 1-wire temp sensors around the house for various purposes. One of which was a sort of hack to know when the hot water heater was in use. I placed one on the inlet side and one on the output side of the tank and when the 2 temperatures diverge by enough I know that the hot water is actually flowing. Within a few minutes of someone turning the tap off the temperature has equalized enough that it can tell the hot water is no longer in use. 

The main reason I set this up initially is that I wanted to have my bathroom lights go off after there was no motion in the bathroom for a while, but I didn’t want them to go off while I was in the shower nor did I want to set the timeout to be so long that they would stay on unnecessarily at other times. So now if the hot water is in use the logic of the master bathroom will not turn off the lights on you, but will keep checking back to see if the water is now off or if there has been more motion.

My day job is home automation software so all the logic for that is running in XTension.

Here is the graph of the output from last night:


The blue and red lines are the inlet and outlet temps of the water heater. Physically they are just a standard 1-wire temp sensor taped to the pipes a few inches up from the water heater. The yellow highlight is when the hot water is considered to be in use. The light green line is another 1-wire sensor just hanging in the attic showing the ambient temp in the attic. You can see 2 spikes to 185 degrees between 5:30 and 6pm last evening and one identical spike on the inlet sensor. 

Those were all caused by very sharp close by lightning hits. These particular sensors are connected to a Barix Barionet device which is a fantastic remote host for 1-wire sensors as well as digital inputs and relay outputs. Very handy for home automation and fully supported by my plugin for it in XTension. I have another device that is just basically an arduino that has a similar sensor that is glued to the side of a power supply so that I can make sure it is not overheating as it is in an electrical box with no ventilation. When those lights are on that sensor reads the same 185f or 85c repeatedly until the load decreases. These 1-wire sensors are just prone to interference and when that happens they return a reading of 85c. 

The reading of 185c is within the range of temperatures the device can actually read so it isn’t good to just filter that out in the driver or plugin or hardware. I am considering for a future firmware build of the 1-wire to wifi kit that if I get an 85c reading I will attempt another reading a few seconds later and only report it if the reading is the same twice. For the moment though the solution to filter them is easy enough inside the XTension ON script for the Unit. In the case of the above graph I am not going to filter it as it is interesting and happens rarely and does not throw off any other calculations or anything. For the sensor on the power supply it happens so frequently that it is frustrating to look at the graph. In that case I use the Change Future Value verb to change the value back to the previous reading if it is exactly equal to 85c. That does potentially ignore some valid measurements, but it does let anything through that is 84.9 or below or 85.1 and above and so I’m not terribly worried about that. The script is very simple and just looks like this:


if (future value) is equal to 185 then

change future value to (value of (thisUnit))

write log "ignored bogus 185 value for porch temp sensors"

end if


 

futureValue tells you the value that the unit will be set to when the script is finished running. The (value of (thisUnit)) portion returns the current value of the unit. This is sometimes initially confusing to people new to working with XTension but it allows you to do things like this or anything where you need to compare the current value with the new value and potentially override or change it. It also lets you do very specific smoothing of readings or throwing out ones that are out of range such as this. The call to ThisUnit just returns the name of the unit that you would normally have to pass to the value of verb so that if you renamed the unit you wouldn’t have to remember to edit the script and if you had many of the devices you want to do this to you could either cut and paste the code, or create a single script that you could call for all of them.


This 185/85 reading is actually a known issue with some 1-wire temp sensors. I don’t see a difference between powered or parasitically powered networks. The sensors in the above graph are parasitically powered but the one that is on the power supply is powered. The parasitically powered ones are on an absolutely horrible network of wires flying through the attic and to say that it is not a single bus or a standard star configuration would be a dramatic understatement. There is no shielding though they are on a single twisted pair of bell wire. Anyplace I wanted to add more sensors I just spliced into it and extended it. That attic network is my test of the absolute worst case I can imagine for testing 1-wire reading devices. The barix does exceptionally well under almost all circumstances except for these lighting storms.


That network now has 10 sensors on it all over the attic and it does sometimes drop a reading for one of them entirely. It also reads the intake and output temperatures from 3 different AC units so that I can verify the temp differential and know if the units are leaking gas and will need a recharge (or in one of the older ones a replacement is coming up I’m afraid) before they actually stop working and we have to make an emergency call to the HVAC folks. That reading also lets me run the fan after an AC or Heat cycle the best length of time to get all the cold or hot out of the unit. I turn the fan to On when a cycle completes and then start watching the temp sensors. As soon as the 2 temperatures are within a few degrees of each other I turn the fan back to Auto. 


I am also going to update the hardware in the next revision of the wifi temp sensor to use the better interface that is outlined in the 1-wire best practices documentation to see if that will help with bad values or interference.  In any case, overall 1-wire sensors work great, are inexpensive and there are a lot of options for getting them into your home automation system. 

Friday, October 4, 2013

creating an applescript record with user defined labels in Xojo

Perhaps this really is documented somewhere, but I couldn't find it. Or perhaps it's so obvious that everyone else has been doing it for a decade but I just figured it out.

In Xojo (IDE previously known as REALbasic) you can create enumerated records with 4 byte codes that are translated into labels by the applescript dictionary.

dim MyRecord as new AppleEventRecord

MyRecord.StringParam( "xxxx") = "my data here"
and if you have an enumeration for the xxxx in your dictionary that says it means "cool stuff" then you can access that record in applescript by saying

set myThing to cool stuff of ThatRecord

and you'll get that data out again. But in order for that to be useful you have to know what those labels are ahead of time. In a script itself you can create a record with labels defined at runtime like:

set myRecord to {label1:"value1", label2:"value2", etc...}

and then you can access them via those label names

set myString to label1 of myRecord

but until yesterday I've never been able to create a record that had user defined labels in Xojo code. It's a simple matter of creating a AppleEventDescList with alternating label/value pairs in it and then placing it inside an AppleEventRecord with the 4 byte code of "usrf"

dim theRecord as new AppleEventRecord
dim theList as new AppleEventDescList

theList.appendString( "label1")
theList.appendString( "value1")
theList.appendString( "label2")
theList.appendString( "value2")
etc...

theRecord.DescListParam( "usrf") = theList

now if you return that record from an event the calling script will be able to treat it like a user defined list and use it the same way like:

set myString to label1 of TheRecord

Specifically i'm using this in a JSON parser where you just wont know the labels before hand so there is no chance to pre-build them as enumerations into the scripting dictionary.

Monday, September 9, 2013

adding animated weather radar to your XTension Web Interface pages

Another monday another tutorial on the Mac Home Automation site. This time how to embed data from other sources into the displays, for example animated gif's of weather maps.



http://machomeautomation.com/doku.php/webremote/radar

These instructions apply to what I do at my day job as a programmer for the Macintosh based home automation software XTension and the new WebRemote system.

Tuesday, July 30, 2013

Getting data out of WeatherMan and into XTension

Another day another WebRemote tutorial showing how to get a live weather report onto your XTension Web based remote control page. WeatherMan is an excellent program available for $.99 from the Mac App Store and has a great scripting dictionary.


The scripts also show how to parse out the forecasted high and low temperatures for each day and the chance of precipitation. Those are all placed in XTension pseudo units and you can either just display the data or use it for other calculations like running your sprinklers or not.

WeatherMan and XTension

Monday, July 29, 2013

a Live Motion Report display for your XTension Web Remote



Just finished the scripting and a short tutorial over on Mac Home Automation that shows how to create a live updated display of motion sensor activity. This is probably one of the most useful things I've got on my web remote page.  MacHomeAutomation/livemotion

Monday, November 5, 2012

batch moving iCal events from one calendar to another with AppleScript

What with all the iOS devices and the cloud and all I thought I would finally sort out the mess which is our iCal calendars around here and put them all on the cloud so that everyone could have read/write access and everything would be shiny and new and wonderful. That took a little more work than it should have, iCal is currently my least favorite of all Apple's software. Searching on the internet though I see I'm not the only one who has had these problems so I document my solution for anyone who might benefit from it.

I had the calendars hosed on just a webDav directory on my own server but this did not allow read/write access for all family members subscribed. I wanted to move them to my iCloud account and then resubscribe everyone (well, technically my wife is the only other member of everyone ;) my first thought was to just export them through iCal to my disk as .ics files and then re-import them into new calendars created on iCloud.

This did not work. I got the following modal error message which had to be dismissed for EVERY SINGLE event in the file before I could get back to normal.


Access to "some event" in "the new calendar name" in account "name of my account" is not permitted. The server responded: "403" to operation CalDAVWriteEntityQueuableOperation.

This is not particularly helpful and the buttons are not really very apple like or helpful either. After signing out and back in again and recreating my iCloud account I was able to get ONE calendar to import without errors, and then they returned.  Thats an old event, so I thought perhaps it was just complaining that events too far in the past weren't allowed to be imported. So I created manually a small ICS file to test with that only had future events in it, but that failed too.

I resorted to applescript. The dictionary has both a duplicate and a move command one or the other should be able to copy or move the events in the calendars I wanted to change. I can change the events from one to the other one at a time by just changing the "calendar" in the popup for the event. That worked fine, so it was allowing me to add things to the calendar, it just didn't like importing it. Or, as it turned out the duplicate or move command. Both of those tries resulted in the same error and total failure. Finally I resorted to the make new event command which requires a bit more work because I had to create the record of all the old properties one bit at a time. And since it will happily return "no value" or "undefined" for properties that aren't set for that event, but it will not accept those as properties for a new event you have to check to make sure each property exists before adding it to the new record. I did not attempt to preserver attendees or other event properties not in the list below so I dont know how to do that. But with this script you can move all the events from one calendar to another without errors from iCal even where an import fails. I suspect it may have something to do with including the unique ID in the export file. Possibly you cannot specify the UID of a new event, or possibly it really means unique, and not just unique within each individual calendar and that is what is causing the error. I left the UID out of the script below but I did not test with trying to include it.

It is not fast, it takes some time for each event to be created, so be patient.


tell application "Calendar"
--Script to move events from one iCal calendar to another
--James Sentman james@sentman.com 11/4/2012
--
--  I found myself unable to import ical calendars that I had exported from another
--  server. I would get an error from the iCal server for each and every event.
--  I have no idea why, it may be just duplicate UID's or something.
--  The "duplicate" command and the "move" command both of which I tried
--  failed with the same error, but I was able to create a new one with the 
--  info gotten from the old calendar. But that wasn't so easy either as not
--  all events have all information and it would not except "no value" answers
--  so I had to add the if exists portion to build the record for the new event.
--  I did not attempt to move things like attendees or other elements of the event
--  just the data you see below.
--
--  INSTRUCTIONS: change the name of these next 2 variables. MyOldCal is
--  the calendar you want to move events FROM and MyNewCal is the name of the
--  calendar that they will be newly created in.
set MyOldCal to calendar "SCDS"
set MyNewCal to calendar "SCDS iCloud"
-- find out how many events we have to create
-- for some reason I would get an error when it reached "count"
-- which generally means that while the count tells you how many records
-- referencing them by index begins at 0 instead of 1, so start at 0
-- and subtract one.
set EventCount to (count of events in MyOldCal) - 1
repeat with i from 0 to EventCount
--get a reference to the old event in the old calendar
set WorkEvent to event i of MyOldCal
--since the work record with the info is appended instead
--of created fresh each time in one step it is necessary to clear 
--it out each time through the loop.
set WorkRecord to {}
--checking if the various properties exist or not 
--stops an error later if one property was undefined
--it will happily return no value for one of them without
--an error, but it will not then accept that in the make
--statement below. So we only add them to the record
--if they are actually there.
if exists description of WorkEvent then
set TheDescription to description of WorkEvent
set WorkRecord to WorkRecord & {description:TheDescription}
end if
if exists start date of WorkEvent then
set TheStartDate to start date of WorkEvent
set WorkRecord to WorkRecord & {start date:TheStartDate}
end if
if exists end date of WorkEvent then
set TheEndDate to end date of WorkEvent
set WorkRecord to WorkRecord & {end date:TheEndDate}
end if
if exists allday event of WorkEvent then
set TheAllDay to allday event of WorkEvent
set WorkRecord to WorkRecord & {allday event:TheAllDay}
end if
if exists recurrence of WorkEvent then
set TheRecurrence to recurrence of WorkEvent
set WorkRecord to WorkRecord & {recurrence:TheRecurrence}
end if
if exists sequence of WorkEvent then
set TheSequence to sequence of WorkEvent
set WorkRecord to WorkRecord & {sequence:TheSequence}
end if
if exists stamp date of WorkEvent then
set TheStampDate to stamp date of WorkEvent
set WorkRecord to WorkRecord & {stamp date:TheStampDate}
end if
if exists excluded dates of WorkEvent then
set TheExcludedDates to excluded dates of WorkEvent
set WorkRecord to WorkRecord & {excluded dates:TheExcludedDates}
end if
if exists status of WorkEvent then
set TheStatus to status of WorkEvent
set WorkRecord to WorkRecord & {status:TheStatus}
end if
if exists summary of WorkEvent then
set TheSummary to summary of WorkEvent
set WorkRecord to WorkRecord & {summary:TheSummary}
end if
if exists location of WorkEvent then
set TheLocation to location of WorkEvent
set WorkRecord to WorkRecord & {location:TheLocation}
end if
--you can try copying the UID also
--but it occurred to me that this may be the whole problem
--as a UID should be unique, and it would not be so
--if you had tried to create an event and specifying it at the time
--so I commented this out and iCal will happily make a new UID for the 
--new event as it should.
--if exists uid of WorkEvent then
-- set TheUID to uid of WorkEvent
-- copy {uid:TheUID} to the end of WorkRecord
--end if
if exists url of WorkEvent then
set TheURL to url of WorkEvent
set WorkRecord to WorkRecord & {url:TheURL}
end if
--and lastly actually make the new event with the old data.
make new event at MyNewCal with properties WorkRecord
end repeat
return EventCount & " events moved"
end tell

Or you can download the script as a script editor file: icalmover.zip

Let me know if thats of any help to anyone, thanks.

Wednesday, April 11, 2012

EMSL Alpha Clock and XTension

I finished this terrific kit a while ago and wrote a blog post about connecting it’s serial port to an xBee radio. I meant to post code snippets and instructions but got mired up after using some of the other digital IO on the xbee for LED’s I evidently hosed something up on the breakout board. I’ve got it sorted out again so here’s the rest.

This is the wonderful Alpha Clock 5 from evilmadscience.com:


the fun part about those gigantic LED displays is that they are alpha numeric, and the clock has a serial port to which you can send text.


You could connect to this in many ways, bit I chose to use an xBee radio since I am working on support for them in XTension at the moment. The serial ports on the xBee as well as control of the IO are available to apple script in XTension and makes for easy wireless displays. The board I originally used was the plain one from sparkfun, no components other than the sockets for the xBee that bring them out to easier to manage solder pads. I must have overheated the pin to a socket or filled one with solder or shorted them internally or something as it stopped delivering any power at all to the xBee at some point while I was adding the extra display LEDs. I have now replaced it with an xBee breakout from adafruit that is working wonderfully. It also properly handles level shifting the serial port which is at 3v level from the xBee and 5v level on the clock board. I’m not sure if this is really all that important or not, SOME of the xBee documentation talks about the serial lines being 5v tolerant, but others demand that it’s vital. In any case I’ve got that working now and it has an on board 3v regulator so I was able to simplify the internal wiring and reduce some of the extra clutter of wires. (the clock throughout all this mucking about with the xBee continued to tell the time wonderfully and accurately ;)



There is the xBee on it’s new adafruit breakout board. For the serial to send messages to the clock only 3 connections are necessary. 5v, gnd and tx from the xBee connected to rx on the clock. Extra solder points for all those things are already on the clock board making it even easier.


the red black and blue wires are all thats necessary to turn it into a remote display to XTension. But now you’ve got all these unused pins on the xBee that are just going to waste! I plan to use this in the bedroom for a subtle display of alarm or other status during the night while not being too obtrusive. The clock already displays zone alarm info for me from XTension, but I wanted some bright LED’s to get my attention to various things. I added 3 bright colored led’s and one candle flicker led so that I could remote control an electric candle next to the clock just for fun ;)


The LED’s were just solder art, no boards or anything, grounds of the 3 extra bright ones are tied together and the Vcc sides have resisters under the heatshrink for the 3.3 volts that comes out of the xBee. The larger flicker led is on a long twisted pair of wire wrap wire so that it can more easily be snuck up to the candle I plan to drop it into.


Once back together I just mounted the xBee to the bottom of the case where it is quite happy to receive signals from the computer upstairs.


The LED’s I just hot glued to the back center of the case so that they would not be visible but would wall wash the wall when turned on.


There’s the clock where it lives on a shelf in my bedroom displaying an alarm zone message, and you can see the little wire running up to the candle. 


The RED alert LED while displaying the time.


The green LED and the candle flicker LED are on in this pic.

In XTension the serial port for each xBee radio is brought out to a local TCP port on the computer to which anything can connect. For myself I’m using applescripts inside of XTension that can be run in response to motion or alarm zone changes. The clock is quite capable of displaying scrolling messages if you handle that on the sender side, but I’m not bothering with that yet, sitting there while a long message scrolls across is not really conducive to getting a quick but of info about activity around the house. Though I may do something soon with a button that causes it to show outdoor temperature and perhaps scroll a short display of weather forecast.

In XTension I created a DIY interface to connect to the serial port and give me access to send data to the clock. The DIY interface is called “bedroom clock” so that I can talk to it by name elsewhere. In my Attachments Script I created some handlers to call to send messages or clear the clock. Here’s the snippet for sending a message to the clock and then having it clear after a certain amount of time:

on WriteToBedroomClock(TheMessage, TheTimeout)
--send the command init string
send data bytes {"&hFF"} interface "bedroom clock"
set s to PadClockString(TheMessage) & "     "
send data "A0" interface "bedroom clock"
send data s interface "bedroom clock"
try
suspend event “Clear Bedroom Clock" for TheTimeout
on error
execute script “Clear Bedroom Clock" in TheTimeout
end try
end WriteToBedroomClock



on PadClockString(TheString)
set w to (TheString as string)
repeat
if (count of w) is less than 5 then
set w to w & " "
else
return w
end if
end repeat
end PadClockString

You can make the call to WriteToBedroomClock( “ALARM”, 5) from anywhere else in the program or externally from anything else via a tell app block. This does not validate that only 5 characters are sent, but if fewer are sent it properly pads them out, the second parameter is the timeout or how long to show the message before it returns to showing the time.

You’ll also need to create a global script called “Clear Bedroom Clock” for this to call after the timeout period. Something like this:

send data bytes {"&hff"} interface "bedroom clock"
send data "MT          " interface "bedroom clock"


thats all thats necessary to make the Alpha Clock display messages, but it has other features as well. Here is some rather odd code to set the time from AppleScript, you have to get a unix date number which turns out to be harder in AppleScript than I imagined. There is no simple way to get the underlying date as a raw number! I searched around until I found someone who had done so by coercing it first through miles and then to a number. Go figure.

  set theNumber to (((current date) - (date ("1/1/1970")) - (time to GMT)) - (4 * hours)) as miles as string


  write log "unix date is: " & theNumber
  send data bytes {"&hFF"} interface "bedroom clock"
  send data "ST" & theNumber interface "bedroom clock"
  write log "bedroom time set"

Create that in a global script and run it whenever necessary, I run it nightly but the clock is very accurate thanks to that chronodot. Notice the end of that first line in that script -(4 * hours) I had to add as that was how many hours off the time was after running the script. I think that (time to GMT) may not be working correctly either because my computer has something setup goofy or perhaps it just doesn’t work I dont know but be prepared to change that as necessary to make it set the proper time in your zone.

More info on the serial protocol for talking to the alpha clock 5 is available on the evil mad science wiki.

Next project will be connecting up this touch sensor so that a gentle brush to the top of the clock displays temperature and weather info :)



.code { background:#f5f8fa; background-repeat:no-repeat; border: solid #5C7B90; border-width: 1px 1px 1px 20px; color: #000000; font: 13px 'Courier New', Courier, monospace; line-height: 16px; margin: 10px 0 10px 10px; max-height: 200px; min-height: 16px; overflow: auto; padding: 28px 10px 10px; width: 90%; } .code:hover { background-repeat:no-repeat; }