Alejandro Acuña
2024-07-30 65a64a81d30f00f1fffd5da6866850e1308e1135
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
package art.servers.gost.access.controller;
 
import art.library.interop.serialization.Serialization;
import art.library.model.devices.DeviceStatus;
import art.library.model.devices.gost.access.AccessEnforcement;
import art.library.model.devices.gost.access.AccessEnforcementInformation;
import art.library.model.devices.gost.access.types.AccessEnforcement_Detection;
import art.library.model.devices.gost.access.types.AccessEnforcement_Detection_Image;
import art.library.model.devices.gost.access.types.AccessEnforcement_Detection_State;
import art.library.model.devices.gost.access.types.AccessEnforcement_Detection_State_Discarded;
import art.library.model.devices.gost.access.types.AccessEnforcement_Detection_State_Vehicle;
import art.servers.gost.access.Shared;
import art.servers.gost.access.configuration.Configuration;
import art.servers.gost.access.configuration.ConfigurationDetail;
import art.servers.gost.access.types.DatabasePoolConnection;
import art.servers.gost.access.utils.OSD;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
 
 
public class Controller_ACCESS_QuercusSpeed_Oviedo extends Controller_ACCESS
{
    private ConfigurationDetail configuration = null;
 
    
    
    public Controller_ACCESS_QuercusSpeed_Oviedo(AccessEnforcement access, DatabasePoolConnection database)
    {
        super(access, database);
        this.configuration =  ((Configuration)Shared.configuration).detail;
        this.setName(Shared.getMessage("Controller access") + " " + access.information.name);
    }
 
 
    public AccessEnforcement getAccessEnforcement()
    {
        return (AccessEnforcement)getDevice();
    }
 
 
        
    public void run()
    {
        Shared.traceInformation(getName(),Shared.getMessage("Starting"));
 
        initialise();
        
        // Status
        {
            AccessEnforcement access = getAccessEnforcement();
            AccessEnforcement clon = Serialization.clone(access);
            clon.getDeviceStatus().status = DeviceStatus.STATUS_ONLINE;
            clon.getDeviceAlarms().clear();
            Shared.model.updateDevice(access, clon);
        }
 
        
        while ((isInterrupted() == false) && (exit == false))
        {
            long lastTimestampUpdate = System.currentTimeMillis();
            
            try
            {
                if (Shared.isServerEnabled() == true)
                {
                     update();
                }
            }
            catch (Exception exception)
            {
            }
 
            AccessEnforcement red = getAccessEnforcement();
            long timetowait = (red.getDeviceInformation().polling * 1000) - (System.currentTimeMillis() - lastTimestampUpdate);
            timetowait = Math.min(timetowait, red.getDeviceInformation().polling * 1000);
 
            if (timetowait > 0)
            {
                try
                {
                    sleep(timetowait);
                }
                catch (Exception e)
                {
                }
            }
 
            if (Shared.model.existsDevice(getAccessEnforcement().getIdentifier()) == false)
            {
                Shared.traceInformation(getName(),Shared.getMessage("Device no longer exists"));
                exit = true;
            }
        }
 
        
        Shared.traceInformation(getName(),Shared.getMessage("Finishing"));
    }
 
 
 
    
    
    
   // <editor-fold defaultstate="collapsed" desc="Download and update detections">
    
    
    
    private void update()
    {
        AccessEnforcement access = getAccessEnforcement();
        AccessEnforcementInformation information = access.getDeviceInformation();
        
        try
        {
            // Read files
            
            File rootFolder = new File(information.oviedo.detectionsFolder);
            
            if (rootFolder.exists() == true)
            {
                File folders[] = rootFolder.listFiles();
                
                // Wait all files to finish copy
 
                try
                {
                    sleep(60000);
                }
                catch (Exception exception)
                {
                }
                
                for (File folder : folders)
                {
                    if (folder.getName().indexOf(information.oviedo.identifier) == 0)
                    {
                        try 
                        { 
                            update(folder);
                        }
                        catch (Exception exception)
                        {
                        }
                    }
                }
            }
        }
        catch (Exception exception)
        {
            Shared.traceError(getName(),Shared.getMessage("Update"), exception);
        }
    }
    
    
    
