Skip to content

Build workflows for your Relays

A module for implementing Relay workflows in Python. This is the SDK that provides a way for your enterprise to extend your I/T tools to your active workers via Relay devices. There are APIs for text-to-speech (say), speech-to-text (listen), LED control, vibration control, location information, NFC tag taps, etc. See https://developer.relaypro.com

Relay

Includes the main functionalities that are used within workflows, such as functions for communicating with the device, sending out notifications to groups, handling workflow events, and performing physical actions on the device such as manipulating LEDs and creating vibrations.

Source code in relay/workflow.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
class Relay:
    """Includes the main functionalities that are used within workflows,
    such as functions for communicating with the device, sending out
    notifications to groups, handling workflow events, and performing physical actions
    on the device such as manipulating LEDs and creating vibrations.
    """

    def __init__(self, workflow: Workflow):
        """Initializes workflow fields.

        Args:
            workflow (Workflow): your workflow.
        """
        self.workflow = workflow
        self.websocket = None
        self.id_futures = {}  # {_id: future}
        self.event_futures = {}
        self.logger = None

    def _get_cid(self):
        # correlation id
        return f'{self.workflow.name}:{id(self.websocket)}'

    def _from_json(self, websocket_message):
        dict_message = json.loads(websocket_message)
        return self._clean_int_arrays(dict_message)

    def _clean_int_arrays(self, dict_message):
        # work around the JSON formatting issue in iBot
        # that gives us an array of ints instead of a string:
        # will be fixed in iBot 3.10 via PE-17571

        if isinstance(dict_message, dict):
            for key in dict_message.keys():
                if isinstance(dict_message[key], (list, dict)):
                    dict_message[key] = self._clean_int_arrays(dict_message[key])
        elif isinstance(dict_message, list):
            all_int = True
            for item in dict_message:
                if not isinstance(item, int):
                    all_int = False
                    break
            if all_int and (len(dict_message) > 0):
                dict_message = "".join(chr(i) for i in dict_message)
        return dict_message

    @staticmethod
    def _validate_trigger(trigger: dict):
        if not isinstance(trigger, dict):
            raise WorkflowException('trigger parameter is not a dictionary')
        if 'args' not in trigger:
            raise WorkflowException('trigger parameter is not a trigger dictionary')
        if 'source_uri' not in trigger['args']:
            raise WorkflowException('there is no source_uri definition in the trigger')

    @staticmethod
    def make_target_uris(trigger: dict):
        """Creates a target URN after receiving a workflow trigger.

        Args:
            trigger (dict): workflow trigger.

        Raises:
            WorkflowException: thrown if the trigger param is not a dictionary.
            WorkflowException: thrown if the trigger param is not a trigger dictionary.
            WorkflowException: thrown if there is no source_uri definition in the trigger.

        Returns:
            a target object created from the trigger.
        """
        Relay._validate_trigger(trigger)
        target = {
            'uris': [trigger['args']['source_uri']]
        }
        return target

    @staticmethod
    def get_source_uri_from_trigger(trigger: dict) -> str:
        """Get the source URN from a workflow trigger

        Args:
            trigger (dict): workflow trigger.

        Raises:
            WorkflowException: thrown if the trigger param is not a dictionary.
            WorkflowException: thrown if the trigger param is not a trigger dictionary.
            WorkflowException: thrown if there is no source_uri definition in the trigger.

        Returns:
            the source URN as a string from the trigger.

        """
        Relay._validate_trigger(trigger)
        source_uri = trigger['args']['source_uri']
        return source_uri

    @staticmethod
    def targets_from_source_uri(source_uri: str):
        """Creates a target object from a source URN.
        Enables the device to perform the desired action after the function
        has been called.  Used interanlly by interaction functions such as
        say(), listen(), vibration(), etc.

        Args:
            source_uri (str): source uri that will be used to create a target.

        Returns:
            the target that was created from a source URN.
        """
        targets = {
            'uris': [source_uri]
        }
        return targets

    async def _handle(self, websocket):

        self.websocket = websocket
        self.logger = CustomAdapter(logger, {'cid': self._get_cid()})

        self.logger.info(f'workflow instance started for {self.websocket.path}')

        try:
            async for m in websocket:
                # TODO: restore after PE-17571
                # self.logger.debug(f'recv raw: {m}')
                e = self._from_json(m)
                self.logger.debug(f'recv: {e}')

                _id = e.get('_id', None)
                _type = e.get('_type', None)

                fut = self.id_futures.pop(_id, None)
                if fut:
                    fut.set_result(e)

                else:
                    handled = False
                    future = self._pop_event_match(e)
                    if future:
                        future.set_result(e)
                        handled = True

                    # events that don't have an _id field (some events do have an _id field for async response data)
                    h = self.workflow.get_handler(e)
                    if h:
                        if _type == 'wf_api_start_event':
                            asyncio.create_task(self._wrapper(h, e['trigger']))

                        elif _type == 'wf_api_stop_event':
                            asyncio.create_task(self._wrapper(h, e['reason']))

                        elif _type == 'wf_api_prompt_event':
                            asyncio.create_task(self._wrapper(h, e['source_uri'], e['type']))

                        elif _type == 'wf_api_button_event':
                            asyncio.create_task(self._wrapper(h, e['button'], e['taps'], e['source_uri']))

                        elif _type == 'wf_api_notification_event':
                            asyncio.create_task(
                                self._wrapper(h, e['event'], e['name'], e['notification_state'], e['source_uri']))

                        elif _type == 'wf_api_timer_event':
                            asyncio.create_task(self._wrapper(h))

                        elif _type == 'wf_api_timer_fired_event':
                            asyncio.create_task(self._wrapper(h, e['name']))

                        elif _type == 'wf_api_speech_event':
                            text = e['text'] if 'text' in e else None
                            audio = e['audio'] if 'audio' in e else None
                            asyncio.create_task(
                                self._wrapper(h, text, audio, e['lang'], e['request_id'], e['source_uri']))

                        elif _type == 'wf_api_progress_event':
                            asyncio.create_task(self._wrapper(h))

                        elif _type == 'wf_api_play_inbox_message_event':
                            asyncio.create_task(self._wrapper(h, e['action']))

                        elif _type == 'wf_api_call_connected_event':
                            asyncio.create_task(
                                self._wrapper(h, e['call_id'], e['direction'], e['device_id'], e['device_name'],
                                              e['uri'], e['onnet'], e['start_time_epoch'], e['connect_time_epoch']))

                        elif _type == 'wf_api_call_disconnected_event':
                            asyncio.create_task(
                                self._wrapper(h, e['call_id'], e['direction'], e['device_id'], e['device_name'],
                                              e['uri'], e['onnet'], e['reason'], e['start_time_epoch'],
                                              e['connect_time_epoch'], e['end_time_epoch']))

                        elif _type == 'wf_api_call_failed_event':
                            asyncio.create_task(
                                self._wrapper(h, e['call_id'], e['direction'], e['device_id'], e['device_name'],
                                              e['uri'], e['onnet'], e['reason'], e['start_time_epoch'],
                                              e['connect_time_epoch'], e['end_time_epoch']))

                        elif _type == 'wf_api_call_received_event':
                            asyncio.create_task(
                                self._wrapper(h, e['call_id'], e['direction'], e['device_id'], e['device_name'],
                                              e['uri'], e['onnet'], e['start_time_epoch']))

                        elif _type == 'wf_api_call_ringing_event':
                            asyncio.create_task(
                                self._wrapper(h, e['call_id'], e['direction'], e['device_id'], e['device_name'],
                                              e['uri'], e['onnet'], e['start_time_epoch']))

                        elif _type == 'wf_api_call_progressing_event':
                            asyncio.create_task(
                                self._wrapper(h, e['call_id'], e['direction'], e['device_id'], e['device_name'],
                                              e['uri'], e['onnet'], e['start_time_epoch'], e['connect_time_epoch']))

                        elif _type == 'wf_api_call_start_request_event':
                            asyncio.create_task(self._wrapper(h, e['uri']))

                        elif _type == 'wf_api_sms_event':
                            asyncio.create_task(self._wrapper(h, e['id'], e['event']))

                        elif _type == 'wf_api_incident_event':
                            asyncio.create_task(self._wrapper(h, e['type'], e['incident_id'], e['reason']))

                        elif _type == 'wf_api_interaction_lifecycle_event':
                            reason = e['reason'] if 'reason' in e else None
                            asyncio.create_task(self._wrapper(h, e['type'], e['source_uri'], reason))

                        elif _type == 'wf_api_resume_event':
                            asyncio.create_task(self._wrapper(h, e['trigger']))

                    elif not handled:
                        if (_type == 'wf_api_prompt_event') or (_type == 'wf_api_speech_event') or (
                                _type == 'wf_api_stop_event'):
                            level = logging.DEBUG
                        else:
                            level = logging.WARNING
                        self.logger.log(level, f'no handler found for _type {e["_type"]}')
        # the "exceptions" module is really what we receive
        except websockets.exceptions.ConnectionClosedError:
            # ibot closes the connection on terminate(); this is expected
            pass

        except Exception as x:
            self.logger.error(f'{x}', exc_info=True)

        finally:
            self.logger.info('workflow instance terminated')

    # run handlers with exception logging; needed since we cannot await handlers
    async def _wrapper(self, h, *args):
        try:
            await h(self, *args)
        except Exception as x:
            self.logger.error(f'{x}', exc_info=True)

    async def _send(self, obj):
        _id = uuid.uuid4().hex
        obj['_id'] = _id

        # TODO: ibot add responses to all _request events? if so, await them here ... and check for error responses

        await self._send_str(json.dumps(obj))

    async def _send_receive(self, obj, uid=None):
        _id = uid if uid else uuid.uuid4().hex
        obj['_id'] = _id
        fut = asyncio.get_event_loop().create_future()
        self.id_futures[_id] = fut

        # TODO: ibot currently loads null as the string 'null'
        await self._send_str(json.dumps(remove_null(obj)))
        # wait on the response
        await fut
        rsp = fut.result()
        if rsp['_type'] == 'wf_api_error_response':
            raise WorkflowException(rsp['error'])
        return fut.result()

    async def _send_str(self, s):
        self.logger.debug(f'send: {s}')
        await self.websocket.send(s)

    async def get_var(self, name: str, default=None):
        """Retrieves a variable that was set either during workflow registration
        or through the set_var() function.  The variable can be retrieved anywhere
        within the workflow, but is erased after the workflow terminates.

        Args:
            name (str): name of the variable to be retrieved.
            default (optional): default value of the variable if it does not exist. Defaults to None.

        Returns:
            the variable requested.
        """
        # TODO: look in self.workflow.state to see all of what is available
        event = {
            '_type': 'wf_api_get_var_request',
            'name': name
        }
        v = await self._send_receive(event)
        return v.get('value', default)

    async def get_number_var(self, name: str, default=None):
        """Retrieves a variable that was set either during workflow registration
        or through the set_var() function of type integer.  The variable can be retrieved anywhere
        within the workflow, but is erased after the workflow terminates.

        Args:
            name (str): name of the variable to be retrieved.
            default (optional): default value of the variable if it does not exist. Defaults to None.

        Returns:
            the variable requested.
        """
        return int(await self.get_var(name, default))

    async def set_var(self, name: str, value: str):
        """Sets a variable with the corresponding name and value. Scope of
        the variable is from start to end of a workflow.  Note that you 
        can only set values of type string.
        Args:
            name (str): name of the variable to be created.
            value (str): value that the variable will hold.
        """
        event = {
            '_type': 'wf_api_set_var_request',
            'name': name,
            'value': value
        }
        response = await self._send_receive(event)
        return response['value']

    async def unset_var(self, name: str):
        """Unsets the value of a variable.  

        Args:
            name (str): the name of the variable whose value you would like to unset.
        """
        event = {
            '_type': 'wf_api_unset_var_request',
            'name': name
        }
        await self._send_receive(event)

    @staticmethod
    def interaction_options(color: str = "0000ff", input_types: list = None, home_channel: str = "suspend"):
        """Options for when an interaction is started via a workflow.

        Args:
            color (str, optional): desired color of LEDs when an interaction is started. Defaults to "0000ff".
            input_types (list, optional): input types you would like for the interaction. Defaults to an empty list.
            home_channel (str, optional): home channel for the device during the interaction. Defaults to "suspend".

        Returns:
            the options specified.
        """
        if input_types is None:
            input_types = []
        options = {
            'color': color,
            'input_types': input_types,
            'home_channel': home_channel
        }
        return options

    async def start_interaction(self, target, name: str, options=None):
        """Starts an interaction with the user.  Triggers an INTERACTION_STARTED event
        and allows the user to interact with the device via functions that require an 
        interaction URN.

        Args:
            target (target): the device that you would like to start an interaction with.
            name (str): a name for your interaction.
            options (optional): can be color, home channel, or input types. Defaults to None.
        """
        event = {
            '_type': 'wf_api_start_interaction_request',
            '_target': target,
            'name': name,
            'options': options
        }
        await self._send_receive(event)

    async def end_interaction(self, target):
        """Ends an interaction with the user.  Triggers an INTERACTION_ENDED event to signify
        that the user is done interacting with the device.

        Args:
            target(str): the interaction that you would like to end.
        """
        event = {
            '_type': 'wf_api_end_interaction_request',
            '_target': self.targets_from_source_uri(target)
        }
        await self._send_receive(event)

    def _set_event_match(self, criteria: dict):
        if not isinstance(criteria, dict):
            raise WorkflowException("criteria is not a dict")
        match_data = criteria.copy()
        uid = uuid.uuid4().hex
        future = asyncio.get_event_loop().create_future()
        match_data['_timestamp'] = time.time()
        match_data['_future'] = future
        self.event_futures[uid] = match_data
        return future

    @staticmethod
    async def _wait_for_event_match(future, timeout: int):
        await asyncio.wait_for(future, timeout)
        event = future.result()
        if event['_type'] == 'wf_api_error_response':
            raise WorkflowException(event['error'])
        return event

    def _pop_event_match(self, event):
        # check if event matches anything we are waiting for
        now = time.time()
        for uid in self.event_futures:
            # purge old items (30 minutes)
            age = now - self.event_futures[uid]['_timestamp']
            if age > 1800:
                self.event_futures.pop(uid, None)
                continue
            matches = True
            criteria = self.event_futures[uid]
            for key in criteria:
                if key == '_timestamp' or key == '_future':
                    continue
                # if event doesn't have criteria item, then fail
                if key not in event:
                    matches = False
                    break
                if self.event_futures[uid][key] != event[key]:
                    matches = False
                    break
            if matches:
                future = self.event_futures[uid]['_future']
                self.event_futures.pop(uid, None)
                return future
        return None

    async def listen(self, target, phrases=None, transcribe: bool = True, alt_lang: str = None, timeout: int = 60):
        """Listens for the user to speak into the device.  Utilizes speech to text functionality to interact
        with the user.

        Args:
            target (str): the interaction URN.
            phrases (string[], optional): optional phrases that you would like to limit the user's response to.
             Defaults to None.
            transcribe (bool, optional): whether you would like to transcribe the user's reponse. Defaults to True.
            timeout (int, optional): timeout for how long the device will wait for user's response. Defaults to 60.
            alt_lang (str, optional): if you would like the device to listen for a response in a specific language.
             Defaults to None.

        Returns:
            text representation of what the user had spoken into the device.
        """
        if phrases is None:
            phrases = []
        if isinstance(phrases, str):
            phrases = [phrases]

        _id = uuid.uuid4().hex
        event = {
            '_type': 'wf_api_listen_request',
            '_target': self.targets_from_source_uri(target),
            'phrases': phrases,
            'transcribe': transcribe,
            'timeout': timeout,
            'alt_lang': alt_lang
        }

        criteria = {
            '_type': 'wf_api_speech_event',
            'request_id': _id
        }
        # need to add this before _send_receive to avoid race condition
        event_future = self._set_event_match(criteria)
        await self._send_receive(event, _id)
        speech_event = await self._wait_for_event_match(event_future, timeout)

        if transcribe:
            return speech_event['text']
        else:
            return speech_event['audio']

    async def play(self, target, filename: str):
        """Plays a custom audio file that was uploaded by the user.

        Args:
            target(str): the interaction URN.
            filename (str): the name of the audio file.

        Returns:
            the response id after the audio file has been played on the device.
        """
        event = {
            '_type': 'wf_api_play_request',
            '_target': self.targets_from_source_uri(target),
            'filename': filename
        }
        response = await self._send_receive(event)
        return response['id']

    async def play_and_wait(self, target, filename: str):
        """Plays a custom audio file that was uploaded by the user.
        Waits until the audio file has finished playing before continuing through
        the workflow.

        Args:
            target(str): the interaction URN.
            filename (str): the name of the audio file.

        Returns:
            the response id after the audio file has been played on the device.
        """
        _id = uuid.uuid4().hex
        event = {
            '_type': 'wf_api_play_request',
            '_target': self.targets_from_source_uri(target),
            'filename': filename
        }

        criteria = {
            '_type': 'wf_api_prompt_event',
            'type': 'stopped',
            'id': _id
        }

        event_future = self._set_event_match(criteria)
        response = await self._send_receive(event, _id)
        await self._wait_for_event_match(event_future, 30)
        return response['id']

    async def say(self, target, text: str, lang: str = 'en-US'):
        """Utilizes text to speech capabilities to make the device 'speak' to the user.

        Args:
            target(str): the interaction URN.
            text (str): what you would like the device to say.
            lang (str, optional): the language of the text that is being spoken. Defaults to 'en-US'.

        Returns:
            the response ID after the device speaks to the user.
        """
        event = {
            '_type': 'wf_api_say_request',
            '_target': self.targets_from_source_uri(target),
            'text': text,
            'lang': lang
        }
        response = await self._send_receive(event)
        return response['id']

    async def say_and_wait(self, target, text: str, lang: str = 'en-US'):
        """Utilizes text to speech capabilities to make the device 'speak' to the user.
        Waits until the text is fully played out on the device before continuing.

        Args:
            target(str): the interaction URN.
            text (str): what you would like the device to say.
            lang (str, optional): the language of the text that is being spoken. Defaults to 'en-US'.

        Returns:
            the response ID after the device speaks to the user.
        """
        _id = uuid.uuid4().hex
        event = {
            '_type': 'wf_api_say_request',
            '_target': self.targets_from_source_uri(target),
            'text': text,
            'lang': lang
        }

        criteria = {
            '_type': 'wf_api_prompt_event',
            'type': 'stopped',
            'id': _id}

        event_future = self._set_event_match(criteria)
        response = await self._send_receive(event, _id)
        await self._wait_for_event_match(event_future, 30)
        logger.debug(f'wait complete for {target}')
        return response['id']

    @staticmethod
    def push_options(priority: str = 'normal', title: str = None, body: str = None, sound: str = 'default'):
        """Push options for a virtual device after receiving a notification on the Relay App.

        Args:
            priority (str, optional): priority of the notification. Can be 'normal', 'high', or 'critical'.
             Defaults to 'normal'.
            title (str, optional): title of the notification. Defaults to None.
            body (str, optional): body of the notification. Defaults to None.
            sound (str, optional): sound to be played when notification appears on app. Can be 'default', or 'sos'.
              Defaults to 'default'.

        Returns:
            the options for priority and sound as specified.
        """

        options = {
            'priority': priority,
            'sound': sound
        }
        if title is not None:
            options['title'] = title
        if body is not None:
            options['body'] = body
        return options

    # target properties: uri: array of string ids

    # repeating tone plus tts until button press
    async def alert(self, target, originator: str, name: str, text: str, push_opts: dict = None):
        """Sends out an alert to the specified group of devices and the Relay Dash.

        Args:
            target(str): the group URN that you would like to send an alert to.
            originator (str): the URN of the device that triggered the alert.
            name (str): a name for your alert.
            text (str): the text that you would like to be spoken to the group as your alert.
            push_opts (dict, optional): push options for if the alert is sent to the Relay app on a virtual device.
             Defaults to an empty value.
        """
        if push_opts is None:
            push_opts = {}
        await self._send_notification(target, originator, 'alert', text, name, push_opts)

    async def cancel_alert(self, target, name: str):
        """Cancels an alert that was sent to a group of devices.  Particularly useful if you would like to cancel
         the alert on all devices after one device has acknowledged the alert.

        Args:
            target(str): the device URN that has acknowledged the alert.
            name (str): the name of the alert.
        """
        await self._send_notification(target, None, 'cancel', None, name)

    async def broadcast(self, target, originator: str, name: str, text: str, push_opts: dict = None):
        """Sends out a broadcast message to a group of devices.  The message is played out on
        all devices, as well as sent to the Relay Dash.

        Args:
            target(str): the group URN that you would like to broadcast your message to.
            originator (str): the device URN that triggered the broadcast.
            name (str): a name for your broadcast.
            text (str): the text that you would like to be broadcasted to your group.
            push_opts (dict, optional): push options for if the broadcast is sent to the Relay app on a virtual
             device. Defaults to an empty value.
        """
        if push_opts is None:
            push_opts = {}
        await self._send_notification(target, originator, 'broadcast', text, name, push_opts)

    async def cancel_broadcast(self, target, name: str):
        """Cancels the broadcast that was sent to a group of devices.

        Args:
            target(str): the device URN that is cancelling the broadcast.
            name (str): the name of the broadcast that you would like to cancel.
        """
        await self._send_notification(target, None, 'cancel', None, name)

    async def _send_notification(self, target, originator: Union[str, None], ntype: str,
                                 text: Union[str, None], name: str, push_opts: dict = None):
        """Used for sending a notification on the server.  Private method that is
        used by alert() and broadcast().

        Args:
            target (str): the group URN that you are sending a notification to.
            originator (str): the device that triggered the notification.
            ntype (str): the type of notification, either 'alert' or 'broadcast'.
            name (str): a name for your notification.
            text (str): the text of your notification.
            push_opts (dict, optional): allows you to customize the push notification sent to a virtual device.
             Defaults to None.
        """
        event = {
            '_type': 'wf_api_notification_request',
            '_target': self.targets_from_source_uri(target),
            'originator': originator,
            'type': ntype,
            'name': name,
            'text': text,
            'target': self.targets_from_source_uri(target),
            'push_opts': push_opts
        }
        await self._send_receive(event)

    async def set_channel(self, target, channel_name: str, suppress_tts: bool = False,
                          disable_home_channel: bool = False):
        """Sets the channel that a device is on.  This can be used to change the channel of a device during a workflow,
        where the channel will also be updated on the Relay Dash.

        Args:
            target (str): the device or interaction URN.
            channel_name (str): the name of the channel you would like to set your device to.
            suppress_tts (bool, optional): whether you would like to surpress text to speech. Defaults to False.
            disable_home_channel (bool, optional): whether you would like to disable the home channel.
             Defaults to False.
        """
        event = {
            '_type': 'wf_api_set_channel_request',
            '_target': self.targets_from_source_uri(target),
            'channel_name': channel_name,
            'suppress_tts': suppress_tts,
            'disable_home_channel': disable_home_channel
        }
        await self._send_receive(event)

    async def get_device_name(self, target):
        """Returns the name of a targeted device.

        Args:
            target (str): the device or interaction URN.

        Returns:
            str: the name of the device.
        """
        v = await self._get_device_info(target, 'name')
        return v['name']

    async def get_device_address(self, target, refresh: bool = False):
        """Returns the address of a targeted device.

        Args:
            target (str): the device or interaction URN.
            refresh (bool, optional): whether you would like to refresh before retrieving the address.
             Defaults to False.

        Returns:
            str: the address of the device.
        """
        return await self.get_device_location(target, refresh)

    async def get_device_location(self, target, refresh: bool = False):
        """Returns the location of a targeted device.

        Args:
            target (str): the device or interaction URN.
            refresh (bool, optional): whether you would like to refresh before retrieving the location.
             Defaults to False.

        Returns:
            str: the location of the device.
        """
        v = await self._get_device_info(target, 'address', refresh)
        return v['address']

    async def get_device_latlong(self, target, refresh: bool = False):
        """Returns the latitude and longitude coordinates of a targeted device.

        Args:
            target (str): the device or interaction URN.
            refresh (bool, optional): whether you would like to refresh before retrieving the coordinates.
             Defaults to False.

        Returns:
            float[]: an array containing the latitude and longitude of the device.
        """
        return await self.get_device_coordinates(target, refresh)

    async def get_device_coordinates(self, target, refresh: bool = False):
        """Retrieves the coordinates of the device's location.

        Args:
            target (str): the device or interaction URN.
            refresh (bool, optional): whether you would like to refresh before retreiving the coordinates.
             Defaults to False.
        """
        v = await self._get_device_info(target, 'latlong', refresh)
        return v['latlong']

    async def get_device_indoor_location(self, target, refresh: bool = False):
        """Returns the indoor location of a targeted device.

        Args:
            target (str): the device or interaction URN.
            refresh (bool, optional): whether you would like to refresh before retrieving the location.
             Defaults to False.

        Returns:
            str: the indoor location of the device.
        """
        v = await self._get_device_info(target, 'indoor_location', refresh)
        return v['indoor_location']

    async def get_device_battery(self, target, refresh: bool = False):
        """Returns the battery of a targeted device.

        Args:
            target (str): the device or interaction URN.
            refresh (bool, optional): whether you would like to refresh before retrieving the battery.
             Defaults to False.

        Returns:
            int: the battery of the device.
        """
        v = await self._get_device_info(target, 'battery', refresh)
        return v['battery']

    async def get_device_type(self, target):
        """Returns the device type of a targeted device, i.e. gen 2, gen 3, etc.

        Args:
            target (str): the device or interaction URN.

        Returns:
            str: the device type.
        """
        v = await self._get_device_info(target, 'type')
        return v['type']

    async def get_device_id(self, target):
        """Returns the ID of a targeted device.

        Args:
            target (str): the device or interaction URN.

        Returns:
            str: the device ID.
        """
        v = await self._get_device_info(target, 'id')
        return v['id']

    async def get_user_profile(self, target):
        """Returns the user profile of a targeted device.

        Args:
            target (str): the device or interaction URN.

        Returns:
            str: the user profile registered to the device.
        """
        v = await self._get_device_info(target, 'username')
        return v['username']

    async def get_device_location_enabled(self, target):
        """Returns whether the location services on a device are enabled.

        Args:
            target (str): the device or interaction URN.

        Returns:
            str: 'true' if the device's location services are enabled, 'false' otherwise.
        """
        v = await self._get_device_info(target, 'location_enabled')
        return v['location_enabled']

    # target can have only one item
    async def _get_device_info(self, target, query, refresh: bool = False) -> dict:
        """Used privately by device information functions to retrieve varying information
         on the device, such as the ID, location, battery, name and type.

        Args:
            target (str): the device or interaction URN.
            query (str): which category of information you are retrieving.
            refresh (bool): whether to refresh before retrieving information on the device.

        Returns:
            str: information on the device based on the query.
        """
        event = {
            '_type': 'wf_api_get_device_info_request',
            '_target': self.targets_from_source_uri(target),
            'query': query,
            'refresh': refresh
        }
        v = await self._send_receive(event)
        return v

    async def set_device_name(self, target, name: str):
        """Sets the name of a targeted device and updates it on the Relay Dash.
        The name remains updated until it is set again via a workflow or updated manually
        on the Relay Dash.

        Args:
            target (str): the device or interaction URN.
            name (str): a new name for your device.
        """
        await self._set_device_info(target, 'label', name)

    # set_device_channel is currently not supported
    # async def set_device_channel(self, target, channel: str):
    #     """Sets the channel of a targeted device and updates it on the Relay Dash.
    #     The new channel remains until it is set again via a workflow or updated on the
    #     Relay Dash.
    #
    #     Args:
    #         target (str): the device or interaction URN.
    #         channel (str): the channel that you would like to update your device to.
    #     """
    #     await self._set_device_info(target, 'channel', channel)

    async def enable_location(self, target):
        """Enables location services on a device.  Location services will remain
        enabled until they are disabled on the Relay Dash or through a workflow.

        Args:
            target (str): the device or interaction URN.
        """
        await self._set_device_info(target, 'location_enabled', 'true')

    async def disable_location(self, target):
        """Disables location services on a device.  Location services will remain
        disabled until they are enabled on the Relay Dash or through a workflow.

        Args:
            target (str): the device or interaction URN.
        """
        await self._set_device_info(target, 'location_enabled', 'false')

    async def _set_device_info(self, target, field, value):
        """Used privately by device information functions to set information
        fields on the device, such as the location, name, and channel of
        the device.

        Args:
            target (str): the device or interaction URN. This can only have one item.
            field (str): the type of information you would like to set, such as the 'name', 'channel', etc.
            value (str): the new value of the field.

        Returns:
            an event containing the updated device information.
        """
        event = {
            '_type': 'wf_api_set_device_info_request',
            '_target': self.targets_from_source_uri(target),
            'field': field,
            'value': value
        }
        await self._send_receive(event)
        return event

    # set_device_mode is currently not supported
    # async def set_device_mode(self, target, mode:str='none'):
    #     """Sets the mode of the device.
    #
    #     Args:
    #         target (str): the device or interaction URN.
    #         mode (str, optional): the updated mode of the device, which can be 'panic', 'alarm', or 'none'.
    #         Defaults to 'none'.
    #     """
    #     event = {
    #         '_type': 'wf_api_set_device_channel_request',
    #         'target': target,
    #         'mode': mode,
    #     }
    #     await self._send_receive(event)
    #     # await self._set_device_info(target, )

    @staticmethod
    def led_info(rotations: int = None, count: int = None, duration: int = None, repeat_delay: int = None,
                 pattern_repeats=None, colors=None):
        """Sets information on a device, such as the number of rotations, count, duration, repeat delay,
        pattern repeats, and colors.

        Args:
            rotations (int, optional): number of rotations. Defaults to None.
            count (int, optional): the number of times the LEDs will perform an action. Defaults to None.
            duration (int, optional): duration of the LED action in milliseconds. Defaults to None.
            repeat_delay (int, optional): the length of delay in milliseconds. Defaults to None.
            pattern_repeats (_type_, optional): the number of times a pattern should repeat. Defaults to None.
            colors (_type_, optional): hex-code of the color for the LEDs. Defaults to None.

        Returns:
            information field that was set on the LEDs.
        """
        info = {}
        if rotations is not None:
            info['rotations'] = rotations
        if count is not None:
            info['count'] = count
        if duration is not None:
            info['duration'] = duration
        if repeat_delay is not None:
            info['repeat_delay'] = repeat_delay
        if pattern_repeats is not None:
            info['pattern_repeats'] = pattern_repeats
        if colors is not None:
            info['colors'] = colors
        return info

    async def led_action(self, target, effect: str = 'flash', args=None):
        """Private method used for performing actions on the LEDs, such as creating 
        a rainbow, flashing, rotating, etc.

        Args:
            target (str): the interaction URN.
            effect (str, optional): effect to perform on LEDs, can be 'rainbow', 'rotate', 'flash', 'breath',
                'static', or 'off'. Defaults to 'flash'.
            args (optional): use led_info() to create args. Defaults to None.
        """
        event = {
            '_type': 'wf_api_set_led_request',
            '_target': self.targets_from_source_uri(target),
            'effect': effect,
            'args': args
        }
        await self._send_receive(event)

    async def switch_all_led_on(self, target, color: str = '0000ff'):
        """Switches all the LEDs on a device on to a specified color.

        Args:
            target (str): the interaction URN.
            color (str, optional): the hex color code you would like the LEDs to be. Defaults to '0000ff'.
        """
        await self.led_action(target, 'static', {'colors': {'ring': color}})

    async def switch_led_on(self, target, index: int, color: str = '0000ff'):
        """Switches on an LED at a particular index to a specified color.

        Args:
            target (str): the interaction URN.
            index (int): the index of an LED, numbered 1-12.
            color (str, optional): the hex color code you would like to turn the LED to. Defaults to '0000ff'.
        """
        await self.led_action(target, 'static', {'colors': {index: color}})

    async def rainbow(self, target, rotations: int = -1):
        """Switches all the LEDs on to a configured rainbow pattern and rotates the rainbow
        a specified number of times.

        Args:
            target (str): the interaction URN.
            rotations (int, optional): the number of times you would like the rainbow to rotate. Defaults to -1,
             meaning the rainbow will rotate indefinitely.
        """
        await self.led_action(target, 'rainbow', {'rotations': rotations})

    async def flash(self, target, color: str = '0000ff', count: int = -1):
        """Switches all the LEDs on a device to a certain color and flashes them
        a specified number of times.

        Args:
            target (str): the interaction URN.
            color (str, optional): the hex color code you would like to turn the LEDs to. Defaults to '0000ff'.
            count (int, optional): the number of times you would like the LEDs to flash. Defaults to -1, meaning
             the LEDs will flash indefinitely.
        """
        await self.led_action(target, 'flash', {'colors': {'ring': color}, 'count': count})

    async def breathe(self, target, color: str = '0000ff', count: int = -1):
        """Switches all the LEDs on a device to a certain color and creates a 'breathing' effect,
        where the LEDs will slowly light up a specified number of times.

        Args:
            target (str): the interaction URN.
            color (str, optional): the hex color code you would like to turn the LEDs to. Defaults to '0000ff'.
            count (int, optional): the number of times you would like the LEDs to 'breathe'. Defaults to -1, meaning
            the LEDs will 'breathe' indefinitely.
        """
        await self.led_action(target, 'breathe', {'colors': {'ring': color}, 'count': count})

    async def rotate(self, target, color: str = '0000ff', rotations: int = -1):
        """Switches all the LEDs on a device to a certain color and rotates them a specified number
        of times.

        Args:
            target (str): the interaction URN.
            color (str, optional): the hex color code you would like to turn the LEDs to. Defaults to '0000ff'.
            rotations (int, optional): the number of times you would like the LEDs to rotate. Defaults to -1, meaning
            the LEDs will rotate indefinitely.
        """
        await self.led_action(target, 'rotate', {'colors': {'1': color}, 'rotations': rotations})

    async def switch_all_led_off(self, target):
        """Switches all the LEDs on a device off.

        Args:
            target (str): the interaction URN.
        """
        await self.led_action(target, 'off', {})

    async def vibrate(self, target, pattern: list = None):
        """Makes the device vibrate in a particular pattern.  You can specify
        how many vibrations you would like, the duration of each vibration in
        milliseconds, and how long you would like the pauses between each vibration to last
        in milliseconds.

        Args:
            target (str): the interaction URN.
            pattern (list, optional): an array representing the pattern of your vibration. Defaults to None.
        """
        if not pattern:
            pattern = [100, 500, 500, 500, 500, 500]

        event = {
            '_type': 'wf_api_vibrate_request',
            '_target': self.targets_from_source_uri(target),
            'pattern': pattern
        }
        await self._send_receive(event)

    async def start_timer(self, timeout: int = 60):
        """Starts an unnamed timer, meaning this will be the only timer on your device.
        The timer will fire when it reaches the value of the 'timeout' parameter.

        Args:
            timeout (int): the number of seconds you would like to wait until the timer fires.
        """
        event = {
            '_type': 'wf_api_start_timer_request',
            'timeout': timeout
        }
        await self._send_receive(event)

    async def stop_timer(self):
        """Stops an unnamed timer.
        """
        event = {
            '_type': 'wf_api_stop_timer_request'
        }
        await self._send_receive(event)

    async def terminate(self):
        """Terminates a workflow.  This method is usually called
        after your workflow has completed, and you would like to end the
        workflow by calling end_interaction(), where you can then terminate
        the workflow.
        """
        event = {
            '_type': 'wf_api_terminate_request'
        }
        # there is no response
        await self._send(event)

    async def create_incident(self, originator, itype: str):
        """Creates an incident that will alert the Relay Dash.

        Args:
            originator (str): the device URN that triggered the incident.
            itype (str): the type of incident that occurred.

        Returns:
            str: the incident ID.
        """
        # TODO: what are the values for itype?
        event = {
            '_type': 'wf_api_create_incident_request',
            'type': itype,
            'originator_uri': originator
        }
        v = await self._send_receive(event)
        return v['incident_id']

    async def resolve_incident(self, incident_id: str, reason: str):
        """Resolves an incident that was created.

        Args:
            incident_id (str): the ID of the incident you would like to resolve.
            reason (str): the reason for resolving the incident.
        """
        event = {
            '_type': 'wf_api_resolve_incident_request',
            'incident_id': incident_id,
            'reason': reason
        }
        await self._send_receive(event)

    # restart/powering down device is currently not supported

    # async def restart_device(self, target):
    #     """Restarts a device during a workflow, without having
    #     to physically restart the device via holding down the '-' button.
    #
    #     Args:
    #         target (str): the URN of the device you would like to restart.
    #     """

    #     event = {
    #         '_type': 'wf_api_device_power_off_request',
    #         '_target': self.targets_from_source_uri(target),
    #         'restart': True
    #     }
    #     await self._send_receive(event)

    # async def power_down_device(self, target):
    #     """Powers down a device during a workflow, without
    #     having to physically power down the device via holding down the '+' button.
    #
    #     Args:
    #         target (str): the URN of the device that you would like to power down.
    #     """
    #     event = {
    #         '_type': 'wf_api_device_power_off_request',
    #         '_target': self.targets_from_source_uri(target),
    #         'restart': False
    #     }
    #     await self._send_receive(event)

    async def stop_playback(self, target, pb_id: str = None):
        event = None
        if type(pb_id) == list:
            event = {
                '_type': 'wf_api_stop_playback_request',
                '_target': self.targets_from_source_uri(target),
                'ids': pb_id
            }
        elif type(pb_id) == str:
            pb_id = [pb_id]
            event = {
                '_type': 'wf_api_stop_playback_request',
                '_target': self.targets_from_source_uri(target),
                'ids': pb_id
            }
        elif pb_id is None:
            event = {
                '_type': 'wf_api_stop_playback_request',
                '_target': self.targets_from_source_uri(target)
            }
        await self._send_receive(event)

    async def translate(self, text: str, from_lang: str = 'en-US', to_lang: str = 'es-ES'):
        """Translates text from one language to another.

        Args:
            text (str): the text that you would like to translate.
            from_lang (str): the language that you would like to translate from.
            to_lang (str): the language that you would like to translate to.

        Returns:
            str: the translated text.
        """
        event = {
            '_type': 'wf_api_translate_request',
            'text': text,
            'from_lang': from_lang,
            'to_lang': to_lang
        }
        response = await self._send_receive(event)
        return response['text']

    # target can have only one item
    async def place_call(self, target, callee_uri: str):
        """Places a call to another device.

        Args:
            target (str): the device which will place the call.
            callee_uri (str): the URN of the device you would like to call.

        Returns:
            the event response.
        """
        event = {
            '_type': 'wf_api_call_request',
            '_target': self.targets_from_source_uri(target),
            'uri': callee_uri
        }
        response = await self._send_receive(event)
        return response['call_id']

    # target can have only one item
    async def answer_call(self, target, call_id: str):
        """Answers an incoming call on your device.

        Args:
            target (str): the device which will answer the call.
            call_id (str): the ID of the call to answer.
        """
        event = {
            '_type': 'wf_api_answer_request',
            '_target': self.targets_from_source_uri(target),
            'call_id': call_id
        }
        await self._send_receive(event)

    # target can have only one item
    async def hangup_call(self, target, call_id: str):
        """Ends (hangs up) a call on a device.

        Args:
            target (str): the device which will do the hangup.
            call_id (str): the call ID.
        """
        event = {
            '_type': 'wf_api_hangup_request',
            '_target': self.targets_from_source_uri(target),
            'call_id': call_id
        }
        await self._send_receive(event)

    async def get_group_members(self, group_uri: str):
        """Returns the members of a particular group.

        Args:
            group_uri (str): the URN of the group that you would like to retrieve members from.

        Returns:
            str[]: a list of the members within the specified group.
        """
        event = {
            '_type': 'wf_api_group_query_request',
            'query': 'list_members',
            'group_uri': group_uri
        }
        response = await self._send_receive(event)
        return response['member_uris']

    async def is_group_member(self, group_name_uri: str, potential_member_name_uri: str):
        """Checks whether a device is a member of a particular group.

        Args:
            group_name_uri (str): the URN of a group.
            potential_member_name_uri: the URN of the device name.

        Returns:
            str: 'true' if the device is a member of the specified group, 'false' otherwise.
        """
        this_group_name = parse_group_name(group_name_uri)
        this_device_name = parse_device_name(potential_member_name_uri)
        this_group_uri = group_member(this_group_name, this_device_name)
        event = {
            '_type': 'wf_api_group_query_request',
            'query': 'is_member',
            'group_uri': this_group_uri
        }
        response = await self._send_receive(event)
        return response['is_member']

    # target can have only one item
    async def set_user_profile(self, target: str, username: str, force: bool = False):
        """Sets the profile of a user by updating the username.

        Args:
            target (str): the device URN whose profile you would like to update.
            username (str): the updated username for the device.
            force (bool, optional): whether you would like to force this update. Defaults to False.
        """
        event = {
            '_type': 'wf_api_set_user_profile_request',
            '_target': self.targets_from_source_uri(target),
            'username': username,
            'force': force
        }
        await self._send_receive(event)

    # target can have only one item
    async def get_unread_inbox_size(self, target):
        """Retrieves the number of messages in a device's inbox.

        Args:
            target (str): the device or interaction URN whose inbox you would like to check.

        Returns:
            str: the number of messages in the specified device's inbox.
        """
        event = {
            '_type': 'wf_api_inbox_count_request',
            '_target': self.targets_from_source_uri(target)
        }
        response = await self._send_receive(event)
        return response['count']

    async def play_unread_inbox_messages(self, target):
        """Play a targeted device's inbox messages.

        Args:
            target (str): the device or interaction URN whose inbox messages you would like to play.
        """
        event = {
            '_type': 'wf_api_play_inbox_messages_request',
            '_target': self.targets_from_source_uri(target)
        }
        await self._send_receive(event)

    async def log_message(self, message: str, category: Optional[str] = 'default', target: Optional[str] = None,
                          content_type: Optional[str] = 'text/plain'):
        """Log an analytics event from a workflow with the specified content and
        under a specified category. This does not log the device who
        triggered the workflow that called this function.

        Args:
            message (str): a description for your analytical event.
            category (str, optional): a category for your analytical event. Defaults to 'default'.
            target (str, optional): URN of the device that triggered this function. Defaults to None.
            content_type (str, optional): encoding of the message string. Defaults to 'text/plain'.
        """
        event = {
            '_type': 'wf_api_log_analytics_event_request',
            'content': message,
            'content_type': content_type,
            'category': category,
            'device_uri': target
        }
        await self._send_receive(event)

    async def log_user_message(self, message: str, target, category: str):
        """Log an analytic event from a workflow with the specified content and
        under a specified category.  This includes the device who triggered the workflow
        that called this function.

        Args:
            message (str): a description for your analytical event.
            target (str, optional): the URN of a the device that triggered this function. Defaults to None.
            category (str): a category for your analytical event.
        """
        event = {
            '_type': 'wf_api_log_analytics_event_request',
            'content': message,
            'content_type': 'text/plain',
            'category': category,
            'device_uri': target
        }
        await self._send_receive(event)

    async def set_timer(self, name: str, timer_type: str = 'timeout', timeout: int = 60, timeout_type: str = 'secs'):
        """ Serves as a named timer that can be either interval or timeout.  Allows you to specify
        the unit of time.

        Args:
            name (str): a name for your timer.
            timer_type (str, optional): can be 'timeout' or 'interval'. Defaults to 'timeout'.
            timeout (int): an integer representing when you would like your timer to fire.
            timeout_type (str, optional): can be 'ms', 'secs', 'mins' or 'hrs'. Defaults to 'secs'.
        """
        event = {
            '_type': 'wf_api_set_timer_request',
            'type': timer_type,
            'name': name,
            'timeout': timeout,
            'timeout_type': timeout_type
        }
        await self._send_receive(event)

    async def clear_timer(self, name: str):
        """Clears the specified timer.

        Args:
            name (str): the name of the timer that you would like to clear.
        """
        event = {
            '_type': 'wf_api_clear_timer_request',
            'name': name
        }
        await self._send_receive(event)

    async def sms(self, stype: str, text: str, uri: str):
        event = {
            '_type': 'wf_api_sms_request',
            'type': stype,
            'text': text,
            'uri': uri
        }
        response = await self._send_receive(event)
        return response['message_id']

    async def enable_home_channel(self, target):
        await self._set_home_channel_state(target, True)

    async def disable_home_channel(self, target):
        await self._set_home_channel_state(target, False)

    async def _set_home_channel_state(self, target, enabled: bool = True):
        event = {
            '_type': 'wf_api_set_home_channel_state_request',
            '_target': self.targets_from_source_uri(target),
            'enabled': enabled
        }
        await self._send_receive(event)

    # target can have only one item
    async def register(self, target, uri: str, password: str, expires: int):
        event = {
            '_type': 'wf_api_register_request',
            '_target': self.targets_from_source_uri(target),
            'uri': uri,
            'password': password,
            'expires': expires
        }
        await self._send_receive(event)

    # invalid_type and missing_type are just for internal testing of error handling

    async def _invalid_type(self):
        event = {
            '_type': 'wf_api_mkinard_breakage',
            'device_id': 'TheQuickBrownFoxJumpedOverTheLazyDog',
            'call_id': 'you can\'t catch me'
        }
        await self._send_receive(event)

    async def _missing_type(self):
        event = {
            'device_id': 'NowIsTheTimeForAllGoodMenToComeToTheAidOfYourCountry',
            'call_id': 'you can\'t catch me'
        }
        await self._send_receive(event)

