def checkForServerAddressInfo(requiredDetils):
    global apiObjectSecondary
    try:
        print("Change In Device Server Info: {}\n".format(requiredDetils))
        if (requiredDetils['baseurl'] is not None
                and requiredDetils['baseurl'] is not None):
            if (dbObject.checkSecondaryAddressAvailable(database)):
                confDetails = dbObject.getAllConfigurationDetails(2, database)
                print("Device Current Server Info: {}\n".format(confDetails))
                isChangeRequired = 0
                if (requiredDetils['baseurl'] != confDetails[0]):
                    isChangeRequired = 1
                if (requiredDetils['suburl'] != confDetails[1]):
                    isChangeRequired = 1
                if isChangeRequired == 1:
                    dbObject.updateConfigurationTable(requiredDetils['baseurl'],\
                                                      requiredDetils['suburl'],\
                                                      database)
                    print("Server Info Updated")
                    apiObjectSecondary = sasAllAPI(2)
                    return 2
            else:
                dbObject.insertIntoConfigurationTable(requiredDetils['baseurl'],\
                                                      requiredDetils['suburl'],\
                                                      database)
                apiObjectSecondary = sasAllAPI(2)
                print("Server Info Inserted\n")
                return 2
        return 1
    except Exception as e:
        fileObject.updateExceptionMessage(
            "sasGetAllConfiguration{checkForServerAddressInfo}: ", str(e))
        return 0
def syncronizationProcess():
    while True:
        try:
            #            print("Current syncronizationProcess Thread ID: {}".format(threading.current_thread()))
            if (fileObject.readSyncStatus() == '1'):
                from sasDatabase import sasDatabase
                dbObject = sasDatabase()
                database = dbObject.connectDataBase()
                deviceId = dbObject.getDeviceId(database)
                if deviceId != 0:
                    global apiObject
                    apiObject = sasAllAPI(2)
                    getRFCardInformation(deviceId, dbObject, database)
                    fingerSyncStatus = getFingerprintInformation(
                        deviceId, dbObject, database)

                    if fingerSyncStatus == "Synced From Server":
                        fileObject.updateSyncStatus('2')
                    elif fingerSyncStatus == "Already Synced":
                        fileObject.updateSyncStatus('0')
                    t.sleep(5)
                else:
                    t.sleep(5)
                dbObject.databaseClose(database)
            else:
                t.sleep(5)
        except Exception as e:
            print("Exception From : {}\n Exception Message: {}".format(
                "syncronizationProcess", str(e)))
            fileObject.updateExceptionMessage(
                "sasMain{syncronizationProcess}: ", str(e))
def enrollNewEmployee(f, deviceId, dbObject, database):
    global apiObject
    apiObject = sasAllAPI(2)
    print("Inside Function: {}".format("enrollNewEmployee"))
    currentDateTime, currentTime = checkCurrentDateTime()
    print("Current Datetime: {}".format(currentDateTime))
    print("Current time: {}".format(currentTime))
    uniqueId = fileObject.readEnrollingUserInfo()
    requestId = fileObject.readRequestId()
    print("UniqueId Received: {}".format(uniqueId))
    #    print("Selected Company: {}".format(selectedCompany))
    print("Request ID: {}".format(requestId))

    try:
        fingerInput = takeFingerprintToEnroll(f, currentDateTime, deviceId,
                                              uniqueId, requestId)
        if fingerInput == "Finger Matched":
            gpioObject.turnLEDON('G+B')
            status = createNewTemplate(f, uniqueId, deviceId, dbObject,
                                       database)
            print("Registration Status: {}".format(status))
            if status == "1":
                #                sendPusherCommand(hardwareId,"REGISTED_SUCCESSFULLY",requestId)
                updateListOfUsedTemplates(f)
                apiObject.replyPusherMessage(deviceId, hardwareId, uniqueId,
                                             "REGISTED_SUCCESSFULLY")
                gpioObject.enrollmentLEDIndicator('G')
                fileObject.updateRequestId("0")
                #                turnLEDON('OFF')
                print("Registered Successfuly")
                #GPIO INDICATOR
            else:
                #                sendPusherCommand(hardwareId,"NOT_REGISTED_SUCCESSFULLY",requestId)
                apiObject.replyPusherMessage(deviceId, hardwareId, uniqueId,
                                             "NOT_REGISTED_SUCCESSFULLY")
                gpioObject.enrollmentLEDIndicator('R')
                fileObject.updateRequestId("0")
                #                turnLEDON('OFF')
                print("Registered Unsuccessfuly")
        else:
            gpioObject.enrollmentLEDIndicator('R')
            #            turnLEDON('OFF')
            fileObject.updateRequestId("0")
    except Exception as e:
        print("Exception From : {}\n Exception Message: {}".format(
            "enrollNewEmployee", str(e)))
        fileObject.updateExceptionMessage("sasMain{enrollNewEmployee}: ",
                                          str(e))
        gpioObject.enrollmentLEDIndicator('R')
        #        fileObject.updateRequestId("0")
        #        sendPusherCommand(hardwareId,"TIME_OUT",requestId)
        apiObject.replyPusherMessage(deviceId, hardwareId, uniqueId,
                                     "TIME_OUT")