    private void update(File folder)
    {
        SimpleDateFormat formato1 = new SimpleDateFormat(Shared.getMessage("ddMMyyyyHHmmss"));
        SimpleDateFormat formato2 = new SimpleDateFormat(Shared.getMessage("dd/MM/yyyy HH:mm:ss.SSS"));
 
        AccessEnforcement access = getAccessEnforcement();
        AccessEnforcementInformation information = access.getDeviceInformation();
        
        BufferedReader reader = null;
        
        int totalDetections = 0;
        int processedDetections = 0;
        
        try
        {
            File idx = getFile(folder, ".idx");
            File txt = getFile(folder, ".txt");
            reader = new BufferedReader(new FileReader(txt));
            String line = reader.readLine();
            while ((line != null) && (line.trim().length()> 0))
            {
                totalDetections = totalDetections + 1;
                String[] tokens = line.split("\\s+");
                
                try
                {
                    int number = Integer.parseInt(tokens[0]);
 
                    AccessEnforcement_Detection detection = new AccessEnforcement_Detection();
                    detection.states = new ArrayList<>();
                    detection.timestamp = formato1.parse(tokens[1]).getTime();
                    detection.device = information;
                    updateImages(detection, idx, number);
 
                    AccessEnforcement_Detection_State detectionState = new AccessEnforcement_Detection_State();
                    detectionState.vehicle = new AccessEnforcement_Detection_State_Vehicle();
                    detectionState.vehicle.plate = tokens[2].toUpperCase();
                    detectionState.vehicle.confidence = (float)Math.min(Integer.parseInt(tokens[3]), Integer.parseInt(tokens[4]));
 
                    if ((detection.images != null) && (detection.images.size() == information.oviedo.numberImages))
                    {
                        if (Shared.controllerDetections.hasPermission(detection, detectionState.vehicle.plate) != null)
                        {
                            detectionState.state = AccessEnforcement_Detection_State.STATE_DISCARDED;
                            detectionState.discarded = new AccessEnforcement_Detection_State_Discarded();
                            detectionState.discarded.code = AccessEnforcement_Detection_State_Discarded.DISCARDED_ALLOWED;
                            detectionState.discarded.timestamp = System.currentTimeMillis();
                            detectionState.discarded.user = Shared.getApplicationName();
                            Shared.printcorrect(getName(),Shared.getMessage("Successful (allowed), plate")  + " = " + detectionState.vehicle.plate + ", " + Shared.getMessage("date") + " = " + formato2.format(detection.timestamp));
                        }
                        else
                        {
                            detectionState.state = AccessEnforcement_Detection_State.STATE_REVISION_PENDING;
                            detectionState.timestamp = System.currentTimeMillis();
                            Shared.printcorrect(getName(),Shared.getMessage("Successful (revision pending), plate")  + " = " + detectionState.vehicle.plate + ", " + Shared.getMessage("date") + " = " + formato2.format(detection.timestamp));
                        }
                    }
                    else
                    {
                        detectionState.state = AccessEnforcement_Detection_State.STATE_DISCARDED;
                        detectionState.discarded = new AccessEnforcement_Detection_State_Discarded();
                        detectionState.discarded.code = AccessEnforcement_Detection_State_Discarded.DISCARDED_MISSING_PICTURES;
                        detectionState.discarded.timestamp = System.currentTimeMillis();
                        detectionState.discarded.description = detectionState.discarded.getDescription(detectionState.discarded.code);
                        // Shared.printerr(getName(),Shared.getMessage("Missing images, plate")  + " = " + detectionState.vehicle.plate + ", " + Shared.getMessage("date") + " = " + formato2.format(detection.timestamp));
                    }
 
                    detection.states.add(detectionState);
 
                    if (updateDatabaseDetection(information, detection) == 0)
                    {
                        Shared.printwarning(getName(),Shared.getMessage("Already imported, plate")  + " = " + detectionState.vehicle.plate + ", " + Shared.getMessage("date") + " = " + formato2.format(detection.timestamp));
                    }
 
                    processedDetections = processedDetections + 1;
                }   
                catch (NumberFormatException exception)
                {
                    // Error al leer la linea
 
                    Shared.printerr(getName(),Shared.getMessage("Line error")  + " = " + txt.getAbsolutePath() + ", '" + line + "'");
                    Shared.traceError(getName(),Shared.getMessage("Update"), folder.getAbsolutePath(), exception);
                }
                
                line = reader.readLine();
            }
            
            reader.close();
            
            if (totalDetections > 0)
            {
                String message = folder.getAbsolutePath() + " : " + processedDetections + " " + Shared.getMessage("of") + " " + totalDetections;
                Shared.traceInformation(getName(),Shared.getMessage("Update"), message);
                if (reader != null) reader.close();
                delete(folder);
            }
        }
        catch (Exception exception) 
        {
            try
            {
                if (reader != null) reader.close();
                File fileerror = new File(information.storage.errorFolder + "/" + folder.getName());
                fileerror.getParentFile().mkdirs();
                Files.move(folder.toPath(), fileerror.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }
            catch (Exception e)
            {
            }
                        
            Shared.traceError(getName(),Shared.getMessage("Update"), folder.getAbsolutePath(), exception);
 
        }
        finally 
        {
            try { if (reader != null) reader.close(); } catch (Exception exception) {};
        }
    }
    
    
    
    
    private void updateImages(AccessEnforcement_Detection detection, File idx, int number)
    {
        BufferedReader reader = null;
        
        AccessEnforcement access = getDevice();
                
        try
        {
            int currentOvreview = 0;
            reader = new BufferedReader(new FileReader(idx));
            String line = reader.readLine();
            while ((line != null) && (line.trim().length()> 0))
            {
                String[] tokens = line.split("\\s+");
 
                int detectionNumber = Integer.parseInt(tokens[1]);
                
                if (detectionNumber == number)
                {
                    int fileNumber = Integer.parseInt(tokens[0]);
                    int imageNumber = Integer.parseInt(tokens[2]);
                    int imageType = Integer.parseInt(tokens[3]);
                    AccessEnforcement_Detection_Image image = new AccessEnforcement_Detection_Image();
                    image.data = Files.readAllBytes(new File(idx.getParentFile().getAbsolutePath() + "/" + String.format("%07d", fileNumber) + ".jpg").toPath());
                    image.format = AccessEnforcement_Detection_Image.FORMAT_JPG;
                    
                    switch(imageType)
                    {
                        case 1: image.name = AccessEnforcement_Detection_Image.NAME_OVERVIEW + " " + (++currentOvreview);
                                OSD.osd(detection, image, access.getDeviceInformation().getOSD(image.name));
                                break;
                                 
                        case 2: image.name = AccessEnforcement_Detection_Image.NAME_PLATE;
                                OSD.osd(detection, image, access.getDeviceInformation().getOSD(image.name));
                                break;
 
                        case 3: image.name = AccessEnforcement_Detection_Image.NAME_PLATE_CLIP; 
                                break;
                    }
                    
                    if (detection.images == null)
                    {
                        detection.images = new ArrayList<AccessEnforcement_Detection_Image>();
                    }
                    
                    detection.images.add(image);
                }
                        
                line = reader.readLine();
            }
        } 
        catch (Exception exception) 
        {
            Shared.traceError(getName(),Shared.getMessage("Update images"), idx.getAbsolutePath(), exception);
        }        
        finally
        {
            try { if (reader != null) reader.close(); } catch (Exception exception) {};
        }
    }
    
        
        
    
    
    
    private File getFile(File folder, String extension) throws Exception
    {
        for (File file : folder.listFiles())
        {
            if (file.getName().toLowerCase().endsWith(extension) == true)
            {
                return file;
            }
        }
        
        throw new Exception(Shared.getMessage("File with extension does no exists") + " : " + extension);
    }
 
    
    
    
    
}