Friday, January 19, 2018

#1 2014-12-14 08:43:37 pm

JoelC
Member
Registered: 2014-11-17
Posts: 187

Controlling and Running a Perpetual Script

I have a SONOS music system in my home office...I would like the SONOS music system to automatically start when I come home and automatically stop when I leave home.

I have looked at the AppleScript Dictionary only to discover that SONOS' Desktop Controller -- the OS X app used to control the SONOS music system -- is not scriptable sad

I have thought about this somewhat and am hoping that I can code / program this functionality using the following two step process:

1.  An AppleScript to trigger the start / stop of the SONOS  music system; and

2.  An Automator Workflow to actually start / stop the SONOS music system.

I have thought further about 1. above and have concluded that one way to trigger the start / stop Automator Workflows is to start / stop the Automator Workflow when my iPhone's static IP address on my home network is / is not detected.

In terms of an AppleScript I have coding the following script which does successfully detect the presence / absence of my iPhone:

Applescript:



set EndofTime to false

repeat while not EndofTime
   
   try
       set IP_address to "aaa.bbb.ccc.ddd" - iPhone static IP address
       
       set ping to do shell script ("ping -c 2 " & IP_address & "| head -2 | tail -1 |cut -d = -f 4")
       
       if ping contains "ms" then
           set iPhoneDetected to "True"
           display dialog ("iPhone Detected - " & ping) buttons {"OK"} default button 1 with title "iPhone Detection Test" giving up after 3
           
       else if ping contains "timeout" then
           set iPhoneDetected to "False"
           display dialog "iPhone Not Detected " buttons {"OK"} default button 1 with title "iPhone Detection Test" giving up after 3
           
       end if
   end try
   
end repeat

While the above AppleScript needs further development [i.e. if iPhone detected then retest in 5 minute increments, etc.] I have run into a few problems for which I would appreciate some assistance.  While the compiled script can be added to the user's Login Item list [i.e. System Preferences / Users & Groups / Login Items] to automatically load when the user logs on:

1.  How do I ensure that the perpetual running of the script does not become a memory hog [i.e.  is there a way to stop the script and then restart the script, etc.]?

2.  Is there code / a way to stop the script from running without Activity Monitor / force quit once the script is perpetually running.


While we are on the subject -- is my proposed two step process workable?

Thanks to all for your help and interest.

Offline

 

#2 2014-12-14 09:55:29 pm

kel1
Member
Registered: 2013-01-11
Posts: 2188

Re: Controlling and Running a Perpetual Script

Hi Joel,

You can run your app at anytime using launch agents. I think that's what you want to do.

Sorry, I did not see where you wanted to detect the iPhone. Don't know 'bout that!

gl,
kel

Last edited by kel1 (2014-12-14 09:58:16 pm)


Os 10.10.3
Mbp

Offline

 

#3 2014-12-14 10:14:39 pm

JoelC
Member
Registered: 2014-11-17
Posts: 187

Re: Controlling and Running a Perpetual Script

kel1 wrote:

Hi Joel,

You can run your app at anytime using launch agents. I think that's what you want to do.

Sorry, I did not see where you wanted to detect the iPhone. Don't know 'bout that!

gl,
kel


@ Kel, appreciate the response though I now need to read up and learn about launch agents!

@ All - and unrelated -- I am now concerned that my two step process is not workable for the same reason an AppleScript is not possible [i.e. SONOS Desktop Controller is not  scriptable app] in that I do not see SONOS in the Automator's library list...would appreciate commentary on this as well!

Thanks..

Offline

 

#4 2014-12-14 11:25:05 pm

kel1
Member
Registered: 2013-01-11
Posts: 2188

Re: Controlling and Running a Perpetual Script

You place the launch agent in your Library and it launches according to what you want to do. What time did you want to launch your script?

Edited: I have  one launching, but you can do almost anything with them.

Try this straight from the horses mouth smile.

https://developer.apple.com/library/mac … dJobs.html

It shows a simple launch agent.

gl,
kel

Last edited by kel1 (2014-12-14 11:30:54 pm)


Os 10.10.3
Mbp

Offline

 

#5 2014-12-14 11:37:40 pm

kel1
Member
Registered: 2013-01-11
Posts: 2188