__init__(workflow)

Initializes workflow fields.

Parameters:

Name Type Description Default
workflow Workflow

your workflow.

required
Source code in relay/workflow.py
676
677
678
679
680
681
682
683
684
685
686
def __init__(self, workflow: Workflow):
    """Initializes workflow fields.

    Args:
        workflow (Workflow): your workflow.
    """
    self.workflow = workflow
    self.websocket = None
    self.id_futures = {}  # {_id: future}
    self.event_futures = {}
    self.logger = None

alert(target, originator, name, text, push_opts=None) async

Sends out an alert to the specified group of devices and the Relay Dash.

Parameters:

Name Type Description Default
target(str)

the group URN that you would like to send an alert to.

required
originator str

the URN of the device that triggered the alert.

required
name str

a name for your alert.

required
text str

the text that you would like to be spoken to the group as your alert.

required
push_opts dict

push options for if the alert is sent to the Relay app on a virtual device. Defaults to an empty value.

None
Source code in relay/workflow.py
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
async def alert(self, target, originator: str, name: str, text: str, push_opts: dict = None):
    """Sends out an alert to the specified group of devices and the Relay Dash.

    Args:
        target(str): the group URN that you would like to send an alert to.
        originator (str): the URN of the device that triggered the alert.
        name (str): a name for your alert.
        text (str): the text that you would like to be spoken to the group as your alert.
        push_opts (dict, optional): push options for if the alert is sent to the Relay app on a virtual device.
         Defaults to an empty value.
    """
    if push_opts is None:
        push_opts = {}
    await self._send_notification(target, originator, 'alert', text, name, push_opts)

