forked from o-gs/dji-firmware-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
comm_og_service_tool.py
executable file
·1734 lines (1390 loc) · 71.4 KB
/
comm_og_service_tool.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
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" OGs Service Tool for Dji products.
The script allows to trigger a few service functions of Dji drones.
"""
# Copyright (C) 2018 Mefistotelis <[email protected]>
# Copyright (C) 2018 Original Gangsters <https://dji-rev.slack.com/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
__version__ = "0.0.7"
__author__ = "Mefistotelis @ Original Gangsters"
__license__ = "GPL"
import sys
import time
import struct
import hashlib
import argparse
from ctypes import c_ubyte, sizeof
sys.path.insert(0, './')
from comm_serialtalk import (
do_send_request, do_receive_reply, SerialMock, open_usb
)
from comm_mkdupc import (
COMM_DEV_TYPE, PACKET_TYPE, ENCRYPT_TYPE, ACK_TYPE, CMD_SET_TYPE,
DecoratedEnum, PacketProperties, DJICmdV1Header,
get_known_payload, flyc_parameter_compute_hash,
)
import comm_mkdupc as dupc # for access to all the DJIPayload_* structs
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
class PRODUCT_CODE(DecoratedEnum):
A2 = 0 # Released 2013-09-04 A2 Flight Controller
P330 = 1 # Released 2013-01-07 Phantom 1
P330V = 2 # Released 2013-10-28 Phantom 2 Vision
P330Z = 3 # Released 2013-12-15 Phantom 2 w/ Zenmuse H3-2D
P330VP = 4 # Released 2014-04-07 Phantom 2 Vision+
WM610 = 5 # Released 2014-11-13 Inspire 1
P3X = 6 # Released 2015-03-09 Phantom 3 Professional
P3S = 7 # Released 2015-03-09 Phantom 3 Advanced
MAT100 = 8 # Released 2015-06-08 Matrice 100
P3C = 9 # Released 2015-08-04 Phantom 3 Standard
MG1 = 10 # Released 2015-11-27 Agras MG-1
WM325 = 11 # Released 2016-01-05 Phantom 3 4K
WM330 = 12 # Released 2016-03-02 Phantom 4 (now referenced as Phantom 4 Standard)
MAT600 = 13 # Released 2016-04-17 Matrice 600
WM220 = 14 # Released 2016-09-28 Mavic Pro (also includes Released 2017-08-24 Mavic Pro Platinum)
WM620 = 15 # Released 2016-11-16 Inspire 2
WM331 = 16 # Released 2016-11-16 Phantom 4 Pro
MAT200 = 17 # Released 2017-02-26 Matrice 200
MG1S = 18 # Released 2017-03-28 Agras MG-1S
WM332 = 19 # Released 2017-04-13 Phantom 4 Advanced
WM100 = 20 # Released 2017-05-24 Spark
WM230 = 21 # Released 2018-01-23 Mavic Air
WM335 = 22 # Released 2018-05-08 Phantom 4 Pro V2
WM240 = 23 # Released 2018-08-23 Mavic 2 Pro/Zoom
WM245 = 24 # Released 2018-10-29 Mavic 2 Enterprise
WM246 = 25 # Released 2018-12-20 Mavic 2 Enterprise Dual
WM160 = 26 # Released 2019-10-30 Mavic Mini
WM231 = 27 # Released 2020-04-28 Mavic Air 2
WM232 = 28 # Released 2021-04-15 (MAVIC) AIR 2S
WM260 = 29 # Released 2021-11-05 (MAVIC) 3
WM247 = 30 # Released 2020-12-15 Mavic 2 Enterprise Advanced
ALT_PRODUCT_CODE = {
'S800': 'A2', # Released 2012-07-25 Hexacopter frame, often sold with Dji A2 Flight Controller
'S1000': 'A2', # Released 2014-02-24 Octocopter frame, often sold with Dji A2 Flight Controller
'S900': 'A2', # Released 2014-08-04 Hexacopter frame, often sold with Dji A2 Flight Controller
'PH3PRO': 'P3X',
'PH3ADV': 'P3S',
'PH3STD': 'P3C',
'P3XW': 'WM325',
'P4': 'WM330',
'PH4': 'WM330',
'PH4PRO': 'WM331',
'PH4ADV': 'WM332',
'SPARK': 'WM100',
'MAVIC': 'WM220',
'MAVAIR': 'WM230',
'M2P': 'WM240',
'M2Z': 'WM240',
'M2E': 'WM245',
'M2ED': 'WM246',
'M2EA': 'WM247',
'MMINI': 'WM160',
'MAVAIR2': 'WM231',
'MAVAIR2S': 'WM232',
'MAV3': 'WM260',
}
class SERVICE_CMD(DecoratedEnum):
FlycParam = 0
GimbalCalib = 1
CameraCalib = 2
class FLYC_PARAM_CMD(DecoratedEnum):
LIST = 0
GET = 1
SET = 2
class GIMBAL_CALIB_CMD(DecoratedEnum):
JOINTCOARSE = 0
LINEARHALL = 1
class CAMERA_CALIB_CMD(DecoratedEnum):
ENCRYPTCHECK = 0
ENCRYPTPAIR = 1
class CAMERA_ENCRYPT_PAIR_TARGET(DecoratedEnum):
ALL = 0
CAMERA = 1
GIMBAL = 4
LB_DM3XX_SKY = 8
default_32byte_key = bytes([ # Default key
0x56, 0x79, 0x6C, 0x0E, 0xEE, 0x0F, 0x38, 0x05, 0x20, 0xE0, 0xBE, 0x70, 0xF2, 0x77, 0xD9, 0x0B,
0x30, 0x72, 0x31, 0x67, 0x31, 0x6E, 0x61, 0x6C, 0x47, 0x61, 0x6E, 0x39, 0x73, 0x74, 0x61, 0x60,
])
def detect_serial_port(po):
""" Detects the serial port device name of a Dji product.
"""
import serial.tools.list_ports
#TODO: detection unfinished
for comport in serial.tools.list_ports.comports():
print(comport.device)
return ''
def open_serial_port(po):
ser = None
if po.bulk:
ser = open_usb(po)
else:
# Open serial port
import serial
if po.port == 'auto':
port_name = detect_serial_port(po)
else:
port_name = po.port
if not po.dry_test:
ser = serial.Serial(port_name, baudrate=po.baudrate, timeout=0)
else:
ser = SerialMock(port_name, baudrate=po.baudrate, timeout=0)
if (po.verbose > 0):
print("Opened {} at {}".format(ser.port, ser.baudrate))
return ser
def get_unique_sequence_number(po):
""" Returns a sequence number for packet.
"""
# This will be unique as long as we do 10ms delay between packets
return int(time.time()*100) & 0xffff
def send_request_and_receive_reply(po, ser, receiver_type, receiver_index, ack_type, cmd_set, cmd_id, payload, seqnum_check=True, retry_num=3):
global last_seq_num
if 'last_seq_num' not in globals():
last_seq_num = get_unique_sequence_number(po)
pktprop = PacketProperties()
pktprop.sender_type = COMM_DEV_TYPE.PC
pktprop.sender_index = 0
pktprop.receiver_type = receiver_type
pktprop.receiver_index = receiver_index
pktprop.seq_num = last_seq_num
pktprop.pack_type = PACKET_TYPE.REQUEST
pktprop.ack_type = ack_type
pktprop.encrypt_type = ENCRYPT_TYPE.NO_ENC
pktprop.cmd_set = cmd_set
pktprop.cmd_id = cmd_id
if hasattr(payload, '__len__'):
pktprop.payload = (c_ubyte * len(payload)).from_buffer_copy(payload)
else:
pktprop.payload = (c_ubyte * sizeof(payload)).from_buffer_copy(payload)
for nretry in range(0, retry_num):
pktreq = do_send_request(po, ser, pktprop)
if pktprop.ack_type == ACK_TYPE.NO_ACK_NEEDED: # Only wait for response if it was requested
pktrpl = None
break
pktrpl = do_receive_reply(po, ser, pktreq,
seqnum_check=(seqnum_check and not po.dry_test))
if pktrpl is not None:
break
last_seq_num += 1
if (po.verbose > 1):
if pktrpl is not None:
print("Received response packet:")
else:
print("No response received.")
if (po.verbose > 0):
if pktrpl is not None:
print(' '.join('{:02x}'.format(x) for x in pktrpl))
return pktrpl, pktreq
def receive_reply_for_request(po, ser, pktreq, seqnum_check=True):
""" Receives and returns response for given request packet.
Does not send the request, just waits for response.
To be used in cases when a packet triggers multiple responses.
"""
pktrpl = do_receive_reply(po, ser, pktreq, seqnum_check=seqnum_check)
if (po.verbose > 1):
if pktrpl is not None:
print("Received response packet:")
else:
print("No response received.")
if (po.verbose > 0):
if pktrpl is not None:
print(' '.join('{:02x}'.format(x) for x in pktrpl))
return pktrpl
def flyc_request_assistant_unlock(po, ser, val):
if (po.verbose > 0):
print("Sending Assistant Unlock request.")
payload = dupc.DJIPayload_FlyController_AssistantUnlockRq()
payload.lock_state = val
if (po.verbose > 2):
print("Prepared request - {:s}:".format(type(payload).__name__))
print(payload)
if po.dry_test:
# use to test the code without a drone
ser.mock_data_for_read(bytes.fromhex("55 0e 04 66 03 0a 9d a5 80 03 df 00 a7 92"))
pktrpl, _ = send_request_and_receive_reply(po, ser,
COMM_DEV_TYPE.FLYCONTROLLER, 0,
ACK_TYPE.ACK_AFTER_EXEC,
CMD_SET_TYPE.FLYCONTROLLER, 0xdf,
payload)
if pktrpl is None:
raise ConnectionError("No response on Assistant Unlock request.")
rplhdr = DJICmdV1Header.from_buffer_copy(pktrpl)
rplpayload = get_known_payload(rplhdr, pktrpl[sizeof(DJICmdV1Header):-2])
if rplpayload is None:
raise ConnectionError("Unrecognized response to Assistant Unlock request.")
if (po.verbose > 2):
print("Parsed response - {:s}:".format(type(rplpayload).__name__))
print(rplpayload)
return rplpayload
def flyc_param_request_2017_get_table_attribs(po, ser, table_no):
payload = dupc.DJIPayload_FlyController_GetTblAttribute2017Rq()
payload.table_no = table_no
if (po.verbose > 2):
print("Prepared request - {:s}:".format(type(payload).__name__))
print(payload)
if po.dry_test:
# use to test the code without a drone
ser.mock_data_for_read(bytes.fromhex("55 19 04 e4 03 0a 9e a5 80 03 e0 00 00 00 00 2f 87 ca 7a 86 01 00 00 55 e7"))
ser.mock_data_for_read(bytes.fromhex("55 0f 04 a2 03 0a a0 a5 80 03 e0 09 00 17 f4"))
pktrpl, _ = send_request_and_receive_reply(po, ser,
COMM_DEV_TYPE.FLYCONTROLLER, 0,
ACK_TYPE.ACK_AFTER_EXEC,
CMD_SET_TYPE.FLYCONTROLLER, 0xe0,
payload)
if pktrpl is None:
raise ConnectionError("No response on get table attribs request.")
rplhdr = DJICmdV1Header.from_buffer_copy(pktrpl)
rplpayload = get_known_payload(rplhdr, pktrpl[sizeof(DJICmdV1Header):-2])
if (rplpayload is None):
raise LookupError("Unrecognized response to get table attribs request.")
if (po.verbose > 2):
print("Parsed response - {:s}:".format(type(rplpayload).__name__))
print(rplpayload)
return rplpayload
def flyc_param_request_2017_get_param_info_by_index(po, ser, table_no, param_idx):
payload = dupc.DJIPayload_FlyController_GetParamInfoByIndex2017Rq()
payload.table_no = table_no
payload.param_index = param_idx
if (po.verbose > 2):
print("Prepared request - {:s}:".format(type(payload).__name__))
print(payload)
if po.dry_test:
# use to test the code without a drone
ser.mock_data_for_read(bytes.fromhex("55 48 04 57 03 0a 1b 70 80 03 e1 00 00 00 00 82 "
"00 08 00 04 00 5c 8f da 40 0a d7 23 3c 00 00 c8 42 67 5f 63 6f 6e 66 69 67 2e 6d 72 5f 63 72 61 "
"66 74 2e 72 6f 74 6f 72 5f 36 5f 63 66 67 2e 74 68 72 75 73 74 00 8f a6"))
pktrpl, _ = send_request_and_receive_reply(po, ser,
COMM_DEV_TYPE.FLYCONTROLLER, 0,
ACK_TYPE.ACK_AFTER_EXEC,
CMD_SET_TYPE.FLYCONTROLLER, 0xe1,
payload)
if pktrpl is None:
raise ConnectionError("No response on parameter {:d} info by index request.".format(param_idx))
rplhdr = DJICmdV1Header.from_buffer_copy(pktrpl)
paraminfo = get_known_payload(rplhdr, pktrpl[sizeof(DJICmdV1Header):-2])
if (paraminfo is None):
raise ConnectionError("Unrecognized response to parameter {:d} info by index request.".format(param_idx))
if (po.verbose > 2):
print("Parsed response - {:s}:".format(type(paraminfo).__name__))
print(paraminfo)
return paraminfo
def flyc_param_request_2015_get_param_info_by_index(po, ser, param_idx):
payload = dupc.DJIPayload_FlyController_GetParamInfoByIndex2015Rq()
payload.param_index = param_idx
if (po.verbose > 2):
print("Prepared request - {:s}:".format(type(payload).__name__))
print(payload)
if po.dry_test:
# use to test the code without a drone
ser.mock_data_for_read(bytes.fromhex("55 2e 04 a7 03 0a 77 45 80 03 f0 00 0a 00 10 00 "
"00 00 00 00 00 00 00 00 00 00 00 00 00 00 67 6c 6f 62 61 6c 2e 73 74 61 74 75 73 00 79 ac"))
pktrpl, _ = send_request_and_receive_reply(po, ser,
COMM_DEV_TYPE.FLYCONTROLLER, 0,
ACK_TYPE.ACK_AFTER_EXEC,
CMD_SET_TYPE.FLYCONTROLLER, 0xf0,
payload)
if pktrpl is None:
raise ConnectionError("No response on parameter {:d} info by index request.".format(param_idx))
rplhdr = DJICmdV1Header.from_buffer_copy(pktrpl)
paraminfo = get_known_payload(rplhdr, pktrpl[sizeof(DJICmdV1Header):-2])
if (paraminfo is None):
raise ConnectionError("Unrecognized response to parameter {:d} info by index request.".format(param_idx))
if (po.verbose > 2):
print("Parsed response - {:s}:".format(type(paraminfo).__name__))
print(paraminfo)
return paraminfo
def flyc_param_request_2015_get_param_info_by_hash(po, ser, param_name):
payload = dupc.DJIPayload_FlyController_GetParamInfoByHash2015Rq()
payload.param_hash = flyc_parameter_compute_hash(po,param_name)
if (po.verbose > 2):
print("Prepared request - {:s}:".format(type(payload).__name__))
print(payload)
if po.dry_test:
# use to test the code without a drone
ser.mock_data_for_read(bytes.fromhex("55 43 04 74 03 0a ff 7c 80 03 f7 00 01 00 02 00 "
"0b 00 14 00 00 00 f4 01 00 00 78 00 00 00 67 5f 63 6f 6e 66 69 67 2e 66 6c 79 69 6e 67 5f 6c 69 "
"6d 69 74 2e 6d 61 78 5f 68 65 69 67 68 74 5f 30 00 5d 71"))
pktrpl, _ = send_request_and_receive_reply(po, ser,
COMM_DEV_TYPE.FLYCONTROLLER, 0,
ACK_TYPE.ACK_AFTER_EXEC,
CMD_SET_TYPE.FLYCONTROLLER, 0xf7,
payload)
if pktrpl is None:
raise ConnectionError("No response on parameter info by hash request.")
rplhdr = DJICmdV1Header.from_buffer_copy(pktrpl)
paraminfo = get_known_payload(rplhdr, pktrpl[sizeof(DJICmdV1Header):-2])
if (paraminfo is None):
raise LookupError("Unrecognized response to parameter info by hash request.")
if (po.verbose > 2):
print("Parsed response - {:s}:".format(type(paraminfo).__name__))
print(paraminfo)
return paraminfo
def flyc_param_request_2015_read_param_value_by_hash(po, ser, param_name):
payload = dupc.DJIPayload_FlyController_ReadParamValByHash2015Rq()
payload.param_hash = flyc_parameter_compute_hash(po,param_name)
if (po.verbose > 2):
print("Prepared request - {:s}:".format(type(payload).__name__))
print(payload)
if po.dry_test:
# use to test the code without a drone
ser.mock_data_for_read(bytes.fromhex("55 14 04 6d 03 0a 00 7d 80 03 f8 00 8a 23 71 03 f4 01 57 ee"))
pktrpl, _ = send_request_and_receive_reply(po, ser,
COMM_DEV_TYPE.FLYCONTROLLER, 0,
ACK_TYPE.ACK_AFTER_EXEC,
CMD_SET_TYPE.FLYCONTROLLER, 0xf8,
payload)
if pktrpl is None:
raise ConnectionError("No response on read parameter value by hash request.")
rplhdr = DJICmdV1Header.from_buffer_copy(pktrpl)
rplpayload = get_known_payload(rplhdr, pktrpl[sizeof(DJICmdV1Header):-2])
if (rplpayload is None):
raise LookupError("Unrecognized response to read parameter value by hash request.")
if sizeof(rplpayload) <= 4:
raise ValueError("Response indicates parameter does not exist or has no retrievable value.")
if (po.verbose > 2):
print("Parsed response - {:s}:".format(type(rplpayload).__name__))
print(rplpayload)
return rplpayload
def flyc_param_request_2017_read_param_value_by_index(po, ser, table_no, param_idx):
payload = dupc.DJIPayload_FlyController_ReadParamValByIndex2017Rq()
payload.table_no = table_no
payload.unknown1 = 1
payload.param_index = param_idx
if (po.verbose > 2):
print("Prepared request - {:s}:".format(type(payload).__name__))
print(payload)
if po.dry_test:
# use to test the code without a drone
ser.mock_data_for_read(bytes.fromhex("55 15 04 a9 03 0a 5a 6c 80 03 e2 00 00 00 00 9e 00 f4 01 10 b1"))
pktrpl, _ = send_request_and_receive_reply(po, ser,
COMM_DEV_TYPE.FLYCONTROLLER, 0,
ACK_TYPE.ACK_AFTER_EXEC,
CMD_SET_TYPE.FLYCONTROLLER, 0xe2,
payload)
if pktrpl is None:
raise ConnectionError("No response on parameter {:d} info by index request.".format(param_idx))
rplhdr = DJICmdV1Header.from_buffer_copy(pktrpl)
rplpayload = get_known_payload(rplhdr, pktrpl[sizeof(DJICmdV1Header):-2])
if (rplpayload is None):
raise ConnectionError("Unrecognized response to parameter {:d} info by index request.".format(param_idx))
if (po.verbose > 2):
print("Parsed response - {:s}:".format(type(rplpayload).__name__))
print(rplpayload)
return rplpayload
def do_assistant_unlock(po, ser):
try:
rplpayload = flyc_request_assistant_unlock(po, ser, 1)
if rplpayload.status != 0:
raise ValueError("Denial status {:d} returned from Assistant Unlock request.".format(rplpayload.status))
except Exception as ex:
if (po.verbose > 0):
print("Error: "+str(ex))
eprint("Assistant Unlock command failed; further commands may not work because of this.")
return False
return True
def flyc_param_request_2017_write_param_value_by_index(po, ser, table_no, param_idx, param_val):
if len(param_val) > 16:
payload = dupc.DJIPayload_FlyController_WriteParamValAnyByIndex2017Rq()
elif len(param_val) > 8:
payload = dupc.DJIPayload_FlyController_WriteParamVal16ByIndex2017Rq()
elif len(param_val) > 4:
payload = dupc.DJIPayload_FlyController_WriteParamVal8ByIndex2017Rq()
elif len(param_val) > 2:
payload = dupc.DJIPayload_FlyController_WriteParamVal4ByIndex2017Rq()
elif len(param_val) > 1:
payload = dupc.DJIPayload_FlyController_WriteParamVal2ByIndex2017Rq()
else:
payload = dupc.DJIPayload_FlyController_WriteParamVal1ByIndex2017Rq()
payload.table_no = table_no
payload.unknown1 = 1
payload.param_index = param_idx
if len(param_val) > 1:
payload.param_value = (c_ubyte * sizeof(payload.param_value)).from_buffer_copy(param_val)
else:
payload.param_value = (c_ubyte).from_buffer_copy(param_val)
if (po.verbose > 2):
print("Prepared request - {:s}:".format(type(payload).__name__))
print(payload)
if po.dry_test:
# use to test the code without a drone
ser.mock_data_for_read(bytes.fromhex("55 15 04 a9 03 0a 1a de 80 03 e3 00 00 00 00 9e 00 f3 01 a7 40"))
pktrpl, _ = send_request_and_receive_reply(po, ser,
COMM_DEV_TYPE.FLYCONTROLLER, 0,
ACK_TYPE.ACK_AFTER_EXEC,
CMD_SET_TYPE.FLYCONTROLLER, 0xe3,
payload)
if pktrpl is None:
raise ConnectionError("No response on write parameter value by index request.")
rplhdr = DJICmdV1Header.from_buffer_copy(pktrpl)
rplpayload = get_known_payload(rplhdr, pktrpl[sizeof(DJICmdV1Header):-2])
if (rplpayload is None):
raise LookupError("Unrecognized response to write parameter value by index request.")
if sizeof(rplpayload) <= 4:
raise ValueError("Response indicates parameter does not exist or is not writeable.")
if (po.verbose > 2):
print("Parsed response - {:s}:".format(type(rplpayload).__name__))
print(rplpayload)
return rplpayload
def flyc_param_request_2015_write_param_value_by_hash(po, ser, param_name, param_val):
if len(param_val) > 16:
payload = dupc.DJIPayload_FlyController_WriteParamValAnyByHash2015Rq()
elif len(param_val) > 8:
payload = dupc.DJIPayload_FlyController_WriteParamVal16ByHash2015Rq()
elif len(param_val) > 4:
payload = dupc.DJIPayload_FlyController_WriteParamVal8ByHash2015Rq()
elif len(param_val) > 2:
payload = dupc.DJIPayload_FlyController_WriteParamVal4ByHash2015Rq()
elif len(param_val) > 1:
payload = dupc.DJIPayload_FlyController_WriteParamVal2ByHash2015Rq()
else:
payload = dupc.DJIPayload_FlyController_WriteParamVal1ByHash2015Rq()
payload.param_hash = flyc_parameter_compute_hash(po, param_name)
payload.param_value = (c_ubyte * sizeof(payload.param_value)).from_buffer_copy(param_val)
if (po.verbose > 2):
print("Prepared request - {:s}:".format(type(payload).__name__))
print(payload)
if po.dry_test:
# use to test the code without a drone
ser.mock_data_for_read(bytes.fromhex("55 14 04 6d 03 0a 37 c6 80 03 f9 00 8a 23 71 03 f3 01 dd dd"))
pktrpl, _ = send_request_and_receive_reply(po, ser,
COMM_DEV_TYPE.FLYCONTROLLER, 0,
ACK_TYPE.ACK_AFTER_EXEC,
CMD_SET_TYPE.FLYCONTROLLER, 0xf9,
payload)
if pktrpl is None:
raise ConnectionError("No response on write parameter value by hash request.")
rplhdr = DJICmdV1Header.from_buffer_copy(pktrpl)
rplpayload = get_known_payload(rplhdr, pktrpl[sizeof(DJICmdV1Header):-2])
if (rplpayload is None):
raise LookupError("Unrecognized response to write parameter value by hash request.")
if sizeof(rplpayload) <= 4:
raise ValueError("Response indicates parameter does not exist or is not writeable.")
if (po.verbose > 2):
print("Parsed response - {:s}:".format(type(rplpayload).__name__))
print(rplpayload)
return rplpayload
def flyc_param_info_limits_to_str(po, paraminfo):
if (isinstance(paraminfo, dupc.DJIPayload_FlyController_GetParamInfoU2015Re) or
isinstance(paraminfo, dupc.DJIPayload_FlyController_GetParamInfoU2017Re)):
limit_min = '{:d}'.format(paraminfo.limit_min)
limit_max = '{:d}'.format(paraminfo.limit_max)
limit_def = '{:d}'.format(paraminfo.limit_def)
elif (isinstance(paraminfo, dupc.DJIPayload_FlyController_GetParamInfoI2015Re) or
isinstance(paraminfo, dupc.DJIPayload_FlyController_GetParamInfoI2017Re)):
limit_min = '{:d}'.format(paraminfo.limit_min)
limit_max = '{:d}'.format(paraminfo.limit_max)
limit_def = '{:d}'.format(paraminfo.limit_def)
elif (isinstance(paraminfo, dupc.DJIPayload_FlyController_GetParamInfoF2015Re) or
isinstance(paraminfo, dupc.DJIPayload_FlyController_GetParamInfoF2017Re)):
limit_min = '{:f}'.format(paraminfo.limit_min)
limit_max = '{:f}'.format(paraminfo.limit_max)
limit_def = '{:f}'.format(paraminfo.limit_def)
else:
limit_min = "n/a"
limit_max = "n/a"
limit_def = "n/a"
return (limit_min, limit_max, limit_def)
def flyc_param_value_to_str(po, paraminfo, param_value):
if (paraminfo.type_id == dupc.DJIPayload_FlyController_ParamType.ubyte.value):
param_bs = bytes(param_value[:1])
value_str = "{:d}".format(struct.unpack("<B", param_bs)[0])
elif (paraminfo.type_id == dupc.DJIPayload_FlyController_ParamType.ushort.value):
param_bs = bytes(param_value[:2])
value_str = "{:d}".format(struct.unpack("<H", param_bs)[0])
elif (paraminfo.type_id == dupc.DJIPayload_FlyController_ParamType.ulong.value):
param_bs = bytes(param_value[:4])
value_str = "{:d}".format(struct.unpack("<L", param_bs)[0])
elif (paraminfo.type_id == dupc.DJIPayload_FlyController_ParamType.ulonglong.value):
param_bs = bytes(param_value[:8])
value_str = "{:d}".format(struct.unpack("<Q", param_bs)[0])
elif (paraminfo.type_id == dupc.DJIPayload_FlyController_ParamType.byte.value):
param_bs = bytes(param_value[:1])
value_str = "{:d}".format(struct.unpack("<b", param_bs)[0])
elif (paraminfo.type_id == dupc.DJIPayload_FlyController_ParamType.short.value):
param_bs = bytes(param_value[:2])
value_str = "{:d}".format(struct.unpack("<h", param_bs)[0])
elif (paraminfo.type_id == dupc.DJIPayload_FlyController_ParamType.long.value):
param_bs = bytes(param_value[:4])
value_str = "{:d}".format(struct.unpack("<l", param_bs)[0])
elif (paraminfo.type_id == dupc.DJIPayload_FlyController_ParamType.longlong.value):
param_bs = bytes(param_value[:8])
value_str = "{:d}".format(struct.unpack("<q", param_bs)[0])
elif (paraminfo.type_id == dupc.DJIPayload_FlyController_ParamType.float.value):
param_bs = bytes(param_value[:4])
value_str = "{:f}".format(struct.unpack("<f", param_bs)[0])
elif (paraminfo.type_id == dupc.DJIPayload_FlyController_ParamType.double.value):
param_bs = bytes(param_value[:8])
value_str = "{:f}".format(struct.unpack("<d", param_bs)[0])
else: # array or future type
value_str = ' '.join('{:02x}'.format(x) for x in param_bs)
return value_str
def flyc_param_str_to_value(po, paraminfo, value_str):
if (paraminfo.type_id == dupc.DJIPayload_FlyController_ParamType.ubyte.value):
param_val = struct.pack("<B", int(value_str,0))
elif (paraminfo.type_id == dupc.DJIPayload_FlyController_ParamType.ushort.value):
param_val = struct.pack("<H", int(value_str,0))
elif (paraminfo.type_id == dupc.DJIPayload_FlyController_ParamType.ulong.value):
param_val = struct.pack("<L", int(value_str,0))
elif (paraminfo.type_id == dupc.DJIPayload_FlyController_ParamType.ulonglong.value):
param_val = struct.pack("<Q", int(value_str,0))
elif (paraminfo.type_id == dupc.DJIPayload_FlyController_ParamType.byte.value):
param_val = struct.pack("<b", int(value_str,0))
elif (paraminfo.type_id == dupc.DJIPayload_FlyController_ParamType.short.value):
param_val = struct.pack("<h", int(value_str,0))
elif (paraminfo.type_id == dupc.DJIPayload_FlyController_ParamType.long.value):
param_val = struct.pack("<l", int(value_str,0))
elif (paraminfo.type_id == dupc.DJIPayload_FlyController_ParamType.longlong.value):
param_val = struct.pack("<q", int(value_str,0))
elif (paraminfo.type_id == dupc.DJIPayload_FlyController_ParamType.float.value):
param_val = struct.pack("<f", float(value_str))
elif (paraminfo.type_id == dupc.DJIPayload_FlyController_ParamType.double.value):
param_val = struct.pack("<d", float(value_str))
else: # array or future type
param_val = bytes.fromhex(value_str)
return param_val
def flyc_param_request_2015_print_response(po, idx, paraminfo, rplpayload):
if paraminfo is None:
# Print headers
if rplpayload is None:
param_val = ""
else:
param_val = "value"
if idx is None:
ident_str = "hash"
else:
ident_str = "idx"
if po.fmt == '2line':
print("{:10s} {:60s}".format(ident_str, "name"))
print("{:6s} {:4s} {:6s} {:7s} {:7s} {:7s} {:7s}".format(
"typeId", "size", "attr", "min", "max", "deflt", param_val))
elif po.fmt == 'tab':
print("{:s}\t{:s}\t{:s}\t{:s}\t{:s}\t{:s}\t{:s}\t{:s}\t{:s}".format(
ident_str, "name", "typeId", "size", "attr", "min", "max", "deflt", param_val))
elif po.fmt == 'csv':
print("{:s};{:s};{:s};{:s};{:s};{:s};{:s};{:s};{:s}".format(
ident_str, "name", "typeId", "size", "attr", "min", "max", "deflt", param_val))
elif po.fmt == '1line':
print("{:10s} {:60s} {:6s} {:4s} {:6s} {:7s} {:7s} {:7s} {:7s}".format(
ident_str, "name", "typeId", "size", "attr", "min", "max", "deflt", param_val))
else: # po.fmt == 'simple':
pass
else:
# Print actual data
if rplpayload is None:
param_val = ""
else:
param_val = flyc_param_value_to_str(po, paraminfo, rplpayload.param_value)
if idx is None:
if rplpayload is not None:
ident_str = "0x{:08x}".format(rplpayload.param_hash)
else:
ident_str = "n/a"
else:
ident_str = "{:d}".format(idx)
# Convert limits to string before, so we can handle all types in the same way
(limit_min, limit_max, limit_def) = flyc_param_info_limits_to_str(po, paraminfo)
if po.fmt == '2line':
print("{:10s} {:60s}".format(ident_str, paraminfo.name.decode("utf-8")))
print("{:6d} {:4d} 0x{:04x} {:7s} {:7s} {:7s} {:7s}".format(
paraminfo.type_id, paraminfo.size, paraminfo.attribute,
limit_min, limit_max, limit_def, param_val))
elif po.fmt == 'tab':
print("{:s}\t{:s}\t{:d}\t{:d}\t0x{:04x}\t{:s}\t{:s}\t{:s}\t{:s}".format(
ident_str, paraminfo.name.decode("utf-8"),
paraminfo.type_id, paraminfo.size, paraminfo.attribute,
limit_min, limit_max, limit_def, param_val))
elif po.fmt == 'csv':
print("{:s};{:s};{:d};{:d};0x{:04x};{:s};{:s};{:s};{:s}".format(
ident_str, paraminfo.name.decode("utf-8"),
paraminfo.type_id, paraminfo.size, paraminfo.attribute,
limit_min, limit_max, limit_def, param_val))
#elif po.fmt == 'json': #TODO maybe output format similar to flyc_param_infos?
elif po.fmt == '1line':
print("{:10s} {:60s} {:6d} {:4d} 0x{:04x} {:7s} {:7s} {:7s} {:7s}".format(
ident_str, paraminfo.name.decode("utf-8"),
paraminfo.type_id, paraminfo.size, paraminfo.attribute,
limit_min, limit_max, limit_def, param_val))
else: # po.fmt == 'simple':
if rplpayload is None:
print("{:s} default = {:s} range = < {:s} .. {:s} >"
.format(paraminfo.name.decode("utf-8"), limit_def, limit_min, limit_max))
else:
print("{:s} = {:s} range = < {:s} .. {:s} >"
.format(paraminfo.name.decode("utf-8"), param_val, limit_min, limit_max))
def flyc_param_request_2017_print_response(po, idx, paraminfo, rplpayload):
if paraminfo is None:
# Print headers
if rplpayload is None:
param_val = ""
else:
param_val = "value"
if idx is None:
ident_str = "hash"
else:
ident_str = "idx"
if po.fmt == '2line':
print("{:10s} {:5s} {:60s}".format(ident_str, "tbl:idx", "name"))
print("{:6s} {:4s} {:7s} {:7s} {:7s} {:7s}".format(
"typeId", "size", "min", "max", "deflt", param_val))
elif po.fmt == 'tab':
print("{:s}\t{:s}\t{:s}\t{:s}\t{:s}\t{:s}\t{:s}\t{:s}\t{:s}".format(
ident_str, "tbl:idx", "name", "typeId", "size", "min", "max", "deflt", param_val))
elif po.fmt == 'csv':
print("{:s};{:s};{:s};{:s};{:s};{:s};{:s};{:s};{:s}".format(
ident_str, "tbl:idx", "name", "typeId", "size", "min", "max", "deflt", param_val))
elif po.fmt == '1line':
print("{:10s} {:5s} {:60s} {:6s} {:4s} {:7s} {:7s} {:7s} {:7s}".format(
ident_str, "tbl:idx", "name", "typeId", "size", "min", "max", "deflt", param_val))
else: # po.fmt == 'simple':
pass
else:
# Print actual data
if rplpayload is None:
param_val = ""
else:
param_val = flyc_param_value_to_str(po, paraminfo, rplpayload.param_value)
if idx is None:
if rplpayload is None:
ident_str = "n/a"
elif hasattr(rplpayload, 'param_hash'):
ident_str = "0x{:08x}".format(rplpayload.param_hash)
else:
ident_str = "0x{:08x}".format(flyc_parameter_compute_hash(po,paraminfo.name.decode("utf-8")))
else:
ident_str = "{:d}".format(idx)
tbl_str = "{:d}:{:d}".format(paraminfo.table_no, paraminfo.param_index)
# Convert limits to string before, so we can handle all types in the same way
(limit_min, limit_max, limit_def) = flyc_param_info_limits_to_str(po, paraminfo)
if po.fmt == '2line':
print("{:10s} {:5s} {:60s}".format(ident_str, tbl_str, paraminfo.name.decode("utf-8")))
print("{:6d} {:4d} {:7s} {:7s} {:7s} {:7s}".format(
paraminfo.type_id, paraminfo.size,
limit_min, limit_max, limit_def, param_val))
elif po.fmt == 'tab':
print("{:s}\t{:s}\t{:s}\t{:d}\t{:d}\t{:s}\t{:s}\t{:s}\t{:s}".format(
ident_str, tbl_str, paraminfo.name.decode("utf-8"),
paraminfo.type_id, paraminfo.size,
limit_min, limit_max, limit_def, param_val))
elif po.fmt == 'csv':
print("{:s};{:s};{:s};{:d};{:d};{:s};{:s};{:s};{:s}".format(
ident_str, tbl_str, paraminfo.name.decode("utf-8"),
paraminfo.type_id, paraminfo.size,
limit_min, limit_max, limit_def, param_val))
#elif po.fmt == 'json': #TODO maybe output format similar to flyc_param_infos?
elif po.fmt == '1line':
print("{:10s} {:5s} {:60s} {:6d} {:4d} {:7s} {:7s} {:7s} {:7s}".format(
ident_str, tbl_str, paraminfo.name.decode("utf-8"),
paraminfo.type_id, paraminfo.size,
limit_min, limit_max, limit_def, param_val))
else: # po.fmt == 'simple':
if rplpayload is None:
print("{:s} default = {:s} range = < {:s} .. {:s} >"
.format(paraminfo.name.decode("utf-8"), limit_def, limit_min, limit_max))
else:
print("{:s} = {:s} range = < {:s} .. {:s} >"
.format(paraminfo.name.decode("utf-8"), param_val, limit_min, limit_max))
def do_flyc_param_request_2015_list(po, ser):
""" List flyc parameters on platforms with single, linear parameters table.
Tested on the following platforms and FW versions:
P3X_FW_V01.07.0060 (2018-07-22)
"""
# Print result data header
flyc_param_request_2015_print_response(po, True, None, None)
for idx in range(po.start, po.start+po.count):
rplpayload = flyc_param_request_2015_get_param_info_by_index(po, ser, idx)
if sizeof(rplpayload) <= 4:
if (po.verbose > 0):
print("Response on parameter {:d} indicates end of list.".format(idx))
break
# Print the result data
flyc_param_request_2015_print_response(po, idx, rplpayload, None)
def do_flyc_param_request_2015_get(po, ser):
""" Get flyc parameter value on platforms with single, linear parameters table.
Tested on the following platforms and FW versions:
P3X_FW_V01.07.0060 (2018-07-22)
"""
# Get param info first, so we know type and size
paraminfo = flyc_param_request_2015_get_param_info_by_hash(po, ser, po.param_name)
# Now get the parameter value
rplpayload = flyc_param_request_2015_read_param_value_by_hash(po, ser, po.param_name)
# Print the result data
flyc_param_request_2015_print_response(po, None, None, True)
flyc_param_request_2015_print_response(po, None, paraminfo, rplpayload)
def do_flyc_param_request_2015_set(po, ser):
""" Set new value of flyc parameter on platforms with single, linear parameters table.
Tested on the following platforms and FW versions:
P3X_FW_V01.07.0060 (2018-07-22)
"""
# Get param info first, so we know type and size
paraminfo = flyc_param_request_2015_get_param_info_by_hash(po, ser, po.param_name)
# Now set the parameter value
param_val = flyc_param_str_to_value(po, paraminfo, po.param_value)
rplpayload = flyc_param_request_2015_write_param_value_by_hash(po, ser, po.param_name, param_val)
# Print the result data
flyc_param_request_2015_print_response(po, None, None, True)
flyc_param_request_2015_print_response(po, None, paraminfo, rplpayload)
def do_flyc_param_request_2017_list(po, ser):
""" List flyc parameters on platforms with multiple parameter tables.
Tested on the following platforms and FW versions:
WM100_FW_V01.00.0900 (2018-07-23)
"""
do_assistant_unlock(po, ser)
# Get info on tables first, so we can flatten them
table_attribs = []
for table_no in range(0, 255):
tab_attr = flyc_param_request_2017_get_table_attribs(po, ser, table_no)
if sizeof(tab_attr) <= 2:
if (po.verbose > 0):
print("Response on table no {:d} indicates end of list.".format(table_no))
break
table_attribs.append(tab_attr)
# Print result data header
flyc_param_request_2017_print_response(po, True, None, None)
idx = 0
for tab_attr in table_attribs:
for tbl_idx in range(0, tab_attr.entries_num):
if idx > po.start+po.count:
break
if idx >= po.start:
rplpayload = flyc_param_request_2017_get_param_info_by_index(po, ser, tab_attr.table_no, tbl_idx)
if sizeof(rplpayload) <= 4:
eprint("Response on parameter {:d} indicates end of list despite larger size reported.".format(idx))
# do not break - this may be error with one specific parameter
else:
# Print the result data
flyc_param_request_2017_print_response(po, idx, rplpayload, None)
idx += 1
def do_flyc_param_request_2017_get(po, ser):
""" Get flyc parameter value on platforms with multiple parameter tables.
Tested on the following platforms and FW versions:
WM100_FW_V01.00.0900 (2018-07-23)
"""
do_assistant_unlock(po, ser)
# Get param info first, so we know type and size
paraminfo = flyc_param_request_2015_get_param_info_by_hash(po, ser, po.param_name)
# Now get the parameter value
rplpayload = flyc_param_request_2015_read_param_value_by_hash(po, ser, po.param_name)
# Print the result data
flyc_param_request_2015_print_response(po, None, None, True)
flyc_param_request_2015_print_response(po, None, paraminfo, rplpayload)
def flyc_param_request_2017_get_param_info_by_name_search(po, ser, param_name):
# Get info on tables first, so we can flatten them
table_attribs = []
for table_no in range(0, 255):
tab_attr = flyc_param_request_2017_get_table_attribs(po, ser, table_no)
if sizeof(tab_attr) <= 2:
if (po.verbose > 0):
print("Response on table no {:d} indicates end of list.".format(table_no))
break
table_attribs.append(tab_attr)
# Now find table location of our param
idx = 0
for tab_attr in table_attribs:
for tbl_idx in range(0, tab_attr.entries_num):
rplpayload = flyc_param_request_2017_get_param_info_by_index(po, ser, tab_attr.table_no, tbl_idx)
if sizeof(rplpayload) <= 4:
eprint("Response on parameter {:d} indicates end of list despite larger size reported.".format(idx))
# do not break - this may be error with one specific parameter
elif rplpayload.name.decode("utf-8") == param_name:
return rplpayload
idx += 1
raise LookupError("Parameter not found during parameter info by name search request.")
return None # unreachble
def do_flyc_param_request_2017_get_alt(po, ser):
""" Get flyc parameter value on platforms with multiple parameter tables, alternative way.
Tested on the following platforms and FW versions:
WM100_FW_V01.00.0900 (2018-07-26)
"""
do_assistant_unlock(po, ser)
# Get param info first, so we know type and size
paraminfo = flyc_param_request_2017_get_param_info_by_name_search(po, ser, po.param_name)
# Now get the parameter value
rplpayload = flyc_param_request_2017_read_param_value_by_index(po, ser, paraminfo.table_no, paraminfo.param_index)
# Print the result data
flyc_param_request_2017_print_response(po, None, None, True)
flyc_param_request_2017_print_response(po, None, paraminfo, rplpayload)