-
Notifications
You must be signed in to change notification settings - Fork 3
/
sammo.py
655 lines (573 loc) · 23.2 KB
/
sammo.py
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
# coding: utf8
__contact__ = "[email protected]"
__copyright__ = "Copyright (c) 2022 Hytech Imaging"
import os.path
import platform
from pathlib import Path
from typing import Optional
from datetime import datetime
from qgis.PyQt.QtCore import Qt, QUrl
from qgis.PyQt.QtGui import QKeySequence, QDesktopServices, QIcon
from qgis.PyQt.QtWidgets import QToolBar, QShortcut, QTableView, QAction
from qgis.core import (
QgsProject,
QgsPointXY,
QgsGeometry,
QgsExpression,
QgsApplication,
QgsFeatureRequest,
)
from .src.core.gps import SammoGpsReader
from .src.core.session import SammoSession
from .src.core.utils import shortcutCreation
from .src.core.thread_simu_gps import ThreadSimuGps
from .src.core.sound_recording_controller import (
RecordType,
SammoSoundRecordingController,
)
from .src.gui.save import SammoSaveAction
from .src.gui.table import SammoTableDock
from .src.gui.status import SammoStatusDock
from .src.gui.export import SammoExportAction
from .src.gui.session import SammoSessionAction
from .src.gui.simu_gps import SammoSimuGpsAction
from .src.gui.settings import SammoSettingsAction
from .src.gui.sightings import SammoSightingsAction
from .src.gui.environment import SammoEnvironmentAction
from .src.gui.attribute_table import SammoAttributeTable
from .src.gui.merge import SammoMergeAction, SammoMergeDialog
from .src.gui.followers import SammoFollowersAction, SammoFollowersTable
class Sammo:
def __init__(self, iface):
self.iface = iface
self.toolbar: QToolBar = self.iface.addToolBar("Sammo ToolBar")
self.toolbar.setObjectName("Sammo ToolBar")
self.filterExpr: str = "True"
self.gps_wait = False
self.loading = False
self.session = SammoSession()
self.sessionAction = self.createSessionAction()
self.settingsAction = self.createSettingsAction()
self.helpAction = self.createHelpAction()
self.toolbar.addSeparator()
self.saveAction = self.createSaveAction()
self.exportAction = self.createExportAction()
self.mergeAction = self.createMergeAction()
self.toolbar.addSeparator()
self.environmentAction = self.createEnvironmentAction()
self.sightingsAction = self.createSightingsAction()
self.followersAction = self.createFollowersAction()
(
self.simuGpsSerialAction,
self.threadSerialSimuGps,
) = self.createSimuGps(True)
self.simuGpsAction, self.threadSimuGps = self.createSimuGps(False)
self.soundRecordingController = self.createSoundRecordingController()
self.gpsReader = self.createGpsReader()
self.statusDock = SammoStatusDock(iface, self.session)
self.statusDock.recordInterrupted.connect(
self.soundRecordingController.interruptRecording
)
self.statusDock.activateGPS.connect(self.activateGPS)
self.tableDock = SammoTableDock(iface)
iface.projectRead.connect(self.onProjectLoaded)
iface.newProjectCreated.connect(self.onProjectLoaded)
self.initShortcuts()
QgsApplication.instance().focusChanged.connect(self.focusOn)
@property
def mainWindow(self):
return self.iface.mainWindow()
def setEnabled(self, status):
self.settingsAction.setEnabled(status)
self.exportAction.setEnabled(status)
self.statusDock.setEnabled(status)
self.environmentAction.setEnabled(status)
self.followersAction.setEnabled(status)
self.sightingsAction.setEnabled(status)
self.saveAction.setEnabled(status)
def createSoundRecordingController(self) -> SammoSoundRecordingController:
controller = SammoSoundRecordingController()
controller.onStopSoundRecordingForEventSignal.connect(
self.onStopSoundRecordingForEvent
)
controller.onSoundRecordingStatusChanged.connect(
self.onSoundRecordingStatusChanged
)
return controller
def createSimuGps(
self, serial: bool
) -> [SammoSimuGpsAction, ThreadSimuGps]:
if not os.environ.get("SAMMO_DEBUG"):
return [None, None]
button = SammoSimuGpsAction(self.mainWindow, self.toolbar, serial)
if serial:
button.onChangeSimuGpsStatusSignal.connect(
self.onChangeSimuGpsSerialStatus
)
else:
button.onChangeSimuGpsStatusSignal.connect(
self.onChangeSimuGpsStatus
)
if serial:
testFilePath = os.path.join(
self.pluginFolder(), "src", "core", "gps_serial_simu.csv"
)
else:
testFilePath = os.path.join(
self.pluginFolder(), "src", "core", "gps_simu.csv"
)
threadGps = ThreadSimuGps(self.session, testFilePath)
return [button, threadGps]
def createGpsReader(self) -> SammoGpsReader:
gps = SammoGpsReader()
gps.start()
return gps
def activateGPS(self) -> None:
self.saveAll()
reader = self.gpsReader
if (
os.environ.get("SAMMO_DEBUG")
and self.threadSerialSimuGps
and self.simuGpsSerialAction.button.isChecked()
):
reader = self.threadSerialSimuGps
elif (
os.environ.get("SAMMO_DEBUG")
and self.threadSimuGps
and self.simuGpsAction.button.isChecked()
):
reader = self.threadSimuGps
if reader.receivers(reader.frame):
reader.frame.disconnect(self.onGpsFrame)
self.statusDock.desactivateGPS()
elif not (reader.worker and reader.worker._gps):
self.iface.messageBar().pushCritical(
"No GPS detected", "retry later"
)
else:
reader.frame.connect(self.onGpsFrame)
self.saveAll()
def createSaveAction(self) -> SammoSaveAction:
button = SammoSaveAction(self.mainWindow, self.toolbar)
button.saveAction.triggered.connect(self.saveAll)
button.validateAction.triggered.connect(self.validate)
button.validateFilter.triggered.connect(self.filterTable)
button.dateFilter.triggered.connect(self.filterTable)
return button
def createExportAction(self) -> SammoExportAction:
button = SammoExportAction(self.mainWindow, self.toolbar, self.session)
return button
def createFollowersAction(self):
button = SammoFollowersAction(self.mainWindow, self.toolbar)
button.action.triggered.connect(self.onFollowersAction)
return button
def createSightingsAction(self) -> SammoSightingsAction:
button = SammoSightingsAction(self.mainWindow, self.toolbar)
button.triggered.connect(self.onSightingsAction)
return button
def createEnvironmentAction(self) -> SammoEnvironmentAction:
button = SammoEnvironmentAction(self.mainWindow, self.toolbar)
button.updateEnvironment.connect(self.onEnvironmentAction)
return button
def createSessionAction(self) -> SammoSessionAction:
button = SammoSessionAction(self.mainWindow, self.toolbar)
button.create.connect(self.onCreateSession)
return button
def createSettingsAction(self) -> SammoSettingsAction:
button = SammoSettingsAction(
self.mainWindow, self.toolbar, self.session
)
button.reloadTables.connect(self.reloadTables)
return button
def createHelpAction(self) -> QAction:
button = QAction(
QIcon((Path(__file__).parent / "images" / "help.png").as_posix()),
"Help",
)
button.setToolTip("Help")
button.triggered.connect(self.openHelp)
self.toolbar.addAction(button)
return button
def createMergeAction(self) -> SammoSessionAction:
button = SammoMergeAction(self.mainWindow, self.toolbar)
button.triggered.connect(self.onMergeAction)
return button
def initGui(self) -> None:
if platform.system() == "Windows":
self.shortcutAction = QAction("Create shorcuts")
self.shortcutAction.triggered.connect(shortcutCreation)
self.iface.addPluginToMenu("Sammo-Boat", self.shortcutAction)
self.csvInitAction = QAction("Open init data folder")
self.csvInitAction.triggered.connect(self.initDataFolder)
self.iface.addPluginToMenu("Sammo-Boat", self.csvInitAction)
def initDataFolder(self) -> None:
QDesktopServices.openUrl(
QUrl.fromLocalFile((Path(__file__).parent / "data").as_posix())
)
def initShortcuts(self) -> None:
self.environmentShortcut = QShortcut(
QKeySequence("Shift+E"), self.mainWindow
)
self.environmentShortcut.activated.connect(self.onEnvironmentAction)
self.followersShortcut = QShortcut(
QKeySequence("Shift+F"), self.mainWindow
)
self.followersShortcut.activated.connect(self.onFollowersAction)
self.sightingsShortcut = QShortcut(
QKeySequence("Space"), self.mainWindow
)
self.sightingsShortcut.activated.connect(self.onSightingsAction)
self.endSoundShortcut = QShortcut(
QKeySequence("Shift+A"), self.mainWindow
)
self.endSoundShortcut.activated.connect(
self.soundRecordingController.interruptRecording
)
# Avoid shorcut overload and recreate undo/redo shortcut
self.iface.mainWindow().findChild(QAction, "mActionUndo").setShortcut(
QKeySequence()
)
self.iface.mainWindow().findChild(QAction, "mActionRedo").setShortcut(
QKeySequence()
)
self.undoShortcut = QShortcut(QKeySequence("Ctrl+Z"), self.mainWindow)
self.undoShortcut.activated.connect(self.undo)
self.redoShortcut = QShortcut(
QKeySequence("Ctrl+Shift+Z"), self.mainWindow
)
self.redoShortcut.activated.connect(self.redo)
self.saveShortcut = QShortcut(QKeySequence("Shift+S"), self.mainWindow)
self.saveShortcut.activated.connect(self.saveAll)
self.zoomInShortcut = QShortcut(
QKeySequence("Ctrl+<"), self.mainWindow
)
self.zoomInShortcut.activated.connect(self.iface.mapCanvas().zoomIn)
self.zoomOutShortcut = QShortcut(
QKeySequence("Ctrl+>"), self.mainWindow
)
self.zoomOutShortcut.activated.connect(self.iface.mapCanvas().zoomOut)
def openHelp(self):
QDesktopServices.openUrl(
QUrl.fromLocalFile(
(
Path(__file__).parent
/ "doc"
/ "build"
/ "html"
/ "index.html"
).as_posix()
)
)
def unload(self):
self.activateGPS() # add End environment Status if needed
self.gpsReader.stop()
if self.threadSimuGps is not None and self.threadSimuGps.isProceeding:
self.threadSimuGps.stop()
if (
self.threadSerialSimuGps is not None
and self.threadSerialSimuGps.isProceeding
):
self.threadSerialSimuGps.stop()
self.soundRecordingController.interruptRecording()
self.soundRecordingController.unload()
self.sessionAction.unload()
self.followersAction.unload()
self.environmentAction.unload()
self.sightingsAction.unload()
if self.simuGpsAction is not None:
self.simuGpsSerialAction.unload()
self.simuGpsAction.unload()
self.statusDock.unload()
self.tableDock.unload()
del self.statusDock
del self.toolbar
def filterTable(self):
self.filterExpr = "True" # To keep advanced filter up in table dock
if self.saveAction.dateFilter.isChecked():
begin = datetime.combine(
datetime.now().date(), datetime.min.time()
)
after = datetime.combine(
datetime.now().date(), datetime.max.time()
)
self.filterExpr += (
" and datetime > to_datetime("
f"'{begin.isoformat()}') and "
"datetime < to_datetime("
f"'{after.isoformat()}')"
)
if self.saveAction.validateFilter.isChecked():
self.filterExpr += " and validated is False"
self.tableDock.refresh(
self.session.environmentLayer, self.filterExpr, False
)
self.tableDock.refresh(
self.session.sightingsLayer, self.filterExpr, False
)
def saveAll(self) -> None:
self.session.saveAll()
def validate(self) -> None:
self.session.validate()
self.session.saveAll()
self.tableDock.refresh(
self.session.environmentLayer, self.filterExpr, False
)
self.tableDock.refresh(
self.session.sightingsLayer, self.filterExpr, False
)
def onGpsFrame(
self,
longitude: float,
latitude: float,
h: int,
m: int,
s: int,
speed: float = -9999.0,
course: float = -9999.0,
) -> None:
updated = True
now = datetime.now()
gpsNow = datetime(now.year, now.month, now.day, h, m, s)
if self.session.lastGpsInfo["datetime"] == gpsNow and (
speed != -9999.0 or course != -9999.0
):
# a GPRMC frame is coming after a GPGGA frame with the same
# datetime but speed/course are valid
self.session.lastGpsInfo["gprmc"]["speed"] = speed
self.session.lastGpsInfo["gprmc"]["course"] = course
self.session.lastGpsInfo["gprmc"]["datetime"] = now
elif self.session.lastGpsInfo["datetime"] != gpsNow:
# a newer GPRMC/GPGGA frame is coming
self.session.lastGpsInfo["geometry"] = QgsGeometry.fromPointXY(
QgsPointXY(longitude, latitude)
)
self.session.lastGpsInfo["datetime"] = gpsNow
if (
speed != -9999.0
or course != -9999.0
or (
gpsNow - self.session.lastGpsInfo["gprmc"]["datetime"]
).total_seconds()
> 59
):
self.session.lastGpsInfo["gprmc"]["speed"] = speed
self.session.lastGpsInfo["gprmc"]["course"] = course
self.session.lastGpsInfo["gprmc"]["datetime"] = now
else:
# we don't need to update GPS info in status panel (offline status
# is managed internally by the panel)
updated = False
if (
not self.session.lastCaptureTime
or (gpsNow - self.session.lastCaptureTime).total_seconds() > 59
):
# Wait for one more frame in case we retrieve the speed/course at
# the next frame. Worst case scenario: we lose 1 frame in database
if (
self.session.lastGpsInfo["gprmc"]["speed"] == -9999.0
and self.session.lastGpsInfo["gprmc"]["course"] == -9999.0
):
# False -> True: speed/course are invalid so we want to wait 1
# more frame
# True -> False: speed/course are invalid but we already waited
# for another frame.
self.gps_wait = not self.gps_wait
else:
# speed/course are valid so we don't need to wait for another
# frame to come
self.gps_wait = False
# we udpate the database if we don't need to wait for speed/course
if not self.gps_wait:
self.session.addGps(
longitude,
latitude,
h,
m,
s,
self.session.lastGpsInfo["gprmc"]["speed"],
self.session.lastGpsInfo["gprmc"]["course"],
)
self.session.lastCaptureTime = gpsNow
# Panel status is updated only if neccessary. This check is necessary
# because if we receive a GPGGA after a GPRMC for the same datetime,
# then speed/course are not valid in this call (so we don't want to
# update the panel).
if updated:
self.iface.mapCanvas().setCenter(QgsPointXY(longitude, latitude))
self.statusDock.updateGpsInfo(
longitude,
latitude,
self.session.lastGpsInfo["gprmc"]["speed"],
self.session.lastGpsInfo["gprmc"]["course"],
)
def onCreateSession(self, sessionDirectory: str) -> None:
# init session
self.loading = True
QgsProject.instance().clear()
self.tableDock.clean()
self.session.init(sessionDirectory)
self.session.saveAll()
self.loading = False
self.gpsReader.active = True
self.setEnabled(True)
self.soundRecordingController.onNewSession(sessionDirectory)
self.tableDock.init(
self.session.environmentLayer, self.session.sightingsLayer
)
self.exportAction.session = self.session
QgsProject.instance().layerWillBeRemoved.connect(self.cleanTableDock)
# init simu
if self.simuGpsAction:
self.simuGpsSerialAction.onNewSession()
self.simuGpsAction.onNewSession()
def cleanTableDock(self, layerId):
if (
self.session.environmentLayer
and layerId == self.session.environmentLayer.id()
):
self.tableDock.removeTable(self.session.environmentLayer.name())
elif (
self.session.sightingsLayer
and layerId == self.session.sightingsLayer.id()
):
self.tableDock.removeTable(self.session.sightingsLayer.name())
def reloadTables(self) -> None:
self.tableDock.clean()
self.tableDock.init(
self.session.environmentLayer, self.session.sightingsLayer
)
def focusOn(self, old, new) -> None:
# Set the active on attribute table focus, to use undo/redo action
if not new:
return
if self.tableDock.widget():
tables = self.tableDock.widget().tables
if (
"Environment" in tables
and new
== self.tableDock.widget()
.tables["Environment"]
.findChild(QTableView, "mTableView")
):
self.iface.setActiveLayer(self.session.environmentLayer)
elif (
"Sightings" in tables
and new
== self.tableDock.widget()
.tables["Sightings"]
.findChild(QTableView, "mTableView")
):
self.iface.setActiveLayer(self.session.sightingsLayer)
def undo(self):
self.iface.activeLayer().undoStack().undo()
def redo(self):
self.iface.activeLayer().undoStack().redo()
def onMergeAction(self) -> None:
self.mergeDialog = SammoMergeDialog()
self.mergeDialog.mergeEnded.connect(self.onCreateSession)
self.mergeDialog.show()
def onEnvironmentAction(self) -> None:
self.soundRecordingController.onStartEnvironment()
self.iface.mapCanvas().setFocus()
layer = self.session.addEnvironmentFeature()
self.tableDock.refresh(layer, self.filterExpr)
self.soundRecordingController.onStopEventWhichNeedSoundRecord(60)
def onSightingsAction(self):
self.soundRecordingController.onStartSightings()
self.iface.mapCanvas().setFocus()
layer = self.session.addSightingsFeature()
self.tableDock.refresh(layer, self.filterExpr)
self.soundRecordingController.onStopEventWhichNeedSoundRecord(60)
def onFollowersAction(self, validation: Optional[QAction] = None):
if validation == self.followersAction.followerTable:
table = SammoAttributeTable.attributeTable(
self.iface, self.session.followersLayer, self.filterExpr
)
table.setWindowFlags(
Qt.Window
| Qt.CustomizeWindowHint
| Qt.WindowTitleHint
| Qt.WindowCloseButtonHint
| Qt.WindowStaysOnTopHint
)
table.show()
return
self.soundRecordingController.onStartFollowers()
self.followersTable = SammoFollowersTable(
self.iface,
self.session.lastGpsInfo["geometry"],
self.session.followersLayer,
)
self.followersTable.addButton.clicked.connect(self.onFollowersAdd)
self.followersTable.okButton.clicked.connect(self.onFollowersOk)
self.followersTable.show()
self.followersAddShortcut = QShortcut(
QKeySequence("F"), self.followersTable
)
self.followersAddShortcut.activated.connect(self.onFollowersAdd)
def onFollowersOk(self):
self.session.saveAll()
self.followersTable.close()
self.soundRecordingController.onStopEventWhichNeedSoundRecord(0)
def onFollowersAdd(self):
self.session.addFollowersFeature(
self.followersTable.datetime,
self.followersTable.geom,
self.followersTable.focalId,
bool(self.followersTable.rowCount()),
)
self.followersTable.refresh()
def onChangeSimuGpsStatus(self, isOn: bool):
if isOn:
self.threadSimuGps.start()
else:
self.threadSimuGps.stop()
def onChangeSimuGpsSerialStatus(self, isOn: bool):
if isOn:
self.threadSerialSimuGps.start()
else:
self.threadSerialSimuGps.stop()
def onStopSoundRecordingForEvent(
self,
recordType: RecordType,
soundFile: str,
soundStart: str,
soundEnd: str,
) -> None:
saveSound = False
# ok button from followers panel may be clicked without actually adding
# features
if recordType == RecordType.FOLLOWERS:
lastDatetime = self.followersTable.datetime
expr = QgsExpression(f"epoch(dateTime) = epoch('{lastDatetime}')")
request = QgsFeatureRequest(expr)
for fet in self.session.followersLayer.getFeatures(request):
saveSound = True
break
else:
saveSound = True
# saveSound information if necessary
if saveSound:
self.session.onStopSoundRecordingForEvent(
recordType, soundFile, soundStart, soundEnd
)
def onSoundRecordingStatusChanged(self, isOn: bool):
self.statusDock.isSoundRecordingOn = isOn
def onProjectLoaded(self) -> None:
if self.loading:
return
self.gpsReader.active = False
self.setEnabled(False)
sessionDir = SammoSession.sessionDirectory(QgsProject.instance())
if not sessionDir:
self.soundRecordingController.interruptRecording()
self.soundRecordingController.unload()
self.session = SammoSession()
self.statusDock.session = self.session
self.settingsAction.session = self.session
self.tableDock.clean()
return
self.onCreateSession(sessionDir)
@staticmethod
def pluginFolder():
return os.path.abspath(os.path.dirname(__file__))