Projekt

Obecné

Profil

Stáhnout (13.9 KB) Statistiky
| Větev: | Tag: | Revize:
1
import {Component, OnInit} from '@angular/core';
2
import {ActivatedRoute} from '@angular/router';
3
import {AnalyticsService} from '../../shared/api/endpoints/services/analytics.service';
4
import {map, tap} from 'rxjs/operators';
5
import {AggregationModel} from '../../shared/models/aggregationModel';
6
import * as moment from 'moment-timezone';
7
import {GraphLoader} from '../../shared/graph-loading/graphloader';
8
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
import {ObservationService} from '../../shared/api/endpoints/services/observation.service';
13

    
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
  viewCount = 0;
25
  data = [];
26
  time = [];
27
  from: Date;
28
  to: Date;
29
  today: Date;
30
  analyticsData: any[] = [];
31
  observationsData: any[] = [];
32
  sensorGroups = [];
33
  selectedSensors: string[] = [];
34
  sensors: Sensor[];
35
  showAggregation = false;
36
  aggregationFunction: AggregationModel[];
37
  selectedAggregationFunction = 'DAY';
38
  useAnalyticsData = false;
39

    
40
  constructor(
41
    private activatedRoute: ActivatedRoute,
42
    private analyticsService: AnalyticsService,
43
    private sensorService: SensorsService,
44
    private toastService: ToastService,
45
    private observationService: ObservationService
46
  ) {
47
    this.unitId = parseInt(this.activatedRoute.snapshot.paramMap.get('unitId'), 10);
48
    this.aggregationFunction = [
49
      {name: 'Hour', code: 'HOUR'},
50
      {name: 'Day', code: 'DAY'},
51
      {name: 'Month', code: 'MONTH'},
52
      {name: 'Year', code: 'YEAR'}
53
    ];
54
    this.today = moment().toDate();
55
    this.sensorService.getUnitSensors({unit_id: this.unitId}).pipe(
56
      tap(sens => {
57
        this.sensors = sens;
58
        this.sensors.sort((a, b)  => a.sensorId - b.sensorId);
59
      }),
60
      tap(() => {
61
        if (this.sensors && this.sensors.length > 0) {
62
          this.sensors.forEach(sensor => {
63
            const sensorType = sensor.sensorId.toString().slice(0, 5);
64
            if (!this.sensorGroups.some(group => group === sensorType)) {
65
              this.sensorGroups.push(sensorType);
66
              setTimeout(() => {
67
                // GraphLoader.getAnalyticsGraph(null, null, null, '#vega_container_' + sensor.sensorId.toString().slice(0, 5));
68
                GraphLoader.getGraph(null, null, null, '#vega_container_' + sensor.sensorId.toString().slice(0, 5),null );
69
              }, 0);
70
            }
71
          });
72
        }
73
      })
74
    ).toPromise().then();
75
  }
76

    
77
  ngOnInit(): void {
78
  }
79

    
80
  showGraph(changedDate: boolean = true, changedSensor: string = null) {
81
    const range: Date[] = [moment().subtract(7, 'days').toDate(), moment().toDate()];
82

    
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
    }
91

    
92
    if (moment(range[1]).diff(moment(range[0]), 'days') > 7) {
93
      this.useAnalyticsData = true;
94
      this.showAggregation = true;
95
      this.getAnalytics(range, changedDate, changedSensor);
96
    } else {
97
      this.useAnalyticsData = false;
98
      this.showAggregation = false;
99
      this.getObservations(range, changedDate, changedSensor);
100
    }
101
  }