answer_call(target, call_id) async

Answers an incoming call on your device.

Parameters:

Name Type Description Default
target str

the device which will answer the call.

required
call_id str

the ID of the call to answer.

required
Source code in relay/workflow.py
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
async def answer_call(self, target, call_id: str):
    """Answers an incoming call on your device.

    Args:
        target (str): the device which will answer the call.
        call_id (str): the ID of the call to answer.
    """
    event = {
        '_type': 'wf_api_answer_request',
        '_target': self.targets_from_source_uri(target),
        'call_id': call_id
    }
    await self._send_receive(event)

breathe(target, color='0000ff', count=-1) async

Switches all the LEDs on a device to a certain color and creates a 'breathing' effect, where the LEDs will slowly light up a specified number of times.

Parameters:

Name Type Description Default
target str

the interaction URN.

required
color str

the hex color code you would like to turn the LEDs to. Defaults to '0000ff'.

'0000ff'
count int

the number of times you would like the LEDs to 'breathe'. Defaults to -1, meaning

-1
Source code in relay/workflow.py
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
async def breathe(self, target, color: str = '0000ff', count: int = -1):
    """Switches all the LEDs on a device to a certain color and creates a 'breathing' effect,
    where the LEDs will slowly light up a specified number of times.

    Args:
        target (str): the interaction URN.
        color (str, optional): the hex color code you would like to turn the LEDs to. Defaults to '0000ff'.
        count (int, optional): the number of times you would like the LEDs to 'breathe'. Defaults to -1, meaning
        the LEDs will 'breathe' indefinitely.
    """
    await self.led_action(target, 'breathe', {'colors': {'ring': color}, 'count': count})

broadcast(target, originator, name, text, push_opts=None) async

Sends out a broadcast message to a group of devices. The message is played out on all devices, as well as sent to the Relay Dash.

Parameters:

Name Type Description Default
target(str)

the group URN that you would like to broadcast your message to.

required
originator str

the device URN that triggered the broadcast.

required
name str

a name for your broadcast.

required
text str

the text that you would like to be broadcasted to your group.

required
push_opts dict

push options for if the broadcast is sent to the Relay app on a virtual device. Defaults to an empty value.

None
Source code in relay/workflow.py
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
async def broadcast(self, target, originator: str, name: str, text: str, push_opts: dict = None):
    """Sends out a broadcast message to a group of devices.  The message is played out on
    all devices, as well as sent to the Relay Dash.

    Args:
        target(str): the group URN that you would like to broadcast your message to.
        originator (str): the device URN that triggered the broadcast.
        name (str): a name for your broadcast.
        text (str): the text that you would like to be broadcasted to your group.
        push_opts (dict, optional): push options for if the broadcast is sent to the Relay app on a virtual
         device. Defaults to an empty value.
    """
    if push_opts is None:
        push_opts = {}
    await self._send_notification(target, originator, 'broadcast', text, name, push_opts)

cancel_alert(target, name) async

Cancels an alert that was sent to a group of devices. Particularly useful if you would like to cancel the alert on all devices after one device has acknowledged the alert.

Parameters:

Name Type Description Default
target(str)

the device URN that has acknowledged the alert.

required
name str

the name of the alert.

required
Source code in relay/workflow.py
1296
1297
1298
1299
1300
1301
1302
1303
1304
async def cancel_alert(self, target, name: str):
    """Cancels an alert that was sent to a group of devices.  Particularly useful if you would like to cancel
     the alert on all devices after one device has acknowledged the alert.

    Args:
        target(str): the device URN that has acknowledged the alert.
        name (str): the name of the alert.
    """
    await self._send_notification(target, None, 'cancel', None, name)

cancel_broadcast(target, name) async

Cancels the broadcast that was sent to a group of devices.

Parameters:

Name Type Description Default
target(str)

the device URN that is cancelling the broadcast.

required
name str

the name of the broadcast that you would like to cancel.

required
Source code in relay/workflow.py
1322
1323
1324
1325
1326
1327
1328
1329
async def cancel_broadcast(self, target, name: str):
    """Cancels the broadcast that was sent to a group of devices.

    Args:
        target(str): the device URN that is cancelling the broadcast.
        name (str): the name of the broadcast that you would like to cancel.
    """
    await self._send_notification(target, None, 'cancel', None, name)

clear_timer(name) async

Clears the specified timer.

Parameters:

Name Type Description Default
name str

the name of the timer that you would like to clear.

required
Source code in relay/workflow.py
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
async def clear_timer(self, name: str):
    """Clears the specified timer.

    Args:
        name (str): the name of the timer that you would like to clear.
    """
    event = {
        '_type': 'wf_api_clear_timer_request',
        'name': name
    }
    await self._send_receive(event)

create_incident(originator, itype) async

Creates an incident that will alert the Relay Dash.

Parameters:

Name Type Description Default
originator str

the device URN that triggered the incident.

required
itype str

the type of incident that occurred.

required

Returns:

Name Type Description
str

the incident ID.

Source code in relay/workflow.py
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
async def create_incident(self, originator, itype: str):
    """Creates an incident that will alert the Relay Dash.

    Args:
        originator (str): the device URN that triggered the incident.
        itype (str): the type of incident that occurred.

    Returns:
        str: the incident ID.
    """
    # TODO: what are the values for itype?
    event = {
        '_type': 'wf_api_create_incident_request',
        'type': itype,
        'originator_uri': originator
    }
    v = await self._send_receive(event)
    return v['incident_id']

disable_location(target) async

Disables location services on a device. Location services will remain disabled until they are enabled on the Relay Dash or through a workflow.

Parameters:

Name Type Description Default
target str

the device or interaction URN.

