applescript to python - help pls

Posted on
Tue Oct 26, 2021 4:51 pm
dtich offline
Posts: 798
Joined: Sep 24, 2005

applescript to python - help pls

hi guys, I've gone on upwork with this stuff too, but they don't understand indigo enough.. even combing through this forum.

my things are simple ones like these below, i got aways into it, but stuck passing command to other app (iRed2)... tried osascript, didn't work either.

ANY thoughts/advice/scripts! are so much appreciated. trying to finally move on from as, but... can't quite manage it myself.


Code: Select all
using terms from application "Indigo 7.3"
   
   on RemoteControl(myRemote, irCode)
      
      with timeout of 3 seconds
         try
            
            set RemoteDev to {myRemote, "/", myRemote} as string
            
            using terms from application "iRed2.app"
               
               tell application "iRed2.app" to «event ird2IpAC» given «class acti»:(«class ICOD» irCode of «class IRAG» RemoteDev)
               
            end using terms from
            
         on error
            tell application "Indigo 7.3"
               «event INDOLog » "error" given «class LgTy»:"iRed:"
            end tell
            
         end try
      end timeout
      
   end RemoteControl
   
end using terms from


Code: Select all
-- Security Spy Camera Control Handler
-- dtich, 1/07

-- examples: CameraControl ("guest room","active"); ("","passive")


on CameraControl(Cam, CamCmd)
   set SecSpyTimeout to 3
   
   
   with timeout of SecSpyTimeout seconds
      try
         using terms from application "SecuritySpy"
            if CamCmd is "active" or CamCmd is "passive" then
               
               if CamCmd is "active" then
                  if Cam is "" then
                     tell application "SecuritySpy"
                        set schedule preset "all capture"
                     end tell
                  else
                     tell application "SecuritySpy"
                        set schedule "Armed 24/7" camera name Cam
                     end tell
                  end if
               end if
               
               
               if CamCmd is "passive" then
                  if Cam is "" then
                     tell application "SecuritySpy"
                        set schedule preset "all off"
                     end tell
                  else
                     tell application "SecuritySpy"
                        set schedule "Unarmed 24/7" camera name Cam
                     end tell
                  end if
               end if
               
            else
               tell application "Indigo 7.3"
                  «event INDOLog » "Command Error - Mode Not Found" given «class LgTy»:"Security Spy:"
               end tell
               --return
               
            end if
            
         end using terms from
      end try
   end timeout
   
   
end CameraControl


adding some screenshots because the code didn't compile without the lib/dict on this machine.. the real terms are in the screen shots... thx
Attachments
Screen Shot 2021-10-26 at 3.48.43 PM.jpg
Screen Shot 2021-10-26 at 3.48.43 PM.jpg (137.4 KiB) Viewed 3723 times
Screen Shot 2021-10-26 at 3.45.46 PM.png
Screen Shot 2021-10-26 at 3.45.46 PM.png (398.56 KiB) Viewed 3723 times

Posted on
Wed Oct 27, 2021 9:20 am
jay (support) offline
Site Admin
User avatar
Posts: 18200
Joined: Mar 19, 2008
Location: Austin, Texas

Re: applescript to python - help pls

The only thing in your AppleScripts that are specific to Indigo are just the lines that log into the Event Log. The simplest solution is to just remove them and all references to Indigo.

In your screenshots of Script Editor, note that it's referencing "Indigo Server" - that works because you probably still have an Indigo 6 server on your system. In the Code snippits, note that it's referencing "Indigo 7.3" which is the Indigo client app, not the server. The Indigo Server is no longer scriptable, so whatever attempted to do the compile just guessed that it was the client you were trying to script, but of course that won't work either.

