Example #1
0
def isDownloadTriggered():
    trigger = 0

    try:
        if isExternalTriggered() == 1:
            ackExternalTrigger()
            trigger = 1
        elif isTimerExpired() == 1:
            trigger = 1
        else:
            trigger = 0

        if trigger == 1:
            if isMinimumTimerExpired() == 1:
                ackTimerTrigger()
                trigger = 1
            else:
                soclogging.logDebug(1, "Last Download less then " + '{:.0f}'.format(
                    parameters.getParameter('timerMinInterval') / 60) + " minutes ago. Cancelling download")
                trigger = 0

        if trigger == 1:
            if state.getState('charged') == 0 and state.getState('unplug') == 0:
                trigger = 0
                soclogging.logDebug(1, "Vehicle was not unplugged or charging since last download. Cancelling download")

    except:
        raise

    return trigger
Example #2
0
def doExternalUpdate():
    attempt = 0

    if state.getState('lastSuccess') == 1:
        maxAttempt = 3
    else:
        maxAttempt = 1

    while attempt < maxAttempt:
        try:
            soc = soc_external.DownloadSoC()
        except:
            soc = 0
            raise

        if soc > 0:
            saveSoc(soc, 0)
            state.setState('lastSuccess', 1)
            break
        else:
            attempt += 1
            state.setState('lastSuccess', 0)
            if attempt < maxAttempt:
                soclogging.logDebug(2, "Retrying in 60 Seconds...")
                time.sleep(60)

    return
Example #3
0
def loadBrandData():
    vin = getParameter('vehicleVin')
    
    if vin[:2]=='KN' or vin[:3]=='U5Y' or vin[:3]=='U6Z':
        setParameter('brand', 'kia')
        #soclogging.logDebug(2, "Vehicle identified as Kia")
    elif vin[:3]=='KMH' or vin[:3]=='TMA':
        setParameter('brand', 'hyundai')
        #soclogging.logDebug(2, "Vehicle identified as Hyundai")
    else:
        setParameter('brand', '')
        soclogging.logDebug(2, "Vehicle WMI unknown")
        raise RuntimeError
    
    if getParameter('brand') == 'kia':
        setParameter('host', 'prd.eu-ccapi.kia.com:8080')
        setParameter('baseUrl', 'https://' + getParameter('host'))
        setParameter('clientId', 'fdc85c00-0a2f-4c64-bcb4-2cfb1500730a')
        setParameter('authClientId', '572e0304-5f8d-4b4c-9dd5-41aa84eed160')
        setParameter('appId', 'e7bcd186-a5fd-410d-92cb-6876a42288bd')
        setParameter('GCMSenderId', '345127537656')
        setParameter('basicToken', 'Basic ZmRjODVjMDAtMGEyZi00YzY0LWJjYjQtMmNmYjE1MDA3MzBhOnNlY3JldA==')
    if getParameter('brand') == 'hyundai':
        setParameter('host', 'prd.eu-ccapi.hyundai.com:8080')
        setParameter('baseUrl', 'https://' + getParameter('host'))
        setParameter('clientId', '6d477c38-3ca4-4cf3-9557-2a1929a94654')
        setParameter('authClientId', '64621b96-0f0d-11ec-82a8-0242ac130003')
        setParameter('appId', '014d2225-8495-4735-812d-2616334fd15d')
        setParameter('GCMSenderId', '414998006775')
        setParameter('basicToken', 'Basic NmQ0NzdjMzgtM2NhNC00Y2YzLTk1NTctMmExOTI5YTk0NjU0OktVeTQ5WHhQekxwTHVvSzB4aEJDNzdXNlZYaG10UVI5aVFobUlGampvWTRJcHhzVg==')
    
    return