Re: Controlling and Running a Perpetual Script

Basically, what you do is create your launch agent plist. You store it in your library launch agents. Then you load it and it starts firing. The good part about this is that it uses very little memory or cpu time. Great stuff.


Os 10.10.3
Mbp

Offline

 

#6 2014-12-15 04:25:59 am

JoelC
Member
Registered: 2014-11-17
Posts: 187

Re: Controlling and Running a Perpetual Script

kel1 wrote:

You place the launch agent in your Library and it launches according to what you want to do. What time did you want to launch your script?

Edited: I have  one launching, but you can do almost anything with them.

Try this straight from the horses mouth smile.

https://developer.apple.com/library/mac … dJobs.html

It shows a simple launch agent.

gl,
kel


Great, much appreciated...now all I need to to determine / find out whether there is a way to control the SONOS Desktop Controller...

Offline

 

#7 2014-12-15 05:18:04 am

mouramartins
Member
From:: Algarve
Registered: 2010-11-21
Posts: 156

Re: Controlling and Running a Perpetual Script

JoelC wrote:

1.  How do I ensure that the perpetual running of the script does not become a memory hog [i.e.  is there a way to stop the script and then restart the script, etc.]?


1 - Use On idle in your script. The return value of the handler is the number of seconds until next idle.
See this for an example:  http://stackoverflow.com/questions/3718 … opup-alert

2 - Save your script as a Stay open application and put it in your Login items.


JoelC wrote:

2.  Is there code / a way to stop the script from running without Activity Monitor / force quit once the script is perpetually running.


You can Command Tab to the script appication and say "Quit"

Offline

 

#8 2014-12-15 03:38:03 pm

JoelC
Member
Registered: 2014-11-17
Posts: 187

Re: Controlling and Running a Perpetual Script

mouramartins wrote:
JoelC wrote:

1.  How do I ensure that the perpetual running of the script does not become a memory hog [i.e.  is there a way to stop the script and then restart the script, etc.]?


1 - Use On idle in your script. The return value of the handler is the number of seconds until next idle.
See this for an example:  http://stackoverflow.com/questions/3718 … opup-alert

2 - Save your script as a Stay open application and put it in your Login items.


JoelC wrote:

2.  Is there code / a way to stop the script from running without Activity Monitor / force quit once the script is perpetually running.


You can Command Tab to the script appication and say "Quit"


Appreciate the response noting both seem doable and simple...I will give them a try!

Offline

 

#9 2014-12-17 04:43:34 pm

Adam Bell
Administrator
From:: Nova Scotia, Canada
Registered: 2005-10-04
Posts: 4660

Re: Controlling and Running a Perpetual Script

There's an app that detects bluetooth proximity and runs a script:

Bluetooth Proximity Tasker. That might help.


iMac running OS X 10.13.1

Offline

 

#10 2014-12-17 08:37:20 pm

JoelC
Member
Registered: 2014-11-17
Posts: 187

Re: Controlling and Running a Perpetual Script

Adam Bell wrote:

There's an app that detects bluetooth proximity and runs a script:

Bluetooth Proximity Tasker. That might help.


Adam:

Appreciate the information, very helpful indeed...now all I need is for SONOS to make their Desktop Controller AppleScript enabled, which it is not sad

Thanks.

Joel

Offline

 

#11 2014-12-20 07:07:48 am

JoelC
Member
Registered: 2014-11-17
Posts: 187

Re: Controlling and Running a Perpetual Script

I will try to get my AS' to run perpetually once I know that I can actually control my SONOS Music System [i.e. no point in spending time on something that cannot be achieved].  With this in mind:


1. I went over to the SONOS Forum to see how others have controlled their SONOS Music Systems using AS only to find out no one has tried this [or, at least posted about i] since SONOS rewrote their OS X Desktop Controller.

One poster did post the following:

One way to pause / play the SONOS Music system is to use curl (which I believe is included in OS X).  The codes are:

Pause:
curl --header 'SOAPACTION: "urn:schemas-upnp-org:service:AVTransport:1#Pause"' --data '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:Pause xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID><Speed>1</Speed></u:Pause></s:Body></s:Envelope>' http://192.168.2.42:1400/MediaRenderer/ … rt/Control