102

    
103
  getAnalytics(range: Date[], changedDate: boolean, changedSensor: string) {
104
    const groupId = changedSensor.toString().slice(0, 5);
105
    if (changedDate) {
106
      this.selectedSensors.forEach(selectSens => {
107
        this.analyticsService.getAnalytics$Response({unit_id: this.unitId, sensor_id: parseInt(selectSens, 10),
108
          from: moment(range[0]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3),
109
          to: moment(range[1]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3), interval: this.selectedAggregationFunction}).pipe(
110
          map((response: HttpResponse<any>) => {
111
            if (response.status === 200) {
112
              return response.body;
113
            } else if (response.status === 204) {
114
              // GraphLoader.getAnalyticsGraph(null, null, null, '#vega_container_' + selectSens.toString().slice(0, 5));
115
              GraphLoader.getGraph(null, null, null, '#vega_container_' + selectSens.toString().slice(0, 5),null );
116
              this.toastService.showWarningNoData();
117
              return response.body;
118
            } else {
119
              return false;
120
            }
121
          })
122
        ).subscribe(data => {
123
          if (data) {
124
            this.analyticsData.push({sensorId: selectSens, data: data[selectSens].data, interval: data[selectSens].interval});
125
            const objectKeys = Object.keys(data);
126
            for(const key of objectKeys ) {
127
              if (data[key].data) {
128
                const view = '#vega_container_' + key.slice(0, 5);
129
                if (this.selectedSensors.some(sens => sens.toString() === key)) {
130
                  // GraphLoader.getAnalyticsGraph(key, data[key].data, data[key].interval, view);
131
                  // GraphLoader.getGraph(this.selectedSensors, this.filteredAnalyticsData(groupId), view, true);
132
                } else {
133
                  GraphLoader.getGraph(null, null, null, view, null);
134
                }
135
              }
136
            }
137
          }
138
        }, err => this.toastService.showError(err.error.message));
139
      });
140
    } else  {
141
      this.analyticsService.getAnalytics$Response({unit_id: this.unitId, sensor_id: parseInt(changedSensor, 10),
142
        from: moment(range[0]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3),
143
        to: moment(range[1]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3), interval: this.selectedAggregationFunction}).pipe(
144
        map((response: HttpResponse<any>) => {
145
          if (response.status === 200) {
146
            return response.body;
147
          } else if (response.status === 204) {
148
            this.toastService.showWarningNoData();
149
            return response.body;
150
          } else {
151
            return false;
152
          }
153
        })
154
      ).subscribe(data => {
155
        if (data) {
156
          this.analyticsData.push({sensorId: changedSensor, data: data[changedSensor].data, interval: data[changedSensor].interval});
157
          const objectKeys = Object.keys(data);
158
          for(const key of objectKeys ) {
159
            if (data[key].data) {
160
              const view = '#vega_container_' + key.slice(0, 5);
161
              if (this.selectedSensors.some(sens => sens.toString() === key)) {
162
               // GraphLoader.getAnalyticsGraph(key, data[key].data, data[key].interval, view);
163
                GraphLoader.getGraph(this.selectedSensors, this.analyticsData, this.filteredSensorsInfos(groupId), view, true);
164
              } else {
165
                // GraphLoader.getAnalyticsGraph(null, null, null, view);
166
                GraphLoader.getGraph(null, null, null, view, null);
167
              }
168
            }
169
          }
170
        }
171
      }, err => this.toastService.showError(err.error.message));
172
    }
173
  }
174

    
175
  /**
176
   * Check button handler.
177
   * @param sensorId checked sensorId
178
   * @param event event for getting if checked or unchecked
179
   */
180
  addSensorToGraph(sensorId: string, event) {
181
    const groupId = sensorId.toString().slice(0, 5);
182
    const sensorGroupElement = '#vega_container_' + groupId;
183
    if (!this.selectedSensors.find(sensId => sensId.toString().slice(0, 5) === groupId)) { // if group of sensors is empty show empty graph
184
      // GraphLoader.getAnalyticsGraph(null, null, null, sensorGroupElement);
185
      GraphLoader.getGraph(null, null, null, sensorGroupElement, null);
186
    } else {
187
      if (this.useAnalyticsData) { // use analytics data
188
        if (event.checked) { // if checked > add to graph
189
          if (this.analyticsData.some(sens => sens.sensorId === sensorId)) { // if already data for selected sensor in memory
190
            // GraphLoader.getAnalyticsGraph(sensorId, this.analyticsData.find(sens => sens.sensorId === sensorId).data,
191
            // this.analyticsData.find((sens => sens.sensorId === sensorId).interval, sensorGroupElement);
192
            GraphLoader.getGraph(this.selectedSensors, this.analyticsData, this.filteredSensorsInfos(groupId), sensorGroupElement, true);
193

    
194
          } else { // get data from server for added sensor and show graph for selected sensors
195
            this.showGraph(false, sensorId);
196
          }
197
        } else { // remove sensor from graph
198
          // GraphLoader.getAnalyticsGraph(sensorId, this.analyticsData.find(sens => sens.sensorId === sensorId).data,
199
          // this.analyticsData.find(sens => sens.sensorId === sensorId).interval, sensorGroupElement);
200
          GraphLoader.getGraph(this.selectedSensors, this.analyticsData, this.filteredSensorsInfos(groupId), sensorGroupElement, true);
201

    
202
        }
203
      } else { // use observations data
204
        if (event.checked) { // if checked > add to graph
205
          if (this.observationsData.some(sens => sens.sensorId.toString() === sensorId)) { // if already data for selected sensor in memory
206
            GraphLoader.getGraph(this.filteredSelectedSensors(groupId), this.filteredObservationData(groupId),
207
              this.filteredSensorsInfos(groupId), sensorGroupElement, false);
208
            // GraphLoader.getMultilineGraph(this.selectedSensors, this.filteredObservationData(groupId), sensorGroupElement)
209
          } else { // get data from server for added sensor and show graph for selected sensors
210
            this.showGraph(false, sensorId);
211
          }
212
        } else { // remove sensor from graph
213
          // GraphLoader.getMultilineGraph(this.selectedSensors, this.filteredObservationData(groupId), sensorGroupElement)
214
          GraphLoader.getGraph(this.filteredSelectedSensors(groupId), this.filteredObservationData(groupId),
215
            this.filteredSensorsInfos(groupId), sensorGroupElement, false);
216

    
217
        }
218
      }
219
    }
220
  }