Example #4
0
def getStatusCached(vehicleId):
    soclogging.logDebug(2, "Receiving cached status")

    statusDict = {}

    url = parameters.getParameter(
        'baseUrl') + '/api/v2/spa/vehicles/' + vehicleId + '/status/latest'
    headers = {
        'Authorization': parameters.getParameter('controlToken'),
        'ccsp-device-id': parameters.getParameter('deviceId'),
        'Content-Type': 'application/json',
        'Stamp': stamps.getStamp()
    }

    try:
        response = kiahttp.getHTTP(
            url=url,
            headers=headers,
            timeout=parameters.getParameter('reqTimeout'))
    except:
        raise

    try:
        responseDict = json.loads(response)
    except:
        soclogging.logDebug(
            1, "Receiving cached status failed, invalid response")
        soclogging.logDebug(2, response)
        raise

    try:
        statusDict['soc12v'] = int(responseDict['resMsg']['vehicleStatusInfo']
                                   ['vehicleStatus']['battery']['batSoc'])
    except:
        statusDict['soc12v'] = 100
        pass

    try:
        statusDict['time'] = timeToStamp(
            responseDict['resMsg']['vehicleStatusInfo']['vehicleStatus']
            ['time'])
        statusDict['socev'] = int(
            responseDict['resMsg']['vehicleStatusInfo']['vehicleStatus']
            ['evStatus']['batteryStatus'])
        statusDict['vehicleLocation'] = responseDict['resMsg'][
            'vehicleStatusInfo']['vehicleLocation']
        statusDict['vehicleStatus'] = responseDict['resMsg'][
            'vehicleStatusInfo']['vehicleStatus']
        statusDict['odometer'] = responseDict['resMsg']['vehicleStatusInfo'][
            'odometer']
    except:
        soclogging.logDebug(
            1, "Receiving cached status failed, invalid response")
        soclogging.logDebug(2, response)
        raise

    return statusDict
Example #5
0
def getVehicleId(vin):
    soclogging.logDebug(2, "Requesting vehicle list")

    url = parameters.getParameter('baseUrl') + '/api/v1/spa/vehicles'
    headers = {
        'Authorization':
        parameters.getParameter('tokenType') + ' ' +
        parameters.getParameter('accessToken'),
        'ccsp-device-id':
        parameters.getParameter('deviceId'),
        'ccsp-application-id':
        parameters.getParameter('appId'),
        'offset':
        '1',
        'Host':
        parameters.getParameter('host'),
        'Connection':
        'close',
        'Accept-Encoding':
        'gzip, deflate',
        'User-Agent':
        'okhttp/3.10.0',
        'Stamp':
        stamps.getStamp()
    }

    try:
        response = kiahttp.getHTTP(
            url=url,
            headers=headers,
            timeout=parameters.getParameter('reqTimeout'))
    except:
        raise

    vehicleId = ''
    try:
        responseDict = json.loads(response)
        for vehicle in responseDict['resMsg']['vehicles']:
            if vehicle['vin'] == vin:
                vehicleId = vehicle['vehicleId']
    except:
        soclogging.logDebug(1, "Vehicle request failed, invalid response")
        soclogging.logDebug(2, response)
        raise

    if vehicleId == '':
        soclogging.logDebug(1, "VIN " + vin + " unknown")
        raise

    soclogging.logDebug(2, "VehicleId = " + vehicleId)

    return vehicleId
Example #6
0
def getCookies():
    soclogging.logDebug(2, "Get cookies for login")

    url = parameters.getParameter('baseUrl') + '/api/v1/user/oauth2/authorize?response_type=code&state=test&client_id=' + \
        parameters.getParameter('clientId') + '&redirect_uri=' + \
        parameters.getParameter('baseUrl') + '/api/v1/user/oauth2/redirect'

    try:
        cookies = kiahttp.getHTTPCookies(url)
    except:
        raise

    return cookies