required
Source code in relay/workflow.py
1571
1572
1573
1574
1575
1576
1577
1578
async def disable_location(self, target):
    """Disables location services on a device.  Location services will remain
    disabled until they are enabled on the Relay Dash or through a workflow.

    Args:
        target (str): the device or interaction URN.
    """
    await self._set_device_info(target, 'location_enabled', 'false')

enable_location(target) async

Enables location services on a device. Location services will remain enabled until they are disabled on the Relay Dash or through a workflow.

Parameters:

Name Type Description Default
target str

the device or interaction URN.

required
Source code in relay/workflow.py
1562
1563
1564
1565
1566
1567
1568
1569
async def enable_location(self, target):
    """Enables location services on a device.  Location services will remain
    enabled until they are disabled on the Relay Dash or through a workflow.

    Args:
        target (str): the device or interaction URN.
    """
    await self._set_device_info(target, 'location_enabled', 'true')

end_interaction(target) async

Ends an interaction with the user. Triggers an INTERACTION_ENDED event to signify that the user is done interacting with the device.

Parameters:

Name Type Description Default
target(str)

the interaction that you would like to end.

required
Source code in relay/workflow.py
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
async def end_interaction(self, target):
    """Ends an interaction with the user.  Triggers an INTERACTION_ENDED event to signify
    that the user is done interacting with the device.

    Args:
        target(str): the interaction that you would like to end.
    """
    event = {
        '_type': 'wf_api_end_interaction_request',
        '_target': self.targets_from_source_uri(target)
    }
    await self._send_receive(event)

flash(target, color='0000ff', count=-1) async

Switches all the LEDs on a device to a certain color and flashes them a specified number of times.

Parameters:

Name Type Description Default
target str

the interaction URN.

required
color str

the hex color code you would like to turn the LEDs to. Defaults to '0000ff'.

'0000ff'
count int

the number of times you would like the LEDs to flash. Defaults to -1, meaning the LEDs will flash indefinitely.

-1
Source code in relay/workflow.py
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
async def flash(self, target, color: str = '0000ff', count: int = -1):
    """Switches all the LEDs on a device to a certain color and flashes them
    a specified number of times.

    Args:
        target (str): the interaction URN.
        color (str, optional): the hex color code you would like to turn the LEDs to. Defaults to '0000ff'.
        count (int, optional): the number of times you would like the LEDs to flash. Defaults to -1, meaning
         the LEDs will flash indefinitely.
    """
    await self.led_action(target, 'flash', {'colors': {'ring': color}, 'count': count})

get_device_address(target, refresh=False) async

Returns the address of a targeted device.

Parameters:

Name Type Description Default
target str

the device or interaction URN.

required
refresh bool

whether you would like to refresh before retrieving the address. Defaults to False.

False

Returns:

Name Type Description
str

the address of the device.

Source code in relay/workflow.py
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
async def get_device_address(self, target, refresh: bool = False):
    """Returns the address of a targeted device.

    Args:
        target (str): the device or interaction URN.
        refresh (bool, optional): whether you would like to refresh before retrieving the address.
         Defaults to False.

    Returns:
        str: the address of the device.
    """
    return await self.get_device_location(target, refresh)

get_device_battery(target, refresh=False) async

Returns the battery of a targeted device.

Parameters:

Name Type Description Default
target str

the device or interaction URN.

required
refresh bool

whether you would like to refresh before retrieving the battery. Defaults to False.

False

Returns:

Name Type Description
int

the battery of the device.

Source code in relay/workflow.py
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
async def get_device_battery(self, target, refresh: bool = False):
    """Returns the battery of a targeted device.

    Args:
        target (str): the device or interaction URN.
        refresh (bool, optional): whether you would like to refresh before retrieving the battery.
         Defaults to False.

    Returns:
        int: the battery of the device.
    """
    v = await self._get_device_info(target, 'battery', refresh)
    return v['battery']

get_device_coordinates(target, refresh=False) async

Retrieves the coordinates of the device's location.

Parameters:

Name Type Description Default
target str

the device or interaction URN.

required
refresh bool

whether you would like to refresh before retreiving the coordinates. Defaults to False.

False
Source code in relay/workflow.py
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
async def get_device_coordinates(self, target, refresh: bool = False):
    """Retrieves the coordinates of the device's location.

    Args:
        target (str): the device or interaction URN.
        refresh (bool, optional): whether you would like to refresh before retreiving the coordinates.
         Defaults to False.
    """
    v = await self._get_device_info(target, 'latlong', refresh)
    return v['latlong']

get_device_id(target) async

Returns the ID of a targeted device.

Parameters:

Name Type Description Default
target str

the device or interaction URN.

required

Returns:

Name Type Description
str

the device ID.

Source code in relay/workflow.py
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
async def get_device_id(self, target):
    """Returns the ID of a targeted device.

    Args:
        target (str): the device or interaction URN.

    Returns:
        str: the device ID.
    """
    v = await self._get_device_info(target, 'id')
    return v['id']

get_device_indoor_location(target, refresh=False) async

Returns the indoor location of a targeted device.

Parameters:

Name Type Description Default
target str

the device or interaction URN.

required
refresh bool

whether you would like to refresh before retrieving the location. Defaults to False.

False

Returns:

Name Type Description
str

the indoor location of the device.

Source code in relay/workflow.py
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
async def get_device_indoor_location(self, target, refresh: bool = False):
    """Returns the indoor location of a targeted device.

    Args:
        target (str): the device or interaction URN.
        refresh (bool, optional): whether you would like to refresh before retrieving the location.
         Defaults to False.

    Returns:
        str: the indoor location of the device.
    """
    v = await self._get_device_info(target, 'indoor_location', refresh)
    return v['indoor_location']

get_device_latlong(target, refresh=False) async

Returns the latitude and longitude coordinates of a targeted device.

Parameters:

Name Type Description Default
target str

the device or interaction URN.

required
refresh bool

whether you would like to refresh before retrieving the coordinates. Defaults to False.

False

Returns:

Type Description

float[]: an array containing the latitude and longitude of the device.

Source code in relay/workflow.py
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
async def get_device_latlong(self, target, refresh: bool = False):
    """Returns the latitude and longitude coordinates of a targeted device.

    Args:
        target (str): the device or interaction URN.
        refresh (bool, optional): whether you would like to refresh before retrieving the coordinates.
         Defaults to False.

    Returns:
        float[]: an array containing the latitude and longitude of the device.
    """
    return await self.get_device_coordinates(target, refresh)

get_device_location(target, refresh=False) async

Returns the location of a targeted device.

Parameters:

Name Type Description Default
target str

the device or interaction URN.

required
refresh bool

whether you would like to refresh before retrieving the location. Defaults to False.

False

Returns:

Name Type Description
str

the location of the device.

Source code in relay/workflow.py
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
async def get_device_location(self, target, refresh: bool = False):
    """Returns the location of a targeted device.

    Args:
        target (str): the device or interaction URN.
        refresh (bool, optional): whether you would like to refresh before retrieving the location.
         Defaults to False.

    Returns:
        str: the location of the device.
    """
    v = await self._get_device_info(target, 'address', refresh)
    return v['address']

get_device_location_enabled(target) async

Returns whether the location services on a device are enabled.

Parameters:

Name Type Description Default
target str

the device or interaction URN.

required

Returns:

Name Type Description
str

'true' if the device's location services are enabled, 'false' otherwise.

Source code in relay/workflow.py
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
async def get_device_location_enabled(self, target):
    """Returns whether the location services on a device are enabled.

    Args:
        target (str): the device or interaction URN.

    Returns:
        str: 'true' if the device's location services are enabled, 'false' otherwise.
    """
    v = await self._get_device_info(target, 'location_enabled')
    return v['location_enabled']

get_device_name(target) async

Returns the name of a targeted device.

Parameters:

Name Type Description Default
target str

the device or interaction URN.

required

Returns:

Name Type Description
str

the name of the device.

Source code in relay/workflow.py
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
async def get_device_name(self, target):
    """Returns the name of a targeted device.

    Args:
        target (str): the device or interaction URN.

    Returns:
        str: the name of the device.
    """
    v = await self._get_device_info(target, 'name')
    return v['name']

get_device_type(target) async

Returns the device type of a targeted device, i.e. gen 2, gen 3, etc.

Parameters:

Name Type Description Default
target str

the device or interaction URN.

required

Returns:

Name Type Description
str

the device type.

Source code in relay/workflow.py
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
async def get_device_type(self, target):
    """Returns the device type of a targeted device, i.e. gen 2, gen 3, etc.

    Args:
        target (str): the device or interaction URN.

    Returns:
        str: the device type.
    """
    v = await self._get_device_info(target, 'type')
    return v['type']

get_group_members(group_uri) async

Returns the members of a particular group.

Parameters:

Name Type Description Default
group_uri str

the URN of the group that you would like to retrieve members from.

required

Returns:

Type Description

str[]: a list of the members within the specified group.

Source code in relay/workflow.py
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
async def get_group_members(self, group_uri: str):
    """Returns the members of a particular group.

    Args:
        group_uri (str): the URN of the group that you would like to retrieve members from.

    Returns:
        str[]: a list of the members within the specified group.
    """
    event = {
        '_type': 'wf_api_group_query_request',
        'query': 'list_members',
        'group_uri': group_uri
    }
    response = await self._send_receive(event)
    return response['member_uris']

get_number_var(name, default=None) async

Retrieves a variable that was set either during workflow registration or through the set_var() function of type integer. The variable can be retrieved anywhere within the workflow, but is erased after the workflow terminates.

Parameters:

Name Type Description Default
name str

name of the variable to be retrieved.

required
default optional

default value of the variable if it does not exist. Defaults to None.

None

Returns:

Type Description

the variable requested.

Source code in relay/workflow.py
968
969
970
971
972
973
974
975
976
977
978
979
980
async def get_number_var(self, name: str, default=None):
    """Retrieves a variable that was set either during workflow registration
    or through the set_var() function of type integer.  The variable can be retrieved anywhere
    within the workflow, but is erased after the workflow terminates.

    Args:
        name (str): name of the variable to be retrieved.
        default (optional): default value of the variable if it does not exist. Defaults to None.

    Returns:
        the variable requested.
    """
    return int(await self.get_var(name, default))

get_source_uri_from_trigger(trigger) staticmethod

Get the source URN from a workflow trigger

Parameters:

Name Type Description Default
trigger dict

workflow trigger.

required

Raises:

Type Description
WorkflowException

thrown if the trigger param is not a dictionary.

WorkflowException

thrown if the trigger param is not a trigger dictionary.

WorkflowException

thrown if there is no source_uri definition in the trigger.

Returns:

Type Description
str

the source URN as a string from the trigger.

Source code in relay/workflow.py
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
@staticmethod
def get_source_uri_from_trigger(trigger: dict) -> str:
    """Get the source URN from a workflow trigger

    Args:
        trigger (dict): workflow trigger.

    Raises:
        WorkflowException: thrown if the trigger param is not a dictionary.
        WorkflowException: thrown if the trigger param is not a trigger dictionary.
        WorkflowException: thrown if there is no source_uri definition in the trigger.

    Returns:
        the source URN as a string from the trigger.

    """
    Relay._validate_trigger(trigger)
    source_uri = trigger['args']['source_uri']
    return source_uri

get_unread_inbox_size(target) async

Retrieves the number of messages in a device's inbox.

Parameters:

Name Type Description Default
target str

the device or interaction URN whose inbox you would like to check.

required

Returns:

Name Type Description
str

the number of messages in the specified device's inbox.

Source code in relay/workflow.py
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
async def get_unread_inbox_size(self, target):
    """Retrieves the number of messages in a device's inbox.

    Args:
        target (str): the device or interaction URN whose inbox you would like to check.

    Returns:
        str: the number of messages in the specified device's inbox.
    """
    event = {
        '_type': 'wf_api_inbox_count_request',
        '_target': self.targets_from_source_uri(target)
    }
    response = await self._send_receive(event)
    return response['count']

get_user_profile(target) async

Returns the user profile of a targeted device.

Parameters:

Name Type Description Default
target str

the device or interaction URN.

required

Returns:

Name Type Description
str

the user profile registered to the device.

Source code in relay/workflow.py
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
async def get_user_profile(self, target):
    """Returns the user profile of a targeted device.

    Args:
        target (str): the device or interaction URN.

    Returns:
        str: the user profile registered to the device.
    """
    v = await self._get_device_info(target, 'username')
    return v['username']

get_var(name, default=None) async

Retrieves a variable that was set either during workflow registration or through the set_var() function. The variable can be retrieved anywhere within the workflow, but is erased after the workflow terminates.

Parameters:

Name Type Description Default
name str

name of the variable to be retrieved.

required
default optional

default value of the variable if it does not exist. Defaults to None.

None

Returns:

Type Description

the variable requested.

Source code in relay/workflow.py
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
async def get_var(self, name: str, default=None):
    """Retrieves a variable that was set either during workflow registration
    or through the set_var() function.  The variable can be retrieved anywhere
    within the workflow, but is erased after the workflow terminates.

    Args:
        name (str): name of the variable to be retrieved.
        default (optional): default value of the variable if it does not exist. Defaults to None.

    Returns:
        the variable requested.
    """
    # TODO: look in self.workflow.state to see all of what is available
    event = {
        '_type': 'wf_api_get_var_request',
        'name': name
    }
    v = await self._send_receive(event)
    return v.get('value', default)

hangup_call(target, call_id) async

Ends (hangs up) a call on a device.

Parameters:

Name Type Description Default
target str

the device which will do the hangup.

required
call_id str

the call ID.

required
Source code in relay/workflow.py
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
async def hangup_call(self, target, call_id: str):
    """Ends (hangs up) a call on a device.

    Args:
        target (str): the device which will do the hangup.
        call_id (str): the call ID.
    """
    event = {
        '_type': 'wf_api_hangup_request',
        '_target': self.targets_from_source_uri(target),
        'call_id': call_id
    }
    await self._send_receive(event)

interaction_options(color='0000ff', input_types=None, home_channel='suspend') staticmethod

Options for when an interaction is started via a workflow.

Parameters:

Name Type Description Default
color str

desired color of LEDs when an interaction is started. Defaults to "0000ff".

'0000ff'
input_types list

input types you would like for the interaction. Defaults to an empty list.

None
home_channel str

home channel for the device during the interaction. Defaults to "suspend".

'suspend'

Returns:

Type Description

the options specified.

Source code in relay/workflow.py
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
@staticmethod
def interaction_options(color: str = "0000ff", input_types: list = None, home_channel: str = "suspend"):
    """Options for when an interaction is started via a workflow.

    Args:
        color (str, optional): desired color of LEDs when an interaction is started. Defaults to "0000ff".
        input_types (list, optional): input types you would like for the interaction. Defaults to an empty list.
        home_channel (str, optional): home channel for the device during the interaction. Defaults to "suspend".

    Returns:
        the options specified.
    """
    if input_types is None:
        input_types = []
    options = {
        'color': color,
        'input_types': input_types,
        'home_channel': home_channel
    }
    return options

is_group_member(group_name_uri, potential_member_name_uri) async

Checks whether a device is a member of a particular group.

Parameters:

Name Type Description Default
group_name_uri str

the URN of a group.

required
potential_member_name_uri str

the URN of the device name.

required

Returns:

Name Type Description
str

'true' if the device is a member of the specified group, 'false' otherwise.

Source code in relay/workflow.py
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
async def is_group_member(self, group_name_uri: str, potential_member_name_uri: str):
    """Checks whether a device is a member of a particular group.

    Args:
        group_name_uri (str): the URN of a group.
        potential_member_name_uri: the URN of the device name.

    Returns:
        str: 'true' if the device is a member of the specified group, 'false' otherwise.
    """
    this_group_name = parse_group_name(group_name_uri)
    this_device_name = parse_device_name(potential_member_name_uri)
    this_group_uri = group_member(this_group_name, this_device_name)
    event = {
        '_type': 'wf_api_group_query_request',
        'query': 'is_member',
        'group_uri': this_group_uri
    }
    response = await self._send_receive(event)
    return response['is_member']

led_action(target, effect='flash', args=None) async

Private method used for performing actions on the LEDs, such as creating a rainbow, flashing, rotating, etc.

Parameters:

Name Type Description Default
target str

the interaction URN.

required
effect str

effect to perform on LEDs, can be 'rainbow', 'rotate', 'flash', 'breath', 'static', or 'off'. Defaults to 'flash'.

'flash'
args optional

use led_info() to create args. Defaults to None.

None
Source code in relay/workflow.py
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
async def led_action(self, target, effect: str = 'flash', args=None):
    """Private method used for performing actions on the LEDs, such as creating 
    a rainbow, flashing, rotating, etc.

    Args:
        target (str): the interaction URN.
        effect (str, optional): effect to perform on LEDs, can be 'rainbow', 'rotate', 'flash', 'breath',
            'static', or 'off'. Defaults to 'flash'.
        args (optional): use led_info() to create args. Defaults to None.
    """
    event = {
        '_type': 'wf_api_set_led_request',
        '_target': self.targets_from_source_uri(target),
        'effect': effect,
        'args': args
    }
    await self._send_receive(event)

led_info(rotations=None, count=None, duration=None, repeat_delay=None, pattern_repeats=None, colors=None) staticmethod

Sets information on a device, such as the number of rotations, count, duration, repeat delay, pattern repeats, and colors.

Parameters:

Name Type Description Default
rotations int

number of rotations. Defaults to None.

None
count int

the number of times the LEDs will perform an action. Defaults to None.

None
duration int

duration of the LED action in milliseconds. Defaults to None.

None
repeat_delay int

the length of delay in milliseconds. Defaults to None.

None
pattern_repeats _type_

the number of times a pattern should repeat. Defaults to None.

None
colors _type_

hex-code of the color for the LEDs. Defaults to None.

None

Returns:

Type Description

information field that was set on the LEDs.

