class derivedKPI(object):
    """ Class to implement derived KPIs calculation"""
    
    def __init__(self):
        """ Initialize  frequently used parameters"""
        file_name = os.path.basename(__file__).split('.')[0]
        self.logger = log_function(file_name)
        self.config_obj = Config()
        user_authentication = self.config_obj.user_authentication()
        gateway = self.config_obj.gateway()
        derived_KPI = self.config_obj.derived_KPI()
        self.auth_URL = user_authentication['Auth_URL']
        self.derivedKPI_url = derived_KPI['DerivedKPI_url']
        self.derivedKPI_fetch_interval = derived_KPI['DerivedKPI_fetch_interval']
        self.access_key = user_authentication['access_key']
        self.user_key = user_authentication['user_key']
        self.user_id = user_authentication['user_id']
        self.token = user_authentication['token']
        self.application_id = user_authentication['application_id']
        self.auth_password = user_authentication['password']
        self.gateway_id = gateway['gateway_id']
        self.redis_obj_perf_data = redis_conn(db_name = 'REDIS_PERF_DATA')
        redis_obj_derived_kpi_data = redis_conn(db_name ='REDIS_DERIVED_KPI')
        try :
            self.api_response = eval(redis_obj_derived_kpi_data.get("Derived_KPI"))
        except Exception,error :
            self.api_response = None
        self.redis_obj_derived_kpi_data = redis_conn(db_name ='REDIS_DERIVED_KPI')
#!/usr/bin/python
import os
import smtplib
import string
import logging.handlers
from datetime import datetime, timedelta
from IotGateway.config import Config
from string import upper
config_obj = Config()
format_simple = config_obj.format_simple()
email_config = config_obj.email_config()
last_mail_time_config = config_obj.last_mail_time()
logger_set = config_obj.set()
#print last_mail_time
user_authentication = config_obj.user_authentication()
#last_mail_time_conf=config_obj.last_mail_time_conf
#print last_mail_time_conf,"last_mail_time_conf"
#log_config_file = os.path.dirname(os.path.abspath(__file__))
loggers = {}


class TlsSMTPHandler(logging.handlers.SMTPHandler):
    def __init__(self,
                 mailhost,
                 fromaddr,
                 toaddrs,
                 subject,
                 last_check,
                 credentials=None,
                 file_name=None,
class registration(object):
    def __init__(self):
        """
        From config file, get and initialization all variables.
        """
        file_name = os.path.basename(__file__).split('.')[0]
        self.logger = log_function(file_name)
        self.redis_obj_register = redis_conn(db_name='REDIS_REGISTER')
        self.config_obj = Config()

    def device_registration_push(self, device=None):
        """
            If device id registered in gateway then get devices id from memcache 
            otherwise call device registration api .
            if device registration api response status '401' 
                then firstly  call user authentication api and authenticate users.
            and register the devices on gateway and return device id and device id
         stored in  memcache
             
        Args:device
    
        return: None(if device registration fail that time return None)  
        """
        try:
            primary_key = "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnoo"
            secondary_key = "111222333444555666777888999000aaabbbcccdddee"
            device_id = self.redis_obj_register.get(device)
            info = self.redis_obj_register.get(
                str(device_id) + "azure_device_info")
            if device_id and info:
                return device_id
            else:
                gateway = self.config_obj.gateway()
                device_registration = self.config_obj.device_registration()
                user_authentication = self.config_obj.user_authentication()
                iot_hub = self.config_obj.iothub()
                data = {
                    'device_id': device,
                    'gateway_id': gateway['gateway_id'],
                    'protocol': iot_hub['protocol'],
                    'access_key': user_authentication['access_key'],
                }
                headers = {
                    'token': user_authentication['token'],
                    'user_id': user_authentication['user_id'],
                    'user_key': user_authentication['user_key']
                }
                #print device_registration['device_registation_url'],data
                response = requests.post(device_registration['device_registation_url'],\
                data = data,verify=False)
                if response.status_code == 401:
                    authData = {
                        'user_name': user_authentication['user_id'],
                        'password': user_authentication['password'],
                        'application_id': user_authentication['application_id']
                    }
                    authResponse = requests.post(
                        user_authentication['Auth_URL'],
                        data=authData,
                        headers=headers,
                        verify=False)
                    authResponseData = json.loads(authResponse.content)
                    if authResponseData['valid']:
                        authResponseData = authResponseData['object']
                        token = authResponseData['access_token']
                        user_key = authResponseData['userKey']
                        access_key = authResponseData['access_key']
                        self.config_obj.write_user_authentication(
                            token, user_key, access_key)
                        #                         data['token'] = authResponseData['access_token']
                        #                         data['userKey'] = authResponseData['userKey']
                        #                         data['access_key'] = authResponseData['access_key']
                        headers['user_key'] = authResponseData['userKey']
                        headers['token'] = authResponseData['access_token']
                        response = requests.post(device_registration['device_registation_url'],\
                    data = data, headers=headers, verify=False)
                response_data = json.loads(response.content)
                print "response_data", response_data
                self.logger.error("--- Registration response --- :{0}".format(
                    str(response_data)))
                if response_data['valid'] and len(response_data['object']) > 0:

                    device_id = response_data['object']
                    id = device_id[0]['id']
                    print "id", id
                    deviceId = get_device(id)
                    print deviceId
                    if deviceId:
                        print "device_id"
                        device_info = "HostName=ttpliot.azure-devices.net" + ";" + str(
                            deviceId) + ";" + str(primary_key)
                        self.redis_obj_register.set(device, device_id[0]['id'])
                        self.redis_obj_register.set(
                            str(device_id[0]['id']) + "azure_device_info",
                            device_info)
                    else:
                        print "device_id[0]['id']", device_id[0][
                            'id'], primary_key, secondary_key
                        device_info = iothub_create_device(
                            device_id[0]['id'], primary_key, secondary_key)
                        self.redis_obj_register.set(device, device_id[0]['id'])
                        self.redis_obj_register.set(
                            str(device_id) + "azure_device_info", device_info)
                else:
                    self.logger.error("Device Registration fail %s",
                                      response.text)
                return None
        except Exception as e:
            self.logger.exception('Exception in device_registration_push: %s',
                                  e)