Repository navigation
Expand file tree
/
Copy pathbotengine_pytest.py
More file actions
3644 lines (3124 loc) · 136 KB
/
Copy pathbotengine_pytest.py
File metadata and controls
3644 lines (3124 loc) · 136 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
"""
Created on July 12, 2016
@author: David Moss
"""
import datetime
import logging
import pytz
# States
STATE_AWAKE = 0
STATE_GOING_TO_SLEEP = 1
STATE_SLEEPING = 2
STATE_WAKING_UP_SOON = 3
DATA_LAST_MOVEMENT_RH = -1
DATA_SLEEP_DURATION_MS = -2
# Logging
LOG_LEVEL = logging.ERROR
NON_SERVICE_LOG_LEVEL = logging.WARNING
SERVICE_LOG_LEVEL = logging.DEBUG
# Name of our core variable
CORE_VARIABLE_NAME = "-core-"
TIMERS_VARIABLE_NAME = "[t]"
QUESTIONS_VARIABLE_NAME = "[q]"
COUNT_VARIABLE_NAME = "[c]"
class BotEnginePyTest:
# You can override this with your own class to validate access or return responses.
# Trigger Types
TRIGGER_UNPAUSED = 0 # 0
TRIGGER_SCHEDULE = 1 << 0 # 1
TRIGGER_MODE = 1 << 1 # 2
TRIGGER_DEVICE_ALERT = 1 << 2 # 4
TRIGGER_DEVICE_MEASUREMENT = 1 << 3 # 8
TRIGGER_QUESTION_ANSWER = 1 << 4 # 16
TRIGGER_DEVICE_FILES = 1 << 5 # 32
TRIGGER_TIMER = 1 << 6 # 64
TRIGGER_METADATA = 1 << 7 # 128
TRIGGER_DATA_STREAM = 1 << 8 # 256
TRIGGER_COMMAND_RESPONSE = 1 << 9 # 512
TRIGGER_LOCATION_CONFIGURATION = 1 << 10 # 1024
TRIGGER_DATA_REQUEST = 1 << 11 # 2048
TRIGGER_MESSAGES = 1 << 12 # 4096
TRIGGER_DOCUMENTS = 1 << 13 # 8192
# Access category types
ACCESS_CATEGORY_MODE = 1
ACCESS_CATEGORY_FILE = 2
ACCESS_CATEGORY_PROFESSIONAL_MONITORING = 3
ACCESS_CATEGORY_DEVICE = 4
ACCESS_CATEGORY_CHALLENGE = 5
ACCESS_CATEGORY_RULES = 6
# Question Responses
QUESTION_RESPONSE_TYPE_BOOLEAN = 1
QUESTION_RESPONSE_TYPE_MULTICHOICE_SINGLESELECT = 2
QUESTION_RESPONSE_TYPE_MULTICHOICE_MULTISELECT = 4
QUESTION_RESPONSE_TYPE_DAYOFWEEK = 6
QUESTION_RESPONSE_TYPE_SLIDER = 7
QUESTION_RESPONSE_TYPE_TIME = 8
QUESTION_RESPONSE_TYPE_DATETIME = 9
QUESTION_RESPONSE_TYPE_TEXT = 10
# Question display types
# BOOLEAN QUESTIONS
QUESTION_DISPLAY_BOOLEAN_ONOFF = 0
QUESTION_DISPLAY_BOOLEAN_YESNO = 1
QUESTION_DISPLAY_BOOLEAN_BUTTON = 2
QUESTION_DISPLAY_BOOLEAN_THUMBS = 3
# MULTIPLE CHOICE - MULTIPLE SELECT QUESTIONS
QUESTION_DISPLAY_MCMS_CHECKBOX = 0
# MULTIPLE CHOICE - SINGLE SELECT QUESTIONS
QUESTION_DISPLAY_MCSS_RADIO_BUTTONS = 0
QUESTION_DISPLAY_MCSS_PICKER = 1
QUESTION_DISPLAY_MCSS_SLIDER = 2
QUESTION_DISPLAY_MCSS_MODAL_BOTTOM_SHEET = 3
# DAY OF WEEK QUESTIONS
QUESTION_DISPLAY_DAYOFWEEK_MULTISELECT = 0
QUESTION_DISPLAY_DAYOFWEEK_SINGLESELECT = 1
# SLIDER
QUESTION_DISPLAY_SLIDER_INTEGER = 0
QUESTION_DISPLAY_SLIDER_FLOAT = 1
QUESTION_DISPLAY_SLIDER_MINSEC = 2
# TIME
QUESTION_DISPLAY_TIME_HOURS_MINUTES_SECONDS_AMPM = 0
QUESTION_DISPLAY_TIME_HOURS_MINUTES_AMPM = 1
# DATETIME
QUESTION_DISPLAY_DATETIME_DATE_AND_TIME = 0
QUESTION_DISPLAY_DATETIME_DATE = 1
# Answer Status
ANSWER_STATUS_NOT_ASKED = -1
ANSWER_STATUS_DELAYED = 0
ANSWER_STATUS_QUEUED = 1
ANSWER_STATUS_AVAILABLE = 2
ANSWER_STATUS_SKIPPED = 3
ANSWER_STATUS_ANSWERED = 4
ANSWER_STATUS_NO_ANSWER = 5
# Professional Monitoring
PROFESSIONAL_MONITORING_NEVER_PURCHASED = 0
PROFESSIONAL_MONITORING_PURCHASED_BUT_NOT_ENOUGH_INFO = 1
PROFESSIONAL_MONITORING_REGISTRATION_PENDING = 2
PROFESSIONAL_MONITORING_REGISTERED = 3
PROFESSIONAL_MONITORING_CANCELLATION_PENDING = 4
PROFESSIONAL_MONITORING_CANCELLED = 5
# Professional monitoring alert status
PROFESSIONAL_MONITORING_ALERT_STATUS_QUIET = 0
PROFESSIONAL_MONITORING_ALERT_STATUS_RAISED = 1
PROFESSIONAL_MONITORING_ALERT_STATUS_CANCELLED = 2
PROFESSIONAL_MONITORING_ALERT_STATUS_REPORTED = 3
# Rule status
RULE_STATUS_INCOMPLETE = 0
RULE_STATUS_ACTIVE = 1
RULE_STATUS_INACTIVE = 2
# Data stream destinations
DATASTREAM_ORGANIZATIONAL_FIELD_TO_INDIVIDUALS = 1
DATASTREAM_ORGANIZATIONAL_FIELD_TO_ORGANIZATIONS = 2
DATASTREAM_ORGANIZATIONAL_FIELD_TO_ALL = 3
# Narrative priority levels
NARRATIVE_PRIORITY_DEBUG = -2
NARRATIVE_PRIORITY_ANALYTIC = -1
NARRATIVE_PRIORITY_DETAIL = 0
NARRATIVE_PRIORITY_INFO = 1
NARRATIVE_PRIORITY_WARNING = 2
NARRATIVE_PRIORITY_CRITICAL = 3
# Narrative types
# High-frequency 'observation' entries for explainable AI and accountability
NARRATIVE_TYPE_OBSERVATION = 0
# Low-frequency 'journal' entries for SUMMARIZED exec-level communications to humans
NARRATIVE_TYPE_JOURNAL = 4
# High-frequency 'journal' entries for real-time CRITICAL exec-level communications to humans
NARRATIVE_TYPE_INSIGHT = 5
# Alert Categories
ALERT_CATAGORY_NONE = 0
ALERT_CATEGORY_LIVE_HERE = 1
ALERT_CATEGORY_FAMILY_FRIEND = 2
ALERT_CATEGORY_SOCIAL_REMINDERS_ONLY = 3
# Location Access
LOCATION_ACCESS_NONE = 0
LOCATION_ACCESS_READONLY = 10
LOCATION_ACCESS_CONTROL_DEVICES = 20
LOCATION_ACCESS_CONTROL_EVERYTHING = 30
# Support Ticket Types
TICKET_TYPE_PROBLEM = 1
TICKET_TYPE_INCIDENT = 2
TICKET_TYPE_QUESTION = 3
TICKET_TYPE_TASK = 4
# Support Ticket Priorities
TICKET_PRIORITY_LOW = 1
TICKET_PRIORITY_NORMAL = 2
TICKET_PRIORITY_HIGH = 3
TICKET_PRIORITY_URGENT = 4
# Tagging
TAG_TYPE_USERS = 1
TAG_TYPE_LOCATIONS = 2
TAG_TYPE_DEVICES = 3
TAG_TYPE_FILES = 4
# Data request types
DATA_REQUEST_TYPE_PARAMETERS = 1
DATA_REQUEST_TYPE_ACTIVITIES = 2
DATA_REQUEST_TYPE_LOCATIONS = 3
DATA_REQUEST_TYPE_MODES = 4
DATA_REQUEST_TYPE_NARRATIVES = 5
DATA_REQUEST_TYPE_DEVICES = 6
BOT_TYPE_LOCATION = 0
BOT_TYPE_ORGANIZATION = 1
BOT_TYPE_ORGANIZATION_RAG = 2
# Location Sub Types
LOCATION_SUB_TYPE_ALL = 0
LOCATION_SUB_TYPE_DEVICE = 1
def __init__(self, inputs={}, bot_variables=None):
"""Constructor"""
self.inputs = inputs
self.loggers = {}
self.reset()
if bot_variables is not None:
import dill
import os
for variable_path in bot_variables:
if not os.path.exists(variable_path):
raise FileNotFoundError(f"Variable file {variable_path} does not exist")
# Unpickle the variables
with open(variable_path, 'rb') as f:
variable = dill.load(f)
name = os.path.basename(variable_path).replace('.variable', '')
self.save_variable(name, variable)
def reset(self):
"""Reset all the flags that let us know how this class was accessed during testing"""
# Logging service names to render
self.logging_service_names = []
self.notify_called = False
self.command_sent = False
self.commands = []
self.professional_monitoring_called = False
self.admin_mail_notified = False
self.mode = "HOME"
self.execute_again_seconds = 0
self.execute_again_timestamp = 0
self.playback = False
self.notification_content = None
self.customer_support_body = None
self.customer_support_comments = []
# Execution time should be consistent
# Set by default to June 1st, 2023 12:00 PM PST
self.time_ms = 1685646000000
# Created tags
self.user_tags = []
self.device_tags = []
self.location_tags = []
self.file_tags = []
# Deleted tags
self.deleted_user_tags = []
self.deleted_device_tags = []
self.deleted_location_tags = []
self.deleted_file_tags = []
# Professional monitoring
self.has_pro_monitoring = True
self.professional_monitoring_raised = False
self.professional_monitoring_code = None
self.professional_monitoring_message = None
self.professional_monitoring_device_id = None
self.professional_monitoring_cancelled = False
# Location settings
self.location_category = None
self.location_rank = None
self.location_comment = None
# Spaces
self.spaces = {}
# States by location id
self.states = {}
# Users
self.users = [
{
"id": 123,
"userName": "john.smith@gmail.com",
"altUsername": "1234567890",
"firstName": "John",
"lastName": "Smith",
"nickname": "Johnny",
"email": {
"email": "john.smith@gmail.com",
"verified": True,
"status": 0,
},
"phone": "1234567890",
"phoneType": 1,
"smsStatus": 1,
"locationAccess": 10,
"temporary": True,
"accessEndDate": "2019-01-29T02:45:30Z",
"accessEndDateMs": 1548747995000,
"category": 1,
"role": 1,
"smsPhone": "1234567890",
"language": "en",
"avatarFileId": 123,
"phoneChannels": {"sms": True, "mms": True, "voice": True},
"schedules": [
{"daysOfWeek": 127, "startTime": 10800, "endTime": 20800}
],
}
]
# Device properties
self.device_properties = {}
# System properties
self.system_properties = {
"ppc.bot.minCountdownThreshold": "10000" # 10 seconds
}
# Questions
self.collections = {}
self.questions = {}
self.questions_to_delete = {}
self.questions_to_ask = {}
self.pro_monitoring_status = {
"callCenter": {
"status": self.PROFESSIONAL_MONITORING_REGISTERED,
"alertStatus": 3,
"alertDate": "2015-09-01T18:00:00Z",
"alertDateMs": 1441130400000,
"alertStatusDate": "2015-09-01T18:00:30Z",
"alertStatusDateMs": 1441130430000,
}
}
# Placeholder for users of this location
self.resident_user_names = [
{"firstName": "Resident", "lastName": "One"},
{"firstName": "Resident", "lastName": "Two"},
]
self.supporter_user_names = [
{"firstName": "Supporter", "lastName": "One"},
{"firstName": "Supporter", "lastName": "Two"},
]
# Last data stream message that was attempted to be sent
self.datastream = {}
# Accumulated list of datastream messages sent during test execution
self.datastream_messages = []
# Timers dictionary by reference
self.timers = {}
# Alarms dictionary by reference
self.alarms = {}
self.variables = {}
self.variables_to_flush = {}
self.organization_properties = {}
self.all_trigger_types = []
# What is this bot's instance ID
self.bot_instance_id = 0
# Is this bot executing locally on a developer laptop
self.local = False
# How many times has this bot been run locally
# Enabling us to know if it's the first run and a new_version() should be triggered, or gather stats if we want.
self.local_execution_count = None
# ============================================================================
# Loggers
# ============================================================================
def _playback_logger_timestamp(self, record, datefmt=None):
"""
Logger playback timestamp override
:param record:
:param datefmt:
:return:
"""
timestamp = self.get_timestamp() / 1000.0
timezone = (
self.get_location_info()
.get("location", {})
.get("timezone", {})
.get("id", "US/Pacific")
)
return datetime.datetime.fromtimestamp(timestamp, pytz.timezone(timezone))
def create_logger(self, name="bot"):
"""Create a logger"""
logging.Formatter.formatTime = self._playback_logger_timestamp
logger = logging.getLogger(name)
if len(self.logging_service_names) > 0 and not any(
[service_name in name for service_name in self.logging_service_names]
):
# All other loggers should describe warning or error messages only
log_level = NON_SERVICE_LOG_LEVEL
else:
log_level = (
LOG_LEVEL if len(self.logging_service_names) == 0 else SERVICE_LOG_LEVEL
)
if not logger.handlers:
# Create a console handler
console_handler = logging.StreamHandler()
console_handler.setLevel(log_level)
fmt = logging.Formatter(
"%(asctime)s %(levelname)-8s %(name)-12s %(message)s"
)
console_handler.setFormatter(fmt)
# Create a blank line handler
blank_handler = logging.StreamHandler()
blank_handler.setLevel(log_level)
blank_handler.setFormatter(logging.Formatter(fmt=""))
# Configure the logger
logger.setLevel(log_level)
logger.addHandler(console_handler)
# Add handlers
logger.console_handler = console_handler
logger.blank_handler = blank_handler
return logger
def get_logger(self, name="bot"):
if name not in self.loggers:
self.loggers[name] = self.create_logger(name)
return self.loggers[name]
def log(self, message, num_of_blank_lines=1):
"""Log with blank lines before the message"""
logger = self.get_logger(f"{__name__}.{__class__.__name__}")
# Switch the handler, output blank lines
logger.removeHandler(logger.console_handler)
logger.addHandler(logger.blank_handler)
for _ in range(num_of_blank_lines):
logger.info("")
# Switch back
logger.removeHandler(logger.blank_handler)
logger.addHandler(logger.console_handler)
logger.info(message)
# ============================================================================
# Inputs
# ============================================================================
def get_inputs(self):
self.get_logger(f"{__name__}.{__class__.__name__}").debug(">get_inputs()")
response = self.inputs
self.get_logger(f"{__name__}.{__class__.__name__}").debug(
"<get_inputs() response=" + str(response)
)
return response
def set_inputs(self, inputs):
self.inputs = inputs
# ============================================================================
# Triggers
# ============================================================================
def set_trigger_type(self, trigger_type):
self.inputs["trigger"] = trigger_type
def get_trigger_type(self):
"""This method will return the type of trigger"""
if "trigger" in self.inputs:
return int(self.inputs["trigger"])
return BotEnginePyTest.TRIGGER_SCHEDULE
def get_trigger_info(self):
"""This method will find and return the information about what triggered this app."""
try:
accessBlock = self.inputs["access"]
except KeyError:
self.get_logger(f"{__name__}.{__class__.__name__}").debug(
"<get_trigger_info"
)
return None
triggerBlock = None
for block in accessBlock:
try:
if block["trigger"]:
triggerBlock = block
break
except KeyError:
pass
self.get_logger(f"{__name__}.{__class__.__name__}").debug("<get_trigger_info")
return triggerBlock
def get_triggers(self):
"""
This method will find and return the information about what triggered this bot.
Location Events (Modes) Example:
{
'category':1,
'control':True,
'trigger':True,
'location':{
'locationId':62,
'prevEvent':'HOME',
'event':'AWAY'
},
'read':True
}
Device Measurements Example:
{
'trigger':True,
'device':{
'deviceType':10014,
'updateDate':1465517032000,
'deviceId':'FFFFFFFF00600a70',
'description':'Practice\xa0Entry\xa0Sensor',
'measureDate':1465517031000
},
'read':True,
'control':True,
'category':4
}
:return: JSON structure describing what triggered this bot
"""
if "access" not in self.inputs:
return []
self.trigger_blocks = []
for block in self.inputs["access"]:
if "trigger" in block:
if block["trigger"]:
self.trigger_blocks.append(block)
return self.trigger_blocks
# ============================================================================
# Blocks
# ============================================================================
def get_measures_block(self):
"""Return the measurements block from our inputs, if any"""
return self.inputs.get("measures", None)
def get_alerts_block(self):
"""Return the alerts block from our inputs, if any"""
return self.inputs.get("alerts", None)
def get_access_block(self):
"""Return the access block from our inputs, if any"""
return self.inputs.get("access", None)
def get_datastream_block(self):
"""
:return: the data stream inputs, if any
"""
return self.inputs.get("dataStream", None)
def get_documents_request_id(self):
"""
:return: the documents request ID
"""
return self.inputs.get("requestId", None)
def get_document_block(self):
"""
:return: the 'document' block for location configuration triggers
"""
return self.inputs.get("document", None)
def get_users_block(self):
"""
:return: The 'users' block for location configuration triggers
"""
return self.inputs.get("users", None)
def get_callcenter_block(self):
"""
:return: The 'callCenter' block for location configuration triggers
"""
return self.inputs.get("callCenter", None)
def get_data_block(self):
"""
:return: The 'data' block for asynchronous data request inputs
"""
return self.inputs.get("data", None)
def get_input_key(self):
"""
:return: the key provided by the input, if any
"""
return self.inputs.get("key", None)
def get_location_block(self):
"""Return the location access block from our inputs, if any"""
access_block = self.get_access_block()
if access_block:
for block in access_block:
if (
"category" in block
and block["category"] == BotEnginePyTest.ACCESS_CATEGORY_MODE
):
if (
block
.get("location", {})
.get("subType", 0) == BotEnginePyTest.LOCATION_SUB_TYPE_DEVICE
):
continue
return block
return {
"category": 1,
"control": True,
"location": {
"id": 0,
"event": "HOME",
"latitude": "47.72328",
"locationId": 0,
"longitude": "-122.17426",
"name": "Apartment 103",
"timezone": {
"dst": True,
"id": "US/Pacific",
"name": "Pacific Standard Time",
"offset": -480,
},
"zip": "98034",
},
"read": True,
"trigger": True,
}
def get_messages_block(self):
"""
:return: the messages block from our inputs, if any
"""
if "messages" in self.inputs:
return self.inputs["messages"]
return None
def get_bundle_id(self):
"""
When you generate a bot, botengine will automatically generate and add a 'bundle.py' file which contains the bundle ID.
This method simply returns the bundle ID from the contents of that file.
:return: The bundle ID for this bot
"""
import bundle # type: ignore
return bundle.BUNDLE_ID
def get_cloud_address(self):
"""
When you generate a bot, botengine will automatically generate and add a 'bundle.py' file which contains the cloud address we're uploading the bot to.
This method simply returns the CLOUD_ADDRESS from the contents of the bundle.py file.
:return: The cloud address for this bot
"""
import bundle # type: ignore
return bundle.CLOUD_ADDRESS
def get_bot_type(self):
"""
When you generate a bot, botengine will automatically generate and add a 'bundle.py' file which contains the bot type.
This method simply returns the BOT_TYPE from the contents of the bundle.py file.
:return: The bot type for this bot
"""
import bundle # type: ignore
return int(bundle.BOT_TYPE if hasattr(bundle, "BOT_TYPE") else 0)
def get_bot_instance_id(self):
"""
:return: The bot instance ID
"""
return self.bot_instance_id
def get_location_id(self):
"""
:return: The location ID for this bot
"""
location_info = self.get_location_info()
if location_info is not None:
if "locationId" in location_info["location"]:
return location_info["location"]["locationId"]
return 0
def get_name_by_user_id(self, user_id):
"""
Returns a dictionary with 'firstName' and 'lastName' if the user exists, or None if the user doesn't exist
:param user_id: User ID to extract the name
:return: { 'firstName': "David", 'lastName': "Moss" }
"""
users = self.get_location_users()
for user in users:
if int(user["id"]) == int(user_id or -1):
name = {"firstName": "", "lastName": ""}
if "firstName" in user:
name["firstName"] = user["firstName"]
if "lastName" in user:
name["lastName"] = user["lastName"]
return name
return None
def get_formatted_name_by_user_id(self, user_id):
"""
Returns the name like "David Moss"
:param user_id:
:return:
"""
name = self.get_name_by_user_id(user_id)
if name is not None:
return "{} {}".format(name["firstName"], name["lastName"]).strip()
return None
def get_organization_id(self):
"""
:return: The organization ID for this bot
"""
return 0
def get_organization_name(self):
"""
:return: The name of the organization this location belongs to.
"""
return "Organization ID {}".format(self.get_organization_id())
def get_organization_signup_code(self):
"""
:return: The sign-up code (short domain name) of the organization this location belongs to. Or None if we don't have it for some reason.
"""
return "pytest"
def get_country_code(self):
"""
:return: The country code of the location.
"""
return "1"
def get_location_info(self, sub_type=LOCATION_SUB_TYPE_ALL):
"""
:param location_id: Location ID to extract
:param sub_type: Sub type of location to extract, or LOCATION_SUB_TYPE_ALL for any
:return: location information from the access block
"""
return self.get_location_block()
def get_locations(self):
"""
:return: All locations available to this bot
"""
locations = []
access_block = self.get_access_block()
if access_block:
for block in access_block:
if (
"category" in block
and block["category"] == BotEnginePyTest.ACCESS_CATEGORY_MODE
):
locations.append(block)
else:
locations.append(self.get_location_block())
return locations
def get_user_id(self):
"""
:return: User ID
"""
return -1
def get_user_first_name(self):
return "PyTest"
def get_user_last_name(self):
return "Harness"
def get_user_name(self):
return "PyTest Harness"
def get_location_name(self):
return "PyTest Location"
# ===========================================================================
# Location Settings
# ===========================================================================
def set_location_priority(self, category, rank, comment=None):
"""
Set the prioritized category of human attention needed for this location.
0 = This location has no devices.
1 = Everything is running okay
2 = This location is learning
3 = Incomplete installation (of devices, people, etc.)
4 = System problem (offline devices, low battery, abnormal device behaviors, etc.)
5 = Subjective warning (abnormal trends, sleeping too much, etc.)
6 = Critical alert (falls, didn't wake up, water leak, etc.)
:param category: Priority from 0 - 6 where 6 requires the most human attention
:param rank: Rank from 100% good to 0% good to compare homes within a specific category
:param comment: Human-understandabld description of why the location has this priority
:return:
"""
self.location_category = category
self.location_rank = rank
self.location_comment = comment
def get_spaces(self):
"""
Get a list of spaces for this location
https://iotapps.docs.apiary.io/#reference/locations/location-spaces/get-spaces
:return: List of spaces
"""
return self.spaces
def set_space(self, space_type, name, space_id=None):
"""
Add / Update a space
https://iotapps.docs.apiary.io/#reference/locations/location-spaces/update-space
:param space_type: Type of space
:param name: Name of space
:param space_id: Space ID to update an existing space definition
"""
self.spaces[name] = (space_type, space_id)
def delete_space(self, space_id):
"""
Delete a space
https://iotapps.docs.apiary.io/#reference/locations/location-spaces/delete-space
:param space_id: Space ID to delete
"""
for name in self.spaces:
s_type, s_id = self.spaces[name]
if s_id == space_id:
del self.spaces[name]
return
def add_occupancy(self, occupancy):
"""
Add occupancy
https://iotapps.docs.apiary.io/#reference/locations/location-occupancy/add-occupancy
:param occupancy: Bitmask mark that locations is occupied or vacant:
0 - none or no data
1 - managed
2 - measured
"""
self.get_logger(f"{__name__}.{__class__.__name__}").warning(
"botengine_pytest: Attempting to add_occupancy() but we haven't implemented this yet."
)
return
def delete_occupancy(self, occupancy):
"""
Delete occupancy
https://iotapps.docs.apiary.io/#reference/locations/location-occupancy/remove-occupancy
:param occupancy: Bitmask mark that locations is occupied or vacant:
0 - none or no data
1 - managed
2 - measured
"""
self.get_logger(f"{__name__}.{__class__.__name__}").warning(
"botengine_pytest: Attempting to delete_occupancy() but we haven't implemented this yet."
)
return
def get_language(self, user_id=None):
"""
Get the language for the bot associated with this organization, bot domain, location, or user.
:param user_id: User ID to get the language for.
:return: language code
"""
import properties # type: ignore
language_code = properties.get_property(
self, "DEFAULT_LANGUAGE", complain_if_missing=False
)
location_info = self.get_location_info()
if location_info is not None:
if "language" in location_info["location"]:
language_code = location_info["location"]["language"]
if user_id is not None:
user = self.get_location_user(user_id)
if user is not None:
if "language" in user:
language_code = user["language"]
# Default to English
return language_code if language_code is not None else "en"
# ============================================================================
# Timestamps
# ============================================================================
def get_timestamp(self):
"""Return the current botengine time
:return: time in ms
"""
if "time" in self.inputs:
self.time_ms = self.inputs["time"]
return self.time_ms
def set_timestamp(self, timestamp):
"""Set the current botengine time
:param timestamp: time in ms
"""
if "time" in self.inputs:
self.inputs["time"] = timestamp
self.time_ms = timestamp
def add_timestamp(self, timestamp):
"""Add the time to the current botengine time
:param timestamp: time in ms
"""
if "time" in self.inputs:
self.inputs["time"] += timestamp
self.time_ms += timestamp
# ============================================================================
# Variables
# ============================================================================
def save_variable(
self, name, value, required_for_each_execution=False, shared=False, overwrite=False
):
self.get_logger(f"{__name__}.{__class__.__name__}").debug(
">save_variable() {}:{}".format(name, value)
)
if shared:
self.save_shared_variable(name, value)
return
self.save_variables(
{name: value},
required_for_each_execution=required_for_each_execution,
shared=shared,
overwrite=overwrite,
)
def save_variables(
self, variables_dictionary, required_for_each_execution=False, shared=False, overwrite=False
):
self.get_logger(f"{__name__}.{__class__.__name__}").debug(
">save_variables() variables={} required_for_each_execution={} shared={} overwrite={}".format(
variables_dictionary, required_for_each_execution, shared, overwrite
)
)
if shared:
for name, value in variables_dictionary.items():
self.save_shared_variable(name, value)
return
if required_for_each_execution:
if CORE_VARIABLE_NAME not in self.variables:
self.variables[CORE_VARIABLE_NAME] = {}
if overwrite:
for name, value in variables_dictionary.items():
self.variables[CORE_VARIABLE_NAME][name] = value
else:
self.variables[CORE_VARIABLE_NAME].update(variables_dictionary)
self.variables_to_flush[CORE_VARIABLE_NAME] = self.variables[CORE_VARIABLE_NAME]
else:
if overwrite:
for name, value in variables_dictionary.items():
self.variables[name] = value
self.variables_to_flush[name] = value
else:
self.variables.update(variables_dictionary)
self.variables_to_flush.update(variables_dictionary)
return
def load_variable(self, name, shared=False):
self.get_logger(f"{__name__}.{__class__.__name__}").debug(
">load_variable() name={} shared={}".format(name, shared)
)
if shared:
return self.load_shared_variable(name)
if CORE_VARIABLE_NAME in self.variables:
if name in self.variables[CORE_VARIABLE_NAME]:
return self.variables[CORE_VARIABLE_NAME][name]
if name in self.variables:
return self.variables[name]
else:
return None
def load_variables(self, names):
return_values = {}