Bottom line: remove all references to Indigo and the script should run. You can then run that script from Indigo as an external script (since you can still run AppleScripts that don't reference Indigo in any way). AppleScript can't run embedded in Indigo but running an external AppleScript file still works with the above caveats.

Jay (Indigo Support)
Twitter | Facebook | LinkedIn

Posted on
Sat Jan 15, 2022 1:38 am
dtich offline
Posts: 798
Joined: Sep 24, 2005

Re: applescript to python - help pls

Error (client) timeout waiting for server response for request ExecuteScriptSource

Jan 14, 2022 at 11:19:57 PM
Warning because embedded scripts execute sequentially they must complete their execution within 10 seconds.
Stopping embedded script executor host2 (pid 79364)
Warning process (pid 79364) failed to quit after polite request -- forcing it to quit now
Stopped "embedded script executor host2"
Error (client) received unexpected packet response ExecuteScriptSource (waiting for )


got that trying to run the external script (below) via embedded import AppleScript call (also below, but not so far below), i realize it has many refs to indigo -- i could use a couple key pointers on how to get these variables in and out of the run handler -- or, whatever the most efficient way to achieve the end goal would be -- instinct tells me a straight py script would be ideal, but i don't have enough python to even start because i'm confused about which variables need to belong to indigo proper and which don't in this case -- THANK YOU:

this is the embedded import script call:

Code: Select all
import applescript

path_to_script_file = "/Library/Application Support/Perceptive Automation/Scripts/sprinkler_next_run.scpt"
my_ascript_from_file = applescript.AppleScript(path=path_to_script_file)


reply = my_ascript_from_file.run()


Code: Select all
property sprinklerScheduleList : {"SPRINKLER program AA (4min-EvThirdDay-PM) CONSTRUCTION", "SPRINKLER program A (2min-EvOtherDay-PM)", "SPRINKLER program A2 (1min-EvOtherDay-AM)", "SPRINKLER program B (2min-Everyday-PM)", "SPRINKLER program B2 (2min-Everyday-AM)", "SPRINKLER program C (4min-Everyday-PM)", "SPRINKLER program C2 (4min-Everyday-AM)"}

tell application "IndigoServer"
   set noneScheduledStr to "none scheduled"
   set soonestTrigger to noneScheduledStr
   repeat with scheduleName in sprinklerScheduleList
      if enabled of time date action scheduleName is true then
         set nextTrigger to (next trigger time of time date action scheduleName)
         if soonestTrigger is noneScheduledStr or nextTrigger < soonestTrigger then
            set soonestTrigger to nextTrigger
         end if
      end if
   end repeat
   
   set value of variable "sprinkler_nextruntime" to soonestTrigger as string
   -- returns in format: Tuesday, April 21, 2009 10:00:00 PM
   
end tell


Posted on
Sat Jan 15, 2022 1:26 pm
dtich offline
Posts: 798
Joined: Sep 24, 2005

Re: applescript to python - help pls

and about to try this little mess (see code below img), afraid i'm gonna lock up the entire server with it as i know it is all kinds of wrong, but, attempting to make this work with the as ired handler that is shown a few posts above.....

Image


code below -- immediate thoughts on what to fix first?? :D -- thanks!!



Code: Select all
import applescript


##define script obj
path_to_script_file = "/Library/Application Support/Perceptive Automation/Scripts/ired_handler.scpt"
ired_handler = applescript.AppleScript(path=path_to_script_file)


##create ind vars
RemoteControlDEV = indigo.variable.create("RemDev", "undefDev")
RemoteControlCMD = indigo.variable.create("RemCmd", "undefCmd")


##set values to pass to handler
## could combine with previous step??
indigo.variable.updateValue(RemoteControlDEV, "Classe/CT-SSP")
indigo.variable.updateValue(RemoteControlCMD, "MUTE")


##pass values to remote applescript????
ired_handler.variable.updateValue("myRemote", RemoteControlDEV)
ired_handler.variable.updateValue("irCode", RemoteControlCMD)



##run handler with new values
reply = ired_handler.run()


Posted on
Sat Jan 15, 2022 2:21 pm
dtich offline
Posts: 798
Joined: Sep 24, 2005

Re: applescript to python - help pls

update. does this almost work?? eliminated most lines resulting in this, which doesn't throw an error, but doesn't work either. is it close at all?

Code: Select all
import applescript


##define script obj
path_to_script_file = "/Library/Application Support/Perceptive Automation/Scripts/ired_handler.scpt"
ired_handler = applescript.AppleScript(path=path_to_script_file)


##run handler with new values
ired_handler.call("RemoteControl", "Classe/CT-SSP", "MUTE")



if i can get these arguments into the AppleScript handler it will work. it runs. no errors thrown, but no result. so i think it's just the syntax of the arguments....? the syntax i used was for a handler with one argument, i need two. is there something simple to adjust here, or does it need a list or dict?

this is the current applscript that works fine locally:

Code: Select all
--RemoteControl("Classe/CT-SSP/Classe/CT-SSP", "SAT (F3)")

on RemoteControl(myRemote, irCode)
   
   with timeout of 1.5 seconds
      try
         
         --set RemoteDev to {myRemote, "/", myRemote} as string
         
         using terms from application "iRed2"
            
            tell application "iRed2" to perform action (Code irCode of Device myRemote)
            
         end using terms from
         
         (*on error
         tell application "IndigoServer"
            log "error" using type "iRed:"
         end tell*)
         
      end try
   end timeout
   
end RemoteControl

thanks!

Posted on
Sat Jan 15, 2022 4:13 pm
dtich offline
Posts: 798
Joined: Sep 24, 2005

Re: applescript to python - help pls

THIS PART UP TO NEXT BOLDED TEXT CAN BE IGNORED. just stupid typos.

also, why doesn't this work?:
Code: Select all
patioamp = indigo.devices[1433506880] # "av/patio amp"

if patioamp.onState:
      indigo.device.turnOFF(1433506880)
else:
      indigo.device.turnON(1433506880)

   


throws this:
Code: Select all
Script Error                    embedded script: 'DeviceCmds' object has no attribute 'turnON'
   Script Error                    Exception Traceback (most recent call shown last):

     embedded script, line 8, at top level
AttributeError: 'DeviceCmds' object has no attribute 'turnON'


for that matter this (below) doesn't work in an action group either. what am i doing wrong? something stupid happening.. sorry, thanks for looking at my grade school problems lol. i do have

Code: Select all
indigo.device.turnOFF(1068916557)

indigo.device.turnOn(1068916557, delay=3)
Last edited by dtich on Sat Jan 15, 2022 10:06 pm, edited 3 times in total.

Posted on
Sat Jan 15, 2022 8:31 pm
dtich offline
Posts: 798
Joined: Sep 24, 2005

Re: applescript to python - help pls

lord. i sorted that. just sloppy capitalization. ugh. what maroon. fingers were on autopilot with my variable naming style.... sorry for the time waste on that.



END OF PART THAT CAN BE IGNORED... :D
Last edited by dtich on Sat Jan 15, 2022 10:05 pm, edited 1 time in total.

Posted on
Sat Jan 15, 2022 9:56 pm
dtich offline
Posts: 798
Joined: Sep 24, 2005

Re: applescript to python - help pls

Code: Select all
import applescript

##define script obj
path_to_script_file = "/Library/Application Support/Perceptive Automation/Scripts/ired_handler.scpt"
ired_handler = applescript.AppleScript(path=path_to_script_file)

##run handler with new values
ired_handler.call("RemoteControl", "Classe/CT-SSP/Classe/CT-SSP", "MUTE")


so, this actually seems to work, partially.

running it does indeed fire the command. the first time.

any subsequent runs, with this or other commands using the same handler (RemoteControl) are MUCH delayed. 6-10seconds. as if the handler is in a loop and locking up the thread. i have no error reporting enabled in this loop at the moment so i can't really pinpoint the issue. and it definitely feels like the kludgy way to implement this, but not sure what other approach to try.

importing the AppleScript each time feels bad too, but that's the method here, yes? if it were and actual handler of an attachment script it would work much better i assume.

any thoughts or methods to narrow it down would be appreciated. thanks !

Posted on
Sun Jan 16, 2022 1:34 pm
matt (support) offline
Site Admin
User avatar
Posts: 21411
Joined: Jan 27, 2003
Location: Texas

Re: applescript to python - help pls

I'm not sure what would be causing it to hang up / delay on subsequent executions. Importing the applescript module every time should be fine. Are there any errors logged in the Event Log? Try changing your Indigo python script to:

Code: Select all
import applescript

path_to_script_file = "/Library/Application Support/Perceptive Automation/Scripts/ired_handler.scpt"
ired_handler = applescript.AppleScript(path=path_to_script_file)
result = ired_handler.call("RemoteControl", "Classe/CT-SSP/Classe/CT-SSP", "MUTE")
indigo.server.log("RemoteControl result: " + str(result))


And your ired_handler.scpt AppleScript to:

Code: Select all
on RemoteControl(myRemote, irCode)
   with timeout of 1.5 seconds
      try
         using terms from application "iRed2"
            tell application "iRed2" to perform action (Code irCode of Device myRemote)
            return "success"
         end using terms from
      end try
   end timeout   
   return "timeout"
end RemoteControl

And see what the Event Log shows. The issue might be iRed2 getting confused/hung if it gets a second request while it is still processing the first.

Image

Posted on
Sun Jan 16, 2022 3:32 pm
dtich offline
Posts: 798
Joined: Sep 24, 2005

Re: applescript to python - help pls

thanks matt, for the error trapping -- yes, this does seem to be ired getting hung, for various reasons. and it seems to get in a bad state and stay there sometimes, actually kicking the irtrans unit offline for some reason. maybe a buffer bug. i've emailed robert, the dev.

thanks a lot for the guidance, i've got lots more to fix here, but it might actually be on the way.

thanks!

Posted on
Mon Jan 17, 2022 9:43 pm
dtich offline
Posts: 798
Joined: Sep 24, 2005

Re: applescript to python - help pls

still have the hanging issues with the iRed handler, but pretty sure that's iRed's issue, hopefully the dev can sort something.

on another note, i've roughed out the sprinkler next run script -- it's in python baby talk, i just don't know some stuff there, and i do scour the dox, but i don't find enough on lists and if/or/and syntax.. so if there's some quick nudges on a couple lines there i'd be grateful. thanks!!


Code: Select all
#indigo.variables[1037337531] # "sprinkler_nextruntime"



sprinklerScheduleList = ["SPRINKLER program AA (4min-EvThirdDay-PM) CONSTRUCTION", "SPRINKLER program A (2min-EvOtherDay-PM)", "SPRINKLER program A2 (1min-EvOtherDay-AM)", "SPRINKLER program B (2min-Everyday-PM)", "SPRINKLER program B2 (2min-Everyday-AM)", "SPRINKLER program C (4min-Everyday-PM)", "SPRINKLER program C2 (4min-Everyday-AM)"]


noneScheduledStr = "none scheduled"
soonestTrigger = noneScheduledStr

for scheduleName in sprinklerScheduleList:

   if indigo.timedateactions.isEnabled(scheduleName, value = "True"):
   #if indigo.timedateactions(scheduleName, enabled = "True"):

         nextTrigger = indigo.timedateactions(scheduleName, nextTime)
         if soonestTrigger = noneScheduledStr
                or if nextTrigger < soonestTrigger then
         
               
   soonestTrigger = nextTrigger



indigo.variable.updateValue(1037337531, value = soonestTrigger)



Posted on
Thu Jan 20, 2022 5:53 pm
matt (support) offline
Site Admin
User avatar
Posts: 21411
Joined: Jan 27, 2003
Location: Texas

Re: applescript to python - help pls

Give this a try (untested of course):
Code: Select all
import datetime

var_nextrun = indigo.variables[1037337531] # "sprinkler_nextruntime"

# ToDo: I would recommend using the integer schedule IDs to populate schedule_list
# instead of strings so the script will continue to work if a schedule is renamed.
# schedule_list = [123, 456, 789, ...]
schedule_list = ["SPRINKLER program AA (4min-EvThirdDay-PM) CONSTRUCTION", "SPRINKLER program A (2min-EvOtherDay-PM)", "SPRINKLER program A2 (1min-EvOtherDay-AM)", "SPRINKLER program B (2min-Everyday-PM)", "SPRINKLER program B2 (2min-Everyday-AM)", "SPRINKLER program C (4min-Everyday-PM)", "SPRINKLER program C2 (4min-Everyday-AM)"]

soonest = datetime.datetime.max

for schedule_id in schedule_list:
   schedule = indigo.schedules[schedule_id]
   if schedule.enabled and schedule.nextExecution > datetime.datetime.min:
      soonest = min(soonest, schedule.nextExecution)

indigo.variable.updateValue(var_nextrun, str(soonest))

Image

Posted on
Thu Jan 20, 2022 6:51 pm
dtich offline
Posts: 798
Joined: Sep 24, 2005

Re: applescript to python - help pls

matt! thanks. that worked.

python is always more efficient and less verbose than i anticipate. very powerful. thanks for the help!

i will use the ids, yes, i get that. already went through that craziness years ago after changing one schedule name and it took me hours to figure out that's what had kinked the whole shebang.... grrr.

thanks again.

Posted on
Fri Jan 21, 2022 11:28 pm
dtich offline
Posts: 798
Joined: Sep 24, 2005

Re: applescript to python - help pls

Ok. I tried. This is irrigation factor script. It's convoluted and redundant math no doubt.. but the original AppleScript was an evolving cobble of formula tweaking and what I ended up with works, and works well, for many years I haven't had to adjust my sprinkler times manually at all. I do know the actual math is wacky, but honestly.. I've no interest in rethinking it, cause it works.

So. Here's the py version I've arrived at. Compiling in an embedded indigo window reaches the end, but throws this:
Jan 21, 2022 at 9:23:52 PM
Script Error embedded script: invalid syntax
Script Error around line 89 - "pass"


that's basically the last line, or the line after really.. don't know what it means. also, i've commented out the last two log lines cause they wouldn't compile even though the syntax seems right to me..??

thoughts appreciated greatly!! thx.

Code: Select all
### init vars and lists

indigo.variable.updateValue(HumidDerate, 1)


tempAvgA = 0
tempAvgB = 0

tempTempA_List = [1322938653,691920204,260089793,1574995402,1850069036,1456307235,119394488,1354783145]
tempTempB_List = [433928592,1250118759,1624471510,444110768,758052807,1494625438,812101647,1354783145]

tempHumidA_List = [1172786570,331598169,1485751975,936737288,554095003,251870260,1568860020,162814321]
tempHumidB_List = [44964193,1077221341,1828836314,95069692,345600646,1518668036,923885739,162814321]


### temp averaging

for temp_id in tempTempA_List:
   tempvar = indigo.variables[temp_id]
   tempAvgA = (tempvar + tempAvgA)
   
tempAvgA = (tempAvgA/8)

for temp_id in tempTempB_List:
   tempvar = indigo.variables[temp_id]
   tempAvgB = (tempvar + tempAvgB)
   
tempAvgB = (tempAvgB/8)

TempAvg = (tempAvgA+tempAvgB)/2


### humid averaging

for humid_id in tempHumidA_List:
   humidvar = indigo.variables[humid_id]
   humidAvgA = (humidvar + humidAvgA)
   
humidAvgA = (humidAvgA/8)

for humid_id in tempHumidB_List:
   humidvar = indigo.variables[humid_id]
   humidAvgB = (humidvar + humidAvgB)
   
humidAvgB = (humidAvgB/8)

HumidAvg = (humidAvgA+humidAvgB)/2
   
   
### set irrFactor

AvgAvgVar = (rnd(((TempAvg / (HumidAvg * HumidDerate)) * 100)) / 100)
indigo.variable.updateValue[1681753265, AvgAvgVar]
#irrFactor" to (round (((TempAvg / (HumidAvg * HumidDerate))) * 100)) / 100


### set max var and banners   

FactorVar = indigo.variables[1681753265] # "irrFactor"   
maxFactorVar = indigo.variables[958042151] # "irrFactorMax"
#indigo.variables[1571233000] # "irrFactorMax_banner"

if indigo.variables.value[1681753265] > indigo.variables.value[958042151]:
   indigo.variable.updateValue(1681753265, maxFactorVar)
   indigo.variable.updateValue(1571233000, "MAX")
   indigo.server.log("Irrigation Factor: " + "Held to maximum preset. Check variables.")
else:
   indigo.variable.updateValue(1571233000, "")
   
FactorVar = indigo.variables[1681753265] # "irrFactor"   

### set average vars   

#indigo.variables[888344166] # "WeatherTempAvg"
#indigo.variables[202189053] # "WeatherHumidAvg"
#indigo.variables[694982593] # "WeatherIndex"

indexAvgVar = ((((TempAvg / HumidAvg) * 0.5) * 100) / 100)

wthrTempAvgvar = indigo.variable.updateValue(888344166, rnd(TempAvg))
wthrHumidAvgvar = indigo.variable.updateValue(202189053, rnd(HumidAvg))
wthrIndexvar = indigo.variable.updateValue(694982593, rnd(indexAvgVar)


### log vars   

#indigo.server.log("Weather Index: " + str(wthrIndexvar))
#indigo.server.log("Irrigation Factor: " + str(FactorVar))

Posted on
Fri Jan 21, 2022 11:49 pm
dtich offline
Posts: 798
Joined: Sep 24, 2005

Re: applescript to python - help pls

And, annoyingly, I don't know how to do this variable math either....

Code: Select all
poolFactortemp = indigo.variables[1681753265] * indigo.variables[1420782175]


indigo.variable.updateValue[677709449, poolFactortemp]



#indigo.variables[1681753265] # "irrFactor"
#indigo.variables[677709449] # "irrFactor_Pool"
#indigo.variables[1420782175] # "irrFactor_Pool_multiplier"



#set value of variable "irrFactor_Pool" to ((value of variable "irrFactor") * (value of variable #"irrFactor_Pool_multiplier"))


Who is online

Users browsing this forum: No registered users and 2 guests