Projekt

Obecné

Profil

Stáhnout (14.7 KB) Statistiky
| Větev: | Tag: | Revize:
1 370c3423 hlavja
import {Component, OnInit} from '@angular/core';
2
import {ActivatedRoute} from '@angular/router';
3
import {AnalyticsService} from '../../shared/api/endpoints/services/analytics.service';
4 ba41c963 hlavja
import {map, tap} from 'rxjs/operators';
5 b5525aef hlavja
import {AggregationModel} from '../../shared/models/aggregationModel';
6 370c3423 hlavja
import * as moment from 'moment-timezone';
7 11efc186 hlavja
import {GraphLoader} from '../../shared/graph-loading/graphloader';
8 cd2a65f3 hlavja
import {SensorsService} from '../../shared/api/endpoints/services/sensors.service';
9
import {HttpResponse} from '@angular/common/http';
10
import {ToastService} from '../../shared/services/toast.service';
11
import {Sensor} from '../../shared/api/endpoints/models/sensor';
12 ba41c963 hlavja
import {ObservationService} from '../../shared/api/endpoints/services/observation.service';
13 370c3423 hlavja
14
15 c4f90f7b Štěpán Červenka
declare var require: any
16
17 370c3423 hlavja
@Component({
18
  selector: 'app-unit',
19
  templateUrl: './unit.component.html',
20
  styleUrls: ['./unit.component.scss']
21
})
22
export class UnitComponent implements OnInit {
23
24
  preselectedSensors: string;
25
  unitId: number;
26 8b522708 Štěpán Červenka
  viewCount = 0;
27 cd2a65f3 hlavja
  data = [];
28
  time = [];
29
  from: Date;
30
  to: Date;
31
  today: Date;
32 2b0d2514 hlavja
  analyticsData: any[] = [];
33
  observationsData: any[] = [];
34 11efc186 hlavja
  sensorGroups = [];
35 b937b726 hlavja
  selectedSensors: string[] = [];
36 cd2a65f3 hlavja
  sensors: Sensor[];
37
  showAggregation = false;
38 b5525aef hlavja
  aggregationFunction: AggregationModel[];
39 ba41c963 hlavja
  selectedAggregationFunction = 'DAY';
40
  useAnalyticsData = false;
41 370c3423 hlavja
42
  constructor(
43
    private activatedRoute: ActivatedRoute,
44 cd2a65f3 hlavja
    private analyticsService: AnalyticsService,
45
    private sensorService: SensorsService,
46 ba41c963 hlavja
    private toastService: ToastService,
47
    private observationService: ObservationService
48 370c3423 hlavja
  ) {
49 cd2a65f3 hlavja
    this.unitId = parseInt(this.activatedRoute.snapshot.paramMap.get('unitId'), 10);
50 370c3423 hlavja
    this.aggregationFunction = [
51
      {name: 'Hour', code: 'HOUR'},
52
      {name: 'Day', code: 'DAY'},
53
      {name: 'Month', code: 'MONTH'},
54
      {name: 'Year', code: 'YEAR'}
55
    ];
56 cd2a65f3 hlavja
    this.today = moment().toDate();
57 ba41c963 hlavja
    this.sensorService.getUnitSensors({unit_id: this.unitId}).pipe(
58
      tap(sens => {
59
        this.sensors = sens;
60 b937b726 hlavja
        this.sensors.sort((a, b)  => a.sensorId - b.sensorId);
61 ba41c963 hlavja
      }),
62
      tap(() => {
63
        if (this.sensors && this.sensors.length > 0) {
64
          this.sensors.forEach(sensor => {
65 b5525aef hlavja
            const sensorType = sensor.sensorId.toString().slice(0, 5);
66 cd2a65f3 hlavja
            if (!this.sensorGroups.some(group => group === sensorType)) {
67
              this.sensorGroups.push(sensorType);
68 2b0d2514 hlavja
              setTimeout(() => {
69 05d4a2a9 hlavja
                // GraphLoader.getAnalyticsGraph(null, null, null, '#vega_container_' + sensor.sensorId.toString().slice(0, 5));
70 66c042f1 Štěpán Červenka
                GraphLoader.getGraph(null, null, null, '#vega_container_' + sensor.sensorId.toString().slice(0, 5),null );
71 2b0d2514 hlavja
              }, 0);
72 cd2a65f3 hlavja
            }
73 a769e543 hlavja
          });
74 cd2a65f3 hlavja
        }
75 ba41c963 hlavja
      })
76
    ).toPromise().then();
77 370c3423 hlavja
  }
78
79
  ngOnInit(): void {
80
  }
81
82 b937b726 hlavja
  showGraph(changedDate: boolean = true, changedSensor: string = null) {
83 a02dd197 hlavja
    const range: Date[] = [moment().subtract(7, 'days').toDate(), moment().toDate()];
84 cd2a65f3 hlavja
85
    if (this.from && !this.to || !this.from && this.to) {
86
      return;
87
    }
88
89
    if (this.from && this.to) {
90
      range[0] = this.from;
91
      range[1] = this.to;
92 370c3423 hlavja
    }
93
94 cd2a65f3 hlavja
    if (moment(range[1]).diff(moment(range[0]), 'days') > 7) {
95 ba41c963 hlavja
      this.useAnalyticsData = true;
96 cd2a65f3 hlavja
      this.showAggregation = true;
97 ba41c963 hlavja
      this.getAnalytics(range, changedDate, changedSensor);
98 cd2a65f3 hlavja
    } else {
99 ba41c963 hlavja
      this.useAnalyticsData = false;
100 cd2a65f3 hlavja
      this.showAggregation = false;
101 ba41c963 hlavja
      this.getObservations(range, changedDate, changedSensor);
102 370c3423 hlavja
    }
103 cd2a65f3 hlavja
  }
104 370c3423 hlavja
105 b937b726 hlavja
  getAnalytics(range: Date[], changedDate: boolean, changedSensor: string) {
106 c4f90f7b Štěpán Červenka
107
    GraphLoader.getGraphWithInterval(this.getDummySensorList(), this.getDummyGraph(), this.getDummyInterval(), this.getDummyLegend(), this.getDummyContainer(), "true");
108
    return;
109
110
111 66c042f1 Štěpán Červenka
    const groupId = changedSensor.toString().slice(0, 5);
112 ba41c963 hlavja
    if (changedDate) {
113
      this.selectedSensors.forEach(selectSens => {
114 b937b726 hlavja
        this.analyticsService.getAnalytics$Response({unit_id: this.unitId, sensor_id: parseInt(selectSens, 10),
115 ba41c963 hlavja
          from: moment(range[0]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3),
116
          to: moment(range[1]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3), interval: this.selectedAggregationFunction}).pipe(
117
          map((response: HttpResponse<any>) => {
118
            if (response.status === 200) {
119
              return response.body;
120
            } else if (response.status === 204) {
121 05d4a2a9 hlavja
              // GraphLoader.getAnalyticsGraph(null, null, null, '#vega_container_' + selectSens.toString().slice(0, 5));
122 66c042f1 Štěpán Červenka
              GraphLoader.getGraph(null, null, null, '#vega_container_' + selectSens.toString().slice(0, 5),null );
123 ba41c963 hlavja
              this.toastService.showWarningNoData();
124
              return response.body;
125
            } else {
126
              return false;
127
            }
128
          })
129
        ).subscribe(data => {
130
          if (data) {
131 b526d17e hlavja
            this.analyticsData.push({sensorId: selectSens, data: data[selectSens].data, interval: data[selectSens].interval});
132 ba41c963 hlavja
            const objectKeys = Object.keys(data);
133
            for(const key of objectKeys ) {
134
              if (data[key].data) {
135
                const view = '#vega_container_' + key.slice(0, 5);
136
                if (this.selectedSensors.some(sens => sens.toString() === key)) {
137 05d4a2a9 hlavja
                  // GraphLoader.getAnalyticsGraph(key, data[key].data, data[key].interval, view);
138
                  // GraphLoader.getGraph(this.selectedSensors, this.filteredAnalyticsData(groupId), view, true);
139 c4f90f7b Štěpán Červenka
                  GraphLoader.getGraph(this.filteredSelectedSensors(groupId),  this.filteredAnalyticsData(groupId),
140
                    this.filteredSensorsInfos(groupId), view, true);
141 ba41c963 hlavja
                } else {
142 66c042f1 Štěpán Červenka
                  GraphLoader.getGraph(null, null, null, view, null);
143 ba41c963 hlavja
                }
144
              }
145
            }
146
          }
147
        }, err => this.toastService.showError(err.error.message));
148
      });
149
    } else  {
150 b937b726 hlavja
      this.analyticsService.getAnalytics$Response({unit_id: this.unitId, sensor_id: parseInt(changedSensor, 10),
151 ba41c963 hlavja
        from: moment(range[0]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3),
152
        to: moment(range[1]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3), interval: this.selectedAggregationFunction}).pipe(
153
        map((response: HttpResponse<any>) => {
154
          if (response.status === 200) {
155
            return response.body;
156
          } else if (response.status === 204) {
157
            this.toastService.showWarningNoData();
158
            return response.body;
159
          } else {
160
            return false;
161
          }
162
        })
163
      ).subscribe(data => {
164
        if (data) {
165
          this.analyticsData.push({sensorId: changedSensor, data: data[changedSensor].data, interval: data[changedSensor].interval});
166
          const objectKeys = Object.keys(data);
167 2b0d2514 hlavja
          for(const key of objectKeys ) {
168
            if (data[key].data) {
169
              const view = '#vega_container_' + key.slice(0, 5);
170
              if (this.selectedSensors.some(sens => sens.toString() === key)) {
171 8cca41c0 Štěpán Červenka
               // GraphLoader.getAnalyticsGraph(key, data[key].data, data[key].interval, view);
172 c4f90f7b Štěpán Červenka
                GraphLoader.getGraph(this.filteredSelectedSensors(groupId),  this.filteredAnalyticsData(groupId),
173
                  this.filteredSensorsInfos(groupId), view, true);
174 ba41c963 hlavja
              } else {
175 05d4a2a9 hlavja
                // GraphLoader.getAnalyticsGraph(null, null, null, view);
176 66c042f1 Štěpán Červenka
                GraphLoader.getGraph(null, null, null, view, null);
177 2b0d2514 hlavja
              }
178 cd2a65f3 hlavja
            }
179
          }
180
        }
181 2b0d2514 hlavja
      }, err => this.toastService.showError(err.error.message));
182 ba41c963 hlavja
    }
183 2b0d2514 hlavja
  }
184
185 a769e543 hlavja
  /**
186
   * Check button handler.
187
   * @param sensorId checked sensorId
188
   * @param event event for getting if checked or unchecked
189
   */
190 b937b726 hlavja
  addSensorToGraph(sensorId: string, event) {
191 a769e543 hlavja
    const groupId = sensorId.toString().slice(0, 5);
192
    const sensorGroupElement = '#vega_container_' + groupId;
193
    if (!this.selectedSensors.find(sensId => sensId.toString().slice(0, 5) === groupId)) { // if group of sensors is empty show empty graph
194 05d4a2a9 hlavja
      // GraphLoader.getAnalyticsGraph(null, null, null, sensorGroupElement);
195 66c042f1 Štěpán Červenka
      GraphLoader.getGraph(null, null, null, sensorGroupElement, null);
196 ba41c963 hlavja
    } else {
197 a769e543 hlavja
      if (this.useAnalyticsData) { // use analytics data
198
        if (event.checked) { // if checked > add to graph
199
          if (this.analyticsData.some(sens => sens.sensorId === sensorId)) { // if already data for selected sensor in memory
200 05d4a2a9 hlavja
            // GraphLoader.getAnalyticsGraph(sensorId, this.analyticsData.find(sens => sens.sensorId === sensorId).data,
201 8cca41c0 Štěpán Červenka
            // this.analyticsData.find((sens => sens.sensorId === sensorId).interval, sensorGroupElement);
202 c4f90f7b Štěpán Červenka
            GraphLoader.getGraph(this.filteredSelectedSensors(groupId),  this.filteredAnalyticsData(groupId),
203
              this.filteredSensorsInfos(groupId), sensorGroupElement, true);
204 8cca41c0 Štěpán Červenka
205 a769e543 hlavja
          } else { // get data from server for added sensor and show graph for selected sensors
206
            this.showGraph(false, sensorId);
207
          }
208
        } else { // remove sensor from graph
209 05d4a2a9 hlavja
          // GraphLoader.getAnalyticsGraph(sensorId, this.analyticsData.find(sens => sens.sensorId === sensorId).data,
210 8cca41c0 Štěpán Červenka
          // this.analyticsData.find(sens => sens.sensorId === sensorId).interval, sensorGroupElement);
211 66c042f1 Štěpán Červenka
          GraphLoader.getGraph(this.selectedSensors, this.analyticsData, this.filteredSensorsInfos(groupId), sensorGroupElement, true);
212 8cca41c0 Štěpán Červenka
213 ba41c963 hlavja
        }
214 a769e543 hlavja
      } else { // use observations data
215
        if (event.checked) { // if checked > add to graph
216 b937b726 hlavja
          if (this.observationsData.some(sens => sens.sensorId.toString() === sensorId)) { // if already data for selected sensor in memory
217 05d4a2a9 hlavja
            GraphLoader.getGraph(this.filteredSelectedSensors(groupId), this.filteredObservationData(groupId),
218
              this.filteredSensorsInfos(groupId), sensorGroupElement, false);
219
            // GraphLoader.getMultilineGraph(this.selectedSensors, this.filteredObservationData(groupId), sensorGroupElement)
220 a769e543 hlavja
          } else { // get data from server for added sensor and show graph for selected sensors
221
            this.showGraph(false, sensorId);
222
          }
223
        } else { // remove sensor from graph
224 05d4a2a9 hlavja
          // GraphLoader.getMultilineGraph(this.selectedSensors, this.filteredObservationData(groupId), sensorGroupElement)
225
          GraphLoader.getGraph(this.filteredSelectedSensors(groupId), this.filteredObservationData(groupId),
226
            this.filteredSensorsInfos(groupId), sensorGroupElement, false);
227 66c042f1 Štěpán Červenka
228 2b0d2514 hlavja
        }
229
      }
230
    }
231 8b522708 Štěpán Červenka
  }
232 ba41c963 hlavja
233 a769e543 hlavja
  /**
234
   * Filter observations data only fro selected sensors.
235
   * @param sensorGroupId id of changed sensor group
236
   */
237
  filteredObservationData(sensorGroupId: string): any {
238
    return this.observationsData.filter(sen => this.selectedSensors.includes(sen.sensorId.toString()) &&
239
      sen.sensorId.toString().slice(0, 5) === sensorGroupId);
240
  }
241
242
  /**
243
   * Filter analytics data only fro selected sensors.
244
   */
245 8cca41c0 Štěpán Červenka
  filteredAnalyticsData(sensorGroupId: string): any {
246
    return this.analyticsData.filter(sen => this.selectedSensors.includes(sen.sensorId.toString()) &&
247
      sen.sensorId.toString().slice(0, 5) === sensorGroupId);
248 a769e543 hlavja
  }
249
250 66c042f1 Štěpán Červenka
251
  filteredSelectedSensors(sensorGroupId: string): any {
252 05d4a2a9 hlavja
    return this.selectedSensors.filter(sen => sen.toString().slice(0, 5) === sensorGroupId );
253 66c042f1 Štěpán Červenka
  }
254
255
  filteredSensorsInfos(sensorGroupId: string): any {
256
    return this.sensors.filter(sen => this.selectedSensors.includes(sen.sensorId.toString()) &&
257 05d4a2a9 hlavja
      sen.sensorId.toString().slice(0, 5) === sensorGroupId);
258 66c042f1 Štěpán Červenka
  }
259
260 b937b726 hlavja
  private getObservations(range: Date[], changedDate: boolean, changedSensorId: string) {
261 66c042f1 Štěpán Červenka
    const groupId = changedSensorId.toString().slice(0, 5);
262 a769e543 hlavja
    if (changedDate) { // if changed date we need new data for all sensors
263
      this.observationsData = []; // empty observation data
264 ba41c963 hlavja
      this.selectedSensors.forEach(selectSens => {
265
        this.observationService.getObservation$Response({
266
          unit_id: this.unitId,
267 b937b726 hlavja
          sensor_id: parseInt(selectSens, 10),
268 ba41c963 hlavja
          from: moment(range[0]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3),
269
          to: moment(range[1]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3)
270
        }).pipe(
271
          map((response: HttpResponse<any>) => {
272
            if (response.status === 200) {
273
              return response.body;
274
            } else if (response.status === 204) {
275
              this.toastService.showWarningNoData();
276
              return response.body;
277
            } else {
278
              return false;
279
            }
280 a769e543 hlavja
          }),
281
          tap((observations) => {
282 ba41c963 hlavja
            if (observations) {
283 a769e543 hlavja
              this.observationsData.push({sensorId: selectSens, sensor:
284
                this.sensors.find(sens => sens.sensorId.toString() === selectSens.toString()), data: observations});
285 ba41c963 hlavja
            }
286 a769e543 hlavja
          }),
287
          tap(() => {
288
            if (this.observationsData && this.observationsData.length > 1) {
289
              const view = '#vega_container_' + selectSens.toString().slice(0, 5);
290
              setTimeout(() => {
291
                console.log(this.selectedSensors);
292 05d4a2a9 hlavja
             // GraphLoader.getMultilineGraph(this.selectedSensors, this.filteredObservationData(selectSens.toString().slice(0, 5)), view);
293
                GraphLoader.getGraph(this.filteredSelectedSensors(groupId),  this.filteredObservationData(groupId),
294
                  this.filteredSensorsInfos(groupId), view, false);
295 b937b726 hlavja
              }, 10);
296 a769e543 hlavja
            }
297
          })
298
        ).toPromise().then().catch(err => this.toastService.showError(err));
299 ba41c963 hlavja
      });
300
    } else {
301
      this.observationService.getObservation$Response({
302
        unit_id: this.unitId,
303 b937b726 hlavja
        sensor_id: parseInt(changedSensorId, 10),
304 ba41c963 hlavja
        from: moment(range[0]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3),
305
        to: moment(range[1]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3)
306
      }).pipe(
307
        map((response: HttpResponse<any>) => {
308
          if (response.status === 200) {
309
            return response.body;
310
          } else if (response.status === 204) {
311
            this.toastService.showWarningNoData();
312
            return response.body;
313
          } else {
314
            return false;
315
          }
316
        })
317
      ).subscribe(
318
        observations => {
319 a769e543 hlavja
          this.observationsData.push({sensorId: changedSensorId, sensor:
320
              this.sensors.find(sens => sens.sensorId.toString() === changedSensorId.toString()), data: observations});
321
          const view = '#vega_container_' + changedSensorId.toString().slice(0, 5);
322 05d4a2a9 hlavja
          GraphLoader.getGraph(this.filteredSelectedSensors(groupId),  this.filteredObservationData(groupId),
323
            this.filteredSensorsInfos(groupId), view, false);
324 ba41c963 hlavja
        }, err => this.toastService.showError(err.error.message));
325
    }
326
  }
327 c4f90f7b Štěpán Červenka
328
329
  getDummyLegend() {
330
    return require('/src/app/sensor/components/dummysensor.json');
331
  }
332
333
  getDummyGraph() {
334
    return require('/src/app/sensor/components/dummymultilinechart.json');
335
  }
336
337
  getDummySensorList() {
338
    return [340414062,340414062,340414064];
339
  }
340
341
  getDummyContainer() {
342
    return "#vega_container_34041";
343
  }
344
345
  getDummyInterval() {
346
    return  24 * 3600 * 1000;
347
  }
348
349
350 370c3423 hlavja
}