def functionKillProgram():
    #print("Killing Started")
    t.sleep(3600)
    apiObjectPrimary = sasAllAPI(1)
    if (apiObjectPrimary.checkServerStatus()):
        os.system("hwclock -w")
    if fileObject.readCurrentTask() != '1':
        while 1:
            print("Current functionKillProgram Thread ID: {}".format(
                threading.current_thread()))
            if fileObject.readCurrentTask() == '1':
                break
            t.sleep(1)
    os.system('sudo pkill -f sasMain.py')
    except Exception as e:
        fileObject.updateExceptionMessage("sasGetConfiguration{getHardwareId}",
                                          str(e))
        cpuserial = "Error"
    return cpuserial


hardwareId = getHardwareId()
gpioObject.doorStatus(0)
#hardwareId = "asdasdas"
currentTask = '1'
syncStatus = '0'
lock = threading.Lock()

from sasAllAPI import sasAllAPI
apiObject = sasAllAPI(2)

REQUESTTIMEOUT = 5
ENROLLMENTTIMEOUT = 150
DOORLOCKTIMEOUT = 5

doorOpenTime = "0"


def configureFingerPrint():
    while True:
        try:
            f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)
            if (f.verifyPassword() == False):
                raise ValueError(
                    'The given fingerprint sensor password is wrong!')
"""
Created on Fri Nov 29 22:38:17 2019

@author: User
"""
import urllib
import tarfile
from shutil import copyfile
import os
import struct
from sasDatabase import sasDatabase
import commands
from sasFile import sasFile
fileObject = sasFile()
from sasAllAPI import sasAllAPI
apiObjectPrimary = sasAllAPI(1)
apiObjectSecondary = sasAllAPI(2)


def getHardwareId():
    cpuserial = ""
    try:
        f = open('/proc/cpuinfo', 'r')
        for line in f:
            if line[0:6] == 'Serial':
                cpuserial = line[10:26]
        f.close()
    except Exception as e:
        fileObject.updateExceptionMessage("sasGetConfiguration{getHardwareId}",
                                          str(e))
        cpuserial = "Error"
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 30 21:54:47 2019

@author: Rizban Hussain
"""
import json
from sasDatabase import sasDatabase
dbObject = sasDatabase()
database = dbObject.connectDataBase()
from sasFile import sasFile
fileObject = sasFile()
from sasAllAPI import sasAllAPI
apiObjectPrimary = sasAllAPI(1)

dbObject.resetUpdatedRequiredStatus(1, database)
deviceId = dbObject.getDeviceId(database)
apiObjectPrimary.confirmUpdateRequest(deviceId)
osVersion = fileObject.readCurrentVersion()


def generateDataToUpdateInfor():
    deviceInfo = dbObject.getAllDeviceInfo(database)
    urls = dbObject.getAllConfigurationDetails(2, database)
    existingEthernetSettings = fileObject.readCurrentEthernetSettings().split(
        '-')
    gsmFlag = fileObject.readGSMStatus()
    wifiNetworks = dbObject.getWifiConfigs(database)
    wifisettings = []
    wifisettings.append({"ssid" : "AqualinkLTD",\
                         "password" : "aqualink@321",\