Projekt

Obecné

Profil

Stáhnout (12.3 KB) Statistiky
| Větev: | Tag: | Revize:
1
import {Component, OnDestroy, 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
import {SensorType} from '../../shared/api/endpoints/models/sensor-type';
14
import {Subscription} from 'rxjs';
15

    
16

    
17
@Component({
18
  selector: 'app-unit',
19
  templateUrl: './unit.component.html',
20
  styleUrls: ['./unit.component.scss']
21
})
22
export class UnitComponent implements OnInit, OnDestroy {
23

    
24
  preselectedSensors: string;
25
  unitId: number;
26
  viewCount = 0;
27
  data = [];
28
  time = [];
29
  from: Date = moment().hour(0).minutes(0).subtract(7, 'days').toDate();
30
  to: Date = moment().toDate();
31
  today: Date = moment().toDate();
32
  analyticsData: any[] = [];
33
  observationsData: any[] = [];
34
  sensorGroups = [];
35
  selectedSensors: string[] = [];
36
  sensors: Sensor[];
37
  showAggregation = false;
38
  aggregationFunction: AggregationModel[];
39
  selectedAggregationFunction = 'DAY';
40
  useAnalyticsData = false;
41
  dateChanged = false;
42
  sensorTypes: SensorType[];
43
  unitDescription: string;
44
  subscription: Subscription[] = [];
45

    
46
  constructor(
47
    private activatedRoute: ActivatedRoute,
48
    private analyticsService: AnalyticsService,
49
    private sensorService: SensorsService,
50
    private toastService: ToastService,
51
    private observationService: ObservationService,
52
    private route: ActivatedRoute,
53
  ) {
54
    this.getInitData();
55
    // get unit sensors and prepare them for view
56
    this.sensorService.getUnitSensors({unit_id: this.unitId}).pipe(
57
      tap(sens => {
58
        this.sensors = sens;
59
        this.sensors.sort((a, b)  => a.sensorId - b.sensorId);
60
      }),
61
      tap(() => {
62
        if (this.sensors && this.sensors.length > 0) {
63
          this.sensors.forEach(sensor => {
64
            const sensorType = sensor.sensorId.toString().slice(0, 5);
65
            if (!this.sensorGroups.some(group => group === sensorType)) { // create sensor groups only for unit sensors
66
              this.sensorGroups.push(sensorType);
67
              setTimeout(() => {
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
  /**
78
   * Unsubscribe after leaving
79
   */
80
  ngOnDestroy(): void {
81
    this.subscription.forEach(subs => subs.unsubscribe());
82
  }
83

    
84
  /**
85
   * Sets up default data
86
   */
87
  getInitData() {
88
    this.route.queryParams.subscribe(params => {
89
      if(params.unitDescription)  {
90
        this.unitDescription = params.unitDescription;
91
      }
92
    });
93
    this.sensorService.getSensorTypes().toPromise().then(types => this.sensorTypes = types);
94
    this.unitId = parseInt(this.activatedRoute.snapshot.paramMap.get('unitId'), 10);
95
    this.aggregationFunction = [
96
      {name: 'Hour', code: 'HOUR'},
97
      {name: 'Day', code: 'DAY'},
98
      {name: 'Month', code: 'MONTH'},
99
      {name: 'Year', code: 'YEAR'}
100
    ];
101
  }
102

    
103
  ngOnInit(): void {
104
  }
105

    
106
  /**
107
   * Shows aggregation select box and get data button
108
   */
109
  aggregationShow() {
110
    this.dateChanged = true;
111
    this.showAggregation = moment(this.to).diff(moment(this.from), 'days') > 7;
112
  }
113

    
114
  /**
115
   * Gets data based on selected time range
116
   */
117
  showGraph(changedDate: boolean = true, changedSensor: string = null) {
118
    if (moment(this.to).diff(moment(this.from), 'days') > 7) {
119
      this.useAnalyticsData = true;
120
      this.showAggregation = true;
121
      const range: Date[] = [this.from, this.to];
122
      this.getAnalytics(range, changedDate, changedSensor);
123
    } else {
124
      this.useAnalyticsData = false;
125
      this.showAggregation = false;
126
      const range: Date[] = [this.from, this.to];
127
      this.getObservations(range, changedDate, changedSensor);
128
    }
129
  }
130

    
131
  /**
132
   * Gets data from analytics endpoint
133
   * @param range from and to interval
134
   * @param changedDate determines if dates changed so we need refresh all data
135
   * @param changedSensorId if selecting sensor only fetch data for this server
136
   */
137
  getAnalytics(range: Date[], changedDate: boolean, changedSensorId: string) {
138
    if (changedDate) { // if changed date we need new data for all sensors
139
      this.selectedSensors.forEach(selectSens => {
140
        this.analyticsEndpointRequest(selectSens, range);
141
      });
142
    } else  { // add data for selected sensor
143
      this.analyticsEndpointRequest(changedSensorId, range);
144
    }
145
  }
146

    
147
  /**
148
   * Endpoint request to get analytics data for sensor
149
   * @param sensorId sensor id to get data
150
   * @param range from and to interval
151
   */
152
  analyticsEndpointRequest(sensorId: string, range: Date[]) {
153
    this.analyticsService.getAnalytics$Response({unit_id: this.unitId, sensor_id: parseInt(sensorId, 10),
154
      from: moment(range[0]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3),
155
      to: moment(range[1]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3), interval: this.selectedAggregationFunction}).pipe(
156
      map((response: HttpResponse<any>) => {
157
        if (response.status === 200) {
158
          return response.body;
159
        } else if (response.status === 204) {
160
          this.toastService.showWarningNoData();
161
          return response.body;
162
        } else {
163
          return false;
164
        }
165
      })
166
    ).subscribe(data => {
167
      if (data) {
168
        this.analyticsData.push({sensorId, data: data[sensorId].data, interval: data[sensorId].interval});
169
        if (data[sensorId].data) {
170
          const groupId = sensorId.slice(0, 5);
171
          const view = '#vega_container_' + groupId;
172
          if (this.selectedSensors.some(sens => sens.toString() === sensorId)) {
173
            // GraphLoader.getAnalyticsGraph(key, data[key].data, data[key].interval, view);
174
            GraphLoader.getGraph(this.selectedSensors, this.analyticsData, this.filteredSensorsInfos(groupId), view, true);
175
          } else {
176
            // GraphLoader.getAnalyticsGraph(null, null, null, view);
177
            GraphLoader.getGraph(null, null, null, view, null);
178
          }
179
        }
180
      }
181
    }, err => this.toastService.showError(err.error.message));
182
  }
183

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

    
203
          } else { // get data from server for added sensor and show graph for selected sensors
204
            this.showGraph(false, sensorId);
205
          }
206
        } else { // remove sensor from graph
207
          // GraphLoader.getAnalyticsGraph(sensorId, this.analyticsData.find(sens => sens.sensorId === sensorId).data,
208
          // this.analyticsData.find(sens => sens.sensorId === sensorId).interval, sensorGroupElement);
209
          GraphLoader.getGraph(this.selectedSensors, this.analyticsData, this.filteredSensorsInfos(groupId), sensorGroupElement, true);
210

    
211
        }
212
      } else { // use observations data
213
        if (event.checked) { // if checked > add to graph
214
          if (this.observationsData.some(sens => sens.sensorId.toString() === sensorId)) { // if already data for selected sensor in memory
215
            GraphLoader.getGraph(this.filteredSelectedSensors(groupId), this.filteredObservationData(groupId),
216
              this.filteredSensorsInfos(groupId), sensorGroupElement, false);
217
          } else { // get data from server for added sensor and show graph for selected sensors
218
            this.showGraph(false, sensorId);
219
          }
220
        } else { // remove sensor from graph
221
            GraphLoader.getGraph(this.filteredSelectedSensors(groupId), this.filteredObservationData(groupId),
222
            this.filteredSensorsInfos(groupId), sensorGroupElement, false);
223
        }
224
      }
225
    }
226
  }
227

    
228
  /**
229
   * Filter observations data only fro selected sensors.
230
   * @param sensorGroupId id of changed sensor group
231
   */
232
  filteredObservationData(sensorGroupId: string): any {
233
    return this.observationsData.filter(sen => this.selectedSensors.includes(sen.sensorId.toString()) &&
234
      sen.sensorId.toString().slice(0, 5) === sensorGroupId);
235
  }
236

    
237
  /**
238
   * Filter analytics data only fro selected sensors.
239
   */
240
  filteredAnalyticsData(sensorGroupId: string): any {
241
    return this.analyticsData.filter(sen => this.selectedSensors.includes(sen.sensorId.toString()) &&
242
      sen.sensorId.toString().slice(0, 5) === sensorGroupId);
243
  }
244

    
245
  /**
246
   * Filter only selected sensors for group of sensors
247
   * @param sensorGroupId group of sensors
248
   */
249
  filteredSelectedSensors(sensorGroupId: string): any {
250
    return this.selectedSensors.filter(sen => sen.toString().slice(0, 5) === sensorGroupId);
251
  }
252

    
253
  /**
254
   * Get sensors only for group
255
   * @param sensorGroupId group id
256
   */
257
  filteredSensorsInfos(sensorGroupId: string): any {
258
    return this.sensors.filter(sen => this.selectedSensors.includes(sen.sensorId.toString()) &&
259
      sen.sensorId.toString().slice(0, 5) === sensorGroupId);
260
  }
261

    
262
  /**
263
   * Gets data from observation endpoint
264
   * @param range from and to interval
265
   * @param changedDate determines if dates changed so we need refresh all data
266
   * @param changedSensorId if selecting sensor only fetch data for this server
267
   */
268
  getObservations(range: Date[], changedDate: boolean, changedSensorId: string) {
269
    if (changedDate) { // if changed date we need new data for all sensors
270
      this.observationsData = []; // empty observation data
271
      this.selectedSensors.forEach(selectSens => {
272
        this.observationEndpointRequest(selectSens, range);
273
      });
274
    } else { // add data for added sensor
275
      this.observationEndpointRequest(changedSensorId, range);
276
    }
277
  }
278

    
279
  /**
280
   * Endpoint request to get observation data for sensor
281
   * @param sensorId sensor id to get data
282
   * @param range from and to interval
283
   */
284
  observationEndpointRequest(sensorId: string, range: Date[]) {
285
    this.observationService.getObservation$Response({
286
      unit_id: this.unitId,
287
      sensor_id: parseInt(sensorId, 10),
288
      from: moment(range[0]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3),
289
      to: moment(range[1]).format('yyyy-MM-DD HH:mm:ssZ').slice(0, -3)
290
    }).pipe(
291
      map((response: HttpResponse<any>) => {
292
        if (response.status === 200) {
293
          return response.body;
294
        } else if (response.status === 204) {
295
          this.toastService.showWarningNoData();
296
          return response.body;
297
        } else {
298
          return false;
299
        }
300
      })
301
    ).subscribe(
302
      observations => {
303
        if (observations) {
304
          const groupId = sensorId.toString().slice(0, 5);
305
          this.observationsData.push({
306
            sensorId, sensor:
307
              this.sensors.find(sens => sens.sensorId.toString() === sensorId.toString()), data: observations
308
          });
309
          const view = '#vega_container_' + sensorId.toString().slice(0, 5);
310
          GraphLoader.getGraph(this.filteredSelectedSensors(groupId), this.filteredObservationData(groupId),
311
            this.filteredSensorsInfos(groupId), view, false);
312
        }
313
      }, err => this.toastService.showError(err.error.message));
314
  }
315
}
(3-3/3)