Source code in relay/workflow.py
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
@staticmethod
def led_info(rotations: int = None, count: int = None, duration: int = None, repeat_delay: int = None,
             pattern_repeats=None, colors=None):
    """Sets information on a device, such as the number of rotations, count, duration, repeat delay,
    pattern repeats, and colors.

    Args:
        rotations (int, optional): number of rotations. Defaults to None.
        count (int, optional): the number of times the LEDs will perform an action. Defaults to None.
        duration (int, optional): duration of the LED action in milliseconds. Defaults to None.
        repeat_delay (int, optional): the length of delay in milliseconds. Defaults to None.
        pattern_repeats (_type_, optional): the number of times a pattern should repeat. Defaults to None.
        colors (_type_, optional): hex-code of the color for the LEDs. Defaults to None.

    Returns:
        information field that was set on the LEDs.
    """
    info = {}
    if rotations is not None:
        info['rotations'] = rotations
    if count is not None:
        info['count'] = count
    if duration is not None:
        info['duration'] = duration
    if repeat_delay is not None:
        info['repeat_delay'] = repeat_delay
    if pattern_repeats is not None:
        info['pattern_repeats'] = pattern_repeats
    if colors is not None:
        info['colors'] = colors
    return info

listen(target, phrases=None, transcribe=True, alt_lang=None, timeout=60) async

Listens for the user to speak into the device. Utilizes speech to text functionality to interact with the user.

Parameters:

Name Type Description Default
target str

the interaction URN.

required
phrases string[]

optional phrases that you would like to limit the user's response to. Defaults to None.

None
transcribe bool

whether you would like to transcribe the user's reponse. Defaults to True.

True
timeout int

timeout for how long the device will wait for user's response. Defaults to 60.

60
alt_lang str

if you would like the device to listen for a response in a specific language. Defaults to None.

None

Returns:

Type Description

text representation of what the user had spoken into the device.

Source code in relay/workflow.py
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
async def listen(self, target, phrases=None, transcribe: bool = True, alt_lang: str = None, timeout: int = 60):
    """Listens for the user to speak into the device.  Utilizes speech to text functionality to interact
    with the user.

    Args:
        target (str): the interaction URN.
        phrases (string[], optional): optional phrases that you would like to limit the user's response to.
         Defaults to None.
        transcribe (bool, optional): whether you would like to transcribe the user's reponse. Defaults to True.
        timeout (int, optional): timeout for how long the device will wait for user's response. Defaults to 60.
        alt_lang (str, optional): if you would like the device to listen for a response in a specific language.
         Defaults to None.

    Returns:
        text representation of what the user had spoken into the device.
    """
    if phrases is None:
        phrases = []
    if isinstance(phrases, str):
        phrases = [phrases]

    _id = uuid.uuid4().hex
    event = {
        '_type': 'wf_api_listen_request',
        '_target': self.targets_from_source_uri(target),
        'phrases': phrases,
        'transcribe': transcribe,
        'timeout': timeout,
        'alt_lang': alt_lang
    }

    criteria = {
        '_type': 'wf_api_speech_event',
        'request_id': _id
    }
    # need to add this before _send_receive to avoid race condition
    event_future = self._set_event_match(criteria)
    await self._send_receive(event, _id)
    speech_event = await self._wait_for_event_match(event_future, timeout)

    if transcribe:
        return speech_event['text']
    else:
        return speech_event['audio']

log_message(message, category='default', target=None, content_type='text/plain') async

Log an analytics event from a workflow with the specified content and under a specified category. This does not log the device who triggered the workflow that called this function.

Parameters:

Name Type Description Default
message str

a description for your analytical event.

required
category str

a category for your analytical event. Defaults to 'default'.

'default'
target str

URN of the device that triggered this function. Defaults to None.

None
content_type str

encoding of the message string. Defaults to 'text/plain'.

'text/plain'
Source code in relay/workflow.py
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
async def log_message(self, message: str, category: Optional[str] = 'default', target: Optional[str] = None,
                      content_type: Optional[str] = 'text/plain'):
    """Log an analytics event from a workflow with the specified content and
    under a specified category. This does not log the device who
    triggered the workflow that called this function.

    Args:
        message (str): a description for your analytical event.
        category (str, optional): a category for your analytical event. Defaults to 'default'.
        target (str, optional): URN of the device that triggered this function. Defaults to None.
        content_type (str, optional): encoding of the message string. Defaults to 'text/plain'.
    """
    event = {
        '_type': 'wf_api_log_analytics_event_request',
        'content': message,
        'content_type': content_type,
        'category': category,
        'device_uri': target
    }
    await self._send_receive(event)

log_user_message(message, target, category) async

Log an analytic event from a workflow with the specified content and under a specified category. This includes the device who triggered the workflow that called this function.

Parameters:

Name Type Description Default
message str

a description for your analytical event.

required
target str

the URN of a the device that triggered this function. Defaults to None.

required
category str

a category for your analytical event.

required
Source code in relay/workflow.py
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
async def log_user_message(self, message: str, target, category: str):
    """Log an analytic event from a workflow with the specified content and
    under a specified category.  This includes the device who triggered the workflow
    that called this function.

    Args:
        message (str): a description for your analytical event.
        target (str, optional): the URN of a the device that triggered this function. Defaults to None.
        category (str): a category for your analytical event.
    """
    event = {
        '_type': 'wf_api_log_analytics_event_request',
        'content': message,
        'content_type': 'text/plain',
        'category': category,
        'device_uri': target
    }
    await self._send_receive(event)

make_target_uris(trigger) staticmethod

Creates a target URN after receiving a workflow trigger.

Parameters:

Name Type Description Default
trigger dict

workflow trigger.

required

Raises:

Type Description
WorkflowException

thrown if the trigger param is not a dictionary.

WorkflowException

thrown if the trigger param is not a trigger dictionary.

WorkflowException

thrown if there is no source_uri definition in the trigger.

Returns:

Type Description

a target object created from the trigger.

Source code in relay/workflow.py
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
@staticmethod
def make_target_uris(trigger: dict):
    """Creates a target URN after receiving a workflow trigger.

    Args:
        trigger (dict): workflow trigger.

    Raises:
        WorkflowException: thrown if the trigger param is not a dictionary.
        WorkflowException: thrown if the trigger param is not a trigger dictionary.
        WorkflowException: thrown if there is no source_uri definition in the trigger.

    Returns:
        a target object created from the trigger.
    """
    Relay._validate_trigger(trigger)
    target = {
        'uris': [trigger['args']['source_uri']]
    }
    return target

place_call(target, callee_uri) async

Places a call to another device.

Parameters:

Name Type Description Default
target str

the device which will place the call.

required
callee_uri str

the URN of the device you would like to call.

required

Returns:

Type Description

the event response.

Source code in relay/workflow.py
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
async def place_call(self, target, callee_uri: str):
    """Places a call to another device.

    Args:
        target (str): the device which will place the call.
        callee_uri (str): the URN of the device you would like to call.

    Returns:
        the event response.
    """
    event = {
        '_type': 'wf_api_call_request',
        '_target': self.targets_from_source_uri(target),
        'uri': callee_uri
    }
    response = await self._send_receive(event)
    return response['call_id']

play(target, filename) async

Plays a custom audio file that was uploaded by the user.

Parameters:

Name Type Description Default
target(str)

the interaction URN.

required
filename str

the name of the audio file.

required

Returns:

Type Description

the response id after the audio file has been played on the device.

Source code in relay/workflow.py
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
async def play(self, target, filename: str):
    """Plays a custom audio file that was uploaded by the user.

    Args:
        target(str): the interaction URN.
        filename (str): the name of the audio file.

    Returns:
        the response id after the audio file has been played on the device.
    """
    event = {
        '_type': 'wf_api_play_request',
        '_target': self.targets_from_source_uri(target),
        'filename': filename
    }
    response = await self._send_receive(event)
    return response['id']

play_and_wait(target, filename) async

Plays a custom audio file that was uploaded by the user. Waits until the audio file has finished playing before continuing through the workflow.

Parameters:

Name Type Description Default
target(str)

the interaction URN.

required
filename str

the name of the audio file.

required

Returns:

Type Description

the response id after the audio file has been played on the device.

Source code in relay/workflow.py
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
async def play_and_wait(self, target, filename: str):
    """Plays a custom audio file that was uploaded by the user.
    Waits until the audio file has finished playing before continuing through
    the workflow.

    Args:
        target(str): the interaction URN.
        filename (str): the name of the audio file.

    Returns:
        the response id after the audio file has been played on the device.
    """
    _id = uuid.uuid4().hex
    event = {
        '_type': 'wf_api_play_request',
        '_target': self.targets_from_source_uri(target),
        'filename': filename
    }

    criteria = {
        '_type': 'wf_api_prompt_event',
        'type': 'stopped',
        'id': _id
    }

    event_future = self._set_event_match(criteria)
    response = await self._send_receive(event, _id)
    await self._wait_for_event_match(event_future, 30)
    return response['id']

play_unread_inbox_messages(target) async

Play a targeted device's inbox messages.

Parameters:

Name Type Description Default
target str

the device or interaction URN whose inbox messages you would like to play.

required
Source code in relay/workflow.py
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
async def play_unread_inbox_messages(self, target):
    """Play a targeted device's inbox messages.

    Args:
        target (str): the device or interaction URN whose inbox messages you would like to play.
    """
    event = {
        '_type': 'wf_api_play_inbox_messages_request',
        '_target': self.targets_from_source_uri(target)
    }
    await self._send_receive(event)

push_options(priority='normal', title=None, body=None, sound='default') staticmethod

Push options for a virtual device after receiving a notification on the Relay App.

Parameters:

Name Type Description Default
priority str

priority of the notification. Can be 'normal', 'high', or 'critical'. Defaults to 'normal'.

'normal'
title str

title of the notification. Defaults to None.

None
body str

body of the notification. Defaults to None.

None
sound str

sound to be played when notification appears on app. Can be 'default', or 'sos'. Defaults to 'default'.

'default'

Returns:

Type Description

the options for priority and sound as specified.

Source code in relay/workflow.py
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
@staticmethod
def push_options(priority: str = 'normal', title: str = None, body: str = None, sound: str = 'default'):
    """Push options for a virtual device after receiving a notification on the Relay App.

    Args:
        priority (str, optional): priority of the notification. Can be 'normal', 'high', or 'critical'.
         Defaults to 'normal'.
        title (str, optional): title of the notification. Defaults to None.
        body (str, optional): body of the notification. Defaults to None.
        sound (str, optional): sound to be played when notification appears on app. Can be 'default', or 'sos'.
          Defaults to 'default'.

    Returns:
        the options for priority and sound as specified.
    """

    options = {
        'priority': priority,
        'sound': sound
    }
    if title is not None:
        options['title'] = title
    if body is not None:
        options['body'] = body
    return options

rainbow(target, rotations=-1) async

Switches all the LEDs on to a configured rainbow pattern and rotates the rainbow a specified number of times.

Parameters:

Name Type Description Default
target str

the interaction URN.

required
rotations int

the number of times you would like the rainbow to rotate. Defaults to -1, meaning the rainbow will rotate indefinitely.

-1
Source code in relay/workflow.py
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
async def rainbow(self, target, rotations: int = -1):
    """Switches all the LEDs on to a configured rainbow pattern and rotates the rainbow
    a specified number of times.

    Args:
        target (str): the interaction URN.
        rotations (int, optional): the number of times you would like the rainbow to rotate. Defaults to -1,
         meaning the rainbow will rotate indefinitely.
    """
    await self.led_action(target, 'rainbow', {'rotations': rotations})

resolve_incident(incident_id, reason) async

Resolves an incident that was created.

Parameters:

Name Type Description Default
incident_id str

the ID of the incident you would like to resolve.

required
reason str

the reason for resolving the incident.

required
Source code in relay/workflow.py
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
async def resolve_incident(self, incident_id: str, reason: str):
    """Resolves an incident that was created.

    Args:
        incident_id (str): the ID of the incident you would like to resolve.
        reason (str): the reason for resolving the incident.
    """
    event = {
        '_type': 'wf_api_resolve_incident_request',
        'incident_id': incident_id,
        'reason': reason
    }
    await self._send_receive(event)

rotate(target, color='0000ff', rotations=-1) async

Switches all the LEDs on a device to a certain color and rotates them a specified number of times.

Parameters:

Name Type Description Default
target str

the interaction URN.

required
color str

the hex color code you would like to turn the LEDs to. Defaults to '0000ff'.

'0000ff'
rotations int

the number of times you would like the LEDs to rotate. Defaults to -1, meaning

-1
Source code in relay/workflow.py
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
async def rotate(self, target, color: str = '0000ff', rotations: int = -1):
    """Switches all the LEDs on a device to a certain color and rotates them a specified number
    of times.

    Args:
        target (str): the interaction URN.
        color (str, optional): the hex color code you would like to turn the LEDs to. Defaults to '0000ff'.
        rotations (int, optional): the number of times you would like the LEDs to rotate. Defaults to -1, meaning
        the LEDs will rotate indefinitely.
    """
    await self.led_action(target, 'rotate', {'colors': {'1': color}, 'rotations': rotations})

say(target, text, lang='en-US') async

Utilizes text to speech capabilities to make the device 'speak' to the user.

Parameters:

Name Type Description Default
target(str)

the interaction URN.

required
text str

what you would like the device to say.

required
lang str

the language of the text that is being spoken. Defaults to 'en-US'.

'en-US'

Returns:

Type Description

the response ID after the device speaks to the user.

Source code in relay/workflow.py
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
async def say(self, target, text: str, lang: str = 'en-US'):
    """Utilizes text to speech capabilities to make the device 'speak' to the user.

    Args:
        target(str): the interaction URN.
        text (str): what you would like the device to say.
        lang (str, optional): the language of the text that is being spoken. Defaults to 'en-US'.

    Returns:
        the response ID after the device speaks to the user.
    """
    event = {
        '_type': 'wf_api_say_request',
        '_target': self.targets_from_source_uri(target),
        'text': text,
        'lang': lang
    }
    response = await self._send_receive(event)
    return response['id']

say_and_wait(target, text, lang='en-US') async

Utilizes text to speech capabilities to make the device 'speak' to the user. Waits until the text is fully played out on the device before continuing.

Parameters:

Name Type Description Default
target(str)

the interaction URN.

required
text str

what you would like the device to say.

required
lang str

the language of the text that is being spoken. Defaults to 'en-US'.

'en-US'

Returns:

Type Description

the response ID after the device speaks to the user.

Source code in relay/workflow.py
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
async def say_and_wait(self, target, text: str, lang: str = 'en-US'):
    """Utilizes text to speech capabilities to make the device 'speak' to the user.
    Waits until the text is fully played out on the device before continuing.

    Args:
        target(str): the interaction URN.
        text (str): what you would like the device to say.
        lang (str, optional): the language of the text that is being spoken. Defaults to 'en-US'.

    Returns:
        the response ID after the device speaks to the user.
    """
    _id = uuid.uuid4().hex
    event = {
        '_type': 'wf_api_say_request',
        '_target': self.targets_from_source_uri(target),
        'text': text,
        'lang': lang
    }

    criteria = {
        '_type': 'wf_api_prompt_event',
        'type': 'stopped',
        'id': _id}

    event_future = self._set_event_match(criteria)
    response = await self._send_receive(event, _id)
    await self._wait_for_event_match(event_future, 30)
    logger.debug(f'wait complete for {target}')
    return response['id']

set_channel(target, channel_name, suppress_tts=False, disable_home_channel=False) async

Sets the channel that a device is on. This can be used to change the channel of a device during a workflow, where the channel will also be updated on the Relay Dash.

Parameters:

Name Type Description Default
target str

the device or interaction URN.

required
channel_name str

the name of the channel you would like to set your device to.

required
suppress_tts bool

whether you would like to surpress text to speech. Defaults to False.

False
disable_home_channel bool

whether you would like to disable the home channel. Defaults to False.

False
Source code in relay/workflow.py
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
async def set_channel(self, target, channel_name: str, suppress_tts: bool = False,
                      disable_home_channel: bool = False):
    """Sets the channel that a device is on.  This can be used to change the channel of a device during a workflow,
    where the channel will also be updated on the Relay Dash.

    Args:
        target (str): the device or interaction URN.
        channel_name (str): the name of the channel you would like to set your device to.
        suppress_tts (bool, optional): whether you would like to surpress text to speech. Defaults to False.
        disable_home_channel (bool, optional): whether you would like to disable the home channel.
         Defaults to False.
    """
    event = {
        '_type': 'wf_api_set_channel_request',
        '_target': self.targets_from_source_uri(target),
        'channel_name': channel_name,
        'suppress_tts': suppress_tts,
        'disable_home_channel': disable_home_channel
    }
    await self._send_receive(event)

set_device_name(target, name) async

Sets the name of a targeted device and updates it on the Relay Dash. The name remains updated until it is set again via a workflow or updated manually on the Relay Dash.

Parameters:

Name Type Description Default
target str

the device or interaction URN.

required
name str

a new name for your device.

required
Source code in relay/workflow.py
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
async def set_device_name(self, target, name: str):
    """Sets the name of a targeted device and updates it on the Relay Dash.
    The name remains updated until it is set again via a workflow or updated manually
    on the Relay Dash.

    Args:
        target (str): the device or interaction URN.
        name (str): a new name for your device.
    """
    await self._set_device_info(target, 'label', name)

set_timer(name, timer_type='timeout', timeout=60, timeout_type='secs') async

Serves as a named timer that can be either interval or timeout. Allows you to specify the unit of time.

Parameters:

Name Type Description Default
name str

a name for your timer.

required
timer_type str

can be 'timeout' or 'interval'. Defaults to 'timeout'.

'timeout'
timeout int

an integer representing when you would like your timer to fire.