Play:
curl --header 'SOAPACTION: "urn:schemas-upnp-org:service:AVTransport:1#Play"' --data '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:Play xmlns:u="urn:schemas-upnp-
org:service:AVTransport:1"><InstanceID>0</InstanceID><Speed>1</Speed></u:Play></s:Body></s:Envelope>' http://192.168.2.42:1400/MediaRenderer/ … rt/Control



2. I then went over to another forum and found the following:

Sure, the command line utility curl is one way. Applescripts can use command line utilities with the "do shell script" command. So try this...

Applescript:


set theURL to "http://my.server.com?type=Show&name=Big+Bang+Theory"
do shell script "curl " & quoted form of theURL

so might be possible as AS does seem to recognize curl commands.


3.  So armed with the above I tried the following AS:

Applescript:


set theURL to "--header 'SOAPACTION: "urn:schemas-upnp-org:service:AVTransport:1#Play"' --data '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:Play xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID><Speed>1</Speed></u:Play></s:Body></s:Envelope>' [url=http://192.168.2.42:1400/MediaRenderer/AVTransport/Control]http://192.168.2.42:1400/MediaRenderer/AVTransport/Control"[/url]

do shell script "curl " & quoted form of theURL

which I could not even test because I got a compile error [i.e. Syntax Error, A identifier can’t go after this “"”.] where the reference is to the "urn portion of the set command.

Would very much appreciate your help and assistance in solving this.

Thanks in advance.


Joel

Offline

 

#12 2014-12-20 07:26:00 am

StefanK
Member
From:: St. Gallen, Switzerland
Registered: 2006-10-21
Posts: 11483
Website

Re: Controlling and Running a Perpetual Script

you have to escape each inner double quote with a backslash

Applescript:


set theURL to "--header 'SOAPACTION: \"urn:schemas-upnp-org:service:AVTransport:1#Play\"' --data '<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><s:Body><u:Play xmlns:u=\"urn:schemas-upnp-org:service:AVTransport:1\"><InstanceID>0</InstanceID><Speed>1</Speed></u:Play></s:Body></s:Envelope>' [url=http://192.168.2.42:1400/MediaRenderer/AVTransport/Control]http://192.168.2.42:1400/MediaRenderer/AVTransport/Control"[/url]
do shell script "curl " & quoted form of theURL


regards

Stefan

Offline

 

#13 2014-12-20 09:02:34 am

JoelC
Member
Registered: 2014-11-17
Posts: 187

Re: Controlling and Running a Perpetual Script

StefanK wrote:

you have to escape each inner double quote with a backslash

Applescript:


set theURL to "--header 'SOAPACTION: \"urn:schemas-upnp-org:service:AVTransport:1#Play\"' --data '<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><s:Body><u:Play xmlns:u=\"urn:schemas-upnp-org:service:AVTransport:1\"><InstanceID>0</InstanceID><Speed>1</Speed></u:Play></s:Body></s:Envelope>' [url=http://192.168.2.42:1400/MediaRenderer/AVTransport/Control]http://192.168.2.42:1400/MediaRenderer/AVTransport/Control"[/url]
do shell script "curl " & quoted form of theURL


Stefan:

Appreciate the solution which worked perfectly though I think that at this point I should have know that!

Thanks,


Joel

Last edited by JoelC (2014-12-20 09:53:43 am)

Offline

 

#14 2014-12-20 10:09:31 am

JoelC
Member
Registered: 2014-11-17
Posts: 187

Re: Controlling and Running a Perpetual Script

PUTTING IT ALL TOGETHER......

As a result of the generous help with others I now have all the ingredients to make the script I need / want...the ingredients are:

1.  A script to pause my SONOS Music system when I leave my home:

Applescript:


do shell script "curl --header 'SOAPACTION: \"urn:schemas-upnp-org:service:AVTransport:1#Pause\"' --data '<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><s:Body><u:Pause xmlns:u=\"urn:schemas-upnp-org:service:AVTransport:1\"><InstanceID>0</InstanceID><Speed>1</Speed></u:Pause></s:Body></s:Envelope>' [url=http://192.168.2.42:1400/MediaRenderer/AVTransport/Control]http://192.168.2.42:1400/MediaRenderer/AVTransport/Control"[/url]

2.  A script to play my SONOS Music system when I arrive home:

Applescript:


do shell script "curl --header 'SOAPACTION: \"urn:schemas-upnp-org:service:AVTransport:1#Play\"' --data '<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><s:Body><u:Play xmlns:u=\"urn:schemas-upnp-org:service:AVTransport:1\"><InstanceID>0</InstanceID><Speed>1</Speed></u:Play></s:Body></s:Envelope>' [url=http://192.168.2.42:1400/MediaRenderer/AVTransport/Control]http://192.168.2.42:1400/MediaRenderer/AVTransport/Control"[/url]

3.  A script to determine whether I am / am not home based on whether my iPhone is present on my home LAN noting that obviously I need a better method of starting / topping this script:

Applescript:


set EndofTime to false

repeat while not EndofTime
   
   try
       set IP_address to "10.193.23.180"
       
       set ping to do shell script ("ping -c 2 " & IP_address & "| head -2 | tail -1 |cut -d = -f 4")
       
       if ping contains "ms" then
           set iPhoneDetected to "True"
           display dialog ("iPhone Detected - " & ping) buttons {"OK"} default button 1 with title "iPhone Detection Test"
           
       else if ping contains "timeout" then
           set iPhoneDetected to "False"
           display dialog "iPhone Not Detected " buttons {"OK"} default button 1 with title "iPhone Detection Test"
           
       end if
   end try
   
end repeat

So what are the issues...I know that to make this work I need to i) comment out / remove the display dialog boxes as they are there for testing purposes and need not be there once the script is running ii) insert a call to the scripts "pause SONOS" and "play SONOS" within the "if blocks" depending on whether my iPhone is detected...what I don't know and what I need help with is how to add code that controls the script so that  can i) ensure the script does not take up too many resources as it will be running at all times ii) start / stop the script when necessary [i.e. I need a way to stop the script which does not currently exist] and iii) whatever else is needed when constantly running such a script.