Example #7
0
def getAuthToken(authCode):
    soclogging.logDebug(2, "Requesting access token")

    url = parameters.getParameter('baseUrl') + '/api/v1/user/oauth2/token'
    data = 'grant_type=authorization_code&redirect_uri=' + parameters.getParameter(
        'baseUrl') + '%2Fapi%2Fv1%2Fuser%2Foauth2%2Fredirect&code=' + authCode
    headers = {
        'Authorization': parameters.getParameter('basicToken'),
        'Content-type': 'application/x-www-form-urlencoded',
        'Content-Length': str(len(data)),
        'Host': parameters.getParameter('host'),
        'Connection': 'close',
        'Accept-Encoding': 'gzip, deflate',
        'User-Agent': 'okhttp/3.10.0'
    }

    try:
        response = kiahttp.postHTTP(
            url=url,
            headers=headers,
            data=data,
            timeout=parameters.getParameter('reqTimeout'))
    except:
        raise

    try:
        accessToken = json.loads(response)
    except:
        soclogging.logDebug(0, "Token request failed, invalid response")
        soclogging.logDebug(2, response)
        raise

    soclogging.logDebug(2, "Access token = " + accessToken['access_token'])

    return accessToken
Example #8
0
def isTimerExpired():
    now = int(time.time())
    secLeft = (state.getState('lastRun') +
               (parameters.getParameter('timerInterval') * 60)) - now

    if secLeft < 0:
        trigger = 1
        soclogging.logDebug(1, "SoC download triggered by timer")
    else:
        trigger = 0
        soclogging.logDebug(
            2, "Next Update: " + '{:.1f}'.format(secLeft / 60) + " minutes")

    return trigger
Example #9
0
def refreshAccessToken(refreshToken):
    soclogging.logDebug(2, "Refreshing access token")

    url = parameters.getParameter('baseUrl') + '/api/v1/user/oauth2/token'
    data = 'grant_type=refresh_token&redirect_uri=https://www.getpostman.com/oauth2/callback&refresh_token=' + refreshToken
    headers = {
        'Authorization': parameters.getParameter('basicToken'),
        'Content-type': 'application/x-www-form-urlencoded',
        'Content-Length': str(len(data)),
        'Host': parameters.getParameter('host'),
        'Connection': 'close',
        'Accept-Encoding': 'gzip, deflate',
        'User-Agent': 'okhttp/3.10.0'
    }

    try:
        response = kiahttp.postHTTP(
            url=url,
            headers=headers,
            data=data,
            timeout=parameters.getParameter('reqTimeout'))
    except:
        raise

    try:
        accessToken = json.loads(response)
        accessToken['refresh_token'] = refreshToken
    except:
        soclogging.logDebug(0, "Token request failed, invalid response")
        soclogging.logDebug(2, response)
        raise

    soclogging.logDebug(2, "Access token = " + accessToken['access_token'])

    return accessToken
Example #10
0
def pushABRP(soc):
    now = int(time.time())
    apiKey = "49589dbf-37a8-4c22-a49c-7d62fe1a6531"
    userToken = parameters.getParameter('abrpToken')

    soclogging.logDebug(2, "Submitting ABRP-Data")

    url = "https://api.iternio.com/1/tlm/send?api_key=" + requests.utils.quote(
        apiKey) + "&token=" + requests.utils.quote(userToken)
    data = {'tlm': {'utc': now, 'soc': soc, 'is_charging': state.isCharging()}}

    try:
        response = requests.post(url, json=data)
    except requests.Timeout as err:
        soclogging.logDebug(1, "ABRP - Connection Timeout")
        pass
    except:
        soclogging.logDebug(1, "ABRP - HTTP Error")
        pass

    if response.status_code != 200:
        soclogging.logDebug(
            1, 'ABRP - Request failed, StatusCode: ' +
            str(response.status_code) + ' - Error: ' + str(response.text))

    return