60
timeout_type str

can be 'ms', 'secs', 'mins' or 'hrs'. Defaults to 'secs'.

'secs'
Source code in relay/workflow.py
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
async def set_timer(self, name: str, timer_type: str = 'timeout', timeout: int = 60, timeout_type: str = 'secs'):
    """ Serves as a named timer that can be either interval or timeout.  Allows you to specify
    the unit of time.

    Args:
        name (str): a name for your timer.
        timer_type (str, optional): can be 'timeout' or 'interval'. Defaults to 'timeout'.
        timeout (int): an integer representing when you would like your timer to fire.
        timeout_type (str, optional): can be 'ms', 'secs', 'mins' or 'hrs'. Defaults to 'secs'.
    """
    event = {
        '_type': 'wf_api_set_timer_request',
        'type': timer_type,
        'name': name,
        'timeout': timeout,
        'timeout_type': timeout_type
    }
    await self._send_receive(event)

set_user_profile(target, username, force=False) async

Sets the profile of a user by updating the username.

Parameters:

Name Type Description Default
target str

the device URN whose profile you would like to update.

required
username str

the updated username for the device.

required
force bool

whether you would like to force this update. Defaults to False.

False
Source code in relay/workflow.py
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
async def set_user_profile(self, target: str, username: str, force: bool = False):
    """Sets the profile of a user by updating the username.

    Args:
        target (str): the device URN whose profile you would like to update.
        username (str): the updated username for the device.
        force (bool, optional): whether you would like to force this update. Defaults to False.
    """
    event = {
        '_type': 'wf_api_set_user_profile_request',
        '_target': self.targets_from_source_uri(target),
        'username': username,
        'force': force
    }
    await self._send_receive(event)

set_var(name, value) async

Sets a variable with the corresponding name and value. Scope of the variable is from start to end of a workflow. Note that you can only set values of type string. Args: name (str): name of the variable to be created. value (str): value that the variable will hold.

Source code in relay/workflow.py
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
async def set_var(self, name: str, value: str):
    """Sets a variable with the corresponding name and value. Scope of
    the variable is from start to end of a workflow.  Note that you 
    can only set values of type string.
    Args:
        name (str): name of the variable to be created.
        value (str): value that the variable will hold.
    """
    event = {
        '_type': 'wf_api_set_var_request',
        'name': name,
        'value': value
    }
    response = await self._send_receive(event)
    return response['value']

start_interaction(target, name, options=None) async

Starts an interaction with the user. Triggers an INTERACTION_STARTED event and allows the user to interact with the device via functions that require an interaction URN.

Parameters:

Name Type Description Default
target target

the device that you would like to start an interaction with.

required
name str

a name for your interaction.

required
options optional

can be color, home channel, or input types. Defaults to None.

None
Source code in relay/workflow.py
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
async def start_interaction(self, target, name: str, options=None):
    """Starts an interaction with the user.  Triggers an INTERACTION_STARTED event
    and allows the user to interact with the device via functions that require an 
    interaction URN.

    Args:
        target (target): the device that you would like to start an interaction with.
        name (str): a name for your interaction.
        options (optional): can be color, home channel, or input types. Defaults to None.
    """
    event = {
        '_type': 'wf_api_start_interaction_request',
        '_target': target,
        'name': name,
        'options': options
    }
    await self._send_receive(event)

start_timer(timeout=60) async

Starts an unnamed timer, meaning this will be the only timer on your device. The timer will fire when it reaches the value of the 'timeout' parameter.

Parameters:

Name Type Description Default
timeout int

the number of seconds you would like to wait until the timer fires.

60
Source code in relay/workflow.py
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
async def start_timer(self, timeout: int = 60):
    """Starts an unnamed timer, meaning this will be the only timer on your device.
    The timer will fire when it reaches the value of the 'timeout' parameter.

    Args:
        timeout (int): the number of seconds you would like to wait until the timer fires.
    """
    event = {
        '_type': 'wf_api_start_timer_request',
        'timeout': timeout
    }
    await self._send_receive(event)

stop_timer() async

Stops an unnamed timer.

Source code in relay/workflow.py
1776
1777
1778
1779
1780
1781
1782
async def stop_timer(self):
    """Stops an unnamed timer.
    """
    event = {
        '_type': 'wf_api_stop_timer_request'
    }
    await self._send_receive(event)

switch_all_led_off(target) async

Switches all the LEDs on a device off.

Parameters:

Name Type Description Default
target str

the interaction URN.

required
Source code in relay/workflow.py
1735
1736
1737
1738
1739
1740
1741
async def switch_all_led_off(self, target):
    """Switches all the LEDs on a device off.

    Args:
        target (str): the interaction URN.
    """
    await self.led_action(target, 'off', {})

switch_all_led_on(target, color='0000ff') async

Switches all the LEDs on a device on to a specified color.

Parameters:

Name Type Description Default
target str

the interaction URN.

required
color str

the hex color code you would like the LEDs to be. Defaults to '0000ff'.

'0000ff'
Source code in relay/workflow.py
1669
1670
1671
1672
1673
1674
1675
1676
async def switch_all_led_on(self, target, color: str = '0000ff'):
    """Switches all the LEDs on a device on to a specified color.

    Args:
        target (str): the interaction URN.
        color (str, optional): the hex color code you would like the LEDs to be. Defaults to '0000ff'.
    """
    await self.led_action(target, 'static', {'colors': {'ring': color}})

switch_led_on(target, index, color='0000ff') async

Switches on an LED at a particular index to a specified color.

Parameters:

Name Type Description Default
target str

the interaction URN.

required
index int

the index of an LED, numbered 1-12.

required
color str

the hex color code you would like to turn the LED to. Defaults to '0000ff'.

'0000ff'
Source code in relay/workflow.py
1678
1679
1680
1681
1682
1683
1684
1685
1686
async def switch_led_on(self, target, index: int, color: str = '0000ff'):
    """Switches on an LED at a particular index to a specified color.

    Args:
        target (str): the interaction URN.
        index (int): the index of an LED, numbered 1-12.
        color (str, optional): the hex color code you would like to turn the LED to. Defaults to '0000ff'.
    """
    await self.led_action(target, 'static', {'colors': {index: color}})

targets_from_source_uri(source_uri) staticmethod

Creates a target object from a source URN. Enables the device to perform the desired action after the function has been called. Used interanlly by interaction functions such as say(), listen(), vibration(), etc.

Parameters:

Name Type Description Default
source_uri str

source uri that will be used to create a target.

required

Returns:

Type Description

the target that was created from a source URN.

Source code in relay/workflow.py
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
@staticmethod
def targets_from_source_uri(source_uri: str):
    """Creates a target object from a source URN.
    Enables the device to perform the desired action after the function
    has been called.  Used interanlly by interaction functions such as
    say(), listen(), vibration(), etc.

    Args:
        source_uri (str): source uri that will be used to create a target.

    Returns:
        the target that was created from a source URN.
    """
    targets = {
        'uris': [source_uri]
    }
    return targets

terminate() async

Terminates a workflow. This method is usually called after your workflow has completed, and you would like to end the workflow by calling end_interaction(), where you can then terminate the workflow.

Source code in relay/workflow.py
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
async def terminate(self):
    """Terminates a workflow.  This method is usually called
    after your workflow has completed, and you would like to end the
    workflow by calling end_interaction(), where you can then terminate
    the workflow.
    """
    event = {
        '_type': 'wf_api_terminate_request'
    }
    # there is no response
    await self._send(event)

translate(text, from_lang='en-US', to_lang='es-ES') async

Translates text from one language to another.

Parameters:

Name Type Description Default
text str

the text that you would like to translate.

required
from_lang str

the language that you would like to translate from.

'en-US'
to_lang str

the language that you would like to translate to.

'es-ES'

Returns:

Name Type Description
str

the translated text.

Source code in relay/workflow.py
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
async def translate(self, text: str, from_lang: str = 'en-US', to_lang: str = 'es-ES'):
    """Translates text from one language to another.

    Args:
        text (str): the text that you would like to translate.
        from_lang (str): the language that you would like to translate from.
        to_lang (str): the language that you would like to translate to.

    Returns:
        str: the translated text.
    """
    event = {
        '_type': 'wf_api_translate_request',
        'text': text,
        'from_lang': from_lang,
        'to_lang': to_lang
    }
    response = await self._send_receive(event)
    return response['text']

unset_var(name) async

Unsets the value of a variable.

Parameters:

Name Type Description Default
name str

the name of the variable whose value you would like to unset.

required
Source code in relay/workflow.py
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
async def unset_var(self, name: str):
    """Unsets the value of a variable.  

    Args:
        name (str): the name of the variable whose value you would like to unset.
    """
    event = {
        '_type': 'wf_api_unset_var_request',
        'name': name
    }
    await self._send_receive(event)

vibrate(target, pattern=None) async

Makes the device vibrate in a particular pattern. You can specify how many vibrations you would like, the duration of each vibration in milliseconds, and how long you would like the pauses between each vibration to last in milliseconds.

Parameters:

Name Type Description Default
target str

the interaction URN.

required
pattern list

an array representing the pattern of your vibration. Defaults to None.

None
Source code in relay/workflow.py
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
async def vibrate(self, target, pattern: list = None):
    """Makes the device vibrate in a particular pattern.  You can specify
    how many vibrations you would like, the duration of each vibration in
    milliseconds, and how long you would like the pauses between each vibration to last
    in milliseconds.

    Args:
        target (str): the interaction URN.
        pattern (list, optional): an array representing the pattern of your vibration. Defaults to None.
    """
    if not pattern:
        pattern = [100, 500, 500, 500, 500, 500]

    event = {
        '_type': 'wf_api_vibrate_request',
        '_target': self.targets_from_source_uri(target),
        'pattern': pattern
    }
    await self._send_receive(event)

Server

A websocket server that gets connected to when a new workflow is instantiated via a trigger.

Events are sent here, and the connection is also used to send actions to the Relay server.

Source code in relay/workflow.py
 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
class Server:
    """
    A websocket server that gets connected to when a new workflow
    is instantiated via a trigger.

    Events are sent here, and the connection is also used to send actions to the Relay server.
    """

    def __init__(self, host: str, port: int, **kwargs):
        """
        Args:
            host: the IP address of the interface that this server should
             listen on. Typically is "0.0.0.0", which represents all interfaces.
            port: the port number that this server should listen on.
            **kwargs: see below

        Keyword Args:
            log_level: sets the threshold level for the logger in this module.
            log_handler: a log handler object to be added to the logger in this
             module. To disable logging output, use `logging.NullHandler()`.
            ssl_key_filename: if an SSLContext is desired for this server,
             this is the filename where the key in PEM format can be found.
             Should also use ssl_cert_filename if this is specified.
            ssl_cert_filename: if an SSLContext is desired for this server,
             this is the filename where the certificate in PEM format can
             be found. Should also use ssl_key_filename if this is specified.
        """

        self.host = host
        self.port = port
        self.workflows = {}  # {path: workflow}
        self.conn_count = 0
        for key in kwargs:
            if key == 'ssl_key_filename':
                self.ssl_key_filename = kwargs[key]
            elif key == 'ssl_cert_filename':
                self.ssl_cert_filename = kwargs[key]
            elif key == 'log_level':
                this_logger = logging.getLogger(__name__)
                this_logger.setLevel(kwargs[key])
            elif key == 'log_handler':
                # if logging.NullHandler() is added then nothing will appear on the console
                this_logger = logging.getLogger(__name__)
                this_logger.addHandler(kwargs[key])

    def register(self, workflow, path: str):

        if path in self.workflows:
            raise ServerException(f'a workflow is already registered at path {path}')
        self.workflows[path] = workflow

    def start(self):

        custom_headers = {'Server': f'{VERSION}'}
        if hasattr(self, 'ssl_key_filename') and hasattr(self, 'ssl_cert_filename'):
            if not os.access(self.ssl_cert_filename, os.R_OK):
                raise ServerException(f"can't read ssl_cert_file {self.ssl_cert_filename}")
            if not os.access(self.ssl_key_filename, os.R_OK):
                raise ServerException(f"can't read ssl_key_file {self.ssl_key_filename}")
            ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
            ssl_context.load_cert_chain(self.ssl_cert_filename, self.ssl_key_filename)
            start_server = websockets.serve(self._handler, self.host, self.port,
                                            extra_headers=custom_headers, ssl=ssl_context)
            logger.info(
                f'Relay workflow server ({VERSION}) listening on {self.host} port {self.port}'
                f' with ssl_context {ssl_context}')
        else:
            start_server = websockets.serve(self._handler, self.host, self.port, extra_headers=custom_headers)
            logger.info(f'Relay workflow server ({VERSION}) listening on {self.host}'
                        f' port {self.port} with plaintext')

        asyncio.get_event_loop().run_until_complete(start_server)

        try:
            asyncio.get_event_loop().run_forever()

        except KeyboardInterrupt:
            logger.debug('server terminated')

    def total_connections(self):
        return self.conn_count

    async def _handler(self, websocket, path: str):

        workflow = self.workflows.get(path, None)
        if workflow:
            logger.debug(f'handling request on path {path}')
            relay = Relay(workflow)
            try:
                self.conn_count += 1
                await relay._handle(websocket)

            finally:
                self.conn_count -= 1

        else:
            logger.warning(f'ignoring request for unregistered path {path}')
            await websocket.close()

__init__(host, port, **kwargs)

Parameters:

Name Type Description Default
host str

the IP address of the interface that this server should listen on. Typically is "0.0.0.0", which represents all interfaces.

required
port int

the port number that this server should listen on.

required
**kwargs

see below

{}

Other Parameters:

Name Type Description
log_level

sets the threshold level for the logger in this module.

log_handler

a log handler object to be added to the logger in this module. To disable logging output, use logging.NullHandler().

ssl_key_filename

if an SSLContext is desired for this server, this is the filename where the key in PEM format can be found. Should also use ssl_cert_filename if this is specified.

ssl_cert_filename

if an SSLContext is desired for this server, this is the filename where the certificate in PEM format can be found. Should also use ssl_key_filename if this is specified.

Source code in relay/workflow.py
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
def __init__(self, host: str, port: int, **kwargs):
    """
    Args:
        host: the IP address of the interface that this server should
         listen on. Typically is "0.0.0.0", which represents all interfaces.
        port: the port number that this server should listen on.
        **kwargs: see below

    Keyword Args:
        log_level: sets the threshold level for the logger in this module.
        log_handler: a log handler object to be added to the logger in this
         module. To disable logging output, use `logging.NullHandler()`.
        ssl_key_filename: if an SSLContext is desired for this server,
         this is the filename where the key in PEM format can be found.
         Should also use ssl_cert_filename if this is specified.
        ssl_cert_filename: if an SSLContext is desired for this server,
         this is the filename where the certificate in PEM format can
         be found. Should also use ssl_key_filename if this is specified.
    """

    self.host = host
    self.port = port
    self.workflows = {}  # {path: workflow}
    self.conn_count = 0
    for key in kwargs:
        if key == 'ssl_key_filename':
            self.ssl_key_filename = kwargs[key]
        elif key == 'ssl_cert_filename':
            self.ssl_cert_filename = kwargs[key]
        elif key == 'log_level':
            this_logger = logging.getLogger(__name__)
            this_logger.setLevel(kwargs[key])
        elif key == 'log_handler':
            # if logging.NullHandler() is added then nothing will appear on the console
            this_logger = logging.getLogger(__name__)
            this_logger.addHandler(kwargs[key])

Workflow

