[go: up one dir, main page]

Menu

[r219]: / calise / objects.py  Maximize  Restore  History

Download this file

349 lines (322 with data), 13.6 kB

  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
# Copyright (C) 2011 Nicolo' Barbon
#
# This file is part of Calise.
#
# Calise is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# Calise is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Calise. If not, see <http://www.gnu.org/licenses/>.
import time
import datetime
import logging
from calise.system import computation
from calise.captured import takeScreenshot, takeSomePic
from calise.sun import getSun, get_daytime_mul
from calise.infos import __LowerName__
caliseCompute = computation()
class objects():
def __init__(self, settings):
self.logger = logging.getLogger(".".join([__LowerName__, "objects"]))
self.arguments = settings
self.oldies = []
self.resetComers()
self.wts = None # weather timestamp
def dumpValues(self, allv=False):
if allv:
return self.oldies
else:
return self.oldies[-1]
def resetComers(self):
self.newcomers = {
"amb": None, # ambient brightness
"scr": None, # screen brightness
"pct": None, # (corrected) brightness percentage
"cbs": None, # current backlight step
"sbs": None, # suggested backlight step
"cts": None, # capture timestamp (epoch)
"css": None, # sun state: either dawn, day, sunset or night
"nss": None, # seconds before next sun state
"slp": None, # thread sleeptime
}
# Takes a list with a certain amount of %newcomers% keys and optimize
# resource usage when grabbing every information.
# Returns a dictionary (with %newcomers% keys)
def grab_infos(self, info_list):
if type(info_list) is not list:
info_list = [info_list]
info_dict = {}
if info_list.count("cts"):
self.getCts()
info_dict["cts"] = self.newcomers["cts"]
if (
info_list.count("css") or
info_list.count("nss") or
info_list.count("slp")):
self.executer(False)
if info_list.count("css"):
info_dict["css"] = self.newcomers["css"]
if info_list.count("nss"):
info_dict["nss"] = self.newcomers["nss"]
if info_list.count("nss"):
info_dict["slp"] = self.newcomers["slp"]
if info_list.count("sbs"):
self.getSbs()
for info in info_list:
info_dict[info] = self.newcomers[info]
elif info_list.count("pct"):
self.getPct()
for info in info_list:
info_dict[info] = self.newcomers[info]
else:
for info in info_list:
if info == "cbs":
info_dict[info] = self.getCbs()
if info == "scr":
info_dict[info] = self.getScr()
if info == "amb":
info_dict[info] = self.getAmb()
return info_dict
# obtain timestamp
def getCts(self):
self.newcomers["cts"] = time.time()
return self.newcomers["cts"]
# simple function to obtain ambient brightness (new or existing value)
def getAmb(self):
if not self.newcomers["cts"]:
self.getCts()
camValues = takeSomePic(
self.arguments["capnum"], self.arguments["capint"])
self.newcomers["amb"] = sum(camValues) / float(len(camValues))
return self.newcomers["amb"]
# simple function to obtain screen brightness (new or existing value)
def getScr(self):
if not self.newcomers["cts"]:
self.getCts()
self.newcomers["scr"] = takeScreenshot()
return self.newcomers["scr"]
# obtains brightness percentage value, corrected if needed (by the amount
# of brightness coming from the screen)
def getPct(self):
self.getAmb()
self.getScr()
self.getCbs()
caliseCompute.percentage(
self.newcomers["amb"],
self.arguments["offset"], self.arguments["delta"],
self.newcomers["scr"],
self.adjustScale(self.newcomers["cbs"]))
self.newcomers["pct"] = caliseCompute.pct
return self.newcomers["pct"]
# simple function to obtain current backlight step (new or existing value)
def getCbs(self):
caliseCompute.get_values('step', self.arguments["path"])
self.newcomers["cbs"] = caliseCompute.bkstp
self.arguments["bfile"] = caliseCompute.bfile
return self.newcomers["cbs"]
# obtain suggested backlight step. This function need every value of
# %newcomers% dictionary
def getSbs(self):
steps = self.arguments["steps"]
bkofs = self.arguments["bkofs"]
self.getPct()
stp = int(self.newcomers["pct"] / (100.0 / steps) - .5 + bkofs)
if self.arguments["invert"]:
stp = steps - 1 + bkofs - stp + bkofs
# out-of-bounds control...
if stp > steps - 1 + bkofs:
stp = steps - 1 + bkofs
elif stp < bkofs:
stp = bkofs
self.newcomers["sbs"] = stp
return self.newcomers["sbs"]
# complementary to getPct function
def adjustScale(self, cur):
steps = self.arguments["steps"]
bkofs = self.arguments["bkofs"]
den = 100.00 / steps
if self.arguments["invert"]:
return (steps - 1 - (cur - bkofs)) * (den / 10.0)
else:
return (cur - bkofs) * (den / 10.0)
""" Backlight-step change writer
Checks for read permission and if so writes current backlight step on sys
brightness file (the one selected throug computation)
If increasing is set either to False or True and if previous backlight
step was lower/higher, writeStep will return False (no change)
"""
def writeStep(self, increasing=None, standalone=False):
if standalone:
self.getCts()
self.getSbs()
bfile = self.arguments["bfile"]
if self.arguments["invert"]:
increasing = not increasing
refer = int(self.newcomers["sbs"]) - int(self.newcomers["cbs"])
if ((
refer > 0 and increasing is True) or ( # dawn condition
refer < 0 and increasing is False) or ( # sunset condition
abs(refer) > 1) or ( # room light lit/shut
abs(refer) > 0 and increasing is None)): # normal statement
try:
fp = open(bfile, 'w')
except IOError as err:
import errno
if err.errno == errno.EACCES:
self.logger.error(
"IOError: [Errno %d] Permission denied: '%s'\n"
"Please set write permission for current user\n"
% (err.errno, bfile))
return 2
else:
with fp:
fp.write(str(self.newcomers["sbs"]) + '\n')
self.newcomers["cbs"] = self.newcomers["sbs"]
return 0
else:
return 1
# get "weather" multiplier, updates only once per hour
def getWtr(self, cur=None):
if cur is None:
cur = time.time()
if self.wts is None or cur - self.wts > 3600:
self.wts = time.time()
mul = get_daytime_mul(
self.arguments["latitude"], self.arguments["longitude"])
self.daytime_mul = mul
return 0
return 1
""" daemon "core"
With the help of the getSun function (which use ephem module) in
calise.sun module, discovers current time of the day and sets sleep time
before a new capture and increasing/decreasing writeStep args accordingly
"""
def executer(self, execute=True, wcheck=False, ctime=None):
if not self.newcomers["cts"]:
self.getCts()
if ctime is None:
cur_time = time.time()
else:
cur_time = ctime
sun = getSun(
self.arguments["latitude"], self.arguments["longitude"])
daw = float(sun[0])
sus = float(sun[1])
# more or less the seconds that the sun needs to get from min to max
# backlight step brightness
daw_tw = int(sun[2])
sus_tw = int(sun[3])
# sleeptime between captures
# if ipotetically during daw_tw/sus_tw the backlight goes from max to
# min, then there will be a step change every %x% sec, to be more
# precise I decided to set sleeptime to %x% / 10
# EDIT: machines with more than 10000 backlight steps blowed up with
# previous formulae, percentage will work better there
daw_sl = daw_tw / 100.0
sus_sl = sus_tw / 100.0
# happens on artic regions, where the sun is always above the horizon
if daw is True and sus is False:
if execute:
r = self.writeStep(increasing=None)
self.logger.debug(
"Function '%s' returned %d" % ("writeStep", r))
self.newcomers["css"] = "day"
self.newcomers["nss"] = None
if wcheck:
self.getWtr(cur_time)
else:
self.daytime_mul = 0.6
sleepTime = 5.0 * self.daytime_mul * 60
if sleepTime + time.time() > self.newcomers["nss"]:
sleepTime = self.newcomers["nss"] - time.time()
# happens on artic regions, where the sun never reaches above the
# horizon
elif daw is False and sus is True:
if execute:
r = self.writeStep(increasing=None)
self.logger.debug(
"Function '%s' returned %d" % ("writeStep", r))
self.newcomers["css"] = "night"
self.newcomers["nss"] = None
sleepTime = (
int(datetime.date.today().strftime("%s")) + 86400 - cur_time)
# happens on artic regions, where the sun never reaches 15 degrees
# above the horizon, so, actually, dawn/sunset time equal half each of
# the time the sun spend above the horizon
elif sus == daw + daw_tw:
if cur_time < daw + daw_tw / 2.0:
if execute:
r = self.writeStep(increasing=True)
self.logger.debug(
"Function '%s' returned %d" % ("writeStep", r))
self.newcomers["css"] = "dawn"
else:
if execute:
r = self.writeStep(increasing=False)
self.logger.debug(
"Function '%s' returned %d" % ("writeStep", r))
self.newcomers["css"] = "sunset"
# dawn
elif cur_time > daw and cur_time <= daw + daw_tw:
if execute:
r = self.writeStep(increasing=True)
self.logger.debug(
"Function '%s' returned %d" % ("writeStep", r))
self.newcomers["css"] = "dawn"
self.newcomers["nss"] = daw + daw_tw - cur_time
sleepTime = daw_sl
# sunset
elif cur_time >= sus - sus_tw and cur_time < sus:
if execute:
r = self.writeStep(increasing=False)
self.logger.debug(
"Function '%s' returned %d" % ("writeStep", r))
self.newcomers["css"] = "sunset"
self.newcomers["nss"] = sus - cur_time
sleepTime = sus_sl
# night
elif cur_time > sus or cur_time < daw:
if execute:
r = self.writeStep(increasing=None)
self.logger.debug(
"Function '%s' returned %d" % ("writeStep", r))
# if current time is before midnight, ask for next day dawn
if cur_time > sus:
tmp = getSun(
self.arguments["latitude"], self.arguments["longitude"],
cur_time + 24 * 60 * 60)
daw = float(tmp[0])
self.newcomers["css"] = "night"
self.newcomers["nss"] = daw - cur_time
sleepTime = daw - cur_time
# day
else:
if execute:
r = self.writeStep(increasing=None)
self.logger.debug(
"Function '%s' returned %d" % ("writeStep", r))
self.newcomers["css"] = "day"
self.newcomers["nss"] = sus - sus_tw - cur_time
if wcheck:
self.getWtr(cur_time)
else:
self.daytime_mul = 0.6
sleepTime = 5.0 * self.daytime_mul * 60
if sleepTime > self.newcomers["nss"]:
sleepTime = self.newcomers["nss"]
self.newcomers["slp"] = sleepTime
capture_time = self.arguments["capnum"] * self.arguments["capint"]
if sleepTime < capture_time + 1.0:
return capture_time + 1.0 + cur_time
else:
return sleepTime - capture_time + cur_time
def append_data(self):
obj = self.newcomers
self.oldies.append(obj)