def test_create_queue_with_options(self):
        # Arrange

        # Act
        queue_options = Queue()
        queue_options.default_message_time_to_live = 'PT1M'
        queue_options.duplicate_detection_history_time_window = 'PT5M'
        queue_options.enable_batched_operations = False
        queue_options.dead_lettering_on_message_expiration = False
        queue_options.lock_duration = 'PT1M'
        queue_options.max_delivery_count = 15
        queue_options.max_size_in_megabytes = 5120
        queue_options.message_count = 0
        queue_options.requires_duplicate_detection = False
        queue_options.requires_session = False
        queue_options.size_in_bytes = 0
        created = self.sbs.create_queue(self.queue_name, queue_options)

        # Assert
        self.assertTrue(created)
        queue = self.sbs.get_queue(self.queue_name)
        self.assertEquals('PT1M', queue.default_message_time_to_live)
        self.assertEquals(
            'PT5M', queue.duplicate_detection_history_time_window)
        self.assertEquals(False, queue.enable_batched_operations)
        self.assertEquals(False, queue.dead_lettering_on_message_expiration)
        self.assertEquals('PT1M', queue.lock_duration)
        self.assertEquals(15, queue.max_delivery_count)
        self.assertEquals(5120, queue.max_size_in_megabytes)
        self.assertEquals(0, queue.message_count)
        self.assertEquals(False, queue.requires_duplicate_detection)
        self.assertEquals(False, queue.requires_session)
        self.assertEquals(0, queue.size_in_bytes)
Exemple #2
0
def watchAzureQueue():
    global Counter
    if AZURE_RECEIVING == False:
        return

    bus_service = ServiceBusService(
        service_namespace='msgtestsb',
        shared_access_key_name='RootManageSharedAccessKey',
        shared_access_key_value='Ar9fUCZQdTL7cVWgerdNOB7sbQp0cWEeQyTRYUjKwpk=')
    queue_options = Queue()
    queue_options.max_size_in_megabytes = '5120'
    queue_options.default_message_time_to_live = 'PT96H'

    bus_service.create_queue('process_incoming', queue_options)
    bus_service.create_queue('whatsapp_sender', queue_options)

    while not isfile('/home/bitnami1/whatsapp/.stopwhatsapp') and Counter > 1:
        msg = bus_service.receive_queue_message('whatsapp_sender',
                                                peek_lock=False)
        if msg != None and msg.body:
            logging.info('%s ' % datetime.now() + msg.body)
            SendQueue.put(msg.body)
        else:
            logging.info('%s ' % datetime.now() + "Empty Azure Queue")
            time.sleep(4.6)
Exemple #3
0
    def test_create_queue_with_options(self):
        # Arrange

        # Act
        queue_options = Queue()
        queue_options.default_message_time_to_live = 'PT1M'
        queue_options.duplicate_detection_history_time_window = 'PT5M'
        queue_options.enable_batched_operations = False
        queue_options.dead_lettering_on_message_expiration = False
        queue_options.lock_duration = 'PT1M'
        queue_options.max_delivery_count = 15
        queue_options.max_size_in_megabytes = 5120
        queue_options.message_count = 0
        queue_options.requires_duplicate_detection = False
        queue_options.requires_session = False
        queue_options.size_in_bytes = 0
        created = self.sbs.create_queue(self.queue_name, queue_options)

        # Assert
        self.assertTrue(created)
        queue = self.sbs.get_queue(self.queue_name)
        self.assertEquals('PT1M', queue.default_message_time_to_live)
        self.assertEquals('PT5M',
                          queue.duplicate_detection_history_time_window)
        self.assertEquals(False, queue.enable_batched_operations)
        self.assertEquals(False, queue.dead_lettering_on_message_expiration)
        self.assertEquals('PT1M', queue.lock_duration)
        self.assertEquals(15, queue.max_delivery_count)
        self.assertEquals(5120, queue.max_size_in_megabytes)
        self.assertEquals(0, queue.message_count)
        self.assertEquals(False, queue.requires_duplicate_detection)
        self.assertEquals(False, queue.requires_session)
        self.assertEquals(0, queue.size_in_bytes)