Source code in relay/workflow.py
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
class Workflow:

    def __init__(self, name: str):
        self.name = name
        self.type_handlers = {}  # {(type, args): func}

    def on_start(self, func):
        """
        A decorator for a handler method for the START event (workflow is starting).

        async def start_handler(workflow:relay.workflow.Workflow, trigger:dict)
        """
        self.type_handlers['wf_api_start_event'] = func

    def on_stop(self, func):
        """
        A decorator for a handler method for the STOP event (workflow is stopping).

        async def stop_handler(workflow:relay.workflow.Workflow, reason:str)
        """
        self.type_handlers['wf_api_stop_event'] = func

    def on_prompt(self, func):
        """
        A decorator for a handler method for the PROMPT event (text-to-speech is streaming in).

        async def prompt_handler(workflow:relay.workflow.Workflow, source_uri:str, prompt_type:str)
        """
        self.type_handlers['wf_api_prompt_event'] = func

    def on_button(self, _func=None, *, button='*', taps='*'):
        """
        A decorator for a handler method for the BUTTON event (the Talk button was pressed).

        async def button_handler(workflow:relay.workflow.Workflow, button:str, taps:str, source_uri:str)
        """
        def on_button_decorator(func):
            self.type_handlers['wf_api_button_event', button, taps] = func

        if _func:
            return on_button_decorator(_func)

        else:
            return on_button_decorator

    def on_notification(self, _func=None, *, name='*', event='*'):
        """
        A decorator for a handler method for the NOTIFICATION event (a broadcast or alert was sent).

        async def button_handler(workflow:relay.workflow.Workflow, button:str, taps:str, source_uri:str)
        """
        def on_notification_decorator(func):
            self.type_handlers['wf_api_notification_event', name, event] = func

        if _func:
            return on_notification_decorator(_func)

        else:
            return on_notification_decorator

    def on_timer(self, func):
        # unnamed timer
        """
        A decorator for a handler method for the TIMER event (the unnamed timer fired).

        async def timer_handler(workflow:relay.workflow.Workflow)
        """
        self.type_handlers['wf_api_timer_event'] = func

    def on_timer_fired(self, func):
        # named timer
        """
        A decorator for a handler method for the TIMER_FIRED event (a named timer fired).

        async def timer_fired_handler(workflow:relay.workflow.Workflow, timer_name:str)
        """
        self.type_handlers['wf_api_timer_fired_event'] = func

    def on_speech(self, func):
        """
        A decorator for a handler method for the SPEECH event (the listen() function is running).

        async def speech_handler(workflow:relay.workflow.Workflow, transcribed_text:str, audio:bytes, language:str,
                                 request_id:str, source_uri:str)
        """
        self.type_handlers['wf_api_speech_event'] = func

    def on_progress(self, func):
        """
        A decorator for a handler method for the PROGRESS event (a long running action is being
        performed across a large number of devices, may get called multiple times).

        async def progress_handler(workflow:relay.workflow.Workflow)
        """
        self.type_handlers['wf_api_progress_event'] = func

    def on_play_inbox_message(self, func):
        """
        A decorator for a handler method for the PLAY_INBOX_MESSAGE event (a missed message
        is being played).

        async def play_inbox_message_handler(workflow:relay.workflow.Workflow, action:str)
        """
        self.type_handlers['wf_api_play_inbox_message_event'] = func

    def on_call_connected(self, func):
        """
        A decorator for a handler method for the CALL_CONNECTED event.
        A call attempt that was ringing, progressing, or incoming is now fully
        connected. This event can occur on both the caller and the callee.

        async def call_connected_handler(workflow:relay.workflow.Workflow, call_id:str, direction:str,
                                         other_device_id:str, other_device_name:str,
                                         uri:str, onnet:bool,
                                         start_time_epoch:int, connect_time_epoch:int)
        """
        self.type_handlers['wf_api_call_connected_event'] = func

    def on_call_disconnected(self, func):
        """
        A decorator for a handler method for the CALL_DISCONNECTED event.
        A call that was once connected has become disconnected. This event can
        occur on both the caller and the callee.

        async def call_disconnected_handler(workflow:relay.workflow.Workflow, call_id:str, direction:str,
                                            other_device_id:str, other_device_name:str,
                                            uri:str, onnet:bool, reason:str,
                                            start_time_epoch:int, connect_time_epoch:int, end_time_epoch:int)
        """
        self.type_handlers['wf_api_call_disconnected_event'] = func

    def on_call_failed(self, func):
        """
        A decorator for a handler method for the CALL_FAILED event.
        A call failed to get connected. This event can occur on both the caller
        and the callee.

        async def call_failed_handler(workflow:relay.workflow.Workflow, call_id:str, direction:str,
                                      other_device_id:str, other_device_name:str,
                                      uri:str, onnet:bool, reason:str,
                                      start_time_epoch:int, connect_time_epoch:int, end_time_epoch:int)
        """
        self.type_handlers['wf_api_call_failed_event'] = func

    def on_call_received(self, func):
        """
        A decorator for a handler method for the CALL_RECEIVED event.
        The device is receiving an inbound call request. This event can occur
        on the callee.

        async def call_received_handler(workflow:relay.workflow.Workflow, call_id:str, direction:str,
                                        other_device_id:str, other_device_name:str,
                                        uri:str, onnet:bool,
                                        start_time_epoch:int)
        """
        self.type_handlers['wf_api_call_received_event'] = func

    def on_call_ringing(self, func):
        """
        A decorator for a handler method for the CALL_RINGING event.
        The device we called is ringing. We are waiting for them to answer.
        This event can occur on the caller.

        async def call_ringing_handler(workflow:relay.workflow.Workflow, call_id:str, direction:str,
                                       other_device_id:str, other_device_name:str,
                                       uri:str, onnet:bool,
                                       start_time_epoch:int)
        """
        self.type_handlers['wf_api_call_ringing_event'] = func

    def on_call_start_request(self, func):
        """
        A decorator for a handler method for the CALL_START_REQUEST event.
        There is a request to make an outbound call. This event can occur on
        the caller after using the "Call X" voice command on the Assistant.

        async def call_start_request_handler(workflow:relay.workflow.Workflow, destination_uri:str)
        """
        self.type_handlers['wf_api_call_start_request_event'] = func

    def on_call_progressing(self, func):
        """
        A decorator for a handler method for the CALL_PROGRESSING event.
        The device we called is making progress on getting connected. This may
        be interspersed with on_call_ringing. This event can occur on the caller.

        async def call_progressing_handler(workflow:relay.workflow.Workflow, call_id:str, direction:str,
                                           other_device_id:str, other_device_name:str,
                                           uri:str, onnet:bool,
                                           start_time_epoch:int, connect_time_epoch:int)
        """
        self.type_handlers['wf_api_call_progressing_event'] = func

    def on_sms(self, func):
        """
        A decorator for a handler method for the SMS event (TBD).

        async def sms_handler(workflow:relay.workflow.Workflow, id:str, event:dict)
        """
        self.type_handlers['wf_api_sms_event'] = func

    def on_incident(self, func):
        """
        A decorator for a handler method for the INCIDENT event (an incident has been created).

        async def incident_handler(workflow:relay.workflow.Workflow, type:str, incident_id:str, reason:str)
        """
        self.type_handlers['wf_api_incident_event'] = func

    def on_interaction_lifecycle(self, func):
        """
        A decorator for a handler method for the INTERACTION_LIFECYCLE event (an interaction
        is starting, resuming, or ending).

        async def interaction_lifecycle_handler(workflow:relay.workflow.Workflow, itype:str, source_uri:str, reason:str)
        """
        self.type_handlers['wf_api_interaction_lifecycle_event'] = func

    def on_resume(self, func):
        """
        A decorator for a handler method for the RESUME event (TBD).

        async def resume_handler(workflow:relay.workflow.Workflow, trigger:dict)
        """
        self.type_handlers['wf_api_resume_event'] = func

    def get_handler(self, event: dict):
        t = event['_type']

        # Assume no-arg handler; if not, check the handlers that require args.
        # For args, check for handler registered with specific values first; if not,
        # then check variations with wildcard values.
        h = self.type_handlers.get(t, None)
        if not h:
            if t == 'wf_api_button_event':
                h = self.type_handlers.get((t, event['button'], event['taps']), None)
                if not h:
                    # prefer button match over taps
                    h = self.type_handlers.get((t, event['button'], '*'), None)
                    if not h:
                        h = self.type_handlers.get((t, '*', event['taps']), None)
                        if not h:
                            h = self.type_handlers.get((t, '*', '*'), None)

            elif t == 'wf_api_notification_event':
                h = self.type_handlers.get((t, event['name'], event['event']), None)
                if not h:
                    # prefer name match over event
                    h = self.type_handlers.get((t, event['name'], '*'), None)
                    if not h:
                        h = self.type_handlers.get((t, '*', event['event']), None)
                        if not h:
                            h = self.type_handlers.get((t, '*', '*'), None)

        return h

on_button(_func=None, *, button='*', taps='*')

A decorator for a handler method for the BUTTON event (the Talk button was pressed).

async def button_handler(workflow:relay.workflow.Workflow, button:str, taps:str, source_uri:str)

Source code in relay/workflow.py
416
417
418
419
420
421
422
423
424
425
426
427
428
429
def on_button(self, _func=None, *, button='*', taps='*'):
    """
    A decorator for a handler method for the BUTTON event (the Talk button was pressed).

    async def button_handler(workflow:relay.workflow.Workflow, button:str, taps:str, source_uri:str)
    """
    def on_button_decorator(func):
        self.type_handlers['wf_api_button_event', button, taps] = func

    if _func:
        return on_button_decorator(_func)

    else:
        return on_button_decorator

on_call_connected(func)

A decorator for a handler method for the CALL_CONNECTED event. A call attempt that was ringing, progressing, or incoming is now fully connected. This event can occur on both the caller and the callee.

async def call_connected_handler(workflow:relay.workflow.Workflow, call_id:str, direction:str, other_device_id:str, other_device_name:str, uri:str, onnet:bool, start_time_epoch:int, connect_time_epoch:int)

Source code in relay/workflow.py
491
492
493
494
495
496
497
498
499
500
501
502
def on_call_connected(self, func):
    """
    A decorator for a handler method for the CALL_CONNECTED event.
    A call attempt that was ringing, progressing, or incoming is now fully
    connected. This event can occur on both the caller and the callee.

    async def call_connected_handler(workflow:relay.workflow.Workflow, call_id:str, direction:str,
                                     other_device_id:str, other_device_name:str,
                                     uri:str, onnet:bool,
                                     start_time_epoch:int, connect_time_epoch:int)
    """
    self.type_handlers['wf_api_call_connected_event'] = func

on_call_disconnected(func)

A decorator for a handler method for the CALL_DISCONNECTED event. A call that was once connected has become disconnected. This event can occur on both the caller and the callee.

async def call_disconnected_handler(workflow:relay.workflow.Workflow, call_id:str, direction:str, other_device_id:str, other_device_name:str, uri:str, onnet:bool, reason:str, start_time_epoch:int, connect_time_epoch:int, end_time_epoch:int)

Source code in relay/workflow.py
504
505
506
507
508
509
510
511
512
513
514
515
def on_call_disconnected(self, func):
    """
    A decorator for a handler method for the CALL_DISCONNECTED event.
    A call that was once connected has become disconnected. This event can
    occur on both the caller and the callee.

    async def call_disconnected_handler(workflow:relay.workflow.Workflow, call_id:str, direction:str,
                                        other_device_id:str, other_device_name:str,
                                        uri:str, onnet:bool, reason:str,
                                        start_time_epoch:int, connect_time_epoch:int, end_time_epoch:int)
    """
    self.type_handlers['wf_api_call_disconnected_event'] = func

on_call_failed(func)

A decorator for a handler method for the CALL_FAILED event. A call failed to get connected. This event can occur on both the caller and the callee.

async def call_failed_handler(workflow:relay.workflow.Workflow, call_id:str, direction:str, other_device_id:str, other_device_name:str, uri:str, onnet:bool, reason:str, start_time_epoch:int, connect_time_epoch:int, end_time_epoch:int)

Source code in relay/workflow.py
517
518
519
520
521
522
523
524
525
526
527
528
def on_call_failed(self, func):
    """
    A decorator for a handler method for the CALL_FAILED event.
    A call failed to get connected. This event can occur on both the caller
    and the callee.

    async def call_failed_handler(workflow:relay.workflow.Workflow, call_id:str, direction:str,
                                  other_device_id:str, other_device_name:str,
                                  uri:str, onnet:bool, reason:str,
                                  start_time_epoch:int, connect_time_epoch:int, end_time_epoch:int)
    """
    self.type_handlers['wf_api_call_failed_event'] = func

on_call_progressing(func)

A decorator for a handler method for the CALL_PROGRESSING event. The device we called is making progress on getting connected. This may be interspersed with on_call_ringing. This event can occur on the caller.

async def call_progressing_handler(workflow:relay.workflow.Workflow, call_id:str, direction:str, other_device_id:str, other_device_name:str, uri:str, onnet:bool, start_time_epoch:int, connect_time_epoch:int)

Source code in relay/workflow.py
566
567
568
569
570
571
572
573
574
575
576
577
def on_call_progressing(self, func):
    """
    A decorator for a handler method for the CALL_PROGRESSING event.
    The device we called is making progress on getting connected. This may
    be interspersed with on_call_ringing. This event can occur on the caller.

    async def call_progressing_handler(workflow:relay.workflow.Workflow, call_id:str, direction:str,
                                       other_device_id:str, other_device_name:str,
                                       uri:str, onnet:bool,
                                       start_time_epoch:int, connect_time_epoch:int)
    """
    self.type_handlers['wf_api_call_progressing_event'] = func

on_call_received(func)

A decorator for a handler method for the CALL_RECEIVED event. The device is receiving an inbound call request. This event can occur on the callee.

async def call_received_handler(workflow:relay.workflow.Workflow, call_id:str, direction:str, other_device_id:str, other_device_name:str, uri:str, onnet:bool, start_time_epoch:int)

Source code in relay/workflow.py
530
531
532
533
534
535
536
537
538
539
540
541
def on_call_received(self, func):
    """
    A decorator for a handler method for the CALL_RECEIVED event.
    The device is receiving an inbound call request. This event can occur
    on the callee.

    async def call_received_handler(workflow:relay.workflow.Workflow, call_id:str, direction:str,
                                    other_device_id:str, other_device_name:str,
                                    uri:str, onnet:bool,
                                    start_time_epoch:int)
    """
    self.type_handlers['wf_api_call_received_event'] = func

on_call_ringing(func)

A decorator for a handler method for the CALL_RINGING event. The device we called is ringing. We are waiting for them to answer. This event can occur on the caller.

async def call_ringing_handler(workflow:relay.workflow.Workflow, call_id:str, direction:str, other_device_id:str, other_device_name:str, uri:str, onnet:bool, start_time_epoch:int)

Source code in relay/workflow.py
543
544
545
546
547
548
549
550
551
552
553
554
def on_call_ringing(self, func):
    """
    A decorator for a handler method for the CALL_RINGING event.
    The device we called is ringing. We are waiting for them to answer.
    This event can occur on the caller.

    async def call_ringing_handler(workflow:relay.workflow.Workflow, call_id:str, direction:str,
                                   other_device_id:str, other_device_name:str,
                                   uri:str, onnet:bool,
                                   start_time_epoch:int)
    """
    self.type_handlers['wf_api_call_ringing_event'] = func

on_call_start_request(func)

A decorator for a handler method for the CALL_START_REQUEST event. There is a request to make an outbound call. This event can occur on the caller after using the "Call X" voice command on the Assistant.

async def call_start_request_handler(workflow:relay.workflow.Workflow, destination_uri:str)

Source code in relay/workflow.py
556
557
558
559
560
561
562
563
564
def on_call_start_request(self, func):
    """
    A decorator for a handler method for the CALL_START_REQUEST event.
    There is a request to make an outbound call. This event can occur on
    the caller after using the "Call X" voice command on the Assistant.

    async def call_start_request_handler(workflow:relay.workflow.Workflow, destination_uri:str)
    """
    self.type_handlers['wf_api_call_start_request_event'] = func

on_incident(func)

A decorator for a handler method for the INCIDENT event (an incident has been created).

async def incident_handler(workflow:relay.workflow.Workflow, type:str, incident_id:str, reason:str)

Source code in relay/workflow.py
587
588
589
590
591
592
593
def on_incident(self, func):
    """
    A decorator for a handler method for the INCIDENT event (an incident has been created).

    async def incident_handler(workflow:relay.workflow.Workflow, type:str, incident_id:str, reason:str)
    """
    self.type_handlers['wf_api_incident_event'] = func

on_interaction_lifecycle(func)

A decorator for a handler method for the INTERACTION_LIFECYCLE event (an interaction is starting, resuming, or ending).

async def interaction_lifecycle_handler(workflow:relay.workflow.Workflow, itype:str, source_uri:str, reason:str)

Source code in relay/workflow.py
595
596
597
598
599
600
601
602
def on_interaction_lifecycle(self, func):
    """
    A decorator for a handler method for the INTERACTION_LIFECYCLE event (an interaction
    is starting, resuming, or ending).

    async def interaction_lifecycle_handler(workflow:relay.workflow.Workflow, itype:str, source_uri:str, reason:str)
    """
    self.type_handlers['wf_api_interaction_lifecycle_event'] = func

on_notification(_func=None, *, name='*', event='*')

A decorator for a handler method for the NOTIFICATION event (a broadcast or alert was sent).

async def button_handler(workflow:relay.workflow.Workflow, button:str, taps:str, source_uri:str)

Source code in relay/workflow.py
431
432
433
434
435
436
437
438
439
440
441
442
443
444
def on_notification(self, _func=None, *, name='*', event='*'):
    """
    A decorator for a handler method for the NOTIFICATION event (a broadcast or alert was sent).

    async def button_handler(workflow:relay.workflow.Workflow, button:str, taps:str, source_uri:str)
    """
    def on_notification_decorator(func):
        self.type_handlers['wf_api_notification_event', name, event] = func

    if _func:
        return on_notification_decorator(_func)

    else:
        return on_notification_decorator

on_play_inbox_message(func)

A decorator for a handler method for the PLAY_INBOX_MESSAGE event (a missed message is being played).

async def play_inbox_message_handler(workflow:relay.workflow.Workflow, action:str)

Source code in relay/workflow.py
482
483
484
485
486
487
488
489
def on_play_inbox_message(self, func):
    """
    A decorator for a handler method for the PLAY_INBOX_MESSAGE event (a missed message
    is being played).

    async def play_inbox_message_handler(workflow:relay.workflow.Workflow, action:str)
    """
    self.type_handlers['wf_api_play_inbox_message_event'] = func

on_progress(func)

A decorator for a handler method for the PROGRESS event (a long running action is being performed across a large number of devices, may get called multiple times).

async def progress_handler(workflow:relay.workflow.Workflow)

Source code in relay/workflow.py
473
474
475
476
477
478
479
480
def on_progress(self, func):
    """
    A decorator for a handler method for the PROGRESS event (a long running action is being
    performed across a large number of devices, may get called multiple times).

    async def progress_handler(workflow:relay.workflow.Workflow)
    """
    self.type_handlers['wf_api_progress_event'] = func

on_prompt(func)

A decorator for a handler method for the PROMPT event (text-to-speech is streaming in).

async def prompt_handler(workflow:relay.workflow.Workflow, source_uri:str, prompt_type:str)

Source code in relay/workflow.py
408
409
410
411
412
413
414
def on_prompt(self, func):
    """
    A decorator for a handler method for the PROMPT event (text-to-speech is streaming in).

    async def prompt_handler(workflow:relay.workflow.Workflow, source_uri:str, prompt_type:str)
    """
    self.type_handlers['wf_api_prompt_event'] = func

on_resume(func)

A decorator for a handler method for the RESUME event (TBD).

async def resume_handler(workflow:relay.workflow.Workflow, trigger:dict)