Would greatly appreciate the boar's assistance in making this work.

Thanks,

Joel

Offline

 

#15 2014-12-20 01:50:11 pm

StefanK
Member
From:: St. Gallen, Switzerland
Registered: 2006-10-21
Posts: 11483
Website

Re: Controlling and Running a Perpetual Script

I strongly advise against sending ping commands continuously.

Better use something like Installation Experiences: iPhone Presence Detection with Bonjour Multicast DNS using python or the Cocoa equivalent NSNetServiceBrowser


regards

Stefan

Offline

 

#16 2014-12-20 01:57:52 pm

JoelC
Member
Registered: 2014-11-17
Posts: 187

Re: Controlling and Running a Perpetual Script

StefanK wrote:

I strongly advise against sending ping commands continuously.

Better use something like Installation Experiences: iPhone Presence Detection with Bonjour Multicast DNS using python or the Cocoa equivalent NSNetServiceBrowser


StefanK:

Appreciate the response and don't doubt what you are saying BUT...

1.  Could you be so kind to explain why you recommend against continuously sending ping commands; and

2.  I took a fast read of python code and while I recognize that I don't need to understand I would not even know where to begin vis-a-vis its setup as I don't have an Indigo server, I don't know python at all, etc.

3.  I would be open to trying / using the Cocao equivalent but would need someone to walk me through the process step by step.

Thanks,


Joel

Offline

 

#17 2014-12-20 02:11:22 pm

StefanK
Member
From:: St. Gallen, Switzerland
Registered: 2006-10-21
Posts: 11483
Website

Re: Controlling and Running a Perpetual Script

polling is always expensive because it consumes permanently system resources like CPU, network bandwidth and potentially also RAM.
The python and the Cocoa method uses a callback function to be notified about a change, the system resources costs are negligible.


regards

Stefan

Offline

 

#18 2014-12-20 02:14:42 pm

JoelC
Member
Registered: 2014-11-17
Posts: 187

Re: Controlling and Running a Perpetual Script

StefanK wrote:

polling is always expensive because it consumes permanently system resources like CPU, network bandwidth and potentially also RAM.
The python and the Cocoa method uses a callback function to be notified about a change, the system resources costs are negligible.


StefanK:

Appreciate the response.

Assuming the Cocao approach will be better / easier for me [remember, I have only been playing with AS for a month or so] what do you suggest is the best way for me to get the Coca call back function up and running noting I know nothing about Cocoa.