def queuehandler(table):
    with open('config.json', 'r') as f:
        config = json.load(f)
    count = 0
    table_key = config['STORAGE']['QUEUE_TABLE_KEY']  # Azure table name

    queue_namespace = config['QUEUE']['NAMESPACE']
    namespace_key = config['QUEUE']['ACCOUNT_KEY']
    SASName = config['QUEUE']['SASNAME']
    queue_name = config['QUEUE']['QUEUE_NAME']
    bus_service = ServiceBusService(service_namespace=queue_namespace,
                                    shared_access_key_value=namespace_key,
                                    shared_access_key_name=SASName)
    try:
        queue_options = Queue()
        queue_options.max_size_in_megabytes = '5120'
        queue_options.default_message_time_to_live = 'PT8H'
        queue_options.requires_duplicate_detection = True
        #queue_options.requires_session = True
        bus_service.create_queue('email_notification', queue_options)
    except Exception as e:
        f = open("exceptions.txt", "a")
        f.write(e)
        print("Exception occured in Service Bus Handler, check log")
    return (bus_service)
Exemple #5
0
    def __init__(self):
        self.bus_service = ServiceBusService(
            service_namespace='msgtestsb',
            shared_access_key_name='RootManageSharedAccessKey',
            shared_access_key_value='Ar9fUCZQdTL7cVWgerdNOB7sbQp0cWEeQyTRYUjKwpk=')
        queue_options = Queue()
        queue_options.max_size_in_megabytes = '5120'
        queue_options.default_message_time_to_live = 'PT96H'

        self.bus_service.create_queue('process_incoming', queue_options)
        self.bus_service.create_queue('whatsapp_sender', queue_options)
        self.bus_service.create_queue('myapp_sender', queue_options)
Exemple #6
0
    def __init__(self):
        self.bus_service = ServiceBusService(
            service_namespace='msgtestsb',
            shared_access_key_name='RootManageSharedAccessKey',
            shared_access_key_value=
            'Ar9fUCZQdTL7cVWgerdNOB7sbQp0cWEeQyTRYUjKwpk=')
        queue_options = Queue()
        queue_options.max_size_in_megabytes = '5120'
        queue_options.default_message_time_to_live = 'PT96H'

        self.bus_service.create_queue('process_incoming', queue_options)
        self.bus_service.create_queue('whatsapp_sender', queue_options)
        self.bus_service.create_queue('myapp_sender', queue_options)
Exemple #7
0
def createQueue(queue_name):
    # Create Queue
    queue_options = Queue()

    # A queue can have a max size of 5GB.
    # i.e. the total size of messages we didn't consume cannot exceed 5GB.
    queue_options.max_size_in_megabytes = '5120'

    # Message time to live determines how long a message will stay in the queue before it expires and is removed or dead lettered.
    # Defaults to 14 days
    queue_options.default_message_time_to_live = 'PT1M'

    queue_client.create_queue(queue_name, queue_options)
