fdc5377087f223bf257cd134ed73471d2f22a8db
[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                         // chart.flush();
71                 },
72                 transition: {
73                         duration: null
74                 },
75                 title: {
76                         text: title
77                 },
78                 data: chartdata,
79                 point: {
80                         r: 1.5 // default 2.5
81                 },
82                 axis: {
83                         x: {
84                                 type: 'timeseries',
85                                 tick: {
86                                         format: function (d) {
87                                                 var strftimeDE = strftime.localizeByIdentifier('de_DE');
88                                                 return strftimeDE(xtickformat, new Date(d));
89                                         },
90                                         fit: false,
91                                         multiline: true, // broken? so →
92                                         rotate: -90
93                                 }
94                         },
95                         y: {
96                                 label: {
97                                         text: 'Temperatur in °C',
98                                         position: 'outer-middle'
99                                 },
100                                 tick: {
101                                         format: function (d) {
102                                                 return d.toFixed(1) + '°';
103                                         }
104                                 }
105                         }
106                 },
107                 zoom: {
108                         enabled: true,
109                         /*
110                         onzoomend: function (domain) {
111                                 var duration = (domain[1] - domain[0]) / 1000; // duration is now the diff of the "viewport in seconds"
112                                 // FIXME?
113                                 var days = duration / 86400;
114                                 if (days > 0) {
115                                         loaddays(this, element, days); // this = chart
116                                 }
117                         }
118                         */
119                 },
120                 tooltip: {
121                         format: {
122                                 // TODO: maybe move to top
123                                 name: function (name, ratio, id, index) {
124                                         var prefix = '';
125                                         if (element.substr(0, 7) == 'chart_w') {
126                                                 var re = /\d+ ?c?m/;
127                                                 prefix = 'Wasser ';
128                                         } else {
129                                                 var re = /Luft/;
130                                         };
131                                         var result = re.exec(name);
132                                         return prefix + result;
133                                 },
134                                 value: function (value, ratio, id, index) {
135                                         return value.toFixed(2) + '°';
136                                 },
137                                 title: function (datetime) {
138                                         // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
139                                         options = {
140                                                 weekday: 'short',
141                                                 year: 'numeric', month: 'numeric', day: 'numeric',
142                                                 hour: 'numeric', minute: 'numeric', second: 'numeric',
143                                                 timeZone: 'Europe/Vienna', timeZoneName: 'short'
144                                         };
145                                         return datetime.toLocaleString('de-AT', options);
146                                 }
147                         }
148                 },
149                 grid: {
150                         y: {
151                                 show: true
152                         }
153                 },
154                 regions: [
155                         {axis: 'y', start: -999, end:   0, class: 'region-frozen'},
156                         {axis: 'y', start:    0, end:  25, class: 'region-ok'},
157                         {axis: 'y', start:   25, end: 100, class: 'region-warm'},
158                         {axis: 'y', start:  100, end: 999, class: 'region-boiling'}
159                 ]
160         });
161
162         // reload data in charts
163         setInterval(
164                 function() {
165                         loaddays(chart, element, days);
166                 },
167                 refresh_interval
168         );
169 };
170
171 function loaddays(chart, element, days) {
172         // TODO: maybe move to top or factor out somehow
173         if (element.substr(0, 7) == 'chart_w') {
174                 chart.load({
175                         url: api_base_url_sensors + beginend(days),
176                         mimeType: 'json'
177                 });
178         } else {
179                 chart.load({
180                         url: api_base_url_weather + beginend(days),
181                         mimeType: 'json'
182                 });
183         }
184 }
185
186 function beginend(days) {
187         var now = Date.now();
188
189         // TODO: this timezone calculation relies on the browser being in Europe/Vienna
190         var refdate = new Date(now);
191         var offset = refdate.getTimezoneOffset(); // -120 for UTC+2
192
193         var end = new Date(now - offset * 60 * 1000).toISOString().substr(0, 19); // 2018-06-13T16:52:30.995Z
194         var begin = new Date(now - days * 60*60*24 * 1000 - offset * 60 * 1000).toISOString().substr(0, 19);
195         return '&begin=' + begin + '&end=' + end;
196 }
197
198 function getwidth(element) {
199         return document.getElementById(element).parentElement.clientWidth * 80 / 100;
200 }
201
202 dayschart('chart_water_1',   'Der See (Tag)',     1, '%H:%M');
203 dayschart('chart_water_7',   'Der See (Woche)',   7, '%a %d');
204 dayschart('chart_water_31',  'Der See (Monat)',  31, '%Y-%m-%d');
205 dayschart('chart_water_365', 'Der See (Jahr)',  365, '%b %Y');
206
207 dayschart('chart_air_1',     'Die Luft (Tag)',     1, '%H:%M');
208 dayschart('chart_air_7',     'Die Luft (Woche)',   7, '%a %d');
209 dayschart('chart_air_31',    'Die Luft (Monat)',  31, '%Y-%m-%d');
210 dayschart('chart_air_365',   'Die Luft (Jahr)',  365, '%b %Y');
211
212 // reload current values
213 setInterval(
214         function() {
215                 var airvalue   = document.getElementById('currentairvalue');
216                 var airtime    = document.getElementById('currentairtime');
217                 var watervalue = document.getElementById('currentwatervalue');
218                 var watertime  = document.getElementById('currentwatertime');
219                 fetch(api_url_currentair)
220                         .then((resp) => resp.json())
221                         .then(function(data) {
222                                 airvalue.innerText = data['value'].toFixed(1);
223                                 airtime.innerText  = strftime('%Y-%m-%d H:%M', new Date(data['timestamp']));
224                         })
225                         .catch(function(error) {
226                                 console.log(error);
227                         });
228                 fetch(api_url_currentwater)
229                         .then((resp) => resp.json())
230                         .then(function(data) {
231                                 watervalue.innerText = data['value'].toFixed(1);
232                                 watertime.innerText  = strftime('%Y-%m-%d H:%M', new Date(data['timestamp']));
233                         })
234                         .catch(function(error) {
235                                 console.log(error);
236                         });
237         },
238         refresh_interval
239 );