Projekt

Obecné

Profil

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