Projekt

Obecné

Profil

Stáhnout (13.8 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), this.filteredSensorsInfos(groupId), sensorGroupElement, false);
207
            //GraphLoader.getMultilineGraph(this.selectedSensors, this.filteredObservationData(groupId), sensorGroupElement)
208
          } else { // get data from server for added sensor and show graph for selected sensors
209
            this.showGraph(false, sensorId);
210
          }
211
        } else { // remove sensor from graph
212
          //GraphLoader.getMultilineGraph(this.selectedSensors, this.filteredObservationData(groupId), sensorGroupElement)
213
          GraphLoader.getGraph(this.filteredSelectedSensors(groupId), this.filteredObservationData(groupId), this.filteredSensorsInfos(groupId), sensorGroupElement, false);
214

    
215
        }
216
      }
217
    }
218
  }
219

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

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

    
237

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

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

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

    
309
            GraphLoader.getGraph(this.filteredSelectedSensors(groupId),  this.filteredObservationData(groupId), this.filteredSensorsInfos(groupId), view, false);
310
        }, err => this.toastService.showError(err.error.message));
311
    }
312
  }
313
}
(3-3/3)