def main(argv):
   print '##################################################################'
   print '#           Test Azure Service bus queue connection              #'
   print '##################################################################'

   configFileName = os.path.dirname(os.path.abspath(__file__)) + '/config.json'

   print 'Start Parameters:'
   print '  configFileName:', configFileName 

   json_data=open(configFileName)
   config_data = json.load(json_data)
   json_data.close()

   print '      Company ID:', config_data["Server"]["id"]
   print '      Gateway ID:', config_data["Server"]["Deviceid"]
   print '     Service Bus:', config_data["Servicebus"]["namespace"]

   queue_name = 'custom_' + config_data["Server"]["id"] + '_' + config_data["Server"]["Deviceid"]
   bus_service = ServiceBusService( service_namespace=config_data["Servicebus"]["namespace"], 
                                    shared_access_key_name=config_data["Servicebus"]["shared_access_key_name"], 
                                    shared_access_key_value=config_data["Servicebus"]["shared_access_key_value"])
   try:
      bus_service.receive_queue_message(queue_name, peek_lock=False)
      print '  Actuator queue: ' + queue_name
   except:
      queue_options = Queue()
      queue_options.max_size_in_megabytes = '1024'
      queue_options.default_message_time_to_live = 'PT15M'
      bus_service.create_queue(queue_name, queue_options)
      print '  Actuator queue: ' + queue_name + ' (Created)'	   
	   
   # List to hold all commands that was send no ACK received
   localCommandSendAckWaitList = []
   while True:
      cloudCommand = bus_service.receive_queue_message(queue_name, peek_lock=False)

      if cloudCommand.body is not None:
          stringCommand = str(cloudCommand.body)
          print 'C: Received "' + stringCommand + '" => ',

          #Tranlate External/Cloud ID to local network ID 
          temp = stringCommand.split("-")
          #print 'stringCommand.split = ', temp
          localNetworkDeviceID = config_data["Devices"].keys()[config_data["Devices"].values().index(temp[0])]
          print 'for DeviceId=' + localNetworkDeviceID

      time.sleep(10)
Exemple #9
0
def watchAzureQueue():
        global Counter
        if AZURE_RECEIVING == False:
            return 

        bus_service = ServiceBusService(
            service_namespace='msgtestsb',
            shared_access_key_name='RootManageSharedAccessKey',
            shared_access_key_value='Ar9fUCZQdTL7cVWgerdNOB7sbQp0cWEeQyTRYUjKwpk=')
        queue_options = Queue()
        queue_options.max_size_in_megabytes = '5120'
        queue_options.default_message_time_to_live = 'PT96H'

        bus_service.create_queue('process_incoming', queue_options)
        bus_service.create_queue('whatsapp_sender', queue_options)
 
        while not isfile('/home/bitnami1/whatsapp/.stopwhatsapp') and Counter > 1:
            msg = bus_service.receive_queue_message('whatsapp_sender', peek_lock=False)
            if msg != None and msg.body:
                logging.info( '%s ' % datetime.now() +  msg.body)
                SendQueue.put(msg.body)
            else:
                logging.info( '%s ' % datetime.now() +  "Empty Azure Queue")
    	        time.sleep(4.6)
Exemple #10
0
 def createQueue(self, queueName, queueOptions=None):
     if queueOptions is None:
         queueOptions = Queue()
         queueOptions.max_size_in_megabytes = '5120'
         queueOptions.default_message_time_to_live = 'PT1M'
     self.serviceBus.create_queue(queueName, queueOptions)
