-
Notifications
You must be signed in to change notification settings - Fork 1
/
holidays_server.py
executable file
·413 lines (348 loc) · 13.1 KB
/
holidays_server.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
#!/usr/bin/env python3
import calendar
import click
import dateparser
from datetime import date
from datetime import datetime
from datetime import timedelta
import holidays
import polyinterface
from polyinterface import LOGGER
import time
class Rule(object):
START_TOKEN = 'every'
FROM_TOKEN = 'from'
TO_TOKEN = 'to'
MONTHLY_TOKEN = 'of the month'
def __init__(self, rule='', desc=''):
self.date = None
self.base = datetime.today()
self.rule = rule
self.desc = desc
def parse(self):
self.parseRule(self.rule)
def parseRule(self, ruleStr):
self.date = None
'''
Parses rule string:
every <day of the week> | <date> | <nth> of the month [ from <date> [ to <date> ]]
<absolute date>
'''
if not ruleStr.startswith(Rule.START_TOKEN):
self.date = dateparser.parse(ruleStr,
settings={
'RELATIVE_BASE': self.base,
'STRICT_PARSING': True
})
if self.date is not None:
self.date = self.date.date()
return
ruleStr = ruleStr[len(Rule.START_TOKEN):]
toPos = ruleStr.find(Rule.TO_TOKEN)
if toPos > 0:
toDate = dateparser.parse(ruleStr[toPos + len(Rule.TO_TOKEN):],
settings={
'PREFER_DATES_FROM': 'future',
'RELATIVE_BASE': self.base
}).date()
if self.base.date() > toDate:
return
ruleStr = ruleStr[:toPos]
fromPos = ruleStr.find(Rule.FROM_TOKEN)
if fromPos > 0:
fromDate = dateparser.parse(ruleStr[fromPos +
len(Rule.FROM_TOKEN):],
settings={
'RELATIVE_BASE': self.base
}).date()
if self.base.date() < fromDate:
return
ruleStr = ruleStr[:fromPos]
dayPos = ruleStr.find(Rule.MONTHLY_TOKEN)
if dayPos > 0:
ruleStr = ruleStr[:dayPos]
self.date = dateparser.parse(str(self.base.month) + '/' + ruleStr,
settings={
'RELATIVE_BASE': self.base
}).date()
if self.date < self.base.date():
self.date = dateparser.parse(str(self.base.month + 1) + '/' +
ruleStr,
settings={
'RELATIVE_BASE': self.base
}).date()
else:
future = dateparser.parse(ruleStr,
settings={
'PREFER_DATES_FROM': 'future',
'RELATIVE_BASE': self.base
}).date()
past = dateparser.parse(ruleStr,
settings={
'RELATIVE_BASE': self.base
}).date()
# workaround for day of the week parsting, which is never TODAY
# either last week or next
diff = (future - past).days
if diff == 7:
self.date = future
elif diff == 14:
self.date = future - timedelta(7)
else:
self.date = past
class DateProvider(object):
TODAY = 'today'
TOMORROW = 'tomorrow'
def __init__(self,
country='US',
weekend=['Saturday', 'Sunday'],
include_holidays='',
exclude_holidays=''):
self.dates = {}
self.country = country
self.holidays = holidays.CountryHoliday(country)
self.set_weekend(weekend)
self.set_include(include_holidays)
self.set_exclude(exclude_holidays)
self.custom_rules = []
self.refresh()
def get_holiday_list(self):
self.holidays.get(date.today())
return list(self.holidays.values())
def add_custom_rule(self, rule, desc):
self.custom_rules.append(Rule(rule, desc))
def get_now(self):
return date.today()
def set_weekend(self, weekend):
self.weekend = {}
for day in weekend:
self.weekend[day] = 'weekend'
def set_include(self, list):
self.include = {}
for day in list:
if len(day) > 0:
self.include[day] = True
def set_exclude(self, list):
self.exclude = {}
for day in list:
if len(day) > 0:
self.exclude[day] = True
def refresh(self):
self.holidays = holidays.CountryHoliday(self.country)
now = self.get_now()
self.dates[DateProvider.TODAY] = now
self.dates[DateProvider.TOMORROW] = now + timedelta(1)
for i in range(0, 7):
dt = now + timedelta(i)
self.dates[calendar.day_name[dt.weekday()]] = dt
for rule in self.custom_rules:
rule.parse()
if rule.date is not None:
self.holidays.append({rule.date: rule.desc})
def is_holiday(self, key):
result = self.holidays.get(self.dates[key])
if (result is not None
and (len(self.include) == 0 or result in self.include)
and result not in self.exclude):
LOGGER.debug('Holiday found for Key %s, Date %s', key,
self.dates[key])
return True
return False
def is_weekend(self, key):
result = self.weekend.get(calendar.day_name[self.dates[key].weekday()])
if result is not None:
LOGGER.debug('Weekend found for Key %s, Date %s', key,
self.dates[key])
return True
return False
def is_day_off(self, key):
return self.is_weekend(key) or self.is_holiday(key)
class Controller(polyinterface.Controller):
def __init__(self, polyglot):
super(Controller, self).__init__(polyglot)
self.dateProvider = DateProvider('US')
self.currentDate = None
self.poly.onConfig(self.process_config)
def start(self):
params = [{
'name': 'country',
'title': 'Country',
'desc': 'Country to get holidays for',
'defaultValue': 'US',
'isRequired': True
}, {
'name': 'includeHolidays',
'title': 'Include Holidays',
'desc': 'List of holidays to include (leave empty to include all)',
'isList': True,
'isRequired': True
}, {
'name': 'excludeHolidays',
'title': 'Exclude Holidays',
'desc': 'List of holidays to exclude',
'isList': True,
'isRequired': True
}, {
'name': 'weekend',
'title': 'Weekend',
'desc': 'Normal weekend (days off) days',
'defaultValue': ['Saturday', 'Sunday'],
'isList': True,
'isRequired': True
}, {
'name':
'rules',
'title':
'Rules',
'desc':
'Rules defining days off',
'isList':
True,
'params': [
{
'name': 'description',
'title': 'Description',
'isRequired': True
},
{
'name': 'dateStr',
'title': 'Date String',
'isRequired': True
},
]
}]
self.poly.save_typed_params(params)
self.addHolidaysList()
LOGGER.info('Started HolidayServer')
self.discover()
self.setDriver('ST', 1)
def addHolidaysList(self):
data = '<h3>Known Holidays</h3><ul>'
for holiday in self.dateProvider.get_holiday_list():
data += '<li>' + holiday + '</li>'
data += '</ul>'
self.poly.add_custom_config_docs(data, True)
def longPoll(self):
if self.currentDate != date.today():
LOGGER.debug('New date detected. Recalculating nodes')
self.refresh()
self.currentDate = date.today()
def refresh(self):
self.setDriver('ST', 1)
self.dateProvider.refresh()
for node in self.nodes.values():
if node != self:
node.refresh()
def process_config(self, config):
typedConfig = config.get('typedCustomData')
if not typedConfig:
return
if self.dateProvider.country != typedConfig['country']:
self.dateProvider = DateProvider(typedConfig['country'])
self.addHolidaysList()
self.dateProvider.set_include(typedConfig['includeHolidays'])
self.dateProvider.set_exclude(typedConfig['excludeHolidays'])
self.dateProvider.set_weekend(typedConfig['weekend'])
self.dateProvider.custom_rules = []
rules = typedConfig.get('rules')
if rules:
for rule in rules:
self.dateProvider.add_custom_rule(rule['dateStr'],
rule['description'])
self.refresh()
def discover(self, *args, **kwargs):
self.customDates = self.polyConfig.get('customData',
{}).get('customDates', {})
self.currentDate = date.today()
self.dateProvider.refresh()
time.sleep(1)
for key in self.dateProvider.dates.keys():
customDate = self.customDates.get(str(
self.dateProvider.dates[key]))
self.addNode(
DayNode(self, self.address, key.lower(), key + ' Day Node',
key, self.dateProvider, self, customDate is True,
customDate is False))
def set_on(self, date):
self.customDates[str(date)] = True
self.saveCustomData({'customDates': self.customDates})
def set_off(self, date):
if str(date) in self.customDates:
self.customDates.pop(str(date))
self.saveCustomData({'customDates': self.customDates})
def set_force_off(self, date):
self.customDates[str(date)] = False
self.saveCustomData({'customDates': self.customDates})
id = 'controller'
commands = {'DISCOVER': discover}
drivers = [{'driver': 'ST', 'value': 0, 'uom': 2}]
class DayNode(polyinterface.Node):
def __init__(self, controllerAddress, primary, address, name, key,
dateProvider, controller, is_day_off, is_force_off):
super(DayNode, self).__init__(controllerAddress, primary, address,
name)
self.key = key
self.dateProvider = dateProvider
self.controller = controller
self.is_day_off = False if is_day_off is None else is_day_off
self.is_force_off = False if is_force_off is None else is_force_off
def start(self):
self.refresh()
def refresh(self):
date = self.dateProvider.dates[self.key]
self.setDriver('GV0', date.month)
self.setDriver('GV1', date.day)
self.setDriver('GV2', date.year)
self.setDriver('ST', self.get_state())
def set_on(self, command):
self.is_day_off = True
self.is_force_off = False
self.setDriver('ST', 1)
time.sleep(1)
self.controller.set_on(self.dateProvider.dates[self.key])
def set_off(self, command):
self.is_day_off = False
self.is_force_off = False
self.setDriver('ST', self.get_state())
time.sleep(1)
self.controller.set_off(self.dateProvider.dates[self.key])
def set_force_off(self, command):
LOGGER.debug("Setting %s to force off", self.key)
self.is_day_off = False
self.is_force_off = True
self.setDriver('ST', self.get_state())
time.sleep(1)
self.controller.set_force_off(self.dateProvider.dates[self.key])
def query(self):
self.reportDrivers()
def get_state(self):
return 1 if not self.is_force_off and (
self.is_day_off or self.dateProvider.is_day_off(self.key)) else 0
drivers = [{
'driver': 'ST',
'value': 0,
'uom': 2
}, {
'driver': 'GV0',
'value': 0,
'uom': 47
}, {
'driver': 'GV1',
'value': 0,
'uom': 9
}, {
'driver': 'GV2',
'value': 0,
'uom': 77
}]
id = 'daynode'
commands = {'DON': set_on, 'DOF': set_off, 'FOFF': set_force_off}
@click.command()
def holidays_server():
polyglot = polyinterface.Interface('HolidayServer')
polyglot.start()
controller = Controller(polyglot)
controller.name = 'Holiday Controller'
controller.runForever()
if __name__ == '__main__':
holidays_server()