d763fdb624e95db1f33b4a39c66791c7f46e916a
[chrisu/seepark.git] / web / static / seepark_web.js
1 var api_base_url_sensors = '/api/1/sensor/type/Wassertemperatur?mode=consolidated&format=c3';
2 var api_base_url_weather = '/api/1/openweathermap/city/3319578?mode=consolidated&format=c3';
3 var api_url_currentair   = '/api/1/currentairtemperature';
4 var api_url_currentwater = '/api/1/currentwatertemperature';
5 var refresh_interval     = 5 * 60 * 1000;
6
7 function dayschart(element, title, days, xtickformat) {
8         var chartdata;
9         if (element.substr(0, 7) == 'chart_w') {
10                 chartdata = {
11                                 url: api_base_url_sensors + beginend(days),
12                                 mimeType: 'json',
13                                 xs: {
14                                         '0416a1ac66ff': '0416a1ac66ff_x',
15                                         '0516a207a4ff': '0516a207a4ff_x',
16                                         '0416a1bab9ff': '0416a1bab9ff_x',
17                                         '0316a2193bff': '0316a2193bff_x'
18                                 },
19                                 names: {
20                                         '0416a1ac66ff': 'Wassertemperatur 30cm Tiefe',
21                                         '0516a207a4ff': 'Wassertemperatur 50cm Tiefe',
22                                         '0416a1bab9ff': 'Wassertemperatur 1m Tiefe',
23                                         '0316a2193bff': 'Wassertemperatur in 30 cm Tiefe'
24                                 },
25                                 xFormat: '%Y-%m-%d %H:%M:%S',
26                                 // https://en.wikipedia.org/wiki/Web_colors
27                                 colors: {
28                                         '0416a1ac66ff': 'lightskyblue',
29                                         '0516a207a4ff': 'royalblue',
30                                         '0416a1bab9ff': 'mediumblue',
31                                         '0316a2193bff': 'midnightblue'
32                                 },
33                                 /*
34                                 xSort: false,
35                                 order: function (a, b) {
36                                         // gets 2 x objects. seems to be a "sort function" for js's sort()
37                                         // -1: a before b etc.
38                                         // only handle cases that appear in the wild
39                                         // console.log("a.id", a.id, "b.id", b.id);
40                                         if (a.id == '0416a1ac66ff') {return -1};
41                                         if (a.id == '0416a1bab9ff') {return  1};
42                                 }
43                                 */
44                 };
45         } else {
46                 chartdata = {
47                                 url: api_base_url_weather + beginend(days),
48                                 mimeType: 'json',
49                                 xs: {
50                                         '3319578': '3319578_x'
51                                 },
52                                 names: {
53                                         '3319578': 'Lufttemperatur in Obsteig'
54                                 },
55                                 xFormat: '%Y-%m-%d %H:%M:%S',
56                                 colors: {
57                                         '3319578': 'red'
58                                 }
59                 };
60         };
61         var chart = c3.generate({
62                 bindto: '#' + element,
63                 size: {
64                         width: getwidth(element)
65                 },
66                 onresized: function () {
67                         chart.resize({
68                                 width: getwidth(element)
69                         });
70                 },
71                 transition: {
72                         duration: null
73                 },
74                 title: {
75                         text: title
76                 },
77                 data: chartdata,
78                 point: {
79                         r: 1.5 // default 2.5
80                 },
81                 axis: {
82                         x: {
83                                 type: 'timeseries',
84                                 tick: {
85                                         format: function (d) {
86                                                 var strftimeDE = strftime.localizeByIdentifier('de_DE');
87                                                 return strftimeDE(xtickformat, new Date(d));
88                                         },
89                                         fit: false,
90                                         multiline: true, // broken? so →
91                                         rotate: -90
92                                 }
93                         },
94                         y: {
95                                 label: {
96                                         text: 'Temperatur in °C',
97                                         position: 'outer-middle'
98                                 },
99                                 tick: {
100                                         format: function (d) {
101                                                 return d.toFixed(1) + '°';
102                                         }
103                                 }
104                         }
105                 },
106                 zoom: {
107                         enabled: true,
108                         /*
109                         onzoomend: function (domain) {
110                                 var duration = (domain[1] - domain[0]) / 1000; // duration is now the diff of the "viewport in seconds"
111                                 // FIXME?
112                                 var days = duration / 86400;
113                                 if (days > 0) {
114                                         loaddays(this, element, days); // this = chart
115                                 }
116                         }
117                         */
118                 },
119                 tooltip: {
120                         format: {
121                                 // TODO: maybe move to top
122                                 name: function (name, ratio, id, index) {
123                                         var prefix = '';
124                                         if (element.substr(0, 7) == 'chart_w') {
125                                                 var re = /\d+ ?c?m/;
126                                                 prefix = 'Wasser ';
127                                         } else {
128                                                 var re = /Luft/;
129                                         };
130                                         var result = re.exec(name);
131                                         return prefix + result;
132                                 },
133                                 value: function (value, ratio, id, index) {
134                                         return value.toFixed(2) + '°';
135                                 },
136                                 title: function (datetime) {
137                                         // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
138                                         options = {
139                                                 weekday: 'short',
140                                                 year: 'numeric', month: 'numeric', day: 'numeric',
141                                                 hour: 'numeric', minute: 'numeric', second: 'numeric',
142                                                 timeZone: 'Europe/Vienna', timeZoneName: 'short'
143                                         };
144                                         return datetime.toLocaleString('de-AT', options);
145                                 }
146                         }
147                 },
148                 grid: {
149                         y: {
150                                 show: true
151                         },
152                         x: {
153                                 show: true
154                         }
155                 },
156                 regions: [
157                         {axis: 'y', start: -999, end:   0, class: 'region-frozen'},
158                         {axis: 'y', start:    0, end:  25, class: 'region-ok'},
159                         {axis: 'y', start:   25, end: 100, class: 'region-warm'},
160                         {axis: 'y', start:  100, end: 999, class: 'region-boiling'}
161                 ]
162         });
163
164         // workaround for unrendered dots
165         setTimeout(function () { chart.flush(); }, 5000);
166
167         // reload data in charts
168         setInterval(
169                 function() {
170                         loaddays(chart, element, days);
171                 },
172                 refresh_interval
173         );
174 };
175
176 function loaddays(chart, element, days) {
177         // TODO: maybe move to top or factor out somehow
178         if (element.substr(0, 7) == 'chart_w') {
179                 chart.load({
180                         url: api_base_url_sensors + beginend(days),
181                         mimeType: 'json',
182                         unload: true
183                 });
184         } else {
185                 chart.load({
186                         url: api_base_url_weather + beginend(days),
187                         mimeType: 'json',
188                         unload: true
189                 });
190         };
191         chart.flush();
192 }
193
194 function beginend(days) {
195         var now = Date.now();
196
197         // TODO: this timezone calculation relies on the browser being in Europe/Vienna
198         var refdate = new Date(now);
199         var offset = refdate.getTimezoneOffset(); // -120 for UTC+2
200
201         var end = new Date(now - offset * 60 * 1000).toISOString().substr(0, 19); // 2018-06-13T16:52:30.995Z
202         var begin = new Date(now - days * 60*60*24 * 1000 - offset * 60 * 1000).toISOString().substr(0, 19);
203         return '&begin=' + begin + '&end=' + end;
204 }
205
206 function getwidth(element) {
207         return document.getElementById(element).parentElement.clientWidth * 80 / 100;
208 }
209
210 dayschart('chart_water_1',   'Der See (Tag)',     1, '%H:%M');
211 dayschart('chart_water_7',   'Der See (Woche)',   7, '%a %d');
212 dayschart('chart_water_31',  'Der See (Monat)',  31, '%Y-%m-%d');
213 dayschart('chart_water_365', 'Der See (Jahr)',  365, '%b %Y');
214
215 dayschart('chart_air_1',     'Die Luft (Tag)',     1, '%H:%M');
216 dayschart('chart_air_7',     'Die Luft (Woche)',   7, '%a %d');
217 dayschart('chart_air_31',    'Die Luft (Monat)',  31, '%Y-%m-%d');
218 dayschart('chart_air_365',   'Die Luft (Jahr)',  365, '%b %Y');
219
220 // reload current values
221 setInterval(
222         function() {
223                 var airvalue   = document.getElementById('currentairvalue');
224                 var airtime    = document.getElementById('currentairtime');
225                 var watervalue = document.getElementById('currentwatervalue');
226                 var watertime  = document.getElementById('currentwatertime');
227                 fetch(api_url_currentair)
228                         .then((resp) => resp.json())
229                         .then(function(data) {
230                                 airvalue.innerText = data['value'].toFixed(1);
231                                 airtime.innerText  = strftime('%Y-%m-%d %H:%M', new Date(data['timestamp']));
232                         })
233                         .catch(function(error) {
234                                 console.log(error);
235                         });
236                 fetch(api_url_currentwater)
237                         .then((resp) => resp.json())
238                         .then(function(data) {
239                                 watervalue.innerText = data['value'].toFixed(1);
240                                 watertime.innerText  = strftime('%Y-%m-%d %H:%M', new Date(data['timestamp']));
241                         })
242                         .catch(function(error) {
243                                 console.log(error);
244                         });
245         },
246         refresh_interval
247 );