Example #11
0
def getHTTPCookies(url):
    try:
        session = requests.Session()
        response = session.get(url)
    except requests.Timeout as err:
        soclogging.logDebug(1, "Connection Timeout")
        raise    
    
    if response.status_code == 200:
        cookies = session.cookies.get_dict()
    else:
        soclogging.logDebug(1, "Receiving cookies failed, StatusCode: " + str(response.status_code))
        raise
        
    return cookies
Example #12
0
def isExternalTriggered():
    trigger = 0

    try:
        f = open(parameters.getParameter('timerFile'), 'r')
        ticksLeft = int(f.read())
        f.close()
    except:
        ticksLeft = 0
        pass

    if ticksLeft > 0:
        trigger = 1
        soclogging.logDebug(1, "SoC download triggered externally")

    return trigger
Example #13
0
def doPrewakeup(vehicleId):
    soclogging.logDebug(2, "Triggering Pre-Wakeup")

    url = parameters.getParameter(
        'baseUrl') + '/api/v1/spa/vehicles/' + vehicleId + '/control/engine'
    data = {
        "action": "prewakeup",
        "deviceId": parameters.getParameter('deviceId')
    }
    headers = {
        'Authorization':
        parameters.getParameter('tokenType') + ' ' +
        parameters.getParameter('accessToken'),
        'ccsp-device-id':
        parameters.getParameter('deviceId'),
        'ccsp-application-id':
        parameters.getParameter('appId'),
        'offset':
        '1',
        'Content-Type':
        'application/json;charset=UTF-8',
        'Content-Length':
        str(len(data)),
        'Host':
        parameters.getParameter('host'),
        'Connection':
        'close',
        'Accept-Encoding':
        'gzip, deflate',
        'User-Agent':
        'okhttp/3.10.0',
        'Stamp':
        stamps.getStamp()
    }

    try:
        response = kiahttp.postHTTP(
            url=url,
            data=data,
            headers=headers,
            timeout=parameters.getParameter('statusTimeout'))
    except:
        raise

    return
Example #14
0
def setLanguage(cookies):
    soclogging.logDebug(2, "Setting language")

    url = parameters.getParameter('baseUrl') + '/api/v1/user/language'
    headers = {'Content-type': 'application/json'}
    data = {"lang": "en"}

    try:
        response = kiahttp.postHTTP(
            url=url,
            data=data,
            headers=headers,
            cookies=cookies,
            timeout=parameters.getParameter('reqTimeout'))
    except:
        raise

    return
Example #15
0
def main():
    try:
        initialize(str(sys.argv[1]))

        lock.checkLockFile()
        lock.createLockFile()
    except:
        exit(1)

    soclogging.logDebug(1, "-------------------------------")
    soclogging.logDebug(1, "Kia/Hyundai SoC Module starting")

    try:
        state.saveUnplugState()
        state.saveChargedState()

        if trigger.isDownloadTriggered() == 1:
            soc.doExternalUpdate()
        elif parameters.getParameter('manualCalc') == 1:
            if state.isCharging() == 1:
                soclogging.logDebug(2, "Manual calculation starting")
                soc.doManualUpdate()
        else:
            soclogging.logDebug(2, "Nothing to do yet")
    except:
        pass

    try:
        state.saveTickTime()
    except:
        pass

    soclogging.logDebug(1, "Kia/Hyundai SoC Module ending")

    try:
        lock.purgeLockFile()
    except:
        exit(1)
        raise

    exit(0)
Example #16
0
def postHTTP(url = '', data = '', headers = '', cookies = '', timeout = 30, allow_redirects = True):
    global lastCookies
    global lastUrl
    
    try:
        if isinstance(data, dict):
            response = requests.post(url, json = data, headers = headers, cookies = cookies, timeout = timeout, allow_redirects = allow_redirects)
        else:
            response = requests.post(url, data = data, headers = headers, cookies = cookies, timeout = timeout, allow_redirects = allow_redirects)        
    except requests.Timeout as err:
        soclogging.logDebug(1, "Connection Timeout")
        raise
    except:
        soclogging.logDebug(1, "HTTP Error")
        raise
    
    if response.status_code == 200 or response.status_code == 204:
        lastUrl = response.url
        return response.text
    else:
        try:
            responseDict = json.loads(response.text)
            if response.status_code == 408:
                errorString = "[" + responseDict['resCode'] + "] " + responseDict['resMsg']
            else:
                errorString = "[" + responseDict['errCode'] + "] " + responseDict['errMsg']
        except:
            errorString = "[XXXX] Unidentified Error"
        soclogging.logDebug(1, 'Request failed, StatusCode: ' + str(response.status_code) + ', Error: ' + errorString)
        raise RuntimeError
        
    return