Source code in relay/workflow.py
604
605
606
607
608
609
610
def on_resume(self, func):
    """
    A decorator for a handler method for the RESUME event (TBD).

    async def resume_handler(workflow:relay.workflow.Workflow, trigger:dict)
    """
    self.type_handlers['wf_api_resume_event'] = func

on_sms(func)

A decorator for a handler method for the SMS event (TBD).

async def sms_handler(workflow:relay.workflow.Workflow, id:str, event:dict)

Source code in relay/workflow.py
579
580
581
582
583
584
585
def on_sms(self, func):
    """
    A decorator for a handler method for the SMS event (TBD).

    async def sms_handler(workflow:relay.workflow.Workflow, id:str, event:dict)
    """
    self.type_handlers['wf_api_sms_event'] = func

on_speech(func)

A decorator for a handler method for the SPEECH event (the listen() function is running).

async def speech_handler(workflow:relay.workflow.Workflow, transcribed_text:str, audio:bytes, language:str, request_id:str, source_uri:str)

Source code in relay/workflow.py
464
465
466
467
468
469
470
471
def on_speech(self, func):
    """
    A decorator for a handler method for the SPEECH event (the listen() function is running).

    async def speech_handler(workflow:relay.workflow.Workflow, transcribed_text:str, audio:bytes, language:str,
                             request_id:str, source_uri:str)
    """
    self.type_handlers['wf_api_speech_event'] = func

on_start(func)

A decorator for a handler method for the START event (workflow is starting).

async def start_handler(workflow:relay.workflow.Workflow, trigger:dict)

Source code in relay/workflow.py
392
393
394
395
396
397
398
def on_start(self, func):
    """
    A decorator for a handler method for the START event (workflow is starting).

    async def start_handler(workflow:relay.workflow.Workflow, trigger:dict)
    """
    self.type_handlers['wf_api_start_event'] = func

on_stop(func)

A decorator for a handler method for the STOP event (workflow is stopping).

async def stop_handler(workflow:relay.workflow.Workflow, reason:str)

Source code in relay/workflow.py
400
401
402
403
404
405
406
def on_stop(self, func):
    """
    A decorator for a handler method for the STOP event (workflow is stopping).

    async def stop_handler(workflow:relay.workflow.Workflow, reason:str)
    """
    self.type_handlers['wf_api_stop_event'] = func

on_timer(func)

A decorator for a handler method for the TIMER event (the unnamed timer fired).

async def timer_handler(workflow:relay.workflow.Workflow)

Source code in relay/workflow.py
446
447
448
449
450
451
452
453
def on_timer(self, func):
    # unnamed timer
    """
    A decorator for a handler method for the TIMER event (the unnamed timer fired).

    async def timer_handler(workflow:relay.workflow.Workflow)
    """
    self.type_handlers['wf_api_timer_event'] = func

on_timer_fired(func)

A decorator for a handler method for the TIMER_FIRED event (a named timer fired).

async def timer_fired_handler(workflow:relay.workflow.Workflow, timer_name:str)

Source code in relay/workflow.py
455
456
457
458
459
460
461
462
def on_timer_fired(self, func):
    # named timer
    """
    A decorator for a handler method for the TIMER_FIRED event (a named timer fired).

    async def timer_fired_handler(workflow:relay.workflow.Workflow, timer_name:str)
    """
    self.type_handlers['wf_api_timer_fired_event'] = func

device_id(gid)

Creates a URN from a device ID.

Parameters:

Name Type Description Default
gid str

the ID of the device.

required

Returns:

Name Type Description
str

the newly constructed URN.

Source code in relay/workflow.py
250
251
252
253
254
255
256
257
258
259
def device_id(gid: str):
    """Creates a URN from a device ID.

    Args:
        gid (str): the ID of the device.

    Returns:
        str: the newly constructed URN.
    """
    return _construct(DEVICE, ID, urllib.parse.quote(gid))

device_name(name)

Creates a URN from a device name.

Parameters:

Name Type Description Default
name str

the name of the device.

required

Returns:

Name Type Description
str

the newly constructed URN.

Source code in relay/workflow.py
212
213
214
215
216
217
218
219
220
221
def device_name(name: str):
    """Creates a URN from a device name.

    Args:
        name (str): the name of the device.

    Returns:
        str: the newly constructed URN.
    """
    return _construct(DEVICE, NAME, urllib.parse.quote(name))

fetch_device(access_token, refresh_token, client_id, subscriber_id, user_id)

A convenience method for getting all the details of a device.

This will return quite a bit of data regarding device configuration and state. The result, if the query was successful, should have a large JSON dictionary.

Parameters:

Name Type Description Default
access_token(str)

the current access token. Can be a placeholder value

required
refresh_token(str)

the permanent refresh_token that can be used to

required
client_id(str)

the auth_sdk_id as returned from "relay env".

required
subscriber_id(str)

the subcriber UUID as returned from "relay whoami".

required
user_id(str)

the IMEI of the target device, such as 990007560023456.

required
Source code in relay/workflow.py
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
def fetch_device(access_token: str, refresh_token: str, client_id: str, subscriber_id: str, user_id: str):
    """A convenience method for getting all the details of a device.

    This will return quite a bit of data regarding device configuration and
    state. The result, if the query was successful, should have a large JSON
    dictionary.

    Args:
        access_token(str): the current access token. Can be a placeholder value
        and this method will generate a new one and return it. If the
        original value of the access token passed in here has expired,
        this method will also generate a new one and return it.

        refresh_token(str): the permanent refresh_token that can be used to
        obtain a new access_token. The caller should treat the refresh
        token as very sensitive data, and secure it appropriately.

        client_id(str): the auth_sdk_id as returned from "relay env".

        subscriber_id(str): the subcriber UUID as returned from "relay whoami".

        user_id(str): the IMEI of the target device, such as 990007560023456.
    """
    url = f'https://{SERVER_HOSTNAME}/relaypro/api/v1/device/{user_id}'
    headers = {
        'Authorization': f'Bearer {access_token}',
        'User-Agent': VERSION
    }
    query_params = {'subscriber_id': subscriber_id}
    response = requests.get(url, headers=headers, params=query_params, timeout=10.0)
    if response.status_code == 401:
        logger.debug(f'got 401 on get, trying to get new access token')
        access_token = _update_access_token(refresh_token, client_id)
        headers['Authorization'] = f'Bearer {access_token}'
        response = requests.post(url, headers=headers, params=query_params, timeout=10.0)
    logger.debug(f'device_info status code={response.status_code}')
    return response, access_token

group_id(gid)

Creates a URN from a group ID.

Parameters:

Name Type Description Default
gid str

the ID of the group.

required

Returns:

Name Type Description
str

the newly constructed URN.

Source code in relay/workflow.py
188
189
190
191
192
193
194
195
196
197
def group_id(gid: str):
    """Creates a URN from a group ID.

    Args:
        gid (str): the ID of the group.

    Returns:
        str: the newly constructed URN.
    """
    return _construct(GROUP, ID, urllib.parse.quote(gid))

group_member(group, device)

Creates a URN for a group member.

Parameters:

Name Type Description Default
group str

the name of the group that the device belongs to.

required
device str

the device ID or name.

required

Returns:

Name Type Description
str

the newly constructed URN.

Source code in relay/workflow.py
236
237
238
239
240
241
242
243
244
245
246
247
def group_member(group: str, device: str):
    """Creates a URN for a group member.

    Args:
        group (str): the name of the group that the device belongs to.
        device (str): the device ID or name.

    Returns:
        str: the newly constructed URN.
    """
    return f'{SCHEME}:{ROOT}:{NAME}:{GROUP}:{urllib.parse.quote(group)}{DEVICE_PATTERN}' + urllib.parse.quote(
        f'{SCHEME}:{ROOT}:{NAME}:{DEVICE}:{device}')

group_name(name)

Creates a URN from a group name.

Parameters:

Name Type Description Default
name str

the name of the group.

required

Returns:

Name Type Description
str

the newly constructed URN.

Source code in relay/workflow.py
200
201
202
203
204
205
206
207
208
209
def group_name(name: str):
    """Creates a URN from a group name.

    Args:
        name (str): the name of the group.

    Returns:
        str: the newly constructed URN.
    """
    return _construct(GROUP, NAME, urllib.parse.quote(name))

interaction_name(name)

Creates a URN from an interaction name.

Parameters:

Name Type Description Default
name str

the name of the interaction

required

Returns:

Name Type Description
str str

the newly constructed URN.

Source code in relay/workflow.py
224
225
226
227
228
229
230
231
232
233
def interaction_name(name: str) -> str:
    """Creates a URN from an interaction name.

    Args:
        name (str): the name of the interaction

    Returns:
        str: the newly constructed URN.
    """
    return _construct(INTERACTION, NAME, urllib.parse.quote(name))

is_interaction_uri(uri)

Checks if the URN is for an interaction.

Parameters:

Name Type Description Default
uri str

the device URN.

required

Returns:

Name Type Description
bool

true if the URN is an interaction URN, false otherwise.

Source code in relay/workflow.py
351
352
353
354
355
356
357
358
359
360
361
362
def is_interaction_uri(uri: str):
    """Checks if the URN is for an interaction.

    Args:
        uri (str): the device URN.

    Returns:
        bool: true if the URN is an interaction URN, false otherwise.
    """
    if INTERACTION_URI_NAME in uri or INTERACTION_URI_ID in uri:
        return True
    return False

is_relay_uri(uri)

Checks if the URN is a Relay URN.

Parameters:

Name Type Description Default
uri str

the device, group, or interaction URN.

required

Returns:

Name Type Description
bool

true if the URN is a Relay URN, false otherwise.

Source code in relay/workflow.py
365
366
367
368
369
370
371
372
373
374
375
376
def is_relay_uri(uri: str):
    """Checks if the URN is a Relay URN.

    Args:
        uri (str): the device, group, or interaction URN.

    Returns:
        bool: true if the URN is a Relay URN, false otherwise.
    """
    if uri.startswith(f'{SCHEME}:{ROOT}'):
        return True
    return False

parse_device_id(uri)

Parses out a device ID from a device or interaction URN.

Parameters:

Name Type Description Default
uri str

the device or interaction URN that you would like to extract the device ID from.

required

Returns:

Name Type Description
str

the device ID.

Source code in relay/workflow.py
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
def parse_device_id(uri: str):
    """Parses out a device ID from a device or interaction URN.

    Args:
        uri (str): the device or interaction URN that you would like to extract the device ID from.

    Returns:
        str: the device ID.
    """
    uri = urllib.parse.unquote(uri)
    if not is_interaction_uri(uri):
        scheme, root, id_type, resource_type, gid = uri.split(':')
        if id_type == ID:
            return gid
    elif is_interaction_uri(uri):
        scheme, root, id_type, resource_type, i_id, i_root, i_id_type, i_resource_type, gid = uri.split(':')
        if id_type == ID and i_id_type == ID:
            return gid
    logger.error('invalid device urn')

parse_device_name(uri)

Parses out a device name from a device or interaction URN.

Parameters:

Name Type Description Default
uri str

the device or interaction URN that you would like to extract the device name from.

required

Returns:

Name Type Description
str

the device name.

Source code in relay/workflow.py
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
def parse_device_name(uri: str):
    """Parses out a device name from a device or interaction URN.

    Args:
        uri (str): the device or interaction URN that you would like to extract the device name from.

    Returns:
        str: the device name.
    """
    uri = urllib.parse.unquote(uri)
    if not is_interaction_uri(uri):
        scheme, root, id_type, resource_type, name = uri.split(':')
        if id_type == NAME:
            return name
    elif is_interaction_uri(uri):
        scheme, root, id_type, resource_type, i_name, i_root, i_id_type, i_resource_type, name = uri.split(':')
        if id_type == NAME and i_id_type == NAME:
            return name
    logger.error('invalid device urn')

parse_group_id(uri)

Parses out a group ID from a group URN.

Parameters:

Name Type Description Default
uri str

the URN that you would like to extract the group ID from.

required

Returns:

Name Type Description
str

the group ID.

Source code in relay/workflow.py
277
278
279
280
281
282
283
284
285
286
287
288
289
def parse_group_id(uri: str):
    """Parses out a group ID from a group URN. 

    Args:
        uri (str): the URN that you would like to extract the group ID from.

    Returns:
        str: the group ID.
    """
    scheme, root, id_type, resource_type, gid = urllib.parse.unquote(uri).split(':')
    if id_type == ID and resource_type == GROUP:
        return gid
    logger.error('invalid group urn')

parse_group_name(uri)

Parses out a group name from a group URN.

Parameters:

Name Type Description Default
uri str

the URN that you would like to extract the group name from.

required

Returns:

Name Type Description
str

the group name.

Source code in relay/workflow.py
262
263
264
265
266
267
268
269
270
271
272
273
274
def parse_group_name(uri: str):
    """Parses out a group name from a group URN.

    Args:
        uri (str): the URN that you would like to extract the group name from.

    Returns:
        str: the group name.
    """
    scheme, root, id_type, resource_type, name = urllib.parse.unquote(uri).split(':')
    if id_type == NAME and resource_type == GROUP:
        return name
    logger.error('invalid group urn')

parse_interaction(uri)

Parses out the name of an interaction from an interaction URN.

Parameters:

Name Type Description Default
uri str

the interaction URN that you would like to parse the interaction from.

required

Returns:

Name Type Description
str

the name of an interaction.

Source code in relay/workflow.py
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
def parse_interaction(uri: str):
    """Parses out the name of an interaction from an interaction URN.

    Args:
        uri (str): the interaction URN that you would like to parse the interaction from.

    Returns:
        str: the name of an interaction.
    """
    uri = urllib.parse.unquote(uri)
    if is_interaction_uri(uri):
        scheme, root, id_type, resource_type, i_name, i_root, i_id_type, i_resource_type, name = uri.split(':')
        interaction_name, discard = i_name.split('?')
        return interaction_name
    logger.error('not an interaction urn')

trigger_workflow(access_token, refresh_token, client_id, workflow_id, subscriber_id, user_id, targets, action_args=None)

A convenience method for sending an HTTP trigger to the Relay server.

This generally would be used in a third-party system to start a Relay workflow via an HTTP trigger and optionally pass data to it with action_args. Under the covers, this uses Python's "request" library for using the https protocol.

If the access_token has expired and the request gets a 401 response, a new access_token will be automatically generated via the refresh_token, and the request will be resubmitted with the new access_token. Otherwise the refresh token won't be used.

This method will return a tuple of (requests.Response, access_token) where you can inspect the http response, and get the updated access_token if it was updated (otherwise the original access_token will be returned).

Parameters:

Name Type Description Default
access_token(str)

the current access token. Can be a placeholder value

required
refresh_token(str)

the permanent refresh_token that can be used to

required
client_id(str)

the auth_sdk_id as returned from "relay env".

required
workflow_id(str)

the workflow_id as returned from "relay workflow list".

required
subscriber_id(str)

the subcriber UUID as returned from "relay whoami".

required
user_id(str)

the IMEI of the target device, such as 990007560023456.

required
targets List[str]

the device targets that the workflow should be considered as

required
action_args optional

a dict of any key/value arguments you want

None
Source code in relay/workflow.py
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
def trigger_workflow(access_token: str, refresh_token: str, client_id: str, workflow_id: str, subscriber_id: str,
                     user_id: str, targets: List[str], action_args: dict = None):
    """A convenience method for sending an HTTP trigger to the Relay server.

    This generally would be used in a third-party system to start a Relay
    workflow via an HTTP trigger and optionally pass data to it with
    action_args.  Under the covers, this uses Python's "request" library
    for using the https protocol.

    If the access_token has expired and the request gets a 401 response,
    a new access_token will be automatically generated via the refresh_token,
    and the request will be resubmitted with the new access_token. Otherwise
    the refresh token won't be used.

    This method will return a tuple of (requests.Response, access_token)
    where you can inspect the http response, and get the updated access_token
    if it was updated (otherwise the original access_token will be returned).

    Args:
        access_token(str): the current access token. Can be a placeholder value
        and this method will generate a new one and return it. If the
        original value of the access token passed in here has expired,
        this method will also generate a new one and return it.

        refresh_token(str): the permanent refresh_token that can be used to
        obtain a new access_token. The caller should treat the refresh
        token as very sensitive data, and secure it appropriately.

        client_id(str): the auth_sdk_id as returned from "relay env".

        workflow_id(str): the workflow_id as returned from "relay workflow list".
        Usually starts with "wf_".

        subscriber_id(str): the subcriber UUID as returned from "relay whoami".

        user_id(str): the IMEI of the target device, such as 990007560023456.

        targets: the device targets that the workflow should be considered as
        having been triggered from.

        action_args (optional): a dict of any key/value arguments you want
        to pass in to the workflow that gets started by this trigger.
    """

    url = f'https://{SERVER_HOSTNAME}/ibot/workflow/{workflow_id}'
    headers = {
        'Authorization': f'Bearer {access_token}',
        'User-Agent': VERSION
    }
    query_params = {
        'subscriber_id': subscriber_id,
        'user_id': user_id
    }
    payload = {"action": "invoke"}
    if action_args:
        payload['action_args'] = action_args
    if targets:
        payload['target_device_ids'] = f'{targets}'
    response = requests.post(url, headers=headers, params=query_params, json=payload, timeout=10.0)
    # check if access token expired, and if so get a new one from the refresh_token, and resubmit
    if response.status_code == 401:
        logger.debug(f'got 401 on workflow trigger, trying to get new access token')
        access_token = _update_access_token(refresh_token, client_id)
        headers['Authorization'] = f'Bearer {access_token}'
        response = requests.post(url, headers=headers, params=query_params, json=payload, timeout=10.0)
    logger.debug(f'workflow trigger status code={response.status_code}')
    return response, access_token