def SendNotification(EMail, PList, dt1, strlink): config = CipherConfig.load('parameters.yaml') Bus_settings = config['Notification']['AzureMessageBus'] MessageBody_settings = config['Notification']['MessageBody'] if Bus_settings['SharedAccessKeyValue'] != None and \ Bus_settings['ServiceNamespace'] != None: Address_list = [EMail] ServiceNameSpace = Bus_settings['ServiceNamespace'] sbs = ServiceBusService(ServiceNameSpace, shared_access_key_name = Bus_settings['SharedAccessKeyName'], shared_access_key_value = Bus_settings['SharedAccessKeyValue'] ) message = { 'EmailType' : 0, 'Subject' : 'Status on ' + dt1, 'FromAddress' : MessageBody_settings['FromAddress'], 'ReplyTo' : '', 'FromName' : MessageBody_settings['FromName'] + ' ' + CipherConfig.Country + '-' + CipherConfig.Environment, 'ToAddresses' : Address_list, 'Message' : 'Processes completed with Alert(s) in the last hour\n\n' + PList + strlink, 'CcAddresses': [], 'BccAddresses': [], 'Metadata': { "TaskName": "This is a test message"} } json = CipherData.toJson(message) msg = Message(json) sbs.send_queue_message(Bus_settings['QueueName'], msg) return
def cleanup_queue(servicebus_config, queue_name): from azure.servicebus.control_client import ServiceBusService client = ServiceBusService( service_namespace=servicebus_config['hostname'], shared_access_key_name=servicebus_config['key_name'], shared_access_key_value=servicebus_config['access_key']) client.delete_queue(queue_name)
def __init__(self, namespace, SAS_name, SAS_value): self.topic_vel = 'cmd_vel' self.topic_stop = 'motor_stop' self.namespace = namespace self.SAS_name = SAS_name self.SAS_value = SAS_value self.topic_options = Topic() self.topic_options.max_size_in_megabytes = '10' #### Try : '1024' self.topic_options.default_message_time_to_live = 'PT5S' self.bus_service = ServiceBusService( service_namespace=self.namespace, shared_access_key_name=self.SAS_name, shared_access_key_value=self.SAS_value) self.cmd_values = { 'N': "100 100", 'S': '-100 -100', 'W': '-50 50', 'E': '50 -50' } self.bot_list = []
def __init__(self): rospy.init_node("queueRead", anonymous=True) self.nodename = rospy.get_name() rospy.loginfo("%s started" % self.nodename) ### initialize variables self.topic_vel = 'cmd_vel' self.topic_stop = 'motor_stop' ### get parameters #### self.SAS_name = (rospy.get_param("~SAS_NAME")) self.SAS_value = (rospy.get_param("~SAS_VALUE")) self.namespace = (rospy.get_param("~TOPIC_NAMESPACE")) self.bot_id = (rospy.get_param("~BOT_ID")) self.bus_service = ServiceBusService( service_namespace=self.namespace, shared_access_key_name=self.SAS_name, shared_access_key_value=self.SAS_value) self.bus_service.create_subscription((self.topic_vel + self.bot_id), self.bot_id) self.bus_service.create_subscription((self.topic_stop + self.bot_id), self.bot_id) ### setup ### self.pub_lmotor = rospy.Publisher('lmotor_cmd', Float32, queue_size=10) self.pub_rmotor = rospy.Publisher('rmotor_cmd', Float32, queue_size=10) self.pub_motor_stop = rospy.Publisher('motorStop', Int16, queue_size=10)
class _QueueTest(_ServiceTest): queue_name = "perfstress-" + str(uuid.uuid4()) queue_client = None async_queue_client = None def __init__(self, arguments): super().__init__(arguments) connection_string = self.get_from_env( "AZURE_SERVICEBUS_CONNECTION_STRING") connection_props = parse_connection_string(connection_string) self.mgmt_client = ServiceBusService( service_namespace=connection_props['namespace'], shared_access_key_name=connection_props['shared_access_key_name'], shared_access_key_value=connection_props['shared_access_key']) async def global_setup(self): await super().global_setup() queue = Queue(max_size_in_megabytes=MAX_QUEUE_SIZE) self.mgmt_client.create_queue(self.queue_name, queue=queue) async def setup(self): await super().setup() # In T1, these operations check for the existance of the queue # so must be created during setup, rather than in the constructor. self.queue_client = self.service_client.get_queue(self.queue_name) self.async_queue_client = self.async_service_client.get_queue( self.queue_name) async def global_cleanup(self): self.mgmt_client.delete_queue(self.queue_name) await super().global_cleanup()
def __init__(self, arguments): super().__init__(arguments) connection_string = self.get_from_env( "AZURE_SERVICEBUS_CONNECTION_STRING") connection_props = parse_connection_string(connection_string) self.mgmt_client = ServiceBusService( service_namespace=connection_props['namespace'], shared_access_key_name=connection_props['shared_access_key_name'], shared_access_key_value=connection_props['shared_access_key'])
def create_standard_queue(sb_config): from azure.servicebus.control_client import ServiceBusService, Queue queue_name = str(uuid.uuid4()) queue_value = Queue(lock_duration='PT30S', requires_duplicate_detection=False, dead_lettering_on_message_expiration=True, requires_session=False) client = ServiceBusService(service_namespace=sb_config['hostname'], shared_access_key_name=sb_config['key_name'], shared_access_key_value=sb_config['access_key']) if client.create_queue(queue_name, queue=queue_value, fail_on_exist=True): return queue_name raise ValueError("Queue creation failed.")
def create_standard_queue(sb_config): from azure.servicebus.control_client import ServiceBusService, Queue queue_name = str(uuid.uuid4()) queue_value = Queue( lock_duration='PT30S', requires_duplicate_detection=False, dead_lettering_on_message_expiration=True, requires_session=False) client = ServiceBusService( service_namespace=sb_config['hostname'], shared_access_key_name=sb_config['key_name'], shared_access_key_value=sb_config['access_key']) if client.create_queue(queue_name, queue=queue_value, fail_on_exist=True): return queue_name raise ValueError("Queue creation failed.")
class AbcServiceBus: def __init__(self): self._namespace = '_namespace' self._topic_name = '_topic_name' self._service_bus = AzureServiceBus() def send_insert_notification(self, record_id): message_json = {'ids': [record_id]} self._service_bus.send_topic_message( namespace_name=self._namespace, topic_name=self._topic_name, message_json=message_json ) return True
def sendWindBeringData(msg): try: bus_service = ServiceBusService( service_namespace='kanmessagebus', shared_access_key_name='client', shared_access_key_value='dNj7Z+fOvV49WNETUL0Guj3KVVdZude/fqzmj95GHKo=') mesage = Message(msg) bus_service.send_topic_message("wind_bearing", mesage) except Exception as e: if hasattr(e, 'message'): print(e.message) else: print(e)
def sendWeatherData(msg): try: bus_service = ServiceBusService( service_namespace='kanmessagebus', shared_access_key_name='weather', shared_access_key_value='tweaVJ8+++wUl3f568/E9vgAH21FK2SpcPBXn5F8Kts=') mesage = Message(msg) bus_service.send_topic_message("weather_station", mesage) except Exception as e: if hasattr(e, 'message'): print(e.message) else: print(e)
def cleanup_topic(servicebus_config, topic_name, client=None): from azure.servicebus.control_client import ServiceBusService client = client or ServiceBusService( service_namespace=servicebus_config['hostname'], shared_access_key_name=servicebus_config['key_name'], shared_access_key_value=servicebus_config['access_key']) client.delete_topic(topic_name)
def cleanup_eventhub(eventhub_config, hub_name, client=None): from azure.servicebus.control_client import ServiceBusService client = client or ServiceBusService( service_namespace=eventhub_config['namespace'], shared_access_key_name=eventhub_config['key_name'], shared_access_key_value=eventhub_config['access_key']) client.delete_event_hub(hub_name)
def __init__(self): ### initialize variables self.topic_vel = os.environ["TOPIC_VELOCITY"] self.topic_stop = os.environ["TOPIC_STOP"] ### get parameters #### self.SAS_name = os.environ["SAS_NAME"] self.SAS_value = os.environ["SAS_VALUE"] self.namespace = os.environ["TOPIC_NAMESPACE"] self.bot_id = os.environ["BOT_ID"] self.LGPWM = os.getenv('LGPWM', int(12)) self.LGIN1 = os.getenv('LGIN1', int(5)) self.LGIN2 = os.getenv('LGIN2', int(6)) self.RGPWM = os.getenv('RGPWM', int(13)) self.RGIN1 = os.getenv('RGIN1', int(16)) self.RGIN2 = os.getenv('RGIN2', int(26)) self.bus_service = ServiceBusService( service_namespace=self.namespace, shared_access_key_name=self.SAS_name, shared_access_key_value=self.SAS_value) self.bus_service.create_subscription((self.topic_vel + self.bot_id), self.bot_id) self.bus_service.create_subscription((self.topic_stop + self.bot_id), self.bot_id) ### setup ### GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(self.LGPWM, GPIO.OUT) GPIO.setup(self.LGIN1, GPIO.OUT) GPIO.setup(self.LGIN2, GPIO.OUT) self.Lpwm = GPIO.PWM(self.LGPWM, 1000) self.Lpwm.start(0) GPIO.setup(self.RGPWM, GPIO.OUT) GPIO.setup(self.RGIN1, GPIO.OUT) GPIO.setup(self.RGIN2, GPIO.OUT) self.Rpwm = GPIO.PWM(self.RGPWM, 1000) self.Rpwm.start(0)
def __init__(self, address, name, shared_access_key_name=None, shared_access_key_value=None, debug=False, **kwargs): """Construct a new Client to interact with the named Service Bus entity. :param address: The full URI of the Service Bus namespace. This can optionally include URL-encoded access name and key. :type address: str :param name: The name of the entity to which the Client will connect. :type name: str :param shared_access_key_name: The name of the shared access policy. This must be supplied if not encoded into the address. :type shared_access_key_name: str :param shared_access_key_value: The shared access key. This must be supplied if not encoded into the address. :type shared_access_key_value: str :param debug: Whether to output network trace logs to the logger. Default is `False`. :type debug: bool """ self.container_id = "servicebus.pysdk-" + str(uuid.uuid4())[:8] self.address = urlparse(address) self.name = name self.debug = debug self.encoding = 'UTF-8' self.connection = None self.entity = kwargs.get('validated_entity') self.properties = dict(self.entity) if self.entity else {} self.requires_session = self.properties.get('requires_session', False) namespace, _, host_base = self.address.hostname.partition('.') url_username = unquote_plus( self.address.username) if self.address.username else None shared_access_key_name = shared_access_key_name or url_username url_password = unquote_plus( self.address.password) if self.address.password else None shared_access_key_value = shared_access_key_value or url_password if not shared_access_key_name or not shared_access_key_value: raise ValueError("Missing shared access key name and/or value.") self.entity_uri = "amqps://{}{}".format(self.address.hostname, self.address.path) self.auth_config = { 'uri': "sb://{}{}".format(self.address.hostname, self.address.path), 'key_name': shared_access_key_name, 'shared_access_key': shared_access_key_value } self.auth_config['transport_type'] = kwargs.get( 'transport_type') or TransportType.Amqp self.mgmt_client = kwargs.get('mgmt_client') or ServiceBusService( service_namespace=namespace, shared_access_key_name=shared_access_key_name, shared_access_key_value=shared_access_key_value, host_base="." + host_base)
def create_stress_eventhub(stress_config, eventhub_name): hub_value = EventHub( message_retention_in_days=stress_config["BASIC_CONFIG"] ["message_retention_in_days"], partition_count=stress_config["BASIC_CONFIG"] ["partition_cnt_to_create"]) if stress_config["CREDENTIALS"]["EVENT_HUB_CONN_STR"]: _, namespace, shared_access_key_name, shared_access_key, _ = parse_eventhub_conn_str( stress_config["CREDENTIALS"]["EVENT_HUB_CONN_STR"]) client = ServiceBusService( service_namespace=namespace, shared_access_key_name=shared_access_key_name, shared_access_key_value=shared_access_key) else: client = ServiceBusService( service_namespace=stress_config["CREDENTIALS"] ["EVENT_HUB_NAMESPACE"], shared_access_key_name=stress_config['CREDENTIALS'] ["EVENT_HUB_SAS_POLICY"], shared_access_key_value=stress_config['CREDENTIALS'] ["EVENT_HUB_SAS_KEY"]) client.delete_event_hub(eventhub_name) if client.create_event_hub(eventhub_name, hub=hub_value, fail_on_exist=True): return eventhub_name raise ValueError("EventHub creation failed.")
def __init__(self, service_namespace=None, host_base=SERVICE_BUS_HOST_BASE, shared_access_key_name=None, shared_access_key_value=None, transport_type=TransportType.Amqp, http_request_timeout=DEFAULT_HTTP_TIMEOUT, http_request_session=None, debug=False): self.service_namespace = service_namespace self.host_base = host_base self.shared_access_key_name = shared_access_key_name self.shared_access_key_value = shared_access_key_value self.transport_type = transport_type self.debug = debug self.mgmt_client = ServiceBusService( service_namespace=service_namespace, host_base=host_base, shared_access_key_name=shared_access_key_name, shared_access_key_value=shared_access_key_value, timeout=http_request_timeout, request_session=http_request_session)
def create_standard_topic(servicebus_config, client=None): from azure.servicebus.control_client import ServiceBusService, Topic topic_name = str(uuid.uuid4()) topic_value = Topic(requires_duplicate_detection=False) client = client or ServiceBusService( service_namespace=servicebus_config['hostname'], shared_access_key_name=servicebus_config['key_name'], shared_access_key_value=servicebus_config['access_key']) if client.create_topic(topic_name, topic=topic_value, fail_on_exist=True): return topic_name raise ValueError("Queue creation failed.")
def create_eventhub(eventhub_config, client=None): from azure.servicebus.control_client import ServiceBusService, EventHub hub_name = str(uuid.uuid4()) hub_value = EventHub(partition_count=2) client = client or ServiceBusService( service_namespace=eventhub_config['namespace'], shared_access_key_name=eventhub_config['key_name'], shared_access_key_value=eventhub_config['access_key']) if client.create_event_hub(hub_name, hub=hub_value, fail_on_exist=True): return hub_name raise ValueError("EventHub creation failed.")
def standard_topic(live_servicebus_config): # pylint: disable=redefined-outer-name from azure.servicebus.control_client import ServiceBusService client = ServiceBusService( service_namespace=live_servicebus_config['hostname'], shared_access_key_name=live_servicebus_config['key_name'], shared_access_key_value=live_servicebus_config['access_key']) try: topic_name = create_standard_topic(live_servicebus_config, client=client) yield topic_name finally: cleanup_topic(live_servicebus_config, topic_name, client=client)
def duplicate_queue(live_servicebus_config): # pylint: disable=redefined-outer-name from azure.servicebus.control_client import ServiceBusService client = ServiceBusService( service_namespace=live_servicebus_config['hostname'], shared_access_key_name=live_servicebus_config['key_name'], shared_access_key_value=live_servicebus_config['access_key']) try: queue_name = create_duplicate_queue(live_servicebus_config, client=client) yield queue_name finally: cleanup_queue(live_servicebus_config, queue_name, client=client)
def setUp(self): super(ServiceBusEventHubTest, self).setUp() self.sbs = ServiceBusService( self.settings.EVENTHUB_NAME, shared_access_key_name=self.settings.EVENTHUB_SAS_KEY_NAME, shared_access_key_value=self.settings.EVENTHUB_SAS_KEY_VALUE, request_session=Session(), ) self._set_service_options(self.sbs, self.settings) self.event_hub_name = self.get_resource_name('uthub')
def live_eventhub(live_eventhub_config): # pylint: disable=redefined-outer-name from azure.servicebus.control_client import ServiceBusService client = ServiceBusService( service_namespace=live_eventhub_config['namespace'], shared_access_key_name=live_eventhub_config['key_name'], shared_access_key_value=live_eventhub_config['access_key']) try: hub_name = create_eventhub(live_eventhub_config, client=client) print("Created EventHub {}".format(hub_name)) live_eventhub_config['event_hub'] = hub_name yield live_eventhub_config finally: cleanup_eventhub(live_eventhub_config, hub_name, client=client) print("Deleted EventHub {}".format(hub_name))
def process_request(queue_name): """ Endpoint to publish messages to Azure service bus :param queue_name: name of queue to publish messages to :return: """ input_data = request.get_json() bus_service = ServiceBusService( service_namespace=SERVICE_NAMESPACE, shared_access_key_name=request.headers.get('sas-token-name'), shared_access_key_value=request.headers.get('sas-token')) for index, input_entity in enumerate(input_data): data: str = json.dumps(input_entity[PAYLOAD_KEY] if PAYLOAD_KEY else input_entity).encode("utf-8") msg = Message(data) try: bus_service.send_queue_message(queue_name, msg) logging.info("Entity %s sent successfully", input_entity["_id"]) except Exception as e: logging.error(e) abort(500) return Response()
def create_standard_subscription(servicebus_config, topic_name, client=None): from azure.servicebus.control_client import ServiceBusService, Subscription subscription_name = str(uuid.uuid4()) sub_value = Subscription(dead_lettering_on_message_expiration=True) client = client or ServiceBusService( service_namespace=servicebus_config['hostname'], shared_access_key_name=servicebus_config['key_name'], shared_access_key_value=servicebus_config['access_key']) if client.create_subscription(topic_name, subscription_name, subscription=sub_value, fail_on_exist=True): return (topic_name, subscription_name) raise ValueError("Queue creation failed.")
def connect(): ''' Setup connection to ServiceBus. Set connection in file: ./queue_account.conf or settign the following env vars: SERVICE_BUS_HOSTNAME # e.g. primare-desa-service-bus SERVICE_BUS_SAS_POLICY # eg. RootManageSharedAccessKey SERVICE_BUS_SAS_KEY # e.g. the key available in azure portal under RootManageSharedAccessKey ''' conf = self.get_live_servicebus_config() try: if self.bus_service: self.logger.warning( "ServiceBusService reset to new credentials") self.bus_service = ServiceBusService( service_namespace=conf['service_namespace'], shared_access_key_name=conf['shared_access_key_name'], shared_access_key_value=conf['shared_access_key_value']) except ValueError: self.bus_service = None self.logger.exception("Exception occurred")
def __init__(self, *, service_namespace=None, host_base=SERVICE_BUS_HOST_BASE, shared_access_key_name=None, shared_access_key_value=None, loop=None, http_request_timeout=DEFAULT_HTTP_TIMEOUT, http_request_session=None, debug=False): self.loop = loop or get_running_loop() self.service_namespace = service_namespace self.host_base = host_base self.shared_access_key_name = shared_access_key_name self.shared_access_key_value = shared_access_key_value self.debug = debug self.mgmt_client = ServiceBusService( service_namespace=service_namespace, host_base=host_base, shared_access_key_name=shared_access_key_name, shared_access_key_value=shared_access_key_value, timeout=http_request_timeout, request_session=http_request_session)
class queueRead(): def __init__(self): rospy.init_node("queueRead", anonymous=True) self.nodename = rospy.get_name() rospy.loginfo("%s started" % self.nodename) ### initialize variables self.topic_vel = 'cmd_vel' self.topic_stop = 'motor_stop' ### get parameters #### self.SAS_name = (rospy.get_param("~SAS_NAME")) self.SAS_value = (rospy.get_param("~SAS_VALUE")) self.namespace = (rospy.get_param("~TOPIC_NAMESPACE")) self.bot_id = (rospy.get_param("~BOT_ID")) self.bus_service = ServiceBusService( service_namespace=self.namespace, shared_access_key_name=self.SAS_name, shared_access_key_value=self.SAS_value) self.bus_service.create_subscription((self.topic_vel + self.bot_id), self.bot_id) self.bus_service.create_subscription((self.topic_stop + self.bot_id), self.bot_id) ### setup ### self.pub_lmotor = rospy.Publisher('lmotor_cmd', Float32, queue_size=10) self.pub_rmotor = rospy.Publisher('rmotor_cmd', Float32, queue_size=10) self.pub_motor_stop = rospy.Publisher('motorStop', Int16, queue_size=10) def read(self): while not rospy.is_shutdown(): try: msg = self.bus_service.receive_subscription_message( (self.topic_vel + self.bot_id), self.bot_id, peek_lock=False) if msg.body is not None: res = list(map(float, msg.body.split(' '))) self.pub_lmotor.publish(res[0]) self.pub_lmotor.publish(res[1]) msg = self.bus_service.receive_subscription_message( (self.topic_stop + self.bot_id), self.bot_id, peek_lock=False) if msg.body is not None: self.pub_lmotor.publish(int(msg.body)) except: pass
def __init__(self, service_namespace=None, host_base=SERVICE_BUS_HOST_BASE, shared_access_key_name=None, shared_access_key_value=None, http_request_timeout=DEFAULT_HTTP_TIMEOUT, http_request_session=None, debug=False): self.service_namespace = service_namespace self.host_base = host_base self.shared_access_key_name = shared_access_key_name self.shared_access_key_value = shared_access_key_value self.debug = debug self.mgmt_client = ServiceBusService( service_namespace=service_namespace, host_base=host_base, shared_access_key_name=shared_access_key_name, shared_access_key_value=shared_access_key_value, timeout=http_request_timeout, request_session=http_request_session)
def __init__(self): self._namespace = '_namespace' self._topic_name = '_topic_name' self._service_bus = AzureServiceBus()
class ServiceBusEventHubTest(ServiceBusTestCase): def setUp(self): super(ServiceBusEventHubTest, self).setUp() self.sbs = ServiceBusService( self.settings.EVENTHUB_NAME, shared_access_key_name=self.settings.EVENTHUB_SAS_KEY_NAME, shared_access_key_value=self.settings.EVENTHUB_SAS_KEY_VALUE, request_session=Session(), ) self._set_service_options(self.sbs, self.settings) self.event_hub_name = self.get_resource_name('uthub') def tearDown(self): if not self.is_playback(): try: self.sbs.delete_event_hub(self.event_hub_name) except: pass return super(ServiceBusEventHubTest, self).tearDown() #--Helpers----------------------------------------------------------------- def _create_event_hub(self, hub_name): self.sbs.create_event_hub(hub_name, None, True) #--Test cases for event hubs ---------------------------------------------- @record def test_create_event_hub_no_options(self): # Arrange # Act created = self.sbs.create_event_hub(self.event_hub_name) # Assert self.assertTrue(created) @record def test_create_event_hub_no_options_fail_on_exist(self): # Arrange # Act created = self.sbs.create_event_hub(self.event_hub_name, None, True) # Assert self.assertTrue(created) @record def test_create_event_hub_with_options(self): # Arrange # Act hub = EventHub() hub.message_retention_in_days = 5 hub.status = 'Active' hub.user_metadata = 'hello world' hub.partition_count = 32 created = self.sbs.create_event_hub(self.event_hub_name, hub) # Assert self.assertTrue(created) created_hub = self.sbs.get_event_hub(self.event_hub_name) self.assertEqual(created_hub.name, self.event_hub_name) self.assertEqual(created_hub.message_retention_in_days, hub.message_retention_in_days) self.assertEqual(created_hub.status, hub.status) self.assertEqual(created_hub.partition_count, hub.partition_count) self.assertEqual(created_hub.user_metadata, hub.user_metadata) self.assertEqual(len(created_hub.partition_ids), hub.partition_count) @record def test_create_event_hub_with_authorization(self): # Arrange # Act hub = EventHub() hub.authorization_rules.append( AuthorizationRule( claim_type='SharedAccessKey', claim_value='None', rights=['Manage', 'Send', 'Listen'], key_name='Key1', primary_key='Wli4rewPGuEsLam95nQEwGR+e8b+ynlupZQ7VfjbQnw=', secondary_key='jS+lERPBmbBVGJ5JzIwVRtSGYoFUeunRoADNTjwU3jU=', ) ) created = self.sbs.create_event_hub(self.event_hub_name, hub) # Assert self.assertTrue(created) created_hub = self.sbs.get_event_hub(self.event_hub_name) self.assertEqual(created_hub.name, self.event_hub_name) self.assertEqual(len(created_hub.authorization_rules), 1) self.assertEqual(created_hub.authorization_rules[0].claim_type, hub.authorization_rules[0].claim_type) self.assertEqual(created_hub.authorization_rules[0].claim_value, hub.authorization_rules[0].claim_value) self.assertEqual(created_hub.authorization_rules[0].key_name, hub.authorization_rules[0].key_name) self.assertEqual(created_hub.authorization_rules[0].primary_key, hub.authorization_rules[0].primary_key) self.assertEqual(created_hub.authorization_rules[0].secondary_key, hub.authorization_rules[0].secondary_key) @record def test_update_event_hub(self): # Arrange self._create_event_hub(self.event_hub_name) # Act hub = EventHub(message_retention_in_days=3) result = self.sbs.update_event_hub(self.event_hub_name, hub) # Assert self.assertIsNotNone(result) self.assertEqual(result.name, self.event_hub_name) self.assertEqual(result.message_retention_in_days, hub.message_retention_in_days) @record def test_update_event_hub_with_authorization(self): # Arrange self._create_event_hub(self.event_hub_name) # Act hub = EventHub() hub.authorization_rules.append( AuthorizationRule( claim_type='SharedAccessKey', claim_value='None', rights=['Manage', 'Send', 'Listen'], key_name='Key1', primary_key='Wli4rewPGuEsLam95nQEwGR+e8b+ynlupZQ7VfjbQnw=', secondary_key='jS+lERPBmbBVGJ5JzIwVRtSGYoFUeunRoADNTjwU3jU=', ) ) result = self.sbs.update_event_hub(self.event_hub_name, hub) # Assert self.assertIsNotNone(result) self.assertEqual(result.name, self.event_hub_name) self.assertEqual(len(result.authorization_rules), 1) self.assertEqual(result.authorization_rules[0].claim_type, hub.authorization_rules[0].claim_type) self.assertEqual(result.authorization_rules[0].claim_value, hub.authorization_rules[0].claim_value) self.assertEqual(result.authorization_rules[0].key_name, hub.authorization_rules[0].key_name) self.assertEqual(result.authorization_rules[0].primary_key, hub.authorization_rules[0].primary_key) self.assertEqual(result.authorization_rules[0].secondary_key, hub.authorization_rules[0].secondary_key) @record def test_get_event_hub_with_existing_event_hub(self): # Arrange self._create_event_hub(self.event_hub_name) # Act event_hub = self.sbs.get_event_hub(self.event_hub_name) # Assert self.assertIsNotNone(event_hub) self.assertEqual(event_hub.name, self.event_hub_name) @record def test_get_event_hub_with_non_existing_event_hub(self): # Arrange # Act with self.assertRaises(AzureServiceBusResourceNotFound): resp = self.sbs.get_event_hub(self.event_hub_name) # Assert @record def test_delete_event_hub_with_existing_event_hub(self): # Arrange self._create_event_hub(self.event_hub_name) # Act deleted = self.sbs.delete_event_hub(self.event_hub_name) # Assert self.assertTrue(deleted) @record def test_delete_event_hub_with_existing_event_hub_fail_not_exist(self): # Arrange self._create_event_hub(self.event_hub_name) # Act deleted = self.sbs.delete_event_hub(self.event_hub_name, True) # Assert self.assertTrue(deleted) @record def test_delete_event_hub_with_non_existing_event_hub(self): # Arrange # Act deleted = self.sbs.delete_event_hub(self.event_hub_name) # Assert self.assertFalse(deleted) @record def test_delete_event_hub_with_non_existing_event_hub_fail_not_exist(self): # Arrange # Act with self.assertRaises(AzureMissingResourceHttpError): self.sbs.delete_event_hub(self.event_hub_name, True) # Assert @record def test_send_event(self): # Arrange self._create_event_hub(self.event_hub_name) # Act result = self.sbs.send_event(self.event_hub_name, 'hello world') result = self.sbs.send_event(self.event_hub_name, 'wake up world') result = self.sbs.send_event(self.event_hub_name, 'goodbye!') # Assert self.assertIsNone(result)
class DAMRWEB: def __init__(self, namespace, SAS_name, SAS_value): self.topic_vel = 'cmd_vel' self.topic_stop = 'motor_stop' self.namespace = namespace self.SAS_name = SAS_name self.SAS_value = SAS_value self.topic_options = Topic() self.topic_options.max_size_in_megabytes = '10' #### Try : '1024' self.topic_options.default_message_time_to_live = 'PT5S' self.bus_service = ServiceBusService( service_namespace=self.namespace, shared_access_key_name=self.SAS_name, shared_access_key_value=self.SAS_value) self.cmd_values = { 'N': "100 100", 'S': '-100 -100', 'W': '-50 50', 'E': '50 -50' } self.bot_list = [] #create topics of cmd_vel and motor stop def createLocalbot(self, bot_id): self.bus_service.create_topic((self.topic_vel + bot_id), self.topic_options) self.bus_service.create_topic((self.topic_stop + bot_id), self.topic_options) # self.bus_service.create_subscription((self.topic_vel+bot_id), bot_id) # self.bus_service.create_subscription((self.topic_stop+bot_id), bot_id) self.bot_list.append(bot_id) pass def remoteControl(self, bot_id, cmd_dirn): msg = Message(self.cmd_values[cmd_dirn].encode('utf-8')) self.bus_service.send_topic_message((self.topic_vel + bot_id), msg) def remoteControlStop(self, bot_id): msg = Message('0 0'.encode('utf-8')) self.bus_service.send_topic_message((self.topic_vel + bot_id), msg) def deleteTopic(self, bot_id): self.bus_service.delete_topic((self.topic_vel + bot_id)) self.bus_service.delete_topic((self.topic_stop + bot_id)) def cleanup(self): for bot in self.bot_list: self.deleteTopic(bot)
class ServiceBusClient(mixins.ServiceBusMixin): """A Service Bus client for a namespace with the specified SAS authentication settings. :param str service_namespace: Service Bus namespace, required for all operations. :param str host_base: Optional. Live host base URL. Defaults to Azure URL. :param str shared_access_key_name: SAS authentication key name. :param str shared_access_key_value: SAS authentication key value. :param loop: An async event loop. :param int http_request_timeout: Optional. Timeout for the HTTP request, in seconds. :param http_request_session: Optional. Session object to use for HTTP requests. :param bool debug: Whether to output AMQP network trace to the logger. Example: .. literalinclude:: ../examples/async_examples/test_examples_async.py :start-after: [START create_async_servicebus_client] :end-before: [END create_async_servicebus_client] :language: python :dedent: 4 :caption: Create a ServiceBusClient. """ def __init__(self, *, service_namespace=None, host_base=SERVICE_BUS_HOST_BASE, shared_access_key_name=None, shared_access_key_value=None, loop=None, http_request_timeout=DEFAULT_HTTP_TIMEOUT, http_request_session=None, debug=False): self.loop = loop or get_running_loop() self.service_namespace = service_namespace self.host_base = host_base self.shared_access_key_name = shared_access_key_name self.shared_access_key_value = shared_access_key_value self.debug = debug self.mgmt_client = ServiceBusService( service_namespace=service_namespace, host_base=host_base, shared_access_key_name=shared_access_key_name, shared_access_key_value=shared_access_key_value, timeout=http_request_timeout, request_session=http_request_session) @classmethod def from_connection_string(cls, conn_str, *, loop=None, **kwargs): """Create a Service Bus client from a connection string. :param conn_str: The connection string. :type conn_str: str Example: .. literalinclude:: ../examples/async_examples/test_examples_async.py :start-after: [START create_async_servicebus_client_connstr] :end-before: [END create_async_servicebus_client_connstr] :language: python :dedent: 4 :caption: Create a ServiceBusClient via a connection string. """ address, policy, key, _ = parse_conn_str(conn_str) parsed_namespace = urlparse(address) namespace, _, base = parsed_namespace.hostname.partition('.') return cls( service_namespace=namespace, shared_access_key_name=policy, shared_access_key_value=key, host_base='.' + base, loop=loop, **kwargs) def get_queue(self, queue_name): """Get an async client for a queue entity. :param queue_name: The name of the queue. :type queue_name: str :rtype: ~azure.servicebus.aio.async_client.QueueClient :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found. :raises: ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the queue is not found. Example: .. literalinclude:: ../examples/async_examples/test_examples_async.py :start-after: [START get_async_queue_client] :end-before: [END get_async_queue_client] :language: python :dedent: 4 :caption: Get a QueueClient for the specified queue. """ try: queue = self.mgmt_client.get_queue(queue_name) except requests.exceptions.ConnectionError as e: raise ServiceBusConnectionError("Namespace: {} not found".format(self.service_namespace), e) except AzureServiceBusResourceNotFound: raise ServiceBusResourceNotFound("Specificed queue does not exist.") return QueueClient.from_entity( self._get_host(), queue, shared_access_key_name=self.shared_access_key_name, shared_access_key_value=self.shared_access_key_value, mgmt_client=self.mgmt_client, loop=self.loop, debug=self.debug) def list_queues(self): """Get async clients for all queue entities in the namespace. :rtype: list[~azure.servicebus.aio.async_client.QueueClient] :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found. """ try: queues = self.mgmt_client.list_queues() except requests.exceptions.ConnectionError as e: raise ServiceBusConnectionError("Namespace: {} not found".format(self.service_namespace), e) queue_clients = [] for queue in queues: queue_clients.append(QueueClient.from_entity( self._get_host(), queue, shared_access_key_name=self.shared_access_key_name, shared_access_key_value=self.shared_access_key_value, mgmt_client=self.mgmt_client, loop=self.loop, debug=self.debug)) return queue_clients def get_topic(self, topic_name): """Get an async client for a topic entity. :param topic_name: The name of the topic. :type topic_name: str :rtype: ~azure.servicebus.aio.async_client.TopicClient :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found. :raises: ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the topic is not found. Example: .. literalinclude:: ../examples/async_examples/test_examples_async.py :start-after: [START get_async_topic_client] :end-before: [END get_async_topic_client] :language: python :dedent: 4 :caption: Get a TopicClient for the specified topic. """ try: topic = self.mgmt_client.get_topic(topic_name) except requests.exceptions.ConnectionError as e: raise ServiceBusConnectionError("Namespace: {} not found".format(self.service_namespace), e) except AzureServiceBusResourceNotFound: raise ServiceBusResourceNotFound("Specificed topic does not exist.") return TopicClient.from_entity( self._get_host(), topic, shared_access_key_name=self.shared_access_key_name, shared_access_key_value=self.shared_access_key_value, loop=self.loop, debug=self.debug) def list_topics(self): """Get an async client for all topic entities in the namespace. :rtype: list[~azure.servicebus.aio.async_client.TopicClient] :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found. """ try: topics = self.mgmt_client.list_topics() except requests.exceptions.ConnectionError as e: raise ServiceBusConnectionError("Namespace: {} not found".format(self.service_namespace), e) topic_clients = [] for topic in topics: topic_clients.append(TopicClient.from_entity( self._get_host(), topic, shared_access_key_name=self.shared_access_key_name, shared_access_key_value=self.shared_access_key_value, loop=self.loop, debug=self.debug)) return topic_clients def get_subscription(self, topic_name, subscription_name): """Get an async client for a subscription entity. :param topic_name: The name of the topic. :type topic_name: str :param subscription_name: The name of the subscription. :type subscription_name: str :rtype: ~azure.servicebus.aio.async_client.SubscriptionClient :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found. :raises: ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the subscription is not found. Example: .. literalinclude:: ../examples/async_examples/test_examples_async.py :start-after: [START get_async_subscription_client] :end-before: [END get_async_subscription_client] :language: python :dedent: 4 :caption: Get a TopicClient for the specified topic. """ try: subscription = self.mgmt_client.get_subscription(topic_name, subscription_name) except requests.exceptions.ConnectionError as e: raise ServiceBusConnectionError("Namespace: {} not found".format(self.service_namespace), e) except AzureServiceBusResourceNotFound: raise ServiceBusResourceNotFound("Specificed subscription does not exist.") return SubscriptionClient.from_entity( self._get_host(), topic_name, subscription, shared_access_key_name=self.shared_access_key_name, shared_access_key_value=self.shared_access_key_value, loop=self.loop, debug=self.debug) def list_subscriptions(self, topic_name): """Get an async client for all subscription entities in the topic. :param topic_name: The topic to list subscriptions for. :type topic_name: str :rtype: list[~azure.servicebus.aio.async_client.SubscriptionClient] :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found. :raises: ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the topic is not found. """ try: subs = self.mgmt_client.list_subscriptions(topic_name) except requests.exceptions.ConnectionError as e: raise ServiceBusConnectionError("Namespace: {} not found".format(self.service_namespace), e) except AzureServiceBusResourceNotFound: raise ServiceBusResourceNotFound("Specificed topic does not exist.") sub_clients = [] for sub in subs: sub_clients.append(SubscriptionClient.from_entity( self._get_host(), topic_name, sub, shared_access_key_name=self.shared_access_key_name, shared_access_key_value=self.shared_access_key_value, loop=self.loop, debug=self.debug)) return sub_clients
import json import RPi.GPIO as GPIO from azure.servicebus.control_client import ServiceBusService, Message, Topic, Rule, DEFAULT_RULE_NAME GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW) bus_service = ServiceBusService( service_namespace='***REPLACE ME, with your Service Bus Namespace Name***', shared_access_key_name= '***REPLACE ME, with your Shared Access Policy Name***', shared_access_key_value= '***REPLACE ME, with your Shared Access Key Value***') while True: msg = bus_service.receive_subscription_message( '***REPLACE ME with your Service Bus Topic Name***', '***REPLACE ME with your Service Bus Topic Subscription Name***', peek_lock=True) if msg.body is not None: value = json.loads(msg.body.decode("utf-8")) print(value["status"]) if value["status"] == 1: GPIO.output(8, GPIO.HIGH) print('The LED has been turned ON.') elif value["status"] == 0: GPIO.output(8, GPIO.LOW) print('The LED has been turned OFF.') else: print("Please enter a valid value.")
class queueRead(): def __init__(self): ### initialize variables self.topic_vel = os.environ["TOPIC_VELOCITY"] self.topic_stop = os.environ["TOPIC_STOP"] ### get parameters #### self.SAS_name = os.environ["SAS_NAME"] self.SAS_value = os.environ["SAS_VALUE"] self.namespace = os.environ["TOPIC_NAMESPACE"] self.bot_id = os.environ["BOT_ID"] self.LGPWM = os.getenv('LGPWM', int(12)) self.LGIN1 = os.getenv('LGIN1', int(5)) self.LGIN2 = os.getenv('LGIN2', int(6)) self.RGPWM = os.getenv('RGPWM', int(13)) self.RGIN1 = os.getenv('RGIN1', int(16)) self.RGIN2 = os.getenv('RGIN2', int(26)) self.bus_service = ServiceBusService( service_namespace=self.namespace, shared_access_key_name=self.SAS_name, shared_access_key_value=self.SAS_value) self.bus_service.create_subscription((self.topic_vel + self.bot_id), self.bot_id) self.bus_service.create_subscription((self.topic_stop + self.bot_id), self.bot_id) ### setup ### GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(self.LGPWM, GPIO.OUT) GPIO.setup(self.LGIN1, GPIO.OUT) GPIO.setup(self.LGIN2, GPIO.OUT) self.Lpwm = GPIO.PWM(self.LGPWM, 1000) self.Lpwm.start(0) GPIO.setup(self.RGPWM, GPIO.OUT) GPIO.setup(self.RGIN1, GPIO.OUT) GPIO.setup(self.RGIN2, GPIO.OUT) self.Rpwm = GPIO.PWM(self.RGPWM, 1000) self.Rpwm.start(0) @staticmethod def motorCall(Gpwm, GIN1, GIN2, msg): if (msg > 0): GPIO.output(GIN1, GPIO.HIGH) GPIO.output(GIN2, GPIO.LOW) else: GPIO.output(GIN1, GPIO.LOW) GPIO.output(GIN2, GPIO.HIGH) pwm_per = abs(msg) Gpwm.ChangeDutyCycle(pwm_per) def motorStop(self): self.Lpwm.ChangeDutyCycle(0) self.Rpwm.ChangeDutyCycle(0) GPIO.output(self.LGIN1, GPIO.LOW) GPIO.output(self.LGIN2, GPIO.LOW) GPIO.output(self.RGIN1, GPIO.LOW) GPIO.output(self.RGIN2, GPIO.LOW) def read(self): while (1): try: msg = self.bus_service.receive_subscription_message( (self.topic_vel + self.bot_id), self.bot_id, peek_lock=False) if msg.body is not None: res = list(map(int, msg.body.split(' '))) queueRead.motorCall(self.Lpwm, self.LGIN1, self.LGIN2, res[0]) queueRead.motorCall(self.Rpwm, self.RGIN1, self.RGIN2, res[1]) msg = self.bus_service.receive_subscription_message( (self.topic_stop + self.bot_id), self.bot_id, peek_lock=False) if msg.body is not None: self.motorStop() except: pass