How to store variables in an HA automation? - automation

Since I’m new to HA and also Jinja2 my thoughts on the following issue are based on how I would realise it with PHP.
I’d like to built an automation that controls an rgb bulb that reminds me on an open window after several timers have passed. Due to the fact that I don’t wanna set specific values for rgb and brightness these attributes are variables.
So the logic behind my intended automation should be:
retrieve current state and attributes of the lamp and store these information in an array to reset the lamp later on:
{{states('light.bulb‘)}}
{{state_attr('light.bulb‘,’brightness')}}
{{state_attr('light.lbulb‘,’rgb_color')}}
$initial_state = array()
$initial_state['state_on_off'] = {{states('light.bulb‘)}}
$initial_state['rgb'] = {{state_attr('light.lbulb‘,’rgb_color')}}
$initial_state['brightness'] = {{states('light.bulb‘)}}
some automation stuff like:
## trigger ###############################
trigger:
- platform: state
entity_id:
- binary_sensor.lumi_lumi_sensor_magnet_aq2_opening_2
to: "on"
for:
hours: 0
minutes: 10
seconds: 0
id: BA
#######################################
## actions ###############################
action:
- if:
- condition: trigger
id: BA
then:
- service: light.turn_on
data:
rgb_color:
## set fixed values
- 67
- 180
- 252
brightness_pct: 20
target:
entity_id: light.bulb
alias: 1st stage
…
some more actions and now set back to initial attributes
…
action:
- if:
- condition: trigger
id: BA
then:
- service:
## depending from the initial state #############
if ($initial_state['state_on_off'] == ’on’){
light.turn_on
} else {
light.turn_off
}
#######################################
data:
rgb_color:
## depending from the initial color #############
$initial_state['rgb']
#######################################
brightness_pct:
## depending from the initial color #############
$initial_state['brightness']
#######################################
target:
entity_id: light.bulb
alias: 3rd stage
Thanks in advance.

Related

Bulk delete of data transfers in BigQuery

over time, many different people have created a test transfer in our demo project and never cleaned it up. I would love to bulk delete all transfers. Does anyone know of a way to do this?
I've built something similar on Cloud Workflows.
Essentially you need a Workflow that will do the steps for you start with BigQuery Data Transfer API and issue a few commands:
get a list of transfer configs
loop through them
issue a delete API call for them
https://cloud.google.com/bigquery-transfer/docs/reference/datatransfer/rest
My code was to cleanup Cloud Workflows (you need to adapt a little bit this one with the Transfer Service API calls)
#cloud workflow to cleanup
main:
steps:
- initialize:
assign:
- project: "marton-data"
- location: "us-central1"
- getList:
call: WorkflowsList
args:
project: ${project}
location: ${location}
result: items
- loopItems:
call: WorkflowListLoopItems
args:
items: ${items}
result: res
- final:
return: ${res}
WorkflowsList:
params: [project,location]
steps:
- list:
call: googleapis.workflows.v1.projects.locations.workflows.list
args:
parent: ${"projects/"+project+"/locations/"+location}
pageSize: 100
result: listResult
- documentFound:
return: ${listResult.workflows}
WorkflowDelete:
params: [name]
steps:
- delete:
call: googleapis.workflows.v1.projects.locations.workflows.delete
args:
name: ${name}
result: deleteResult
- logStep:
call: sys.log
args:
text: ${"Calling "+name+" \r\n Results returned "+json.encode_to_string(deleteResult)}
- deleteDone:
return: ${deleteResult}
WorkflowListLoopItems:
params: [items]
steps:
- init:
assign:
- i: 0
- result: ""
- check_condition:
switch:
- condition: ${items[i].name=="projects/marton-data/locations/us-central1/workflows/workflow_cleanup"}
next: assign_loop
- condition: ${len(items) > i}
next: iterate
next: exit_loop
- iterate:
steps:
- process_item:
call: WorkflowDelete
args:
name: ${items[i].name}
result: result
- assign_loop:
assign:
- i: ${i+1}
next: check_condition
- exit_loop:
return: ${result}
logMessage:
params: [collection]
steps:
- log:
call: http.post
args:
url: https://logging.googleapis.com/v2/entries:write
auth:
type: OAuth2
body:
entries:
- logName: ${"projects/" + sys.get_env("GOOGLE_CLOUD_PROJECT_ID") + "/logs/workflow_logger"}
resource:
type: "audited_resource"
labels: {}
jsonPayload: ${collection}

Rasa Custom Actions Not working - Google Colab

I am trying to implement RASA Chatbot on Colab and finding hard to customize Actions.. Rest all works fine, except the actions.. I feel that my chatbox is not entering my actions.. Can anyone please guide me..
nlu_md = """
## intent:greet
- Hello
- hello
- good morning
## intent:justbook
- table for 1
- make reservations for me
- make reservations for 1 person
"""
%store nlu_md > nlu.md
stories_md = """
## Story 1
* greet
- action_print
"""
%store stories_md > stories.md
domain_yml = """
%YAML 1.1
---
actions:
- utter_booking_confirmation
- utter_greeting
- utter_thankyou
- __main__.Printer
- action_print
entities:
- time
- date
- number_of_people
intents:
- time
- when
- book
- greet
- justbook
templates:
utter_greeting:
- text: Welcome to the restaurant ! How can I help you ?
utter_thankyou:
- text: Thank You for using our services ! See you again soon !
utter_confirm:
- text: Your booking is confirmed for {number_of_people} on {date} at {time}. Thank You. See you soon
"""
%store domain_yml > domain.yml
Actions
from rasa_core_sdk import Tracker
from rasa_core_sdk import Action
from rasa_core_sdk.events import SlotSet
from rasa_core_sdk.executor import CollectingDispatcher
from rasa_core.actions import Action
class Printer(Action):
def name(self):
return "action_print"
def run(self, dispatcher, tracker, domain):
no_of_people=tracker.slots['number_of_people']
time=tracker.slots['time']
date=tracker.slots['date']
print('ENTERED PRINTER')
dispatcher.utter_message('hi i am in Printer')
#return ''
Chatbox!
from rasa_core.agent import Agent
from rasa_core.utils import EndpointConfig
from rasa_core.interpreter import RasaNLUInterpreter
from rasa_core.utils import EndpointConfig
agent = Agent.load('models/dialogue',interpreter=RasaNLUInterpreter('/content/drive/My Drive/restaurant bot/models/nlu/default/restaurantbot'),
action_endpoint=EndpointConfig(url="http://127.0.0.1:5055/webhook"))
print("Bot is ready to talk! Start conversation with 'hi'")
while True:
st = input()
if st == 'stop':
break
responses = agent.handle_text(st)
for response in responses:
print(response["text"])
Expected Output
I am expecting output : Entered Printer HI I am in Printer.
Output I get I dont get the expected output, I just get the text box for input..

Any example to have a java class instance to call once and use in all scenarios in karate with different feature files

I have been using DBUtils class from karate demo, i knew this class was nothing to deal with karate. I have a concern like an example which was given has DBUtlis class is called in background for each and every scenario and it should be mentioned in all featurefiles Background:.
Anything like we configure once and use that DB instance variable in all scenarios?? If yes examples please.
Update after below comment by peter:
config:
Main Feature File:
Reusing DB instance in another feature file
Please confirm whether this is right approach or not?
Dry Run for a String:
var result = karate.callSingle('classpath:featureFiles/dbBackground.feature', config);
config.PersonName = result.name;
Main Feature:
Feature: DB Background
Background:
* def name = "Sandeep";
Other feature:
Feature: Get Account Details
Background:
* def actualname = PersonName;
#golden
Scenario: user 1 details
* def expectedFormat = read('../requestFiles/format.json')
Given url 'https://reqres.in/api/users'
And params ({id: '1'})
When method Get
Then match response.data.email == "george.bluth#reqres.in"
Then print '###################################name is: ', actualname
Then print '###################################name is: ', PersonName
Console result seeing null:
Updated Dry run 2:
Feature: DB Background
Background:
* def name = "Sandeep";
#golden
Scenario: user sample details
* def expectedFormat = read('../requestFiles/format.json')
Given url 'https://reqres.in/api/users'
And params ({id: '1'})
When method Get
Then match response.data.email == "george.bluth#reqres.in"
output:
19:31:33.416 [ForkJoinPool-1-worker-0] DEBUG com.jayway.jsonpath.internal.path.CompiledPath - Evaluating path: $['data']['email']
19:31:33.416 [ForkJoinPool-1-worker-0] INFO com.intuit.karate - [print] ###################################name is: Sandeep
19:31:33.432 [ForkJoinPool-1-worker-0] INFO com.intuit.karate - [print] ###################################name is: Sandeep
Yes you can initialize it in karate-config.js and then it will be a global variable.
Also look at karate.callSingle(): https://github.com/intuit/karate#hooks

How to create multiple instances from a template map in groovy

For an internal status logging in my jenkins pipeline I have created a "template map which I want do use in multiple stages which are running independently in parallel
def status= [
a : '',
b: [
b1: '',
b2: '',
b3: ''
],
c: [
c1: '',
c2 : ''
]
]
this status template I want to pass to multiple parallel running functions/executors. Inside the parallel branches I want to modify the status independently. See the following minimal example
def status= [
a : '',
b: [
b1: '',
b2: '',
b3: ''
],
c: [
c1: '',
c2 : ''
]
]
def label1 = "windows"
def label2 = ''
parallel firstBranch: {
run_node(label1, status)
}, secondBranch: {
run_node(label2, status)
},
failFast: true|false
def run_node (label, status){
node(label) {
status.b.b1 = env.NODE_NAME +"_"+ env.EXECUTOR_NUMBER
sleep(1)
echo "env.NODE_NAME_env.EXECUTOR_NUMBER: ${status.b.b1}"
// expected: env.NODE_NAME_env.EXECUTOR_NUMBER
this.a_function(status)
echo "env.NODE_NAME_env.EXECUTOR_NUMBER: ${status.b.b1}"
// expected(still): env.NODE_NAME_env.EXECUTOR_NUMBER (off current node)
// is: env.NODE_NAME_env.EXECUTOR_NUMBERmore Info AND probably from the wrong node
}
}
def a_function(status){
status.b.b1 += "more Info"
echo "env.NODE_NAME_env.EXECUTOR_NUMBERmore Info: ${status.b.b1}"
// expected: env.NODE_NAME_env.EXECUTOR_NUMBERmore Info
sleep(0.5)
echo "env.NODE_NAME_env.EXECUTOR_NUMBERmore Info: ${status.b.b1}"
// expected: env.NODE_NAME_env.EXECUTOR_NUMBERmore Info
}
Which results in
[firstBranch] env.NODE_NAME_env.EXECUTOR_NUMBER:
LR-Z4933-39110bdb_0
[firstBranch] env.NODE_NAME_env.EXECUTOR_NUMBERmore Info:
LR-Z4933-39110bdb_0more Info
[firstBranch] env.NODE_NAME_env.EXECUTOR_NUMBER>more Info:
LR-Z4933-39110bdb_0more Info
[firstBranch] env.NODE_NAME_env.EXECUTOR_NUMBER:
LR-Z4933-39110bdb_0more Info
[secondBranch] env.NODE_NAME_env.EXECUTOR_NUMBER:
LR-Z4933-39110bdb_0more Info
[secondBranch] env.NODE_NAME_env.EXECUTOR_NUMBERmore Info:
LR-Z4933-39110bdb_0more Infomore Info
[secondBranch] env.NODE_NAME_env.EXECUTOR_NUMBERmore Info:
LR-Z4933-39110bdb_0more Infomore Info
[secondBranch] env.NODE_NAME_env.EXECUTOR_NUMBER:
LR-Z4933-39110bdb_0more Infomore Info
Note that in the status in the first branch is overwritten by the second branch and the other way around.
How to realize independent status variables when passing thm as a parameter to functions
You could define the template map. When you need multiple instances of the same which you may want to modify differently per instance by using cloned template map.
Here is short code snippet to show the example.
def template = [a: '', b: '']
def instancea = template.clone()
def instanceb = template.clone()
def instancec = template.clone()
instancea.a = 'testa'
instanceb.a = 'testb'
instancec.a = 'testc'
println instancea
println instanceb
println instancec
Of course, you can include bigger map, the above is only for demonstration.
You are passing status by reference to the function. But even if you do a status.clone(), I suspect this isn't a deep copy of status. status.b probably still points to the same reference. You need to make a deep copy of status and send that deep copy to the function.
I'm not sure a deep copy of a framework map is the right way to do this. You could just send an empty map [:] and let the called functions add the pieces to the map that they need. If you really need to pre-define the content of the map, then I think you should add a class and create new objects from that class.

Key Releases Psychopy

I'm fairly new to psychopy but I'm having a lot of trouble recording keyboard events so far. The keyboard demo works so I know it is possible, but when I implement the code in my own program it doesn't record any keyboard activity at all. Right now my program is super simple as I'm just trying to get the hang of it. I have a picture and want to record the duration of keypresses during the time the picture is on screen. I have a couple print statements as sanity checks and when I run it (and am using the keyboard) it doesn't print anything. Here's an outline of my code:
from psychopy.iohub import launchHubServer, EventConstants
io = launchHubServer()
keyboard = io.devices.keyboard
keyboard.reporting = True
#-------Start Routine "trial"-------
continueRoutine = True
io.clearEvents('all')
duration_lst=[]
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *image* updates
if t >= 0.0 and image.status == NOT_STARTED:
# keep track of start time/frame for later
image.tStart = t # underestimates by a little under one frame
image.frameNStart = frameN # exact frame index
image.setAutoDraw(True)
if image.status == STARTED and t >= (0.0 + (5.0- win.monitorFramePeriod*0.75)): #most of one frame period left
image.setAutoDraw(False)
# *ISI* period
if t >= 0.0 and ISI.status == NOT_STARTED:
# keep track of start time/frame for later
ISI.tStart = t # underestimates by a little under one frame
ISI.frameNStart = frameN # exact frame index
ISI.start(0.5)
elif ISI.status == STARTED: #one frame should pass before updating params and completing
ISI.complete() #finish the static period
# get keyboard events
for event in keyboard.getEvents():
print event
if event.type == EventConstants.KEYBOARD_CHAR:
key_press_duration=event.duration
duration_lst.append(key_press_duration)
print duration_lst
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
I tried stripping off all unnecessary stuff here (variables, window, stimuli etc.) and uses keyboard.getReleases() so it boils down to this:
from psychopy import iohub
io = iohub.launchHubServer()
keyboard = io.devices.keyboard
print 'press something now!'
while True:
# get keyboard releases
for event in keyboard.getReleases():
print 'Released!'
This should print all info about each key release in the console. It works for me, at least. If it also works for you, the problem is probably related to something else in your script.