-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathsocketMiddleware.js
More file actions
1678 lines (1520 loc) · 54.5 KB
/
socketMiddleware.js
File metadata and controls
1678 lines (1520 loc) · 54.5 KB
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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// this redux middleware intercepts all actions from the
// socket actions
import {
initSocket,
socketConnected,
socketDisconnected,
} from "../slices/socketSlice"
// drone actions
import {
ConnectionType,
emitConnectToDrone,
emitGetComPorts,
emitIsConnectedToDrone,
setComPorts,
setConnected,
setConnectedToSimulator,
setConnecting,
setConnectionModal,
setConnectionStatus,
setFetchingComPorts,
setForceArmModalOpened,
setForceDisarmModalOpened,
setSelectedComPorts,
} from "../slices/droneConnectionSlice"
import {
clearSimulationLoadingNotificationId,
setSimulationLoadingNotificationId,
setSimulationStatus,
SimulationStatus,
} from "../slices/simulationParamsSlice"
// socket factory
import { dataFormatters } from "../../helpers/dataFormatters.js"
import { isGlobalFrameHomeCommand } from "../../helpers/filterMissions.js"
import { FRAME_CLASS_MAP } from "../../helpers/mavlinkConstants.js"
import {
closeLoadingNotification,
redColor,
showErrorNotification,
showLoadingNotification,
showSuccessNotification,
showWarningNotification,
} from "../../helpers/notification.js"
import SocketFactory from "../../helpers/socket"
import {
emitGetFlightModeConfig,
emitGetGripperConfig,
setChannelsConfig,
setCurrentPwmValue,
setFailsafeConfig,
setFlightModeChannel,
setFlightModesList,
setFrameClass,
setFrameTypeDirection,
setFrameTypeName,
setFrameTypeOrder,
setGetGripperEnabled,
setGripperConfig,
setNumberOfMotors,
setRadioCalibrationModalOpen,
setRadioPwmChannels,
setRefreshingFailsafeConfigData,
setRefreshingFlightModeData,
setRefreshingGripperConfigData,
setSerialPortsConfig,
setServoConfig,
setServoPwmOutputs,
setShowMotorTestWarningModal,
updateChannelsConfigParam,
updateFailsafeConfigParam,
updateGripperConfigParam,
updateSerialPortConfigParam,
updateServoConfigParam,
} from "../slices/configSlice.js"
import {
appendToGpsTrack,
calculateGpsTrackHeadingThunk,
resetGpsTrack,
setAttitudeData,
setBatteryData,
setDroneAircraftType,
setEkfStatusReportData,
setEscTelemetryData,
setFlightSwVersion,
setGps2RawIntData,
setGpsData,
setGpsRawIntData,
setGuidedModePinData,
setHasEverHadGpsFix,
setHeartbeatData,
setHomePosition,
setLastGraphMessage,
setLoiterRadius,
setNavControllerOutput,
setOnboardControlSensorsEnabled,
setOnboardControlSensorsHealth,
setRSSIData,
setSelectedDisplayTelemetry,
setTelemetryData,
setTotalTimeFlying,
setVibrationData,
} from "../slices/droneInfoSlice"
import {
addFiles,
resetFiles,
setIsReadingFile,
setLoadingListFiles,
setLogPath,
setReadFileData,
setReadFileProgress,
} from "../slices/ftpSlice.js"
import {
addIdToItem,
closeDashboardMissionFetchingNotificationNoSuccessThunk,
closeDashboardMissionFetchingNotificationThunk,
setCurrentMission,
setCurrentMissionItems,
setDrawingFenceItems,
setDrawingMissionItems,
setDrawingRallyItems,
setIsFetchingDashboardMission,
setMissionProgressData,
setMissionProgressModal,
setShouldFetchAllMissionsOnDashboard,
setTargetInfo,
setUnwrittenChanges,
setUpdatePlannedHomePositionFromLoadData,
setUpdatePlannedHomePositionFromLoadModal,
} from "../slices/missionSlice"
import {
emitRefreshParams,
resetParamsWriteProgressData,
setAutoPilotRebootModalOpen,
setFetchingParam,
setFetchingVars,
setFetchingVarsProgress,
setHasFetchedOnce,
setModifiedParams,
setParams,
setParamSearchValue,
setParamsFailedToWrite,
setParamsFailedToWriteModalOpen,
setParamsWriteProgressData,
setParamsWriteProgressModalOpen,
setRebootData,
setRebootPromptModalOpen,
setShownParams,
updateParamValue,
} from "../slices/paramsSlice.js"
import { pushMessage } from "../slices/statusTextSlice.js"
import { handleEmitters } from "./emitters.js"
const SocketEvents = Object.freeze({
Connect: "connect",
Disconnect: "disconnect",
isConnectedToDrone: "is_connected_to_drone",
listComPorts: "list_com_ports",
linkDebugStats: "link_debug_stats",
onSimulationResult: "simulation_result",
onSimulationLoading: "simulation_loading",
})
const DroneSpecificSocketEvents = Object.freeze({
onForwardingStatus: "forwarding_status",
onDroneError: "drone_error",
onArmDisarm: "arm_disarm",
onSetCurrentFlightMode: "set_current_flight_mode_result",
onNavResult: "nav_result",
onHomePositionResult: "home_position_result",
onIncomingMsg: "incoming_msg",
onNavRepositionResult: "nav_reposition_result",
onGetLoiterRadiusResult: "nav_get_loiter_radius_result",
onSetLoiterRadiusResult: "nav_set_loiter_radius_result",
})
const ParamSpecificSocketEvents = Object.freeze({
onRebootAutopilot: "reboot_autopilot",
onGetParamsResult: "get_params_result",
onParamRequestUpdate: "param_request_update",
onParamSetSuccess: "param_set_success",
onParamError: "params_error",
onExportParamsResult: "export_params_result",
onSetMultipleParamsProgress: "set_multiple_params_progress",
})
const MissionSpecificSocketEvents = Object.freeze({
onMissionControlResult: "mission_control_result",
onWriteMissionResult: "write_mission_result",
onImportMissionResult: "import_mission_result",
onExportMissionResult: "export_mission_result",
onCurrentMissionAll: "current_mission_all",
onCurrentMission: "current_mission",
onTargetInfo: "target_info",
onCurrentMissionProgress: "current_mission_progress",
})
const ConfigSpecificSocketEvents = Object.freeze({
onFailsafeConfig: "failsafe_config",
onGripperEnabled: "is_gripper_enabled",
onSetGripperEnabledResult: "set_gripper_enabled_result",
onSetGripperDisabledResult: "set_gripper_disabled_result",
onSetGripperResult: "set_gripper_result",
onGripperConfig: "gripper_config",
setGripperParamResult: "set_gripper_param_result",
setFailsafeParamResult: "set_failsafe_param_result",
onMotorTestResult: "motor_test_result",
onFlightModeConfig: "flight_mode_config",
onSetFlightModeResult: "set_flight_mode_result",
onSetFlightModeChannelResult: "set_flight_mode_channel_result",
onFrameTypeConfig: "frame_type_config",
onRcConfig: "rc_config",
onSetRcConfigResult: "set_rc_config_result",
onBatchSetRcConfigResult: "batch_set_rc_config_result",
onServoConfig: "servo_config",
onSetServoConfigResult: "set_servo_config_result",
onBatchSetServoConfigResult: "batch_set_servo_config_result",
onTestServoPwmResult: "test_servo_result",
onSerialPortsConfig: "serial_ports_config",
onSetSerialPortConfigResult: "set_serial_port_config_result",
onBatchSetSerialPortConfigResult: "batch_set_serial_port_config_result",
})
const FtpSpecificSocketEvents = Object.freeze({
onListFilesResult: "list_files_result",
onListLogFilesResult: "list_log_files_result",
onReadFileResult: "read_file_result",
onReadFileProgress: "read_file_progress",
})
const socketMiddleware = (store) => {
let socket
function handleRcChannels(msg) {
let chans = {}
const chanCount = msg.chancount || 16 // default to 16 channels if chancount is 0
for (let i = 1; i < chanCount + 1; i++) {
chans[i] = msg[`chan${i}_raw`]
}
store.dispatch(setRadioPwmChannels(chans))
}
function handleServoOutputRaw(msg) {
const outputs = {}
for (let i = 1; i <= 16; i++) {
const pwm = msg[`servo${i}_raw`]
if (typeof pwm === "number") outputs[i] = pwm
}
store.dispatch(setServoPwmOutputs(outputs))
}
function syncSingleParamInParamsSlice(paramId, value) {
if (!paramId || value === undefined) {
return
}
store.dispatch(
updateParamValue({
param_id: paramId,
param_value: value,
}),
)
}
function syncBatchParamsInParamsSlice(paramsList) {
if (!Array.isArray(paramsList) || paramsList.length === 0) {
return
}
for (const param of paramsList) {
const paramId = param?.param_id
const paramValue =
param?.param_value !== undefined ? param.param_value : param?.value
syncSingleParamInParamsSlice(paramId, paramValue)
}
}
const incomingMessageHandler = (msg) => {
switch (msg.mavpackettype) {
case "VFR_HUD":
store.dispatch(setTelemetryData(msg))
break
case "ATTITUDE":
store.dispatch(setAttitudeData(msg))
break
case "GLOBAL_POSITION_INT":
store.dispatch(setGpsData(msg))
store.dispatch(
appendToGpsTrack({
lat: msg.lat,
lon: msg.lon,
}),
)
store.dispatch(calculateGpsTrackHeadingThunk())
break
case "NAV_CONTROLLER_OUTPUT":
store.dispatch(setNavControllerOutput(msg))
break
case "HEARTBEAT":
store.dispatch(setHeartbeatData(msg))
break
case "STATUSTEXT":
store.dispatch(pushMessage(msg))
break
case "SYS_STATUS":
store.dispatch(
setOnboardControlSensorsEnabled(msg.onboard_control_sensors_enabled),
)
store.dispatch(
setOnboardControlSensorsHealth(msg.onboard_control_sensors_health),
)
break
case "GPS_RAW_INT": {
// MAVLink GPS_RAW_INT provides 'eph' (HDOP * 100).
const hdop = msg.eph != null ? msg.eph / 100.0 : null
store.dispatch(
setGpsRawIntData({
...msg,
hdop,
}),
)
store.dispatch(calculateGpsTrackHeadingThunk())
break
}
case "GPS2_RAW": {
// MAVLink GPS2_RAW provides 'eph' (HDOP * 100).
const hdop = msg.eph != null ? msg.eph / 100.0 : null
store.dispatch(
setGps2RawIntData({
...msg,
hdop,
}),
)
break
}
case "RC_CHANNELS":
// NOTE: UNABLE TO TEST IN SIMULATOR!
store.dispatch(setRSSIData(msg.rssi))
handleRcChannels(msg)
break
case "MISSION_CURRENT":
store.dispatch(setCurrentMission(msg))
break
case "BATTERY_STATUS":
store.dispatch(setBatteryData(msg))
break
case "EKF_STATUS_REPORT": {
const data = {
compass_variance: msg.compass_variance,
pos_horiz_variance: msg.pos_horiz_variance,
pos_vert_variance: msg.pos_vert_variance,
terrain_alt_variance: msg.terrain_alt_variance,
velocity_variance: msg.velocity_variance,
flags: msg.flags,
}
store.dispatch(setEkfStatusReportData(data))
window.ipcRenderer.invoke("app:update-ekf-status", data)
break
}
case "VIBRATION": {
const data = {
vibration_x: msg.vibration_x,
vibration_y: msg.vibration_y,
vibration_z: msg.vibration_z,
clipping_0: msg.clipping_0,
clipping_1: msg.clipping_1,
clipping_2: msg.clipping_2,
}
store.dispatch(setVibrationData(data))
window.ipcRenderer.invoke("app:update-vibe-status", data)
break
}
case "ESC_TELEMETRY_1_TO_4":
case "ESC_TELEMETRY_5_TO_8":
store.dispatch(setEscTelemetryData(msg))
break
case "SERVO_OUTPUT_RAW":
handleServoOutputRaw(msg)
break
}
}
return (next) => (action) => {
if (initSocket.match(action)) {
// client side execution
if (!socket && typeof window !== "undefined") {
socket = SocketFactory.create()
/*
========================
= UNDERLYING CONNECTION =
========================
*/
// handle socket connection events
// EXAMPLE SOCKET.ON EVENT
socket.socket.on(SocketEvents.Connect, () => {
// DISPATCH ALL ACTIONS HERE
// SINCE IT'S MIDDLEWARE, OTHER FUNCTIONS CAN ALSO BE CALLED
console.log(`Connected to socket from redux, ${socket.socket.id}`)
store.dispatch(socketConnected())
store.dispatch(emitIsConnectedToDrone())
})
socket.socket.on(SocketEvents.Disconnect, () => {
console.log(`Disconnected from socket via redux, ${socket.socket.id}`)
store.dispatch(socketDisconnected())
})
/*
====================
= DRONE CONNECTIONS =
====================
*/
socket.socket.on("connected", () => {
store.dispatch(setConnected(true))
})
socket.socket.on("disconnect", () => {
store.dispatch(setConnected(false))
store.dispatch(setConnecting(false))
store.dispatch(
closeDashboardMissionFetchingNotificationNoSuccessThunk(),
)
})
socket.socket.on("is_connected_to_drone", (msg) => {
if (msg) {
store.dispatch(setConnected(true))
} else {
store.dispatch(setConnected(false))
store.dispatch(setConnecting(false))
store.dispatch(emitGetComPorts())
}
})
socket.socket.on("reboot_connecting", () => {
store.dispatch(setConnecting(true))
})
// Fetch com ports and list them
socket.socket.on("list_com_ports", (msg) => {
store.dispatch(setFetchingComPorts(false))
store.dispatch(setComPorts(msg))
const possibleComPort = msg.find(
(port) =>
port.toLowerCase().includes("mavlink") ||
port.toLowerCase().includes("ardupilot"),
)
if (!store.getState().droneConnection.selected_com_ports) {
// If no com port is selected, select a possible mavlink/ardupilot port if it exists, otherwise select the first port
if (possibleComPort !== undefined) {
store.dispatch(setSelectedComPorts(possibleComPort))
} else if (msg.length > 0) {
store.dispatch(setSelectedComPorts(msg[0]))
}
}
})
// Flags that the drone is disconnected
socket.socket.on("disconnected_from_drone", () => {
store.dispatch(setConnected(false))
store.dispatch(setConnectedToSimulator(false))
store.dispatch(
setGpsData({
mavpackettype: "GLOBAL_POSITION_INT",
time_boot_ms: 0,
lat: 0,
lon: 0,
alt: 0,
relative_alt: 0,
vx: 0,
vy: 0,
vz: 0,
hdg: 0,
timestamp: 0,
}),
)
store.dispatch(
setHomePosition({
lat: 0,
lon: 0,
alt: 0,
}),
)
store.dispatch(resetGpsTrack())
store.dispatch(setIsFetchingDashboardMission(false))
store.dispatch(
closeDashboardMissionFetchingNotificationNoSuccessThunk(),
)
window.ipcRenderer.send("window:update-title", "FGCS")
})
// Flags an error with the com port
socket.socket.on("connection_error", (msg) => {
console.error("Connection error: " + msg.message)
showErrorNotification(msg.message)
store.dispatch(setConnecting(false))
store.dispatch(setConnected(false))
})
// Setting connection status
socket.socket.on("drone_connect_status", (msg) => {
store.dispatch(
setConnectionStatus({
message: msg.message,
sub_message: msg.sub_message || "",
progress: msg.progress,
}),
)
})
// Flags that the drone is connected
socket.socket.on("connected_to_drone", (msg) => {
store.dispatch(
setHomePosition({
lat: 0,
lon: 0,
alt: 0,
}),
)
store.dispatch(setDroneAircraftType(msg.aircraft_type)) // There are two aircraftTypes, make sure to not use FLA one haha :D
if (msg.aircraft_type !== 1 && msg.aircraft_type !== 2) {
showErrorNotification("Aircraft not of type quadcopter or plane")
}
store.dispatch(setFlightSwVersion(msg.flight_sw_version))
store.dispatch(setConnected(true))
store.dispatch(setConnecting(false))
store.dispatch(setConnectionModal(false))
store.dispatch(setGuidedModePinData({ lat: 0, lon: 0, alt: 0 }))
store.dispatch(setRebootData({}))
store.dispatch(setAutoPilotRebootModalOpen(false))
store.dispatch(setShouldFetchAllMissionsOnDashboard(true))
store.dispatch(setShowMotorTestWarningModal(true))
store.dispatch(resetGpsTrack())
store.dispatch(resetFiles())
store.dispatch(setIsReadingFile(false))
store.dispatch(setReadFileData(null))
store.dispatch(setTotalTimeFlying(0))
store.dispatch(setHasEverHadGpsFix(false))
store.dispatch(setIsFetchingDashboardMission(false))
})
socket.socket.on(ParamSpecificSocketEvents.onRebootAutopilot, (msg) => {
store.dispatch(setRebootData(msg))
if (msg.success) {
store.dispatch(setAutoPilotRebootModalOpen(false))
showSuccessNotification(msg.message)
store.dispatch(setRebootData({}))
} else {
store.dispatch(setConnecting(false))
}
})
// Simulation status messages
socket.socket.on(SocketEvents.onSimulationLoading, (msg) => {
const operationId = msg.operationId || "simulation-loading"
const state = store.getState()
const idsByOp =
state.simulationParams.loadingNotificationIdsByOperation
const existingId = idsByOp?.[operationId]
if (msg.loading) {
if (existingId != null) {
closeLoadingNotification(
existingId,
"Cancelled",
"Overwritten by new loading notification",
)
}
const id = showLoadingNotification(msg.title, msg.message)
store.dispatch(
setSimulationLoadingNotificationId({
operationId,
notificationId: id,
}),
)
} else {
if (existingId != null) {
closeLoadingNotification(
existingId,
msg.title,
msg.message,
msg.success === false ? { color: redColor } : {},
)
store.dispatch(
clearSimulationLoadingNotificationId({ operationId }),
)
}
}
})
// Simulation final messages
socket.socket.on(SocketEvents.onSimulationResult, (msg) => {
if (msg.running === true) {
store.dispatch(setSimulationStatus(SimulationStatus.Running))
} else if (msg.running === false) {
store.dispatch(setSimulationStatus(SimulationStatus.Idle))
}
// Else result does not change the status
msg.success
? showSuccessNotification(msg.message)
: showErrorNotification(msg.message)
if (msg.connect) {
const storeState = store.getState()
store.dispatch(setConnecting(true))
store.dispatch(
emitConnectToDrone({
port: `tcp:127.0.0.1:${msg.port}`,
baud: 115200,
connectionType: ConnectionType.Network,
forwardingAddress: storeState.droneConnection.forwardingAddress,
}),
)
store.dispatch(setConnectedToSimulator(true))
}
})
socket.socket.on("fetching_param", (msg) => {
store.dispatch(setFetchingParam(msg.message))
})
// Link stats
socket.socket.on(SocketEvents.linkDebugStats, (msg) => {
window.ipcRenderer.invoke("app:update-link-stats", msg)
})
/*
Telemetry Socket Connection Events
*/
socket.telemetrySocket.on("connect", () => {
console.log(
`Connected to telemetry socket: ${socket.telemetrySocket.id}`,
)
})
socket.telemetrySocket.on("disconnect", () => {
console.log(
`Disconnected from telemetry socket: ${socket.telemetrySocket.id}`,
)
})
// I don't understand whatsoever why this doesn't work with the standard
// on method.
socket.telemetrySocket.onAny((eventName, ...args) => {
if (eventName !== DroneSpecificSocketEvents.onIncomingMsg) {
return
}
const msg = args[0]
incomingMessageHandler(msg)
// Data points on dashboard, the below code updates the value in the store when a new message
// comes in in the type of specificData.
const packetType = msg.mavpackettype
const storeState = store.getState()
if (storeState !== undefined) {
const selectedDisplayTelemetry =
storeState.droneInfo.selectedDisplayTelemetry
let hasSelectedDisplayTelemetryChange = false
const updatedSelectedDisplayTelemetry =
selectedDisplayTelemetry.map((dataItem) => {
if (
typeof dataItem.currently_selected === "string" &&
dataItem.currently_selected.startsWith(packetType)
) {
const specificData = dataItem.currently_selected.split(".")[1]
if (Object.prototype.hasOwnProperty.call(msg, specificData)) {
const nextValue = msg[specificData]
if (dataItem.value !== nextValue) {
hasSelectedDisplayTelemetryChange = true
return { ...dataItem, value: nextValue }
}
}
}
return dataItem
})
if (hasSelectedDisplayTelemetryChange) {
store.dispatch(
setSelectedDisplayTelemetry(updatedSelectedDisplayTelemetry),
)
}
}
// Handle graph messages
function getGraphDataFromMessage(msg, targetMessageKey) {
const returnDataArray = []
// SAFETY: if storeState or selectedGraphs missing, bail cleanly
const selectedGraphs = storeState?.droneInfo?.graphs?.selectedGraphs
if (!selectedGraphs) return false
for (const graphKey in selectedGraphs) {
const messageKey = selectedGraphs[graphKey] // e.g. "ATTITUDE.yaw"
if (!messageKey) continue
// Safer than `includes` (prevents weird accidental matches)
if (!messageKey.startsWith(`${targetMessageKey}.`)) continue
const [, valueName] = messageKey.split(".")
const raw = msg?.[valueName]
// SAFETY: skip if value isn't present
if (raw === undefined || raw === null) continue
// Coerce to number if possible
const rawNum = Number(raw)
if (!Number.isFinite(rawNum)) continue
let formatted_value = rawNum
// Applying Data Formatters (guarded)
if (messageKey in dataFormatters) {
// formatter expects a string in your original code
formatted_value = dataFormatters[messageKey](rawNum.toFixed(3))
}
returnDataArray.push({
data: { x: Date.now(), y: formatted_value },
graphKey,
})
}
return returnDataArray.length ? returnDataArray : false
}
let graphData = false
try {
graphData = getGraphDataFromMessage(msg, msg.mavpackettype)
} catch (e) {
console.error("Graph extraction crashed:", e, {
mavpackettype: msg?.mavpackettype,
})
graphData = false
}
// keep existing tab behaviour
store.dispatch(setLastGraphMessage(graphData))
// forward to any open graph windows
if (graphData) {
window.ipcRenderer
.invoke("app:update-graph-windows", graphData)
.catch((e) => console.error("update-graph-windows failed:", e))
}
// Handle Flight Mode incoming data
if (
msg.mavpackettype === "RC_CHANNELS" &&
storeState.config.flightModeChannel !== "UNKNOWN"
) {
store.dispatch(
setCurrentPwmValue(
msg[`chan${storeState.config.flightModeChannel}_raw`],
),
)
}
})
socket.socket.on(
MissionSpecificSocketEvents.onImportMissionResult,
(msg) => {
if (msg.success) {
const storeState = store.getState()
if (msg.mission_type === "mission") {
const missionItemsWithIds = []
for (let missionItem of msg.items) {
missionItemsWithIds.push(addIdToItem(missionItem))
}
// Check if first item is a home location, then open modal to
// select whether to update planned home position
if (missionItemsWithIds.length > 0) {
const potentialHomeLocation = missionItemsWithIds[0]
const currentPlannedHomeLocation =
storeState.missionInfo.plannedHomePosition
// Check if the potential home location is different from the current planned home location
if (
isGlobalFrameHomeCommand(potentialHomeLocation) &&
(potentialHomeLocation.x !==
currentPlannedHomeLocation.lat ||
potentialHomeLocation.y !==
currentPlannedHomeLocation.lon ||
potentialHomeLocation.z !==
currentPlannedHomeLocation.alt)
) {
store.dispatch(
setUpdatePlannedHomePositionFromLoadData({
lat: potentialHomeLocation.x,
lon: potentialHomeLocation.y,
alt: potentialHomeLocation.z,
from: "file",
}),
)
store.dispatch(
setUpdatePlannedHomePositionFromLoadModal(true),
)
}
}
store.dispatch(setDrawingMissionItems(missionItemsWithIds))
store.dispatch(
setUnwrittenChanges({
...storeState.missionInfo.unwrittenChanges,
mission: true,
}),
)
} else if (msg.mission_type === "fence") {
const fenceItemsWithIds = []
for (let fence of msg.items) {
fenceItemsWithIds.push(addIdToItem(fence))
}
store.dispatch(setDrawingFenceItems(fenceItemsWithIds))
store.dispatch(
setUnwrittenChanges({
...storeState.missionInfo.unwrittenChanges,
fence: true,
}),
)
} else if (msg.mission_type === "rally") {
const rallyItemsWithIds = []
for (let rallyItem of msg.items) {
rallyItemsWithIds.push(addIdToItem(rallyItem))
}
store.dispatch(setDrawingRallyItems(rallyItemsWithIds))
store.dispatch(
setUnwrittenChanges({
...storeState.missionInfo.unwrittenChanges,
rally: true,
}),
)
}
showSuccessNotification(msg.message)
} else {
showErrorNotification(msg.message)
}
},
)
socket.socket.on(
MissionSpecificSocketEvents.onExportMissionResult,
(msg) => {
msg.success
? showSuccessNotification(msg.message)
: showErrorNotification(msg.message)
},
)
}
}
if (setConnected.match(action)) {
// Setup socket listeners on drone connection
if (action.payload) {
socket.socket.on(
DroneSpecificSocketEvents.onForwardingStatus,
(msg) => {
if (msg.success) {
showSuccessNotification(msg.message)
} else {
showErrorNotification(msg.message)
}
},
)
socket.socket.on(DroneSpecificSocketEvents.onDroneError, (msg) => {
showErrorNotification(msg.message)
})
socket.socket.on(DroneSpecificSocketEvents.onArmDisarm, (msg) => {
if (!msg.success) {
const offerForce = msg.data?.offer_force === true
// Check if this was a disarm attempt and was not a force disarm
if (msg.data?.was_disarming && !msg.data?.was_force && offerForce) {
store.dispatch(setForceDisarmModalOpened(true))
} else if (
!msg.data?.was_disarming &&
!msg.data?.was_force &&
offerForce
) {
// Failed non-force arm attempt — offer force arm
store.dispatch(setForceArmModalOpened(true))
} else {
showErrorNotification(msg.message)
}
}
})
socket.socket.on(
DroneSpecificSocketEvents.onSetCurrentFlightMode,
(msg) => {
msg.success
? showSuccessNotification(msg.message)
: showErrorNotification(msg.message)
},
)
socket.socket.on(DroneSpecificSocketEvents.onNavResult, (msg) => {
msg.success
? showSuccessNotification(msg.message)
: showErrorNotification(msg.message)
})
socket.socket.on(
DroneSpecificSocketEvents.onHomePositionResult,
(msg) => {
if (msg.success) {
store.dispatch(setHomePosition(msg.data)) // use actual home position
} else {
// If home position could not be fetched because GPS fix has never
// been acquired, we can ignore this message
if (msg.data === "NEVER_HAD_GPS_FIX") {
return
}
showErrorNotification(msg.message)
}
},
)
socket.socket.on(ParamSpecificSocketEvents.onGetParamsResult, (msg) => {
if (msg.success) {
store.dispatch(setParams(msg.data))
store.dispatch(setShownParams(msg.data))
}
store.dispatch(setHasFetchedOnce(true))
store.dispatch(setFetchingVars(false))
store.dispatch(setFetchingVarsProgress({ progress: 0, param_id: "" }))
store.dispatch(setParamSearchValue(""))
})
socket.socket.on(
ParamSpecificSocketEvents.onParamRequestUpdate,
(msg) => {
store.dispatch(
setFetchingVarsProgress({
progress:
(msg.current_param_index / msg.total_number_of_params) * 100,
param_id: msg.current_param_id,
}),
)
},
)
socket.socket.on(ParamSpecificSocketEvents.onParamSetSuccess, (msg) => {
const paramsSetSuccessfully = msg.data.params_set_successfully
const paramsNotSet = msg.data.params_could_not_set
if (paramsNotSet.length > 0 && paramsSetSuccessfully.length > 0) {
showWarningNotification(msg.message)
} else if (paramsNotSet.length > 0) {
showErrorNotification(msg.message)
} else {
showSuccessNotification(msg.message)
}
const modifiedParams = store.getState().paramsSlice.modifiedParams
// Only clear the params that got set successfully
store.dispatch(
setModifiedParams(
modifiedParams.filter(
(param) =>
!paramsSetSuccessfully.some(
(setParam) => setParam.param_id === param.param_id,
),
),
),
)
// Update the param in the params list also
for (let param of paramsSetSuccessfully) {
store.dispatch(updateParamValue(param))
}
store.dispatch(resetParamsWriteProgressData())
store.dispatch(setParamsWriteProgressModalOpen(false))
if (paramsNotSet.length !== 0) {
store.dispatch(setParamsFailedToWrite(paramsNotSet))
store.dispatch(setParamsFailedToWriteModalOpen(true))
}