historygenerator.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. #
  2. # Copyright (c) 2013-2016 Nick Dajda <nick.dajda@gmail.com>
  3. #
  4. # Distributed under the terms of the GNU GENERAL PUBLIC LICENSE
  5. #
  6. """Extends the Cheetah generator search list to add html historic data tables in a nice colour scheme.
  7. Tested on Weewx release 3.0.1.
  8. Works with all databases.
  9. Observes the units of measure and display formats specified in skin.conf.
  10. WILL NOT WORK with Weewx prior to release 3.0.
  11. -- Use this version for 2.4 - 2.7: https://github.com/brewster76/fuzzy-archer/releases/tag/v2.0
  12. To use it, add this generator to search_list_extensions in skin.conf:
  13. [CheetahGenerator]
  14. search_list_extensions = user.historygenerator.MyXSearch
  15. 1) The $alltime tag:
  16. Allows tags such as $alltime.outTemp.max for the all-time max
  17. temperature, or $seven_day.rain.sum for the total rainfall in the last
  18. seven days.
  19. 2) Nice colourful tables summarising history data by month and year:
  20. Adding the section below to your skins.conf file will create these new tags:
  21. $min_temp_table
  22. $max_temp_table
  23. $avg_temp_table
  24. $rain_table
  25. ############################################################################################
  26. #
  27. # HTML month/year colour coded summary table generator
  28. #
  29. [HistoryReport]
  30. # minvalues, maxvalues and colours should contain the same number of elements.
  31. #
  32. # For example, the [min_temp] example below, if the minimum temperature measured in
  33. # a month is between -50 and -10 (degC) then the cell will be shaded in html colour code #0029E5.
  34. #
  35. # Default is temperature scale
  36. minvalues = -50, -10, -5, 0, 5, 10, 15, 20, 25, 30, 35
  37. maxvalues = -10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 60
  38. colours = "#0029E5", "#0186E7", "#02E3EA", "#04EC97", "#05EF3D2, "#2BF207", "#8AF408", "#E9F70A", "#F9A90B", "#FC4D0D", "#FF0F2D"
  39. monthnames = Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
  40. # The Raspberry Pi typically takes 15+ seconds to calculate all the summaries with a few years of weather date.
  41. # refresh_interval is how often in minutes the tables are calculated.
  42. refresh_interval = 60
  43. [[min_temp]] # Create a new Cheetah tag which will have a _table suffix: $min_temp_table
  44. obs_type = outTemp # obs_type can be any weewx observation, e.g. outTemp, barometer, wind, ...
  45. aggregate_type = min # Any of these: 'sum', 'count', 'avg', 'max', 'min'
  46. [[max_temp]]
  47. obs_type = outTemp
  48. aggregate_type = max
  49. [[avg_temp]]
  50. obs_type = outTemp
  51. aggregate_type = avg
  52. [[rain]]
  53. obs_type = rain
  54. aggregate_type = sum
  55. # Override default temperature colour scheme with rain specific scale
  56. minvalues = 0, 25, 50, 75, 100, 150
  57. maxvalues = 25, 50, 75, 100, 150, 1000
  58. colours = "#E0F8E0", "#A9F5A9", "#58FA58", "#2EFE2E", "#01DF01", "#01DF01"
  59. """
  60. from datetime import datetime
  61. import time
  62. import syslog
  63. import os.path
  64. from weewx.cheetahgenerator import SearchList
  65. from weewx.tags import TimespanBinder
  66. import weeutil.weeutil
  67. class MyXSearch(SearchList):
  68. def __init__(self, generator):
  69. SearchList.__init__(self, generator)
  70. self.table_dict = generator.skin_dict['HistoryReport']
  71. # Calculate the tables once every refresh_interval mins
  72. self.refresh_interval = int(self.table_dict.get('refresh_interval', 5))
  73. self.cache_time = 0
  74. self.search_list_extension = {}
  75. # Make bootstrap specific labels in config file available to
  76. if 'BootstrapLabels' in generator.skin_dict:
  77. self.search_list_extension['BootstrapLabels'] = generator.skin_dict['BootstrapLabels']
  78. else:
  79. syslog.syslog(syslog.LOG_DEBUG, "%s: No bootstrap specific labels found" % os.path.basename(__file__))
  80. # Make observation labels available to templates
  81. if 'Labels' in generator.skin_dict:
  82. self.search_list_extension['Labels'] = generator.skin_dict['Labels']
  83. else:
  84. syslog.syslog(syslog.LOG_DEBUG, "%s: No observation labels found" % os.path.basename(__file__))
  85. def get_extension_list(self, valid_timespan, db_lookup):
  86. """For weewx V3.x extensions. Should return a list
  87. of objects whose attributes or keys define the extension.
  88. valid_timespan: An instance of weeutil.weeutil.TimeSpan. This will hold the
  89. start and stop times of the domain of valid times.
  90. db_lookup: A function with call signature db_lookup(data_binding), which
  91. returns a database manager and where data_binding is an optional binding
  92. name. If not given, then a default binding will be used.
  93. """
  94. # Time to recalculate?
  95. if (time.time() - (self.refresh_interval * 60)) > self.cache_time:
  96. self.cache_time = time.time()
  97. #
  98. # The all time statistics
  99. #
  100. # If this generator has been called in the [SummaryByMonth] or [SummaryByYear]
  101. # section in skin.conf then valid_timespan won't contain enough history data for
  102. # the colourful summary tables.
  103. alltime_timespan = weeutil.weeutil.TimeSpan(db_lookup().first_timestamp, db_lookup().last_timestamp)
  104. # First, get a TimeSpanStats object for all time. This one is easy
  105. # because the object valid_timespan already holds all valid times to be
  106. # used in the report.
  107. all_stats = TimespanBinder(alltime_timespan, db_lookup, formatter=self.generator.formatter,
  108. converter=self.generator.converter)
  109. # Now create a small dictionary with keys 'alltime' and 'seven_day':
  110. self.search_list_extension['alltime'] = all_stats
  111. #
  112. # The html history tables
  113. #
  114. t1 = time.time()
  115. ngen = 0
  116. for table in self.table_dict.sections:
  117. noaa = True if table == 'NOAA' else False
  118. table_options = weeutil.weeutil.accumulateLeaves(self.table_dict[table])
  119. # Show all time unless starting date specified
  120. startdate = table_options.get('startdate', None)
  121. if startdate is not None:
  122. table_timespan = weeutil.weeutil.TimeSpan(int(startdate), db_lookup().last_timestamp)
  123. table_stats = TimespanBinder(table_timespan, db_lookup, formatter=self.generator.formatter,
  124. converter=self.generator.converter)
  125. else:
  126. table_stats = all_stats
  127. table_name = table + '_table'
  128. self.search_list_extension[table_name] = self._statsHTMLTable(table_options, table_stats, table_name,
  129. NOAA=noaa)
  130. ngen += 1
  131. t2 = time.time()
  132. syslog.syslog(syslog.LOG_INFO, "%s: Generated %d tables in %.2f seconds" %
  133. (os.path.basename(__file__), ngen, t2 - t1))
  134. return [self.search_list_extension]
  135. def _statsHTMLTable(self, table_options, table_stats, table_name, NOAA=False):
  136. """
  137. table_options: Dictionary containing skin.conf options for particluar table
  138. all_stats: Link to all_stats TimespanBinder
  139. """
  140. bgColours = zip(table_options['minvalues'], table_options['maxvalues'], table_options['colours'])
  141. if NOAA is True:
  142. unit_formatted = ""
  143. else:
  144. obs_type = table_options['obs_type']
  145. aggregate_type = table_options['aggregate_type']
  146. converter = table_stats.converter
  147. # obs_type
  148. readingBinder = getattr(table_stats, obs_type)
  149. # Some aggregate come with an argument
  150. if aggregate_type in ['max_ge', 'max_le', 'min_le', 'sum_ge']:
  151. try:
  152. threshold_value = float(table_options['aggregate_threshold'][0])
  153. except KeyError:
  154. syslog.syslog(syslog.LOG_INFO, "%s: Problem with aggregate_threshold. Should be in the format: [value], [units]" %
  155. (os.path.basename(__file__)))
  156. return "Could not generate table %s" % table_name
  157. threshold_units = table_options['aggregate_threshold'][1]
  158. try:
  159. reading = getattr(readingBinder, aggregate_type)((threshold_value, threshold_units))
  160. except IndexError:
  161. syslog.syslog(syslog.LOG_INFO, "%s: Problem with aggregate_threshold units: %s" % (os.path.basename(__file__),
  162. str(threshold_units)))
  163. return "Could not generate table %s" % table_name
  164. else:
  165. try:
  166. reading = getattr(readingBinder, aggregate_type)
  167. except KeyError:
  168. syslog.syslog(syslog.LOG_INFO, "%s: aggregate_type %s not found" % (os.path.basename(__file__),
  169. aggregate_type))
  170. return "Could not generate table %s" % table_name
  171. unit_type = reading.converter.group_unit_dict[reading.value_t[2]]
  172. unit_formatted = ''
  173. # 'units' option in skin.conf?
  174. if 'units' in table_options:
  175. unit_formatted = table_options['units']
  176. else:
  177. if (unit_type == 'count'):
  178. unit_formatted = "Days"
  179. else:
  180. if unit_type in reading.formatter.unit_label_dict:
  181. unit_formatted = reading.formatter.unit_label_dict[unit_type]
  182. # For aggregrate types which return number of occurrences (e.g. max_ge), set format to integer
  183. # Don't catch error here - we absolutely need the string format
  184. if unit_type == 'count':
  185. format_string = '%d'
  186. else:
  187. format_string = reading.formatter.unit_format_dict[unit_type]
  188. htmlText = '<table class="table">'
  189. htmlText += " <thead>"
  190. htmlText += " <tr>"
  191. htmlText += " <th>%s</th>" % unit_formatted
  192. for mon in table_options.get('monthnames', ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']):
  193. htmlText += " <th>%s</th>" % mon
  194. htmlText += " </tr>"
  195. htmlText += " </thead>"
  196. htmlText += " <tbody>"
  197. for year in table_stats.years():
  198. year_number = datetime.fromtimestamp(year.timespan[0]).year
  199. htmlLine = (' ' * 8) + "<tr>\n"
  200. if NOAA is True:
  201. htmlLine += (' ' * 12) + "%s\n" % \
  202. self._NoaaYear(datetime.fromtimestamp(year.timespan[0]), table_options)
  203. else:
  204. htmlLine += (' ' * 12) + "<td>%d</td>\n" % year_number
  205. for month in year.months():
  206. if NOAA is True:
  207. #for property, value in vars(month.dateTime.value_t[0]).iteritems():
  208. # print property, ": ", value
  209. if (month.timespan[1] < table_stats.timespan.start) or (month.timespan[0] > table_stats.timespan.stop):
  210. # print "No data for... %d, %d" % (year_number, datetime.fromtimestamp(month.timespan[0]).month)
  211. htmlLine += "<td>-</td>\n"
  212. else:
  213. htmlLine += self._NoaaCell(datetime.fromtimestamp(month.timespan[0]), table_options)
  214. else:
  215. if unit_type == 'count':
  216. try:
  217. value = getattr(getattr(month, obs_type), aggregate_type)((threshold_value, threshold_units)).value_t
  218. except:
  219. value = [0, 'count']
  220. else:
  221. value = converter.convert(getattr(getattr(month, obs_type), aggregate_type).value_t)
  222. htmlLine += (' ' * 12) + self._colorCell(value[0], format_string, bgColours)
  223. htmlLine += (' ' * 8) + "</tr>\n"
  224. htmlText += htmlLine
  225. #extra </tr> that's not needed
  226. #htmlText += (' ' * 8) + "</tr>\n"
  227. htmlText += (' ' * 4) + "</tbody>\n"
  228. htmlText += "</table>\n"
  229. return htmlText
  230. def _colorCell(self, value, format_string, bgColours):
  231. """Returns a '<td> bgcolor = xxx y.yy </td>' html table entry string.
  232. value: Numeric value for the observation
  233. format_string: How the numberic value should be represented in the table cell.
  234. bgColours: An array containing 3 lists. [minvalues], [maxvalues], [html colour code]
  235. """
  236. if value is not None:
  237. cellText = "<td"
  238. #changed background color code to HTML5
  239. for c in bgColours:
  240. if (value >= int(c[0])) and (value <= int(c[1])):
  241. cellText += " style=\"background-color: %s\"" % c[2]
  242. #for c in bgColours:
  243. # if (value >= int(c[0])) and (value <= int(c[1])):
  244. # cellText += " bgcolor = \"%s\"" % c[2]
  245. formatted_value = format_string % value
  246. cellText += "> %s </td>" % formatted_value
  247. else:
  248. cellText = "<td>-</td>\n"
  249. return cellText
  250. def _NoaaCell(self, dt, table_options):
  251. cellText = '<td> <a href="text.php?report=%s" class="btn btn-default btn-xs active" role="button"> %s </a> </td>' % \
  252. (dt.strftime(table_options['month_filename']), dt.strftime("%m-%y"))
  253. return cellText
  254. def _NoaaYear(self, dt, table_options):
  255. cellText = '<td> <a href="text.php?report=%s" class="btn btn-primary btn-xs active" role="button"> %s </a> </td>' % \
  256. (dt.strftime(table_options['year_filename']), dt.strftime("%Y"))
  257. return cellText