Example #17
0
def getHTTP(url = '', headers = '', cookies = '', timeout = 30):
    global lastCookies
    global lastUrl
    
    try:
        response = requests.get(url, headers = headers, cookies = cookies, timeout = timeout)        
    except requests.Timeout as err:
        soclogging.logDebug(1, "Connection Timeout")
        raise
    except:
        soclogging.logDebug(1, "HTTP Error")
        raise
    
    if response.status_code == 200 or response.status_code == 204:
        lastCookies = response.cookies.get_dict()
        return response.text
    else:
        try:
            responseDict = json.loads(response.text)
            if response.status_code == 400 or response.status_code == 408 or response.status_code == 503:
                errorString = "[" + responseDict['resCode'] + "] " + responseDict['resMsg']
            else:
                errorString = "[" + responseDict['errCode'] + "] " + responseDict['errMsg']
        except:
            errorString = "[XXXX] Unidentified Error" + " " + response.text
        soclogging.logDebug(1, 'Request failed, StatusCode: ' + str(response.status_code) + ', Error: ' + errorString)
        raise RuntimeError
        
    return
Example #18
0
def loadBrandData():
    vin = getParameter('vehicleVin')

    if vin[:2] == 'KN' or vin[:3] == 'U5Y' or vin[:3] == 'U6Z':
        setParameter('brand', 'kia')
        #soclogging.logDebug(2, "Vehicle identified as Kia")
    elif vin[:3] == 'KMH' or vin[:3] == 'TMA':
        setParameter('brand', 'hyundai')
        #soclogging.logDebug(2, "Vehicle identified as Hyundai")
    else:
        setParameter('brand', '')
        soclogging.logDebug(2, "Vehicle WMI unknown")
        raise RuntimeError

    if getParameter('brand') == 'kia':
        setParameter('host', 'prd.eu-ccapi.kia.com:8080')
        setParameter('baseUrl', 'https://' + getParameter('host'))
        setParameter('clientId', 'fdc85c00-0a2f-4c64-bcb4-2cfb1500730a')
        setParameter('authClientId', 'f4d531c7-1043-444d-b09a-ad24bd913dd4')
        setParameter('appId', 'e7bcd186-a5fd-410d-92cb-6876a42288bd')
        setParameter(
            'basicToken',
            'Basic ZmRjODVjMDAtMGEyZi00YzY0LWJjYjQtMmNmYjE1MDA3MzBhOnNlY3JldA=='
        )
    if getParameter('brand') == 'hyundai':
        setParameter('host', 'prd.eu-ccapi.hyundai.com:8080')
        setParameter('baseUrl', 'https://' + getParameter('host'))
        setParameter('clientId', '6d477c38-3ca4-4cf3-9557-2a1929a94654')
        setParameter('authClientId', '97516a3c-2060-48b4-98cd-8e7dcd3c47b2')
        setParameter('appId', '99cfff84-f4e2-4be8-a5ed-e5b755eb6581')
        setParameter(
            'basicToken',
            'Basic NmQ0NzdjMzgtM2NhNC00Y2YzLTk1NTctMmExOTI5YTk0NjU0OktVeTQ5WHhQekxwTHVvSzB4aEJDNzdXNlZYaG10UVI5aVFobUlGampvWTRJcHhzVg=='
        )

    return