Thanks,


Joel

Offline

 

#19 2014-12-21 12:24:09 pm

JoelC
Member
Registered: 2014-11-17
Posts: 187

Re: Controlling and Running a Perpetual Script

As much as I wanted to move this project / script forward I have hit a standstill in that:

1. I am going to heed StefanK's suggestion warning about not perpetually ping my iPhone's IP address for the reasons he notes in post #17 to this thread.

2.  I was -- because I am not familiar with the use of Cocoa's NSNetServiceBrowser -- going to use the method approach suggested by Adam Bell in post #9 of this thread but ran into problems in that I cannot pair my iPhone 5S to my mid-2012 MBA as I seem to be one of the many users who are having this pairing problem [so much for the Apple ecosystem "just works" which is why I moved from Windows to OS X].

I spent 3+ hours on the pie with Apple technical support and got nowhere...in fact, no one really wanted to help in that the MBA people passed me to the iOS people who on turned wanted to pass me back to the MBA people...this is extremely frustrating given this is a known issue between product both of which are made by the same company!

3.  With 1. and 2. above I am stuck in that I i) either need someone to teach or walk me through NSNetServiceBrowser or ii) for Apple to fix this pairing problem.

Thanks to all for reading this,


Joel

Offline

 

#20 2014-12-21 12:52:20 pm

StefanK
Member
From:: St. Gallen, Switzerland
Registered: 2006-10-21
Posts: 11483
Website

Re: Controlling and Running a Perpetual Script

sorry for having mentioned Cocoa.
With "playing with AS for a month" and  "I know nothing about Cocoa" I guess it's as difficult to implement as the python method

When using your polling method  at least create a stay open application with an on idle handler and a return value of one or more seconds to reduce the overload

Last edited by StefanK (2014-12-21 12:52:54 pm)


regards

Stefan

Offline

 

#21 2014-12-21 12:59:07 pm

JoelC
Member
Registered: 2014-11-17
Posts: 187

Re: Controlling and Running a Perpetual Script

StefanK wrote:

sorry for having mentioned Cocoa.
With "playing with AS for a month" and  "I know nothing about Cocoa" I guess it's as difficult to implement as the python method

When using your polling method  at least create a stay open application with an on idle handler and a return value of one or more seconds to reduce the overload


Appreciate the response...I will post my code to determine whether anyone here can improve on it...that said, I do have one question, does anyone here know whether to it is or is not true that an iPhone CANNOT be paired to a MacBook because after 3+ hours of speaking with Apple and finally getting passed to a level 2 support technician I was told that this is not possible [which, personally, I find hard to believe].

Thanks...

Offline

 

#22 2014-12-21 02:45:56 pm

JoelC
Member
Registered: 2014-11-17
Posts: 187

Re: Controlling and Running a Perpetual Script

StefanK wrote:

When using your polling method  at least create a stay open application with an on idle handler and a return value of one or more seconds to reduce the overload


StefanK

As a result of your post and my resulting conclusion that it would likely be best to try to code the script on my own I av it a go and came up with the following:

Applescript:


set EndofTime to false
set IP_address to "192.168.2.11"


repeat while not EndofTime
   -- Ping for absence / presence of iPhone [i.e. me] which triggers start/stop of SONOS Music system
   set ping to do shell script ("ping -c 2 " & IP_address & "| head -2 | tail -1 |cut -d = -f 4")
   
   
   -- Set iPhoneDetected to result of ping for absnece / presence of iPhone
   if ping contains "ms" then
       set iPhoneDetected to true
       -- display dialog ("iPhone Detected - " & ping) buttons {"OK"} default button 1 with title "iPhone Detection Test" -- Commented out, included for testing purposes only            
   else if ping contains "timeout" then
       set iPhoneDetected to false
       -- display dialog "iPhone Not Detected " buttons {"OK"} default button 1 with title "iPhone Detection Test" -- Comemnted out, included for testig purposes only            
   end if
   
   
   -- When iPhone absent run script to pause/stop SONOS Music system
   if iPhoneDetected is equal to false then
       set callSONOSPause to "/Users/JoelC/Documents/Apple/Scripts/SONOS Pause Play/20141220_script to pause sonos_complete.scpt" as string
       run script callSONOSPause
   end if
   
   
   -- When iPhone present runs script to play / start SONOS Music system
   if iPhoneDetected is equal to true then
       set callSONOSPlay to "/Users/JoelC/Documents/Apple/Scripts/SONOS Pause Play/20141220_script to play sonos at a preset volume_complete.scpt" as string
       run script callSONOSPlay
   end if
   
   -- When it is the bootom and top of every hour provide the user with the opportunity to exit the script noting this needs to be refined pending the implemenation of the idle handler
   if ((the minutes of the (current date) is 0) or (the minutes of the (current date) is 30)) then
       display dialog "Do you want to exit/stop the SONOS Music System auto pause/play script?" buttons {"Yes", "No"} default button 2 with icon 1 giving up after 5
       set continueResponse to button returned of result
       if continueResponse is equal to "Yes" then set EndofTime to true
   end if
   
   