Exemple #11
0
def main(argv):
   print '##################################################################'
   print '#                         NRF24 gateway                          #'
   print '##################################################################'


   # Wait while internet appear
   import urllib2 
   loop_value = 1
   while (loop_value < 10):
      try:
           urllib2.urlopen("http://google.com")
      except:
           print( "Network: currently down." )
           time.sleep( 10 )
           loop_value = loop_value + 1
      else:
           print( "Network: Up and running." )
           loop_value = 10


   pipes = [[0xf0, 0xf0, 0xf0, 0xf0, 0xd2], [0xf0, 0xf0, 0xf0, 0xf0, 0xe1]]
   configFileName = os.path.dirname(os.path.abspath(__file__)) + '/config.json'
   debugMode = 0

   try:
      opts, args = getopt.getopt(argv,"hd:f:",["debug=","configFile="])
   except getopt.GetoptError:
      print 'smart_gateway.py -d <debugMode:0/1>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print 'Example for call it in debug mode: smart_gateway.py -d 1 -f config.json'
         sys.exit()
      elif opt in ("-d", "--debug"):
         debugMode = arg
      elif opt in ("-f", "--configFile"):
         configFileName = arg

   print 'Start Parameters:'
   print '       debugMode:', debugMode
   print '  configFileName:', configFileName 

   json_data=open(configFileName)
   config_data = json.load(json_data)
   json_data.close()

   print '      Server URL:', config_data["Server"]["url"]
   print '      Company ID:', config_data["Server"]["id"]
   print '      Gateway ID:', config_data["Server"]["Deviceid"]
   print '     Service Bus:', config_data["Servicebus"]["namespace"]

   print ''
   nowPI = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")

   href = config_data["Server"]["url"] + 'API/Device/GetServerDateTime'
   token = config_data["Server"]["key"]
   authentication = config_data["Server"]["id"] + ':' + token
   headers = {'Content-Type': 'application/json; charset=utf-8', 'Accept': 'application/json', 'Authentication': authentication}
   #r = requests.get(href, headers=headers, verify=False)
   r = requests.get(href, headers=headers)
   if r.status_code == 200:
       nowPI = r.json()
       print ("Setting up time to: " + nowPI)
       os.popen('sudo -S date -s "' + nowPI + '"', 'w').write("123")
   else:
       print 'Error in setting time. Server response code: %i' % r.status_code

   queue_name = 'custom_' + config_data["Server"]["id"] + '_' + config_data["Server"]["Deviceid"]
   bus_service = ServiceBusService( service_namespace=config_data["Servicebus"]["namespace"], 
                                    shared_access_key_name=config_data["Servicebus"]["shared_access_key_name"], 
                                    shared_access_key_value=config_data["Servicebus"]["shared_access_key_value"])
   try:
      bus_service.receive_queue_message(queue_name, peek_lock=False)
      print '  Actuator queue: ' + queue_name
   except:
      queue_options = Queue()
      queue_options.max_size_in_megabytes = '1024'
      queue_options.default_message_time_to_live = 'PT15M'
      bus_service.create_queue(queue_name, queue_options)
      print '  Actuator queue: ' + queue_name + ' (Created)'	   
	   
   href = config_data["Server"]["url"] + 'api/Device/DeviceConfigurationUpdate'
   token = config_data["Server"]["key"]
   authentication = config_data["Server"]["id"] + ":" + token


   if debugMode==1: print(authentication)
   headers = {'Content-Type': 'application/json; charset=utf-8', 'Accept': 'application/json', 'Timestamp': nowPI, 'Authentication': authentication}
    
   deviceDetail = {}
   deviceDetail["DeviceIdentifier"] = config_data["Server"]["Deviceid"]
   deviceDetail["DeviceType"] = "Custom"
   deviceDetail["DeviceConfigurations"] = [{'Key':'IPPrivate','Value':[(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]},
                                           {'Key':'IPPublic','Value': requests.get('http://icanhazip.com/').text},
                                           {'Key': 'Configuration', 'Value': json.dumps(config_data) },
                                           {'Key':'MAC','Value': ':'.join(("%012X" % get_mac())[i:i+2] for i in range(0, 12, 2))}
                                          ]

   payload = {'Device': deviceDetail}
   if debugMode == 1: print 'Request Content: {0}'.format(json.dumps(payload))
   #r = requests.post(href, headers=headers, data=json.dumps(payload), verify=False)
   r = requests.post(href, headers=headers, data=json.dumps(payload))


   if r.status_code == 200:
      if debugMode == 1: print 'Configuration Response Content: {0}'.format(r.content)
      data = json.loads(r.text)    
      for entry in data['Device']['DeviceConfigurations']:
          if entry['Key'] == 'Configuration':     
             with open(configFileName, 'w') as outfile:
                json.dump(json.loads(entry['Value']), outfile)
      print 'Device configuration Successfully updated'
   else:
      print 'Error in Device configuration update. Server response code: {0} {1}'.format(r.status_code, r.content)


   GPIO.setwarnings(False)

   radio = NRF24()
   radio.begin(0, 0, 25, 18) #set gpio 25 as CE pin
   radio.setRetries(15,15)
   radio.setPayloadSize(32)
   radio.setChannel(0x4c)
   radio.setDataRate(NRF24.BR_250KBPS)
   radio.setPALevel(NRF24.PA_MAX)
   radio.setAutoAck(1)
   radio.openWritingPipe(pipes[1])
   radio.openReadingPipe(1, pipes[0])

   radio.startListening()
   radio.stopListening()

   print ''
   print 'NRF24 Module Configuration Details:'
   radio.printDetails()
   radio.startListening()

   print ''
   cloudCommandLastCheck = datetime.now()

   # List to hold all commands that was send no ACK received
   localCommandSendAckWaitList = []
   while True:
       pipe = [0]
       cloudCommand = ''
       nowPI = datetime.now()
       while not radio.available(pipe, True):
           radioTime = datetime.now()
           tdelta = nowPI-radioTime
           time.sleep(1)
           if (abs(tdelta.total_seconds()) > 10): break

       recv_buffer = []
       radio.read(recv_buffer)
       out = ''.join(chr(i) for i in recv_buffer)

       nowPI = datetime.now()

       if debugMode == 1: print localCommandSendAckWaitList

       if out.find(';')>0:
          out = out.split(';')[0]
          print 'L: Received: ' + out

          temp =out.split("_")
          if debugMode == 1: print (temp)
    
          if temp[0] in config_data["Devices"]:
             if temp[1] == 'ack':
               # Clean list once ACK from SN is received
                localCommandSendAckWaitList= [x for x in localCommandSendAckWaitList if x != temp[2]]
                print '<- Broadcast complete, ACK received for: ' + temp[2]
             else:
                sendMeasure(config_data, nowPI.strftime("%Y-%m-%dT%H:%M:%S"), temp[1], temp[2], config_data["Devices"][temp[0]], debugMode)
                print 'L: Generated selfok'
                sendMeasure(config_data, nowPI.strftime("%Y-%m-%dT%H:%M:%S"), 'live', 1, config_data["Server"]["Deviceid"], debugMode)
          else:
             if temp[0] == '???':
                 print 'New Device Registration, HandshakeID=' + temp[2]
                 localId = sendSensorRegistration(config_data,  nowPI.strftime("%Y-%m-%dT%H:%M:%S"), 'new custom device (' + temp[2] + ')')
                 if localId != 0:
                      localCommandSendAckWaitList.append('???_v02_' + temp[2] + '_' + localId) 
                      # Reload config data as we succesfully registered new device
                      json_data=open(configFileName)
                      config_data = json.load(json_data)
                      json_data.close()
             else:
                 print '-> ignore'

       if queue_name <> '':
          # if check timeout is gone go to Azure and grab command to execute
          tdelta = nowPI-cloudCommandLastCheck
          if (abs(tdelta.total_seconds()) > 10):
             cloudCommandLastCheck = datetime.now()
             thread = Thread(target=checkCloudCommand, args=(bus_service, queue_name, localCommandSendAckWaitList, config_data))
             thread.start()

          if debugMode == 1: print localCommandSendAckWaitList
          # Repeat sending/span commands while list is not empty
          for localCommand in localCommandSendAckWaitList:
             radio.stopListening()
             buf = list(localCommand)
             radio.write(buf)
             print 'L: Broadcast Command: ' + localCommand 
             time.sleep(1)
             radio.startListening()
Exemple #12
0
def main(argv):
   print '##################################################################'
   print '#                         NRF24 gateway                          #'
   print '##################################################################'


   # Wait while internet appear
   import urllib2 
   loop_value = 1
   while (loop_value < 10):
      try:
           urllib2.urlopen("http://google.com")
      except:
           print( "Network: currently down." )
           time.sleep( 10 )
           loop_value = loop_value + 1
      else:
           print( "Network: Up and running." )
           loop_value = 10


   pipes = [[0xf0, 0xf0, 0xf0, 0xf0, 0xd2], [0xf0, 0xf0, 0xf0, 0xf0, 0xe1]]
   configFileName = os.path.dirname(os.path.abspath(__file__)) + '/config.json'
   debugMode = 0

   try:
      opts, args = getopt.getopt(argv,"hd:f:",["debug=","configFile="])
   except getopt.GetoptError:
      print 'smart_gateway.py -d <debugMode:0/1>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print 'Example for call it in debug mode: smart_gateway.py -d 1 -f config.json'
         sys.exit()
      elif opt in ("-d", "--debug"):
         debugMode = arg
      elif opt in ("-f", "--configFile"):
         configFileName = arg

   print 'Start Parameters:'
   print '       debugMode:', debugMode
   print '  configFileName:', configFileName 

   json_data=open(configFileName)
   config_data = json.load(json_data)
   json_data.close()

   print '      Server URL:', config_data["Server"]["url"]
   print '      Company ID:', config_data["Server"]["id"]
   print '      Gateway ID:', config_data["Server"]["Deviceid"]
   print '     Service Bus:', config_data["Servicebus"]["namespace"]

   print ''
   nowPI = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")

   href = config_data["Server"]["url"] + 'API/Device/GetServerDateTime'
   token = config_data["Server"]["key"]
   authentication = config_data["Server"]["id"] + ':' + token
   headers = {'Content-Type': 'application/json; charset=utf-8', 'Accept': 'application/json', 'Authentication': authentication}
   #r = requests.get(href, headers=headers, verify=False)
   r = requests.get(href, headers=headers)
   if r.status_code == 200:
       nowPI = r.json()
       print ("Setting up time to: " + nowPI)
       os.popen('sudo -S date -s "' + nowPI + '"', 'w').write("123")
   else:
       print 'Error in setting time. Server response code: %i' % r.status_code
	   
   href = config_data["Server"]["url"] + 'api/Device/DeviceConfigurationUpdate'
   token = config_data["Server"]["key"]
   authentication = config_data["Server"]["id"] + ":" + token


   if debugMode==1: print(authentication)
   headers = {'Content-Type': 'application/json; charset=utf-8', 'Accept': 'application/json', 'Timestamp': nowPI, 'Authentication': authentication}
    
   deviceDetail = {}
   deviceDetail["DeviceIdentifier"] = config_data["Server"]["Deviceid"]
   deviceDetail["DeviceType"] = "Custom"
   deviceDetail["DeviceConfigurations"] = [{'Key':'IPPrivate','Value':[(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]},
                                           {'Key':'IPPublic','Value': requests.get('http://icanhazip.com/').text},
                                           {'Key': 'Configuration', 'Value': json.dumps(config_data) },
                                           {'Key':'MAC','Value': ':'.join(("%012X" % get_mac())[i:i+2] for i in range(0, 12, 2))}
                                          ]

   payload = {'Device': deviceDetail}
   if debugMode == 1: print 'Request Content: {0}'.format(json.dumps(payload))
   #r = requests.post(href, headers=headers, data=json.dumps(payload), verify=False)
   r = requests.post(href, headers=headers, data=json.dumps(payload))


   if r.status_code == 200:
      if debugMode == 1: print 'Configuration Response Content: {0}'.format(r.content)
      data = json.loads(r.text)    
      for entry in data['Device']['DeviceConfigurations']:
          if entry['Key'] == 'Configuration':     
             with open(configFileName, 'w') as outfile:
                json.dump(json.loads(entry['Value']), outfile)
      print 'Device configuration Successfully updated'
   else:
      print 'Error in Device configuration update. Server response code: {0} {1}'.format(r.status_code, r.content)

   
   queue_name = 'custom_' + config_data["Server"]["id"] + '_' + config_data["Server"]["Deviceid"]
   bus_service = ServiceBusService( service_namespace=config_data["Servicebus"]["namespace"], 
                                    shared_access_key_name=config_data["Servicebus"]["shared_access_key_name"], 
                                    shared_access_key_value=config_data["Servicebus"]["shared_access_key_value"])
   try:
      bus_service.receive_queue_message(queue_name, peek_lock=True)
      print '  Succesfully connected to queue'
      print '  Actuator queue: ' + queue_name
   except:
      queue_options = Queue()
      queue_options.max_size_in_megabytes = '1024'
      queue_options.default_message_time_to_live = 'PT15M'
      bus_service.create_queue(queue_name, queue_options)
      print '  Succesfully created queue'
      print '  Actuator queue: ' + queue_name + ' (Created)'

   GPIO.setwarnings(False)

   radio = NRF24()
   radio.begin(0, 0, 25, 18) #set gpio 25 as CE pin
   radio.setRetries(15,15)
   radio.setPayloadSize(32)
   radio.setChannel(0x4c)
   radio.setDataRate(NRF24.BR_250KBPS)
   radio.setPALevel(NRF24.PA_MAX)
   radio.setAutoAck(1)
   radio.openWritingPipe(pipes[1])
   radio.openReadingPipe(1, pipes[0])

   radio.startListening()
   radio.stopListening()

   print ''
   print 'NRF24 Module Configuration Details:'
   radio.printDetails()
   radio.startListening()

   print ''
   cloudCommandLastCheck = datetime.now()

   # List to hold all commands that was send no ACK received
   localCommandSendAckWaitList = []
   while True:
       pipe = [0]
       cloudCommand = ''
       nowPI = datetime.now()
       while not radio.available(pipe, True):
           radioTime = datetime.now()
           tdelta = nowPI-radioTime
           time.sleep(1)
           if (abs(tdelta.total_seconds()) > 10): break

       recv_buffer = []
       radio.read(recv_buffer)
       out = ''.join(chr(i) for i in recv_buffer)

       nowPI = datetime.now()

       if debugMode == 1: print localCommandSendAckWaitList

       if out.find(';')>0:
          out = out.split(';')[0]
          print 'L: Received: ' + out

          temp =out.split("_")
          if debugMode == 1: print (temp)
    
          if temp[0] in config_data["Devices"]:
             if temp[1] == 'ack':
               # Clean list once ACK from SN is received
                localCommandSendAckWaitList= [x for x in localCommandSendAckWaitList if x != temp[2]]
                print '<- Broadcast complete, ACK received for: ' + temp[2]
             else:
                sendMeasure(config_data, nowPI.strftime("%Y-%m-%dT%H:%M:%S"), temp[1], temp[2], config_data["Devices"][temp[0]], debugMode)
                print 'L: Generated selfok'
                sendMeasure(config_data, nowPI.strftime("%Y-%m-%dT%H:%M:%S"), 'live', 1, config_data["Server"]["Deviceid"], debugMode)
          else:
             if temp[0] == '???':
                 print 'New Device Registration, HandshakeID=' + temp[2]
                 localId = sendSensorRegistration(config_data,  nowPI.strftime("%Y-%m-%dT%H:%M:%S"), 'new custom device (' + temp[2] + ')')
                 if localId != 0:
                      localCommandSendAckWaitList.append('???_v02_' + temp[2] + '_' + localId) 
                      # Reload config data as we succesfully registered new device
                      json_data=open(configFileName)
                      config_data = json.load(json_data)
                      json_data.close()
             else:
                 print '-> ignore'

       if queue_name <> '':
          # if check timeout is gone go to Azure and grab command to execute
          tdelta = nowPI-cloudCommandLastCheck
          manager = ThreadManager(bus_service, queue_name, localCommandSendAckWaitList, config_data)
          thread = manager.new_thread()
          if (abs(tdelta.total_seconds()) > 10) and thread is not None:
             cloudCommandLastCheck = datetime.now()
             thread.run()

          if debugMode == 1: print localCommandSendAckWaitList
          # Repeat sending/span commands while list is not empty
          for localCommand in localCommandSendAckWaitList:
             radio.stopListening()
             buf = list(localCommand)
             radio.write(buf)
             print 'L: Broadcast Command: ' + localCommand 
             time.sleep(1)
             radio.startListening()
 def create_queue(self):
     q_opt = Queue()
     q_opt.max_size_in_megabytes = '1024'
     q_opt.default_message_time_to_live = 'PT1M'
     self.bus_service.create_queue(self.queue_name, q_opt)