221

    
222
  /**
223
   * Filter observations data only fro selected sensors.
224
   * @param sensorGroupId id of changed sensor group
225
   */
226
  filteredObservationData(sensorGroupId: string): any {
227
    return this.observationsData.filter(sen => this.selectedSensors.includes(sen.sensorId.toString()) &&
228
      sen.sensorId.toString().slice(0, 5) === sensorGroupId);
229
  }
230

    
231
  /**
232
   * Filter analytics data only fro selected sensors.
233
   */
234
  filteredAnalyticsData(sensorGroupId: string): any {
235
    return this.analyticsData.filter(sen => this.selectedSensors.includes(sen.sensorId.toString()) &&
236
      sen.sensorId.toString().slice(0, 5) === sensorGroupId);
237
  }
238

    
239

    
240
  filteredSelectedSensors(sensorGroupId: string): any {
241
    return this.selectedSensors.filter(sen => sen.toString().slice(0, 5) === sensorGroupId );
242
  }
243

    
244
  filteredSensorsInfos(sensorGroupId: string): any {
245
    return this.sensors.filter(sen => this.selectedSensors.includes(sen.sensorId.toString()) &&
246
      sen.sensorId.toString().slice(0, 5) === sensorGroupId);
247
  }
248

    
249
  private getObservations(range: Date[], changedDate: boolean, changedSensorId: string) {
250
    const groupId = changedSensorId.toString().slice(0, 5);
251
    if (changedDate) { // if changed date we need new data for all sensors
252
      this.observationsData = []; // empty observation data
253
      this.selectedSensors.forEach(selectSens => {
254
        this.observationService.getObservation$Response({
255
          unit_id: this.unitId,
256
          sensor_id: parseInt(selectSens, 10),
257
          from: moment(range[0]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3),
258
          to: moment(range[1]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3)
259
        }).pipe(
260
          map((response: HttpResponse<any>) => {
261
            if (response.status === 200) {
262
              return response.body;
263
            } else if (response.status === 204) {
264
              this.toastService.showWarningNoData();
265
              return response.body;
266
            } else {
267
              return false;
268
            }
269
          }),
270
          tap((observations) => {
271
            if (observations) {
272
              this.observationsData.push({sensorId: selectSens, sensor:
273
                this.sensors.find(sens => sens.sensorId.toString() === selectSens.toString()), data: observations});
274
            }
275
          }),
276
          tap(() => {
277
            if (this.observationsData && this.observationsData.length > 1) {
278
              const view = '#vega_container_' + selectSens.toString().slice(0, 5);
279
              setTimeout(() => {
280
                console.log(this.selectedSensors);
281
             // GraphLoader.getMultilineGraph(this.selectedSensors, this.filteredObservationData(selectSens.toString().slice(0, 5)), view);
282
                GraphLoader.getGraph(this.filteredSelectedSensors(groupId),  this.filteredObservationData(groupId),
283
                  this.filteredSensorsInfos(groupId), view, false);
284
              }, 10);
285
            }
286
          })
287
        ).toPromise().then().catch(err => this.toastService.showError(err));
288
      });
289
    } else {
290
      this.observationService.getObservation$Response({
291
        unit_id: this.unitId,
292
        sensor_id: parseInt(changedSensorId, 10),
293
        from: moment(range[0]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3),
294
        to: moment(range[1]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3)
295
      }).pipe(
296
        map((response: HttpResponse<any>) => {
297
          if (response.status === 200) {
298
            return response.body;
299
          } else if (response.status === 204) {
300
            this.toastService.showWarningNoData();
301
            return response.body;
302
          } else {
303
            return false;
304
          }
305
        })
306
      ).subscribe(
307
        observations => {
308
          this.observationsData.push({sensorId: changedSensorId, sensor:
309
              this.sensors.find(sens => sens.sensorId.toString() === changedSensorId.toString()), data: observations});
310
          const view = '#vega_container_' + changedSensorId.toString().slice(0, 5);
311
          GraphLoader.getGraph(this.filteredSelectedSensors(groupId),  this.filteredObservationData(groupId),
312
            this.filteredSensorsInfos(groupId), view, false);
313
        }, err => this.toastService.showError(err.error.message));
314
    }
315
  }
316
}
(3-3/3)