/
drm_requests.py
2545 lines (2118 loc) · 90.8 KB
/
drm_requests.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
# Copyright 2022, 2023, Digi International Inc.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
import json
import re
import textwrap
import xml.etree.ElementTree as et
from datetime import datetime, timedelta, timezone
from xml.etree.ElementTree import ParseError
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from devicecloud import DeviceCloud, DeviceCloudHttpException, DeviceCloudException
from devicecloud.monitor import MonitorAPI, TCPDeviceCloudMonitor, MON_TRANSPORT_TYPE_ATTR
from devicecloud.monitor_tcp import TCPClientManager
from devicecloud.sci import DeviceTarget
from devicecloud.file_system_service import ErrorInfo, FileSystemServiceException
from django.http import JsonResponse
from login.auth import DeviceCloudUser
from connectcorecore.models import ConnectCoreDevice
CLI_TYPE_DATA = "data"
CLI_TYPE_START = "start"
CLI_TYPE_TERMINATE = "terminate"
CONTENT_TYPE_PRETTY_JSON = "application/pretty+json"
CONTENT_TYPE_OCTET_STREAM = "application/octet-stream"
DATA_POINTS_BUFFER_DURATION = 5
DATA_POINTS_BUFFER_SIZE = 10
DEFAULT_FLASH_SIZE = "0"
DEFAULT_IP = "0.0.0.0"
DEFAULT_MEMORY_TOTAL = "0"
DEFAULT_MAC = "00:00:00:00:00:00"
DEFAULT_N_SAMPLES = "6"
DEFAULT_SAMPLE_RATE = "10"
DEFAULT_VIDEO_RESOLUTION = "No video device found"
DUMMY_FILE_CONTENT = "Ignore me"
DUMMY_FILE_NAME = "dummy_file_for_dir_creation"
ERROR_ADD_FW_VERSION = "Error adding new firmware version: %s"
ERROR_CANCEL_FW_UPDATE = "Error canceling firmware update process: %s"
ERROR_CHECK_FW_UPDATE_PROGRESS = "Error checking firmware update progress: %s"
ERROR_CHECK_FW_UPDATE_STATUS = "Error checking firmware update status: %s"
ERROR_CREATE_DIRECTORY = "Could not create directory"
ERROR_CREATE_FILE = "Error creating file: %s"
ERROR_DEVICE_NOT_ANSWER = "Device did not answer. Make sure the application is running in the device."
ERROR_DEVICE_NOT_SUPPORT_RCI = "Device does not support configuration through RCI"
ERROR_DOWNLOAD_FILE = "Error '%s' downloading file: %s"
ERROR_DRM_REQUEST = "Error in the DRM request: {}."
ERROR_GET_CONFIG = "Error reading configuration: %s"
ERROR_GET_DATA_USAGE = "Error reading account data usage: %s"
ERROR_LIST_DIR = "Error '%s' listing directory: %s"
ERROR_LIST_FW_REPO = "Error listing firmware repository files: %s"
ERROR_LIST_FILESET = "Error listing fileset files: %s"
ERROR_NO_POST_REQUEST = "AJAX request must be sent using POST"
ERROR_NO_PROGRESS_INFO = "No progress information"
ERROR_NO_SESSION_ID = "No CLI session ID received"
ERROR_NOT_AUTHENTICATED = "Not authenticated"
ERROR_PARSING = "Error parsing Digi Remote Manager answer"
ERROR_REMOVE_FILE = "Error '%s' removing file: %s"
ERROR_SET_CONFIG = "Error saving configuration: %s"
ERROR_TIMEOUT = "Timeout waiting for device response"
ERROR_UNKNOWN = "unknown"
ERROR_UNRECOGNIZED_ANSWER = "unrecognized answer"
ERROR_UPDATE_FW_REQUEST = "Error sending firmware update request: %s"
ERROR_UPLOAD_FILE = "Error '%s' uploading file: %s"
FS_TYPE_DIRECTORY = "dir"
FS_TYPE_FILE = "file"
GROUP_UPLOAD_PROGRESS = "upload_progress.{}"
ID_ANY_LEVEL = ".//"
ID_BOARD_ID = "board_id"
ID_BOARD_VARIANT = "board_variant"
ID_BLUETOOTH_MAC = "bluetooth_mac"
ID_BT_MAC = "bt-mac"
ID_CANCEL = "cancel"
ID_CONTENT_TYPE = "content-type"
ID_CURRENT_DIRECTORY = "current_dir"
ID_DATA = "data"
ID_DATA_DETAILS = "data_details"
ID_DATA_SUMMARY = "data_summary"
ID_DATA_USAGE_DEVICES = "data_usage_devices"
ID_DATA_USAGE_MONITORS = "data_usage_monitors"
ID_DATA_USAGE_TOTAL = "data_usage_total"
ID_DATA_USAGE_WEB = "data_usage_web"
ID_DATA_USAGE_WEB_SERVICES = "data_usage_web_services"
ID_DEPRECATED = "deprecated"
ID_DESC = "desc"
ID_DEVICE_ID = "device_id"
ID_DEVICE_TYPE = "device_type"
ID_DEVICES = "devices"
ID_DEY_VERSION = "dey_version"
ID_DPNAME = "dpName"
ID_ERROR = "error"
ID_ERROR_MSG = "error_msg"
ID_ERROR_MESSAGE = "error_message"
ID_FILE = "file"
ID_FILENAME = "filename"
ID_FILES = "files"
ID_FILE_SIZE = "file_size"
ID_FLASH_SIZE = "flash_size"
ID_FW_VERSION = "firmware_version"
ID_HARDWARE = "hardware"
ID_INFO = "information_link"
ID_INITIALIZE = "initialize"
ID_INTERVAL = "interval"
ID_INVENTORY = "inventory"
ID_IP = "ip"
ID_KERNEL_VERSION = "kernel_version"
ID_KINETIS = "kinetis"
ID_LAST_MODIFIED = "last_modified"
ID_LIST = "list"
ID_MAC = "mac"
ID_MCA_FW_VERSION = "mca_fw_version"
ID_MCA_HW_VERSION = "mca_hw_version"
ID_MEMORY_TOTAL = "memory_total"
ID_MESSAGE = "message"
ID_MODULE_VARIANT = "module_variant"
ID_MONITOR_ID = "monitor_id"
ID_NAME = "name"
ID_N_DP_UPLOAD = "n_dp_upload"
ID_N_DP_UPLOAD_CCCSD = "system_monitor_upload_samples_size"
ID_NUM_SAMPLES_UPLOAD = "num_samples_upload"
ID_PATH = "path"
ID_PLAY = "play"
ID_PRODUCTION = "production"
ID_PROGRESS = "progress"
ID_RESOLUTION = "resolution"
ID_SAMPLE_RATE = "sample_rate"
ID_SAMPLE_RATE_CCCSD = "system_monitor_sample_rate"
ID_SECURITY = "security_related"
ID_SERIAL_NUMBER = "serial_number"
ID_SERVICE_DESCRIPTION = "service_description"
ID_SESSION_ID = "session_id"
ID_SIZE = "size"
ID_STATUS = "status"
ID_STREAM = "stream"
ID_TARGETS = "targets"
ID_TIMESTAMP = "timestamp"
ID_TOTAL_DATA_USAGE_DEVICES_MB = "device_data_usage_mb"
ID_TOTAL_DATA_USAGE_MB = "total_data_usage_mb"
ID_TOTAL_DATA_USAGE_WS_MB = "web_service_data_usage_mb"
ID_TOTAL_MEMORY = "total_mem"
ID_TOTAL_STORAGE = "total_st"
ID_TYPE = "type"
ID_UBOOT_VERSION = "uboot_version"
ID_USAGE = "usage"
ID_UPDATE_RUNNING = "update_running"
ID_VALID = "valid"
ID_VALUE = "value"
ID_VERSION = "version"
ID_VIDEO_RESOLUTION = "video_resolution"
ID_WIFI_IP = "wifi_ip"
ID_WIFI_MAC = "wifi_mac"
IFACE_WIFI = "wlan0"
NUM_ETHERNET_INTERFACES = 2
OPERATION_CLI = "cli"
OPERATION_DATA_SERVICE = "data_service"
OPERATION_REBOOT = "reboot"
OPERATION_SEND_MESSAGE = "send_message"
PREFIX_VALID_DEVICE = ""
PROVISION_TYPE_ID = "id"
PROVISION_TYPE_IMEI = "imei"
PROVISION_TYPE_MAC = "mac"
REGEX_DEV_REQUEST_RESPONSE = ".*<device_request .*>(.*)<\\/device_request>.*"
REGEX_DO_CMD_RESPONSE = ".*<do_command target=[^>]*>(.*)<\\/do_command>.*"
REGEX_INFO_HW = "SN=([0-9a-zA-Z-_:\\/]+) MACHINE=([0-9a-zA-Z-_:\\/]+) VARIANT=([0-9a-zA-Z\\/]+) " \
"SBC_VARIANT=([0-9a-zA-Z\\/]+) BOARD_ID=([0-9a-zA-Z\\/]+)"
REGEX_INFO_KINETIS = "HW_VERSION=([0-9a-zA-Z-_:\\/]+) FW_VERSION=([0-9a-zA-Z-_:\\/]+)"
REGEX_MONITOR_ERROR = ".*<error>(.*)<\\/error>.*"
REQ_CLI_INITIALIZE = "<initialize/>"
REQ_CLI_SEND_DATA = "<write session_id='{}' format='base64'>{}</write>"
REQ_CLI_START = "<start idle_timeout='{}' session_id='{}'/>"
REQ_CLI_TERMINATE = "<terminate session_id='{}'/>"
REQ_DEVICE_REQUEST = "<requests>" \
" <device_request target_name='{}'>" \
"{}" \
"</device_request>" \
"</requests>"
REQ_DO_COMMAND = "<rci_request version='1.1'>" \
" <do_command target='{}'>" \
" {}" \
" </do_command>" \
"</rci_request>"
REQ_QUERY_SETTING_SM = "<rci_request version='1.1'>" \
" <query_setting>" \
" <system_monitor/>" \
" </query_setting>" \
"</rci_request>"
REQ_QUERY_STATE = "<rci_request version='1.1'>" \
" <query_state/>" \
"</rci_request>"
REQ_SET_SETTING_SM = "<rci_request version='1.1'>" \
" <set_setting>" \
" <system_monitor>" \
" <sample_rate>{}</sample_rate>" \
" <n_dp_upload>{}</n_dp_upload>" \
" </system_monitor>" \
" </set_setting>" \
"</rci_request>"
SCHEMA_MONITOR_CLI = '[' \
'{{#each this}}' \
'{{#if @index}}, {{/if}}' \
'{ ' \
'{{#if CLIEvent.type}}' \
'{{#endsWith CLIEvent.type "data"}}' \
'"data": "{{{CLIEvent.data}}}",' \
'{{/endsWith}}' \
'{{#endsWith CLIEvent.type "terminate"}}' \
'"session_id": "{{CLIEvent.sessionId}}",' \
'{{#endsWith CLIEvent.hint "Idle Timeout Exceeded"}}' \
'"error": "{{CLIEvent.hint}}",' \
'{{/endsWith}}' \
'{{/endsWith}}' \
'{{/if}}' \
'"type": "{{CLIEvent.type}}"' \
'}' \
'{{/each}}' \
']'
SCHEMA_MONITOR_DEVICE = '[' \
'{{#each this}}' \
'{{#if @index}}, {{/if}}' \
'{ ' \
'"device_id": "{{device.id}}",' \
'"status": "{{device.connection_status}}"' \
'}' \
'{{/each}}' \
']'
SCHEMA_MONITOR_DP = '[' \
'{{#each this}}' \
'{{#if @index}}, {{/if}}' \
'{' \
'"stream": "{{remainingPathComponents (remainingPathComponents DataPoint.streamId)}}",' \
'"value": {{DataPoint.data}} ' \
'}' \
'{{/each}}' \
']'
SCHEMA_MONITOR_DP_FILTER = '{{#eachFiltered this}}' \
'{{#endsWith DataPoint.streamId "%s"}}' \
'{{#if @first}}' \
'{' \
'"stream": "{{remainingPathComponents (remainingPathComponents DataPoint.streamId)}}",' \
'"value": {{DataPoint.data}} ' \
'},' \
'{{/if}}' \
'{{/endsWith}}' \
'{{/eachFiltered}}'
SCHEMA_MONITOR_DP_DUMMY = '{"a": 0}'
SERVICE_WEB_SERVICE = "WebService messaging"
SERVICE_MONITOR = "Push Monitoring"
STATUS_ACTIVE = "active"
STATUS_CANCELED = "canceled"
STATUS_FAILED = "failed"
STREAMS_LIST = ["wlan0/state", "wlan0/rx_bytes", "wlan0/tx_bytes",
"hci0/state", "hci0/rx_bytes", "hci0/tx_bytes",
"eth0/state", "eth0/rx_bytes", "eth0/tx_bytes",
"eth1/state", "eth1/rx_bytes", "eth1/tx_bytes",
"lo/state", "lo/rx_bytes", "lo/tx_bytes",
"uptime", "frequency", "cpu_temperature", "cpu_load",
"used_memory", "free_memory"]
TARGET_DEVICE_INFO = "device_info"
TARGET_GET_CONFIG = "get_config"
TARGET_GET_CCCSD_CONFIG = "cccsd_get_config"
TARGET_PLAY_MUSIC = "play_music"
TARGET_SET_AUDIO_VOLUME = "set_audio_volume"
TARGET_SET_CONFIG = "set_config"
TARGET_SET_CCCSD_CONFIG = "cccsd_set_config"
TARGET_SET_LED = "user_led"
TARGET_SET_VIDEO_BRIGHTNESS = "set_video_brightness"
WS_DATA_USAGE_API = "/ws/v1/reports/usage/{}"
WS_FILES_API = "/ws/v1/files/{}"
WS_FW_REPOSITORY_API = "/ws/v1/firmware/inventory/FE080003/{}"
WS_FIRMWARE_UPDATES_API = "/ws/v1/firmware_updates/{}"
WS_MONITOR_API = "/ws/Monitor/{}"
CLI_SESSION_TIMEOUT = 300
# Variables.
monitor_managers = {}
def is_authenticated(request):
"""
Returns whether the user is authenticated or not.
Args:
request (:class:`.WSGIRequest`): The request used to verify if the
user is authenticated or not.
Returns:
boolean: `True` if the user stored in the request session is
authenticated, `False`otherwise.
"""
dc_session = get_device_cloud(request)
if dc_session is not None and dc_session is not False and dc_session.has_valid_credentials():
return True
return False
def get_device_cloud(request):
"""
Returns the Device Cloud instance for the given request.
Args:
request (:class:`.WSGIRequest`): The request containing the user and
password to generate the corresponding Device Cloud instance.
Returns:
:class:`.DeviceCloud`: The Device Cloud instance for the corresponding
user and password stored in the request session.
"""
return get_device_cloud_session(request.session)
def get_device_cloud_session(session):
"""
Returns the Device Cloud instance for the given session.
Args:
session (:class:`.SessionStore`): The Django session containing the
user and password to generate the corresponding Device Cloud
instance.
Returns:
:class:`.DeviceCloud`: The Device Cloud instance for the corresponding
user and password stored in the session.
"""
user = session.get("user")
if user is None:
return None
user_serialized = DeviceCloudUser.from_json(json.loads(user))
return DeviceCloud(user_serialized.username, user_serialized.password,
base_url=user_serialized.server)
def check_ajax_request(request):
"""
Checks whether the given AJAX request is valid and the user is
authenticated.
Args:
request (:class:`.WSGIRequest`): The HTTP request.
Returns:
`None` if the request is valid, or a `JsonResponse` with the error
if it is not.
"""
if is_authenticated(request):
if (not request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
or request.method != "POST"):
return JsonResponse({ID_ERROR: ERROR_NO_POST_REQUEST}, status=400)
return None
return JsonResponse({ID_ERROR: ERROR_NOT_AUTHENTICATED}, status=401)
def get_exception_response(exc):
"""
Returns the JSON response with the error contained in the given exception.
Args:
exc (:class:`.Exception`): The exception.
Returns:
A JSON response with the details of the exception.
"""
return JsonResponse({ID_ERROR: (ERROR_DRM_REQUEST.format(exc.response.text)
if isinstance(exc, DeviceCloudHttpException) else str(exc))},
status=400)
def send_device_request(request, target):
"""
Sends a Device Request to DRM to the device with the given ID.
Args:
request (:class:`.WSGIRequest`): the AJAX request.
target (String): the target of the Device Request.
Returns:
A JSON with the response or the error.
"""
error = check_ajax_request(request)
if error:
return error
dc_session = get_device_cloud(request)
device_id = request.POST[ID_DEVICE_ID]
data = request.POST[ID_DATA] if ID_DATA in request.POST else None
try:
resp = send_request(dc_session, device_id, target, data)
if resp is not None:
return JsonResponse({ID_DATA: resp}, status=200)
return JsonResponse({ID_VALID: True}, status=200)
except DeviceCloudHttpException as exc:
return get_exception_response(exc)
def send_request(dc_session, device_id, target, data=None):
"""
Sends a Device Request to the device with the given device ID using the
given target and data.
Args:
dc_session (:class:`.DeviceCloud`): the Device Cloud instance.
device_id (String): the device ID of the DRM device.
target (String): the target of the Device Request.
data (String, optional): the data of the Device Request.
Returns:
The Device Request response (if any).
Raises:
DeviceCloudHttpException: if there is any error sending the Device
Request.
"""
request = REQ_DEVICE_REQUEST.format(
target, data if data is not None else "").strip()
resp = dc_session.sci.send_sci(OPERATION_DATA_SERVICE, DeviceTarget(device_id), request)
if resp.status_code != 200:
raise DeviceCloudHttpException(resp)
re_search = re.search(REGEX_DEV_REQUEST_RESPONSE, resp.text, re.IGNORECASE)
if re_search:
return re_search.group(1)
return None
def send_do_command(dc_session, device_id, target, data=None):
"""
Sends a 'do_command' request to the device with the given device ID using
the given data.
Args:
dc_session (:class:`.DeviceCloud`): the Device Cloud instance.
device_id (String): the device ID of the DRM device.
target (String): the 'do_command' target.
data (String, optional): the data of the 'do_command' request.
Returns:
String: The 'do_command' XML response (if any).
Raises:
DeviceCloudHttpException: if there is any error sending the request.
"""
request = REQ_DO_COMMAND.format(target, data if data is not None else "")
# Send the request and get the answer. Set cache to False in order to get
# the answer from the device and not from DRM.
resp = dc_session.sci.send_sci(OPERATION_SEND_MESSAGE, DeviceTarget(device_id),
request, cache=False)
if resp.status_code != 200:
raise DeviceCloudHttpException(resp)
re_search = re.search(REGEX_DO_CMD_RESPONSE, resp.text, re.IGNORECASE)
if re_search:
return re_search.group(1)
return None
def get_cc_devices(request):
"""
Returns a list containing the ConnectCore devices of the DRM account.
Args:
request (:class:`.WSGIRequest`): The request used to generate the
Device Cloud instance.
Returns:
:class:`.HttpResponse`: An HTTP response with the list of the
ConnectCore devices within the DRM account in JSON format.
"""
cc_devices = []
dc_session = get_device_cloud(request)
devices = list(dc_session.devicecore.get_devices())
for device in devices:
# Get the type of the device and verify it is a ConnectCore device.
if (device.get_device_type() == ""
or not device.get_device_type().startswith(PREFIX_VALID_DEVICE)):
continue
cc_device = ConnectCoreDevice(device.get_connectware_id(), device.get_device_type(),
device.get_device_json()[ID_DPNAME] if ID_DPNAME in device.get_device_json()
else "")
cc_devices.append(cc_device)
# Set the online property to the farm.
cc_device.is_online = device.is_connected()
# If the location of the device is valid, set it to the farm.
lat, lon = device.get_latlon()
if lat is not None and lon is not None:
cc_device.location = (lat, lon)
# Sort list.
cc_devices.sort(key=lambda element: element.type)
cc_devices.sort(key=lambda element: element.name)
cc_devices.sort(key=lambda element: element.is_online, reverse=True)
return cc_devices
def provision_device(request, provision_value, provision_type):
"""
Registers the device with the given provision value in the DRM account.
Args:
request (:class:`.WSGIRequest`): The request used to generate the
Device Cloud instance.
provision_value (String): The provision value to register.
provision_type (String): The provision type to register.
Returns:
Dictionary: Dictionary with the result.
"""
dc_session = get_device_cloud(request)
resp = {}
answer = {}
try:
if provision_type == PROVISION_TYPE_ID:
resp = dc_session.devicecore.provision_device(device_id=provision_value)
elif provision_type == PROVISION_TYPE_MAC:
resp = dc_session.devicecore.provision_device(mac_address=provision_value)
elif provision_type == PROVISION_TYPE_IMEI:
resp = dc_session.devicecore.provision_device(imei=provision_value)
if ID_ERROR in resp and resp[ID_ERROR] is True:
answer[ID_ERROR] = resp[ID_ERROR_MSG]
except DeviceCloudHttpException as exc:
answer[ID_ERROR] = exc.response.text
return answer
def set_play_music_state(request, device_id, play, music_file):
"""
Sets the play music state for the given device.
Args:
request (:class:`.WSGIRequest`): The request used to generate the
Device Cloud instance.
device_id (String): the device ID of the ConnectCore DRM device.
play (String): the new value of the play music.
music_file (String): the music file to play.
Returns:
String: 'OK' on success, 'ERROR' otherwise.
"""
dc_session = get_device_cloud(request)
request_data = "%s" % json.dumps({"play": play, "music_file": music_file})
try:
return send_request(dc_session, device_id, TARGET_PLAY_MUSIC,
data=request_data)
except DeviceCloudHttpException as exc:
return exc.response.text
def set_cc_device_audio_volume(request, device_id, value):
"""
Sets the audio volume of the given device.
Args:
request (:class:`.WSGIRequest`): The request used to generate the
Device Cloud instance.
device_id (String): the device ID of the ConnectCore DRM device.
value (String): the new value to set to the audio volume.
Returns:
String: 'OK' on success, 'ERROR' otherwise.
"""
dc_session = get_device_cloud(request)
request_data = "%s" % value
try:
return send_request(dc_session, device_id, TARGET_SET_AUDIO_VOLUME,
data=request_data)
except DeviceCloudHttpException as exc:
return exc.response.text
def set_cc_device_video_brightness(request, device_id, value):
"""
Sets the video brightness of the given device.
Args:
request (:class:`.WSGIRequest`): The request used to generate the
Device Cloud instance.
device_id (String): the device ID of the ConnectCore DRM device.
value (String): the new value to set to the video brightness.
Returns:
String: 'OK' on success, 'ERROR' otherwise.
"""
dc_session = get_device_cloud(request)
request_data = "%s" % value
try:
return send_request(dc_session, device_id, TARGET_SET_VIDEO_BRIGHTNESS,
data=request_data)
except DeviceCloudHttpException as exc:
return exc.response.text
def set_led(request, device_id, _led_name, value):
"""
Sets the new value of the given LED for the given device.
Args:
request (:class:`.WSGIRequest`): The request used to generate the
Device Cloud instance.
device_id (String): the device ID of the ConnectCore DRM device.
_led_name (String): the LED name.
value (String): the new LED value.
Returns:
String: 'OK' on success, 'ERROR' otherwise.
"""
dc_session = get_device_cloud(request)
request_data = ("%s" % value).lower()
try:
return send_request(dc_session, device_id, TARGET_SET_LED,
data=request_data)
except DeviceCloudHttpException as exc:
return exc.response.text
def get_current_data_point(dc_session, stream_id):
"""
Returns the latest data point value from the stream with the given ID.
Args:
dc_session (:class:`.DeviceCloud`): the Device Cloud instance.
stream_id (String): the ID of the stream to get the data point from.
Returns:
String: the latest data point from the given stream, `None` if there is
not any stream with the given ID.
"""
stream = dc_session.streams.get_stream_if_exists(stream_id)
if stream is not None:
return stream.get_current_value()
return None
def get_data_points(request, stream_name):
"""
Returns the list of data points in JSON format of the given data stream.
Args:
request (:class:`.WSGIRequest`): the AJAX request.
stream_name (String): the data stream name.
Returns:
A JSON with the data points or the error.
"""
error = check_ajax_request(request)
if error:
return error
dc_session = get_device_cloud(request)
data = json.loads(request.body.decode(request.encoding))
device_id = data[ID_DEVICE_ID]
interval = data[ID_INTERVAL]
if interval is None:
interval = 1
else:
interval = int(data[ID_INTERVAL])
stream_id = "{}/{}".format(device_id, stream_name)
strm = dc_session.streams.get_stream(stream_id)
datapoints = []
# Establish rollup values for requests exceeding 1 hour.
rollup_interval = None
rollup_method = None
if interval != 1:
rollup_method = "average"
if interval == 24: # Day -> 48 samples
rollup_interval = "half"
elif interval == 168: # Week -> 168 samples
rollup_interval = "hour"
elif interval == 720: # Month -> 31 samples
rollup_interval = "day"
for d_point in strm.read(
start_time=(datetime.now(timezone.utc) - timedelta(hours=interval)),
newest_first=False,
rollup_interval=rollup_interval,
rollup_method=rollup_method):
datapoints.append({
ID_TIMESTAMP: d_point.get_timestamp().timestamp() * 1000,
ID_DATA: (d_point.get_data() / 1024) if "memory" in stream_name else d_point.get_data()
})
return {ID_DATA: datapoints}
def query_rci_device_state(request, device_id):
"""
Obtains the state information of the device using RCI.
Args:
request (:class:`.WSGIRequest`): The request used to generate the
Device Cloud instance.
device_id (String): The device ID of the ConnectCore DRM device.
Return:
Dictionary: Dictionary containing the device information.
"""
info = {}
dc_session = get_device_cloud(request)
resp = dc_session.sci.send_sci(OPERATION_SEND_MESSAGE,
DeviceTarget(device_id),
REQ_QUERY_STATE,
allow_offline=True,
cache=False,
wait_for_reconnect=False,
sync_timeout=5)
if resp.status_code != 200:
raise DeviceCloudHttpException(resp)
try:
root = et.fromstring(resp.content)
errors = root.findall("%s%s" % (ID_ANY_LEVEL, ID_ERROR))
if errors:
desc_element = errors[0].findall("%s%s" % (ID_ANY_LEVEL, ID_DESC))
info[ID_ERROR] = desc_element[0].text if desc_element else ERROR_TIMEOUT
return info
uboot_version = root.findall("%s%s" % (ID_ANY_LEVEL, ID_UBOOT_VERSION))
if uboot_version:
info[ID_UBOOT_VERSION] = uboot_version[0].text
kernel_version = root.findall("%s%s" % (ID_ANY_LEVEL, ID_KERNEL_VERSION))
if kernel_version:
info[ID_KERNEL_VERSION] = kernel_version[0].text
dey_version = root.findall("%s%s" % (ID_ANY_LEVEL, ID_DEY_VERSION))
if dey_version:
info[ID_DEY_VERSION] = dey_version[0].text
hardware = root.findall("%s%s" % (ID_ANY_LEVEL, ID_HARDWARE))
if hardware:
re_search = re.search(REGEX_INFO_HW, hardware[0].text, re.IGNORECASE)
if re_search and len(re_search.groups()) >= 5:
info[ID_SERIAL_NUMBER] = re_search.group(1)
info[ID_DEVICE_TYPE] = re_search.group(2)
info[ID_MODULE_VARIANT] = re_search.group(3)
info[ID_BOARD_VARIANT] = re_search.group(4)
info[ID_BOARD_ID] = re_search.group(5)
kinetis = root.findall("%s%s" % (ID_ANY_LEVEL, ID_KINETIS))
if kinetis:
re_search = re.search(REGEX_INFO_KINETIS, kinetis[0].text, re.IGNORECASE)
if re_search and len(re_search.groups()) >= 2:
info[ID_MCA_HW_VERSION] = re_search.group(1)
info[ID_MCA_FW_VERSION] = re_search.group(2)
except ParseError:
info[ID_ERROR] = ERROR_PARSING
return info
def get_device_information(request, device_id):
"""
Obtains the information of the device.
Args:
request (:class:`.WSGIRequest`): The request used to generate the
Device Cloud instance.
device_id (String): The device ID of the ConnectCore DRM device.
Return:
Dictionary: Dictionary containing the device information.
"""
info = {}
dc_session = get_device_cloud(request)
try:
resp = send_request(dc_session, device_id, TARGET_DEVICE_INFO, data="")
if resp is None or "not registered" in resp:
info[ID_ERROR] = ERROR_DEVICE_NOT_ANSWER
return info
if "CCAPI Error" in resp:
info[ID_ERROR] = resp
return info
information = json.loads(resp)
if ID_UBOOT_VERSION in information:
info[ID_UBOOT_VERSION] = information[ID_UBOOT_VERSION]
if ID_KERNEL_VERSION in information:
info[ID_KERNEL_VERSION] = information[ID_KERNEL_VERSION]
if ID_DEY_VERSION in information:
info[ID_DEY_VERSION] = information[ID_DEY_VERSION]
if ID_SERIAL_NUMBER in information:
info[ID_SERIAL_NUMBER] = information[ID_SERIAL_NUMBER]
if ID_DEVICE_TYPE in information:
info[ID_DEVICE_TYPE] = information[ID_DEVICE_TYPE]
if ID_MODULE_VARIANT in information:
info[ID_MODULE_VARIANT] = information[ID_MODULE_VARIANT]
if ID_BOARD_VARIANT in information:
info[ID_BOARD_VARIANT] = information[ID_BOARD_VARIANT]
if ID_BOARD_ID in information:
info[ID_BOARD_ID] = information[ID_BOARD_ID]
if ID_MCA_HW_VERSION in information:
info[ID_MCA_HW_VERSION] = information[ID_MCA_HW_VERSION]
if ID_MCA_FW_VERSION in information:
info[ID_MCA_FW_VERSION] = information[ID_MCA_FW_VERSION]
if ID_TOTAL_MEMORY in information:
info[ID_MEMORY_TOTAL] = information[ID_TOTAL_MEMORY]
else:
info[ID_MEMORY_TOTAL] = DEFAULT_MEMORY_TOTAL
if ID_TOTAL_STORAGE in information:
info[ID_FLASH_SIZE] = information[ID_TOTAL_STORAGE]
else:
info[ID_FLASH_SIZE] = DEFAULT_FLASH_SIZE
if ID_RESOLUTION in information and len(information[ID_RESOLUTION]) > 0:
info[ID_VIDEO_RESOLUTION] = "%s pixels" % information[ID_RESOLUTION]
else:
info[ID_VIDEO_RESOLUTION] = DEFAULT_VIDEO_RESOLUTION
if ID_BT_MAC in information:
info[ID_BLUETOOTH_MAC] = information[ID_BT_MAC]
else:
info[ID_BLUETOOTH_MAC] = DEFAULT_MAC
if IFACE_WIFI in information:
info[ID_WIFI_MAC] = information[IFACE_WIFI][ID_MAC]
info[ID_WIFI_IP] = information[IFACE_WIFI][ID_IP]
else:
info[ID_WIFI_MAC] = DEFAULT_MAC
info[ID_WIFI_IP] = DEFAULT_IP
for index in range(0, NUM_ETHERNET_INTERFACES):
if "eth%s" % index in information:
info["ethernet%s_mac" % index] = information["eth%s" % index][ID_MAC]
info["ethernet%s_ip" % index] = information["eth%s" % index][ID_IP]
else:
info["ethernet%s_mac" % index] = DEFAULT_MAC
info["ethernet%s_ip" % index] = DEFAULT_IP
except DeviceCloudHttpException as exc:
info[ID_ERROR] = exc.response.text
return info
# Get firmware version
info[ID_FW_VERSION] = "-"
devices = list(dc_session.devicecore.get_devices())
for device in devices:
if device.get_connectware_id() != device_id:
continue
info[ID_FW_VERSION] = device.get_firmware_level_description()
# Check if we have all the required information.
if not info.get(ID_UBOOT_VERSION, None):
information = query_rci_device_state(request, device_id)
error = information.get(ID_ERROR, None)
if error:
if ERROR_DEVICE_NOT_SUPPORT_RCI in error:
information[ID_ERROR] = "Could not get device information"
return information
info[ID_UBOOT_VERSION] = information.get(ID_UBOOT_VERSION, None)
info[ID_KERNEL_VERSION] = information.get(ID_KERNEL_VERSION, None)
info[ID_DEY_VERSION] = information.get(ID_DEY_VERSION, None)
info[ID_SERIAL_NUMBER] = information.get(ID_SERIAL_NUMBER, None)
info[ID_DEVICE_TYPE] = information.get(ID_DEVICE_TYPE, None)
info[ID_MODULE_VARIANT] = information.get(ID_MODULE_VARIANT, None)
info[ID_BOARD_VARIANT] = information.get(ID_BOARD_VARIANT, None)
info[ID_BOARD_ID] = information.get(ID_BOARD_ID, None)
info[ID_MCA_HW_VERSION] = information.get(ID_MCA_HW_VERSION, None)
info[ID_MCA_FW_VERSION] = information.get(ID_MCA_FW_VERSION, None)
# Send request to retrieve device information from system monitor settings.
try:
resp = get_system_monitor_settings(request, device_id)
if ID_ERROR in resp:
info[ID_ERROR] = resp[ID_ERROR]
return info
info[ID_SAMPLE_RATE] = resp[ID_SAMPLE_RATE]
info[ID_NUM_SAMPLES_UPLOAD] = resp[ID_NUM_SAMPLES_UPLOAD]
except DeviceCloudHttpException as exc:
info[ID_ERROR] = exc.response.text
return info
return info
def get_general_device_status(request, device_id):
"""
Obtains the status of the device.
Args:
request (:class:`.WSGIRequest`): The request used to generate the
Device Cloud instance.
device_id (String): The device ID of the ConnectCore DRM device.
Return:
Dictionary: Dictionary containing the device general status.
"""
dc_session = get_device_cloud(request)
status = {}
streams = dc_session.streams.get_streams(stream_prefix=device_id)
for stream in streams:
stream_id = stream.get_stream_id()
try:
data = stream.get_current_value(True).get_data()
except (DeviceCloudException, DeviceCloudHttpException):
data = ""
status[stream_id.replace("%s/" % device_id, "")] = data
return status
def initialize_cli_session(request, device_id):
"""
Initializes a CLI session with the given device ID.
Args:
request (:class:`.WSGIRequest`): The request used to generate the
Device Cloud instance.
device_id (String): The ID of the ConnectCore device to initialize
the CLI session with.
Returns:
Dictionary: Dictionary containing the answer.
"""
answer = {}
dc_session = get_device_cloud(request)
resp = dc_session.sci.send_sci(OPERATION_CLI,
DeviceTarget(device_id),
REQ_CLI_INITIALIZE,
wait_for_reconnect=False,
sync_timeout=5)
if resp.status_code != 200:
raise DeviceCloudHttpException(resp)
try:
root = et.fromstring(resp.content)
errors = root.findall("%s%s" % (ID_ANY_LEVEL, ID_ERROR))
if errors:
desc_element = errors[0].findall("%s%s" % (ID_ANY_LEVEL, ID_DESC))
answer[ID_ERROR] = desc_element[0].text if desc_element else ERROR_TIMEOUT
return answer
initialize_element = root.findall("%s%s" % (ID_ANY_LEVEL, ID_INITIALIZE))
if initialize_element is not None and initialize_element[0] is not None \
and initialize_element[0].attrib[ID_SESSION_ID] is not None:
answer[ID_SESSION_ID] = initialize_element[0].attrib[ID_SESSION_ID]
else:
answer[ID_ERROR] = ERROR_NO_SESSION_ID
except ParseError:
answer[ID_ERROR] = ERROR_PARSING
return answer
def start_cli_session(session, device_id, session_id):
"""
Starts the CLI session with the given session ID.
Args:
session (:class:`.SessionStore`): The Django session.
device_id (String): The ID of the ConnectCore device to start
the CLI session with.
session_id (String): The ID CLI session to start.
Returns: