Esempio n. 1
0
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
Esempio n. 2
0
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
Esempio n. 3
0
from pymongo import MongoClient
import json

mongo_conn_str = os.getenv('PROD_MONGODB')
shared_access_key = os.getenv('shared_access_key')
shared_access_value = os.getenv('shared_access_value')
service_namespace = os.getenv('service_namespace')
print(service_namespace)

bus_service = ServiceBusService(service_namespace=service_namespace, shared_access_key_name=shared_access_key,
                                shared_access_key_value=shared_access_value)
topic_name = "on-prem-test"  # the topic name already defined in azure
subscription = "heroku_consumer"  # unique name for this application/consumer
bus_service.create_topic(topic_name)
# create subscription
bus_service.create_subscription(topic_name, subscription)

# get subscription message
msg = bus_service.receive_subscription_message(
    topic_name, subscription, peek_lock=False)
msg_body = None
entity = None
if msg.body is None:
    print('No messages to retrieve')
    exit()
else:
    msg_body = msg.body.decode("utf-8")
    entity = json.loads(msg_body)
    print(msg_body)

try:
class AzureQueueManager(QueueManager):
    '''Class to abstract the queue infrastructure
    '''

    bus_service = None

    def __init__():
        # setop logger in upper class
        super().__init__()

    def get_live_servicebus_config():
        '''inspired by https://github.com/Azure/azure-sdk-for-python/blob/master/azure-servicebus/conftest.py'''
        parser = ConfigParser.RawConfigParser()
        parser.read('queue_account.conf')
        conf['service_bus_hostname'] = parser.get(
            'ServiceBusService_account',
            'service_bus_hostname',
            fallback=os.environ['SERVICE_BUS_HOSTNAME'])
        conf['service_namespace'] = parser.get(
            'ServiceBusService_account',
            'service_namespace',
            fallback=os.environ['SERVICE_BUS_HOSTNAME'])
        conf['shared_access_key_name'] = parser.get(
            'ServiceBusService_account',
            'shared_access_key_name',
            fallback=os.environ['SERVICE_BUS_SAS_POLICY'])
        conf['shared_access_key_value'] = parser.get(
            'ServiceBusService_account',
            'shared_access_key_value',
            fallback=os.environ['SERVICE_BUS_SAS_KEY'])
        conf['shared_access_connection_str'] = parser.get(
            'ServiceBusService_account',
            'shared_access_connection_str',
            fallback=os.environ['SERVICE_BUS_CONNECTION_STR'])
        return conf

    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 isConnected():
        return self.bus_service is not None

    def topics():
        return self.bus_service.list_topics()

    def subscribe(topic_name, subscribe_name):
        '''Subscribe to a topic: topic_name and calling 
        subscription as subscribe_name.
        Subscription have to explicitaly removed to disconnect to  a topic.
        I't configured to avoid throwing exception if topic already exists.
        TODO: SQL filtering
        '''
        if not topic_name:
            raise Exception('No topic name set')
        if not subscribe_name:
            raise Exception('No named subscription is set')
        fail_on_exist = False
        self.bus_service.create_subscription(topic_name, subscribe_name,
                                             fail_on_exist)

    def removeSubscribtion(topic_name, subscribe_name):
        '''Remove subscription named: subscribe_name to a topic: topic_name.
        It's configured to avoid throwing exception if topic does not exists.
        TODO: SQL filtering
        '''
        if not topic_name:
            raise Exception('No topic name set')
        if not subscribe_name:
            raise Exception('No named subscription is set')
        fail_not_exist = False
        self.bus_service.delete_subscription(topic_name, subscribe_name,
                                             fail_not_exist)

    def peekMessage(topic_name, subscription_name, timeout=60):
        '''Peek a message without removing and loking it.
        Get message from topic: topic_name and subscription as subscribe_name.
        Subscription have to explicitaly removed to disconnect to  a topic.
        Unlock is done following peek_lock_subscription_message logic.
        '''
        return self.bus_service.peek_lock_subscription_message(
            topic_name, subscription_name, timeout)

    def removeMessage(topic_name,
                      subscription_name,
                      identifier={
                          'sequence_number': None,
                          'lock_token': None
                      }):
        '''Remove a locked message of a topic_name beloging to a subscription_name.
        Mesage is referred via sequence_number and/or lock_token retrieved
        during peekMessage/peek_lock_subscription_message
        '''
        self.bus_service.delete_subscription_message(
            topic_name=topic_name,
            subscription_name=subscription_name,
            sequence_number=identifier['sequence_number'],
            lock_token=identifier['lock_token'])

    def unlockMessage(topic_name,
                      subscription_name,
                      identifier={
                          'sequence_number': None,
                          'lock_token': None
                      }):
        '''Remove a locked message of a topic_name beloging to a subscription_name.
        Mesage is referred via sequence_number and/or lock_token retrieved
        during peekMessage/peek_lock_subscription_message
        '''
        self.bus_service.unlock_subscription_message(
            topic_name=topic_name,
            subscription_name=subscription_name,
            sequence_number=identifier['sequence_number'],
            lock_token=identifier['lock_token'])