end repeat

I have two issues for which I would ask for your assistance:

1.  Although I understand the idea behind the idle handler I am unsure how to implement it because i) if I am home I don't need to ping/test for the absence/presence of my iPhone for say 30 minutes [i.e. I don't care whether the music continues for 30 minutes after I leave the house] but ii) if I amanita home I need to ping/test for the absence/presence of iPhone say every 30 or 60 seconds to make sure it is on when I actually walk into the door. How do I do this?


2.  I have a logic problem in my code...because i) the ping is continually running and continuously detecting my iPhone and ii) the callSONOSPlay script includes a volume setting control I cannot change the volume of the SONOS because the script is overriding it...as such I need to build in some logic that will not reset the volume until after it next detects the absence of my iPhone [and yes, I can setup a separate script that simply controls the volume]...any suggestions on how best to do this?

Thanks,

Joel

Offline

 

#23 2014-12-21 03:06:41 pm

StefanK
Member
From:: St. Gallen, Switzerland
Registered: 2006-10-21
Posts: 11483
Website

Re: Controlling and Running a Perpetual Script

a script with an on idle handler looks like this,
it requires to save the code as application with stay open option checked

Applescript:


on run
   -- set up variables
end run

on idle
   -- do something
   return 60 -- call idle again after 60 seconds
end idle

on quit
   -- do some cleanup
   continue quit
end quit


regards

Stefan

Offline

 

#24 2014-12-21 10:13:53 pm

JoelC
Member
Registered: 2014-11-17
Posts: 187

Re: Controlling and Running a Perpetual Script

StefanK wrote:

a script with an on idle handler looks like this,
it requires to save the code as application with stay open option checked

Applescript:


on run
   -- set up variables
end run

on idle
   -- do something
   return 60 -- call idle again after 60 seconds
end idle

on quit
   -- do some cleanup
   continue quit
end quit


StefanK:

A huge thank you or pointing me in the right direction...I do however have 3 follow ups with respect to the script that appears below:

1.  At first I had the settings for the variables for firstDetection and IP_Address in the "On Run" section of the code but soon discovered that the settings in the 'On Run" section are not carried over to the "On Idle" section.

a) Is there a to get the variables in the "On Run" section to carry over to the "On Idle" section?

b) Why do the variables in the "On Run" section not automatically carry over to the "On Idle" section?


2.  I am having a problem with the firstDetection variable...I am trying to setup a control variable for efficiency in that I am trying to unnecessary avoid calling the SONOS scripts Pause / Play / Volume unless there is a status change in the iPhone's detection.

With the "On Run" section's variables not being carried over to the "On Idle" sections variables I simply cannot figure out a way to do this because i) not setting the value at the top of the "On Idle" section cause the script to fail because the firstDetection has no value and ii) setting the value at the top of the "On Idle" section cause the value to be reset on each successive ping...how do I solve this?


3.  With this being my first attempt at using "On Idle" code please feel free to make any and all suggestions for improvement.


Applescript:



on run
   set firstDetection to true -- Set variable to true so the first time the iPhone is detected the SONOS Music System is started
end run