Example #19
0
def pushABRP(soc):
    now = int(time.time())
    apiKey = "49589dbf-37a8-4c22-a49c-7d62fe1a6531"
    userTokenArray = parameters.getParameter('abrpToken').split(';')

    soclogging.logDebug(2, "Submitting ABRP-Data")

    for userToken in userTokenArray:
        url = "https://api.iternio.com/1/tlm/send?api_key=" + \
            requests.utils.quote(apiKey) + "&token=" + requests.utils.quote(userToken)
        data = {
            'tlm': {
                'utc': now,
                'soc': soc,
                'is_charging': state.isCharging()
            }
        }

        try:
            f = open(parameters.getParameter('auxDataFile'), 'r')
            auxData = json.loads(f.read())
            f.close()
            data['tlm']['odometer'] = auxData['odometer']['value']
            data['tlm']['lat'] = auxData['vehicleLocation']['coord']['lat']
            data['tlm']['lon'] = auxData['vehicleLocation']['coord']['lon']
            data['tlm']['speed'] = auxData['vehicleLocation']['speed']['value']
            data['tlm']['is_parked'] = auxData['vehicleStatus']['doorLock']
        except:
            pass

        try:
            response = requests.post(url, json=data)
        except requests.Timeout as err:
            soclogging.logDebug(1, "ABRP - Connection Timeout")
            pass
        except:
            soclogging.logDebug(1, "ABRP - HTTP Error")
            pass

        if response.status_code != 200:
            soclogging.logDebug(
                1, 'ABRP - Request failed, StatusCode: ' +
                str(response.status_code) + ' - Error: ' + str(response.text))

    return
Example #20
0
def getControlToken(pin):
    soclogging.logDebug(2, "Sending PIN")

    url = parameters.getParameter('baseUrl') + '/api/v1/user/pin'
    data = {"deviceId": parameters.getParameter('deviceId'), "pin": pin}
    headers = {
        'Authorization':
        parameters.getParameter('tokenType') + ' ' +
        parameters.getParameter('accessToken'),
        'Content-type':
        'application/json;charset=UTF-8',
        'Content-Length':
        str(len(data)),
        'Host':
        parameters.getParameter('host'),
        'Connection':
        'close',
        'Accept-Encoding':
        'gzip, deflate',
        'User-Agent':
        'okhttp/3.10.0'
    }

    try:
        response = kiahttp.putHTTP(
            url=url,
            data=data,
            headers=headers,
            timeout=parameters.getParameter('reqTimeout'))
    except:
        raise

    try:
        responseDict = json.loads(response)
        controlToken = 'Bearer ' + responseDict['controlToken']
    except:
        soclogging.logDebug(1, "Sending PIN failed, invalid response")
        soclogging.logDebug(2, response)
        raise

    soclogging.logDebug(2, "Control token = " + controlToken)

    return controlToken
Example #21
0
def getDeviceId():
    soclogging.logDebug(2, "Requesting DeviceId")

    url = parameters.getParameter(
        'baseUrl') + '/api/v1/spa/notifications/register'
    data = {
        "pushRegId": parameters.getParameter('GCMSenderId'),
        "pushType": "GCM",
        "uuid": str(uuid.uuid1())
    }
    headers = {
        'ccsp-service-id': parameters.getParameter('clientId'),
        'Content-type': 'application/json;charset=UTF-8',
        'Content-Length': str(len(data)),
        'Host': parameters.getParameter('host'),
        'Connection': 'close',
        'Accept-Encoding': 'gzip, deflate',
        'User-Agent': 'okhttp/3.10.0',
        'Stamp': stamps.getStamp()
    }

    try:
        response = kiahttp.postHTTP(
            url=url,
            data=data,
            headers=headers,
            timeout=parameters.getParameter('reqTimeout'))
    except:
        raise

    try:
        responseDict = json.loads(response)
        deviceId = responseDict['resMsg']['deviceId']
    except:
        soclogging.logDebug(1, "Could not receive DeviceId, invalid response")
        soclogging.logDebug(2, response)
        raise

    soclogging.logDebug(2, "DeviceId = " + deviceId)

    return deviceId
