forked from acockburn/occusim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
occusim.py
executable file
·267 lines (230 loc) · 11 KB
/
occusim.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
import appdaemon.plugins.hass.hassapi as hass
import datetime
import re
import random
#
# App to simulate occupancy in an empty house
#
__version__ = "1.1.5"
class OccuSim(hass.Hass):
def initialize(self):
if "test" in self.args and self.args["test"] == "1":
self.test = True
else:
self.test = False
self.timers = ()
# Set a timer to recreate the day's events at 3am
if "reset_time" in self.args:
time = self.parse_time(self.args["reset_time"])
else:
time = datetime.time(3, 0, 0)
self.run_daily(self.create_events, time)
# Create today's random events
self.create_events({})
def create_events(self, kwargs):
# self.log_notify("Running Create Events")
events = {}
steps = ()
randoms = ()
for arg in self.args:
m = re.search("step_(.+)_name", arg)
if m:
steps = steps + (m.group(1),)
m = re.search("random_(.+)_name", arg)
if m:
randoms = randoms + (m.group(1),)
# First pick up absolute events
for step in steps:
event = None
step = "step_" + step + "_"
if (step + "start") in self.args:
stepname = self.args[step + "name"]
cbargs = {}
cbargs["step"] = stepname
if (step + "days") in self.args:
cbargs["days"] = self.args[step + "days"]
span = 0
for arg in self.args:
if re.match(step + "on", arg) or re.match(step + "off", arg):
cbargs[arg] = self.args[arg]
start_p = self.args[step + "start"]
start = self.parse_time(start_p)
end_p = self.args.get(step + "end")
if end_p != None:
end = self.parse_time(end_p)
start_ts = datetime.datetime.combine(self.date(), start).timestamp()
end_ts = datetime.datetime.combine(self.date(), end).timestamp()
span = int(end_ts - start_ts)
if span > 0:
event = datetime.datetime.combine(self.date(), start) + datetime.timedelta(
seconds=random.randrange(span))
elif span == 0:
event = datetime.datetime.combine(self.date(), start)
elif span < 0:
self.log("step_{} end < start - ignoring end".format(i))
event = datetime.datetime.combine(self.date(), start)
events[stepname] = {}
events[stepname]["event"] = event
events[stepname]["args"] = cbargs.copy()
# Now relative events - multiple passes required as the order could be arbitrary
changes = 1
while changes > 0:
changes = 0
for step in steps:
event = None
step = "step_" + step + "_"
if (step + "relative") in self.args:
stepname = self.args[step + "name"]
if stepname not in events:
cbargs = {}
cbargs["step"] = stepname
if (step + "days") in self.args:
cbargs["days"] = self.args[step + "days"]
span = 0
for arg in self.args:
if re.match(step + "on", arg) or re.match(step + "off", arg):
cbargs[arg] = self.args[arg]
steprelative = self.args[step + "relative"]
if steprelative in events:
start_offset_p = self.args[step + "start_offset"]
start_offset = self.parse_time(start_offset_p)
start = events[steprelative]["event"] + datetime.timedelta(hours=start_offset.hour,
minutes=start_offset.minute,
seconds=start_offset.second)
end_offset_p = self.args.get(step + "end_offset")
if end_offset_p != None:
end_offset = self.parse_time(end_offset_p)
end = events[steprelative]["event"] + datetime.timedelta(hours=end_offset.hour,
minutes=end_offset.minute,
seconds=end_offset.second)
span = int(end.timestamp() - start.timestamp())
if span > 0:
event = start + datetime.timedelta(seconds=random.randrange(span))
elif span == 0:
event = start
elif span < 0:
self.log("step_{} end < start - ignoring end".format(i))
event = start
events[stepname] = {}
events[stepname]["event"] = event
events[stepname]["args"] = cbargs.copy()
changes += 1
list = ""
for step in steps:
stepname = self.args["step_" + step + "_name"]
if stepname not in events:
list += stepname + " "
if list != "":
self.log("unable to schedule the following steps due to missing prereq step: {}".format(list), "WARNING")
# Schedule random events
for step in randoms:
event = None
step = "random_" + step + "_"
stepname = self.args[step + "name"]
cbonargs = {}
cboffargs = {}
if (step + "days") in self.args:
cbonargs["days"] = self.args[step + "days"]
cboffargs["days"] = self.args[step + "days"]
span = 0
for arg in self.args:
if re.match(step + "(on|tgl)", arg):
cbonargs[arg] = self.args[arg]
if re.match(step + "(off|tgl)", arg):
cboffargs[arg] = self.args[arg]
startstep = self.args[step + "start"]
endstep = self.args[step + "end"]
starttime = events[startstep]["event"]
endtime = events[endstep]["event"]
tspan = int(endtime.timestamp() - starttime.timestamp())
mind_p = self.args[step + "minduration"]
mind = self.parse_time(mind_p)
mindts = datetime.datetime.combine(self.date(), mind).timestamp()
mindtsdur = mindts - datetime.datetime.combine(self.date(), mind).replace(hour=0, minute=0, second=0).timestamp()
mins = datetime.timedelta(seconds=mindtsdur)
# self.log("minsdur {} {}".format(mindtsdur, mindts))
maxd_p = self.args[step + "maxduration"]
maxd = self.parse_time(maxd_p)
maxdts = datetime.datetime.combine(self.date(), maxd).timestamp()
dspan = int(maxdts - mindts)
# self.log("dspan {} ".format(dspan))
delta = datetime.timedelta(seconds=random.randrange(dspan))
next = starttime + delta + mins
# self.log("next {} {} ".format(delta, next))
i = 1
while next < endtime:
eventname = stepname + "_" + str(i)
events[eventname] = {}
events[eventname]["event"] = next
if (i % 2) == 0: # even
cboffargs["step"] = eventname
events[eventname]["args"] = cboffargs.copy()
else: # odd
cbonargs["step"] = eventname
events[eventname]["args"] = cbonargs.copy()
delta = datetime.timedelta(seconds=random.randrange(dspan))
next = next + delta + mins
i += 1
# self.log("next {} {} ".format(delta, next))
# Take all the events we found and schedule them
for event in sorted(events.keys(), key=lambda event: events[event]["event"]):
stepname = events[event]["args"]["step"]
start = events[event]["event"]
args = events[event]["args"]
if start > self.datetime():
# schedule it
if "enable" in self.args:
args["constrain_input_boolean"] = self.args["enable"]
if "select" in self.args:
args["constrain_input_select"] = self.args["select"]
if "days" in events[event]["args"]:
args["constrain_days"] = events[event]["args"]["days"]
self.run_at(self.execute_step, start, **args)
if "dump_times" in self.args:
self.log("{}: @ {}".format(stepname, start))
else:
self.log("{} in the past - ignoring".format(stepname))
def execute_step(self, kwargs):
# Set the house up for the specific step
self.step = kwargs["step"]
self.log_notify("Executing step {}".format(self.step))
for arg in kwargs:
if re.match(".+_on_.+", arg):
self.activate(kwargs[arg], "on")
elif re.match(".+_off_.+", arg):
self.activate(kwargs[arg], "off")
elif re.match(".+_tgl_.+", arg):
self.activate(kwargs[arg], "toggle")
def activate(self, entity, action):
type = action
m = re.match('event\.(.+)\,(.+)', entity)
if m:
if not self.test: self.fire_event(m.group(1), **{m.group(2): self.step})
if "log" in self.args:
self.log("fired event {} with {} = {}".format(m.group(1), m.group(2), self.step))
return
m = re.match('input_select\.', entity)
if m:
if not self.test: self.select_option(entity, self.step)
self.log("set {} to value {}".format(entity, self.step))
return
if action == "on":
if not self.test: self.turn_on(entity)
else:
if re.match("scene\.", entity) or re.match("script\.", entity):
type = "on"
if not self.test: self.turn_on(entity)
else:
if not self.test:
if type == "off":
self.turn_off(entity)
else:
self.toggle(entity)
if "log" in self.args:
self.log("turned {} {}".format(type, entity))
def log_notify(self, message):
if "log_msg" in self.args:
self.log(message)
if "notify" in self.args:
# self.notify(message)
self.set_state("sensor.notify_message", state=message)