Controlling and Running a Perpetual Script

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

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 :frowning:

Thanks.

Joel

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:

[i]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”>01</u:Pause></s:Body></s:Envelope>’ http://192.168.2.42:1400/MediaRenderer/AVTransport/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”>01</u:Play></s:Body></s:Envelope>’ http://192.168.2.42:1400/MediaRenderer/AVTransport/Control[/i]

  1. 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…


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.

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

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

you have to escape each inner double quote with a backslash


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

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:

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]

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

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]

  1. 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:

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

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

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

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!

  1. 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

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…

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:


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

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


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?

  1. 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?

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


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

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


property firstDetection : true

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

StefanK:

Much appreciated and completely understood.

That said, I am running into a problem…I am thinking – perhaps incorrectly – that it would be best to use global variables because that would avoid the need to check / confirm / set the value of firstDetection when quitting as well as be more efficient from a memory management perspective [i.e. I understand that one aspect of a property is that whatever value it has when a script is exited it will have and retain that value when the script is next run unless the script recompiled].

With that I tried to use the following code to define global variables:


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

but I am getting an error message that IP_address is not defined within the “On Idle” portion of the script.

What am I doing wrong as I thought that by defining IP_address as global that it would be available within the “On Idle” portion of the script?

Thanks,

Joel

PS. We are almost there…

this kind of global statement is supposed to be outside any handler at the beginning of the script


global firstDetection, IP_address

on run
	set firstDetection to true -- set up variables
	set IP_address to "192.168.2.11"
end run