Example #22
0
def doManualUpdate():
    try:
        f = open(parameters.getParameter('meterFile'), 'r')
        currentMeter = float(f.read())
        f.close()
    except:
        soclogging.logDebug(2, "Could not find current meter file")
        raise

    try:
        lastMeter = state.getState('lastMeter')
        lastSoc = state.getState('lastSoc')
        f.close()
    except:
        raise

    batterySize = parameters.getParameter('batterySize')
    efficiency = parameters.getParameter('efficiency')
    meterDiff = currentMeter - lastMeter
    meterDiffEff = meterDiff * (efficiency / 100)
    socDiff = 100 * (meterDiffEff / batterySize)
    newSoc = int(max(min(lastSoc + socDiff, 100), 1))

    soclogging.logDebug(
        2, "Charged since last update: " + '{:.3f}'.format(meterDiff) +
        " kWh = " + '{:.3f}'.format(meterDiffEff) + " kWh @ " +
        '{:.0f}'.format(efficiency) + "% efficency")
    soclogging.logDebug(
        2, "Charged since last update: " + '{:.3f}'.format(meterDiffEff) +
        " kWh of " + '{:.0f}'.format(batterySize) + " kWh = " +
        '{:.2f}'.format(socDiff) + "% SoC")
    soclogging.logDebug(
        1, "Estimated SoC: " + '{:.0f}'.format(lastSoc) +
        "% (last update) + " + '{:.2f}'.format(socDiff) +
        "% (extrapolation) = " + '{:.0f}'.format(newSoc) + "% SoC")

    saveSoc(newSoc, 1)

    return
Example #23
0
def DownloadSoC():
    soclogging.logDebug(0, "SoC download starting")
    now = int(time.time())

    auxData = {}

    try:
        kiaauth.updateAuthToken()
        kiaauth.requestNewControlToken()
    except:
        soclogging.logDebug(0, "Login failed")
        raise

    try:
        vehicleId = kiaif.getVehicleId(parameters.getParameter('vehicleVin'))
        status = kiaif.getStatusCached(vehicleId)
    except:
        soclogging.logDebug(0, "Collecting data from server failed")
        raise

    try:
        auxData['vehicleLocation'] = status['vehicleLocation']
        auxData['vehicleStatus'] = status['vehicleStatus']
        auxData['odometer'] = status['odometer']
    except:
        pass

    if (now - status['time']) < (
            parameters.getParameter('cacheValid')) and status['socev'] > 0:
        soclogging.logDebug(2, "Cached data is current")
    else:
        if status['soc12v'] < parameters.getParameter('soc12vLimit'):
            soclogging.logDebug(
                0, "12 V-battery low - 12 V-SoC: " + cachedStatus['soc12v'] +
                " %; Download cancelled")
            raise RuntimeError

        try:
            kiaif.doPrewakeup(vehicleId)
            status = kiaif.getStatusFull(vehicleId)
        except:
            soclogging.logDebug(0, "Collecting data from vehicle failed")
            raise

        try:
            auxData['vehicleStatus'] = status['vehicleStatus']
        except:
            pass

    if status['soc12v'] >= 80:
        soclogging.logDebug(
            2, "Received SoC (12 V-battery): " + str(status['soc12v']) + "%")
    elif status['soc12v'] >= 70 and status['soc12v'] < 80:
        soclogging.logDebug(
            1, "Received SoC (12 V-battery): " + str(status['soc12v']) + "%")
    elif status['soc12v'] < 70:
        soclogging.logDebug(
            0, "Received SoC (12 V-battery): " + str(status['soc12v']) + "%")

    soc = status['socev']
    soclogging.logDebug(0, "Received SoC (HV-battery): " + str(soc) + "%")

    try:
        f = open(parameters.getParameter('auxDataFile'), 'w')
        f.write(json.dumps(auxData))
        f.close()
    except:
        pass

    soclogging.logDebug(1, "SoC download ending")

    return soc