on idle
   
   
   set IP_address to "192.168.2.11" -- Set iPhone IP address
   
   -- Ping for absence/presence of iPhone [i.e. me] which triggers start/stop of SONOS Music system
   set ping to do shell script ("ping -c 2 " & IP_address & "| head -2 | tail -1 |cut -d = -f 4")
   
   
   -- Set results of ping for absence/presence of iPhone to iPhoneDetected
   if ping contains "ms" then
       set iPhoneDetected to true
       display dialog ("iPhone Detected - " & ping) buttons {"OK"} default button 1 with title "iPhone Detection Test" -- Commented out, included for testing purposes only
       display dialog ("first Detection - " & firstDetection) default button 1 with title "iPhone Detection Test" -- Commented out, included for testing purposes only            
   else if ping contains "timeout" then
       set iPhoneDetected to false
       display dialog "iPhone Not Detected " buttons {"OK"} default button 1 with title "iPhone Detection Test" -- Commented out, included for testing purposes only
       display dialog ("first Detection - " & firstDetection) default button 1 with title "iPhone Detection Test" -- Commented out, included for testing purposes only                
   end if
   
   
   -- When result of ping for absence/presence of iPhone is absent then run the script to pause/stop SONOS Music system
   if ((iPhoneDetected is equal to false) and (firstDetection is equal to false)) then
       
       set callSONOSPause to "/Users/JoelC/Documents/Apple/Scripts/SONOS Pause Play/20141220_script to pause sonos_complete.scpt" as string
       run script callSONOSPause
       
       set firstDetection to true -- Set varaiable to true so that the next time the iPhone is detected the SONOS Music System is started
   end if
   
   
   -- When result of ping for absence/presence of iPhone is presnet then run the script to play / start SONOS Music system
   if ((iPhoneDetected is equal to true) and (firstDetection is equal to true)) then
       
       set firstDetection to false
       
       set callSONOSVolume to "/Users/JoelC/Documents/Apple/Scripts/SONOS Pause Play/20141220_script for a preset volume_complete.scpt" as string
       run script callSONOSVolume
       
       set callSONOSPlay to "/Users/JoelC/Documents/Apple/Scripts/SONOS Pause Play/20141220_script to play sonos_complete.scpt" as string
       run script callSONOSPlay
   end if
   
   -- Set the idle time between pings for absence/presence of of the iPhone
   set timeControl to time of (current date)
   
   if ((timeControl is greater than 82800) or (timeControl is less than 28800)) then -- No pinging between 8:00 PM and 8:00 AM    
       if (timeControl is greater than 82800) then set returnTime to ((83699 - timeControl) + 28800) as integer
       if (timeControl is less than 28800) then set returnTime to (28800 - timeControl) as integer
       return returnTime
   else
       if iPhoneDetected is equal to false then set returnTime to 60 as integer -- Ping for absence/presence of iPhone every 1 minute when result is absence
       if iPhoneDetected is equal to true then set returnTime to 300 as integer --Ping for absence/presence if iPhone every 5 minutes when result is presence
       return returnTime
   end if
   
end idle


on quit
   display dialog "Do you also want to pause/stop the SONOS Music System?" with title "SONOS Music System Automatic Pause / Play" buttons {"Yes", "No"} default button 2 with icon 1 giving up after 15
   set pauseMusic to button returned of result
   if (pauseMusic is equal to "Yes") then
       set callSONOSPause to "/Users/JoelC/Documents/Apple/Scripts/SONOS Pause Play/20141220_script to pause sonos_complete.scpt" as string
       run script callSONOSPause
   end if
   
   display dialog "Exit/stopping the SONOS Music System pause/play script" with title "SONOS Music System Automatic Pause / Play" buttons {"Okay"} default button 1 with icon 1 giving up after 5
   continue quit
end quit


Thanks,


Joel

Last edited by JoelC (2014-12-21 10:14:36 pm)

Offline

 

#25 2014-12-21 11:58:18 pm

StefanK
Member
From:: St. Gallen, Switzerland
Registered: 2006-10-21
Posts: 11483
Website

Re: Controlling and Running a Perpetual Script

variables in AppleScript are local by default, that means they are valid within the scope of a handler.
Define a variable as global or use a property to extend the scope

Applescript:


property firstDetection : true

The value of a property is set at compile time and is persistent in a script applet even during relaunch

Last edited by StefanK (2014-12-22 12:00:52 am)


regards

Stefan

Offline

 

Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)