Example #24
0
def getAuthCode(cookies):
    soclogging.logDebug(2, "Sending username/password")

    url = parameters.getParameter('baseUrl') + '/api/v1/user/integrationinfo'
    headers = {'Content-type': 'application/json'}

    try:
        response = kiahttp.getHTTP(
            url=url,
            headers=headers,
            cookies=cookies,
            timeout=parameters.getParameter('reqTimeout'))
    except:
        raise

    try:
        responseDict = json.loads(response)
        userId = responseDict['userId']
        serviceId = responseDict['serviceId']
        soclogging.logDebug(2, "UserId = " + userId)
        soclogging.logDebug(2, "ServiceId = " + serviceId)
    except:
        soclogging.logDebug(0, "Login failed, invalid response")
        soclogging.logDebug(2, response)
        raise

    url = 'https://eu-account.' + parameters.getParameter(
        'brand'
    ) + '.com/auth/realms/eu' + parameters.getParameter(
        'brand'
    ) + 'idm/protocol/openid-connect/auth?client_id=' + parameters.getParameter(
        'authClientId'
    ) + '&scope=openid%20profile%20email%20phone&response_type=code&hkid_session_reset=true&redirect_uri=' + parameters.getParameter(
        'baseUrl'
    ) + '/api/v1/user/integration/redirect/login&ui_locales=en&state=' + serviceId + ':' + userId
    headers = {}

    try:
        response = kiahttp.getHTTP(
            url=url,
            headers=headers,
            cookies=cookies,
            timeout=parameters.getParameter('reqTimeout'))
    except:
        raise

    left = response.find('action="') + 8
    right = response.find('"', left)
    url = response[left:right].replace('&amp;', '&')
    data = urlparse.urlencode({
        'username':
        parameters.getParameter('accountName'),
        'password':
        parameters.getParameter('accountPassword'),
        'credentialId':
        '',
        'rememberMe':
        'on'
    })
    headers = {
        'Content-type':
        'application/x-www-form-urlencoded',
        'User-Agent':
        'Mozilla/5.0 (iPhone; CPU iPhone OS 11_1 like Mac OS X) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0 Mobile/15B92 Safari/604.1'
    }
    cookiesForm = {'AUTH_SESSION_ID': kiahttp.lastCookies['AUTH_SESSION_ID']}

    try:
        response = kiahttp.postHTTP(
            url=url,
            data=data,
            headers=headers,
            cookies=cookiesForm,
            timeout=parameters.getParameter('reqTimeout'))
        parsed = urlparse.urlparse(kiahttp.lastUrl)
        intUserId = ''.join(parse_qs(parsed.query)['intUserId'])
        soclogging.logDebug(2, "intUserId = " + intUserId)
    except:
        soclogging.logDebug(0, "Login failed, invalid response")
        soclogging.logDebug(2, response)
        raise

    url = parameters.getParameter('baseUrl') + '/api/v1/user/silentsignin'
    headers = {'Content-type': 'application/json'}
    data = {'intUserId': intUserId}

    try:
        response = kiahttp.postHTTP(
            url=url,
            data=data,
            headers=headers,
            cookies=cookies,
            timeout=parameters.getParameter('reqTimeout'),
            allow_redirects=False)
        responseDict = json.loads(response)
        responseUrl = responseDict['redirectUrl']
        parsed = urlparse.urlparse(responseUrl)
        authCode = ''.join(parse_qs(parsed.query)['code'])
    except:
        soclogging.logDebug(0, "Login failed, invalid response")
        soclogging.logDebug(2, response)
        raise

    soclogging.logDebug(2, "AuthCode = " + authCode)

    return authCode