def save_vehicledata(self, data): vehicledata = self.populate_vehicledata(data) try: self._logger.info( "SaveVehicleData: Vehicle data for referenceid: {} programcode: {} data: {}" .format(vehicledata.referenceid, vehicledata.programcode, data), extra={ "programcode": vehicledata.programcode, "referenceid": vehicledata.referenceid, "action": "SaveVehicleData", }, ) # Create an vehicle data item. vehicle_table = self._Table( request_key=vehicledata.programcode + "-" + vehicledata.referenceid, event_datetime=get_utc_epoch(), referenceid=vehicledata.referenceid, programcode=vehicledata.programcode, timestamp=datetime.now(), vin=vehicledata.vin, language=vehicledata.language, longitude=float(vehicledata.longitude), latitude=float(vehicledata.latitude), ) # Save the data in dynamodb vehicle_table.save() hexvaluedata = self.populate_hex( vehicledata.referenceid, vehicledata.latitude, vehicledata.longitude, vehicledata.vin, vehicledata.language, ) hexdata = VehicleHexData(Value=hexvaluedata) vehicledata.hexvehicledata = hexdata vehicledata.status = InternalStatusType.SUCCESS vehicledata.responsemessage = "Successfully Saved." return vehicledata except Exception as e: self._logger.error( "SaveVehicleData: error occured: {}".format(e), exc_info=True, stack_info=True, extra={ "programcode": vehicledata.programcode, "referenceid": vehicledata.referenceid, "action": "SaveVehicleData", }, ) vehicledata.responsemessage = e.args[0] vehicledata.status = InternalStatusType.INTERNALSERVERERROR return vehicledata
def map_supplementtable( msisdn: str, programcode: ProgramCode, request: VehicleDataRequest, tblsupplement: ConnectedVehicleSupplementTable, ): return tblsupplement( msisdn=msisdn, programcode=programcode, request_key="{}-{}".format(programcode, msisdn), timestamp=convert_epoch_to_utc_timestamp(int(request.timestamp)), event_datetime=get_utc_epoch(), registrationnumber=request.vehicleData.registration.number, registrationstatecode=request.vehicleData.registration.stateCode, registrationcountrycode=request.vehicleData.registration.countryCode, crankinhibition=float(request.vehicleData.crankInhibition), ignitionkey=request.vehicleData.ignitionKey, evbatterypercentage=request.vehicleData.evBatteryPercentage, fuellevelpercentage=float(request.vehicleData.fuelLevelPercentage), range=int(request.vehicleData.range.value), rangeunit=request.vehicleData.range.unit, tirepressureunit=request.vehicleData.tyrePressureDelta.unit, tirepressurefrontleft=float( request.vehicleData.tyrePressureDelta.frontLeft), tirepressurefrontright=float( request.vehicleData.tyrePressureDelta.frontRight), tirepressurerearleft=float( request.vehicleData.tyrePressureDelta.rearLeft), tirepressurerearright=float( request.vehicleData.tyrePressureDelta.rearRight), )
def map_primarytable( msisdn: str, programcode: ProgramCode, vehicledata: VehicleDataRequest, custom_extension: CustomExtension, tblprimary: ConnectedVehicleTable, ): return tblprimary( msisdn=msisdn, programcode=programcode, request_key="{}-{}".format(programcode, msisdn), countrycode=custom_extension.vehicleInfo.country, eventid=vehicledata.EventID, language=custom_extension.vehicleInfo.language, servicetype=vehicledata.Data.bcallType, timestamp=convert_epoch_to_utc_timestamp(vehicledata.Timestamp), event_datetime=get_utc_epoch(), # UTC epoch latitude=float( custom_extension.vehicleInfo.vehicleLocation. positionLatitude if custom_extension.vehicleInfo.vehicleLocation. positionLatitude is not None else vehicledata.Data.latitude), longitude=float( custom_extension.vehicleInfo.vehicleLocation. positionLongitude if custom_extension.vehicleInfo.vehicleLocation. positionLongitude is not None else vehicledata.Data.longitude), altitude=str( custom_extension.vehicleInfo.vehicleLocation.positionAltitude) if custom_extension.vehicleInfo.vehicleLocation.positionAltitude is not None else None, vin=custom_extension.vehicleInfo.vin, brand=custom_extension.vehicleInfo.brand, modelname=custom_extension.vehicleInfo.model, modelyear=custom_extension.vehicleInfo.year, calltype=custom_extension.calltype, vehicletype=custom_extension.vehicleInfo.vehicleType, enginestatus=custom_extension.vehicleInfo.engineStatusEnum, odometer=custom_extension.vehicleInfo.odometer, positiondirection="{}".format( custom_extension.vehicleInfo.vehicleLocation.positionDirection), vehiclespeed=custom_extension.vehicleInfo.vehicleSpeed, callreason=vehicledata.Data.callReason, calltrigger=vehicledata.Data.callTrigger, )
def map_primarytable( msisdn: str, programcode: ProgramCode, request: VehicleDataRequest, tblprimary: ConnectedVehicleTable, savevehicledata: Json, ): return tblprimary( msisdn=msisdn, programcode=programcode, request_key="{}-{}".format(programcode, msisdn), countrycode=request.countryCode, timestamp=convert_epoch_to_utc_timestamp(int(request.timestamp)), event_datetime=get_utc_epoch(), # UTCs epoch latitude=float(request.gpsData.latitude), longitude=float(request.gpsData.longitude), vin=request.vehicleData.vin, brand=programcode.upper(), mileage=int(request.vehicleData.mileage.value), mileageunit=request.vehicleData.mileage.unit, JSONData=savevehicledata, )
def get_vehicledata(self, msisdn: str, programcode: ProgramCode): try: self._logger.info( "GetVehicleData: Payload received for msisdn: {} programcode: {}" .format(msisdn, programcode), extra={ "programcode": programcode, "msisdn": msisdn, "action": "GetVehicleData", "cts-version": CtsVersion.TWO_DOT_ZERO, }, ) if not self._config.base_url.endswith("/"): self._config.base_url = "{url}{suffix}".format( url=self._config.base_url, suffix="/") dataresponse = None # check and get data from database based of db check flag if self._config.dynamodb_check_enable: dataresponse = get_data_from_database(self, msisdn, programcode, CtsVersion.TWO_DOT_ZERO) if dataresponse is not None: return dataresponse else: response = requests.get( "{serviceurl}{msisdn}".format( serviceurl=self._config.base_url, msisdn=msisdn), verify=self._config.root_cert, ) self._logger.info( "GetVehicleData: Response from vordel for msisdn: {} is: " "status_code: {}, response_text: {}, response_reason: {}". format(msisdn, response.status_code, response.text, response.reason), extra={ "programcode": programcode, "msisdn": msisdn, "response": str(response), "action": "GetVehicleData", "cts-version": CtsVersion.TWO_DOT_ZERO, }, ) validjsonresponse = ( response.headers.get("content-type") is not None and "json" in response.headers.get("content-type").lower()) if (response.status_code == HTTP_200_OK and validjsonresponse and checkjsonnode("data", response.json())): responsejson = response.json()["data"] self._logger.info( "GetVehicleData: Successfully received response for msisdn:{} status:{} programcode:{} response_payload:{}" .format(msisdn, Status.SUCCESS, programcode, responsejson), extra={ "programcode": programcode, "msisdn": msisdn, "action": "GetVehicleData", "cts-version": CtsVersion.TWO_DOT_ZERO, }, ) vehicledata = VehicleData( status=InternalStatusType.SUCCESS, responsemessage="Successfully retrieved", msisdn=msisdn, programcode=programcode, event_datetime=get_utc_epoch(), calldate=responsejson["callDate"], calltime=responsejson["callTime"], timestamp=datetime.strptime( "{} {}".format(responsejson["callDate"], responsejson["callTime"]), "%Y-%m-%d %H:%M", ), odometer=responsejson["odometer"], odometerscale=OdometerScale( responsejson["odometerScale"]), activationtype=responsejson["activationType"], latitude=responsejson["location"]["latitude"], longitude=responsejson["location"]["longitude"], headingdirection=responsejson["location"] ["headingDirection"], vin=responsejson["vehicle"]["vin"], brand=responsejson["vehicle"]["brand"], modelname=responsejson["vehicle"]["modelName"], modelyear=responsejson["vehicle"]["modelYear"], modelcode=responsejson["vehicle"]["modelCode"], modeldesc=responsejson["vehicle"]["modelDesc"], market=responsejson["vehicle"]["ocuSim"]["market"], ) # Save the data in dynamodb for audit and return the model on success self.save_vehicledata(msisdn, programcode, vehicledata) return vehicledata errorjson = (response.json()["error"] if validjsonresponse and checkjsonnode("error", response.json()) else seterrorjson(response.reason, response.text)) errorstatus = internalstatustype_conversion( errorjson["status"]) self._logger.error( "GetVehicleData: Error occurred for msisdn:{} status:{} programcode:{} error_response_payload:{}" .format( msisdn, errorstatus, programcode, errorjson if validjsonresponse else "ErrorResponse {}".format(response), ), exc_info=True, stack_info=True, extra={ "programcode": programcode, "msisdn": msisdn, "action": "GetVehicleData", "cts-version": CtsVersion.TWO_DOT_ZERO, }, ) return VehicleData( status=errorstatus, responsemessage="{code}{description}".format( code=errorjson["errorCode"] if checkjsonnode( "errorCode", errorjson) else "", description=", {}".format( errorjson["errorDescription"]) if checkjsonnode( "errorDescription", errorjson) else "", ), ) except Exception as e: self._logger.error( "GetVehicleData: Gateway error: Aeris: Error Occured: {} for msisdn: {}" .format(e, msisdn), exc_info=True, stack_info=True, extra={ "programcode": programcode, "msisdn": msisdn, "action": "GetVehicleData", "cts-version": CtsVersion.TWO_DOT_ZERO, }, ) return VehicleData( status=InternalStatusType.INTERNALSERVERERROR, responsemessage=e.args[0] if e.args.__len__() > 0 else None, )
def test_get_utc_epoch_returns_valid_utc_timestamp(): utc_epoch = get_utc_epoch() utc_dt = datetime.utcnow() assert convert_epoch_to_utc_timestamp(utc_epoch).strftime( "%Y-%m-%dT%H:%M:%S") == utc_dt.strftime("%Y-%m-%dT%H:%M:%S")
def get_vehicledata_for_config_enabled_client_only( self, id: str, programcode: ProgramCode, ctsversion: CtsVersion ): try: self._logger.info( "GetVehicleData: Read Vehicle data from DynamoDB for id: {} programcode: {}".format( id, programcode ), extra={ "programcode": programcode, "id": id, "action": "GetVehicleData", "cts-version": ctsversion, }, ) dynamodb_check_timelimit = ( self._config.dynamodb_check_timelimit if isnotnull_whitespaceorempty(self._config.dynamodb_check_timelimit) else 0 ) if ( self._config.dynamodb_check_enable and dynamodb_check_timelimit > 0 and isnotnull_whitespaceorempty(id) ): # Query for Items Matching current timestamp within given time limit and Partition/Sort Key in descending order for dataresponse in self._Table.query( hash_key=programcode + "-" + id, range_key_condition=self._Table.event_datetime.between( convert_utc_timestamp_to_epoch( datetime.utcnow() - timedelta(minutes=dynamodb_check_timelimit) ), get_utc_epoch(), ), scan_index_forward=False, limit=1, ): if dataresponse: self._logger.info( "GetVehicleData: Successfully retrieved vehicle data from DynamoDB for id: {} programcode: {}".format( id, programcode ), extra={ "programcode": programcode, "id": id, "action": "GetVehicleData", "cts-version": ctsversion, }, ) return dataresponse else: return None return None return None except Exception as e: self._logger.error( "GetVehicleData: Error retrieving data from DynamoDB for id:{} e:{}".format( id, e ), exc_info=True, stack_info=True, extra={ "id": id, "programcode": programcode, "cts-version": ctsversion, "action": "GetVehicleData", }, ) return None
def map_vehicledata_response(msisdn, programcode, response_status, response): return VehicleData( msisdn=msisdn, status=response_status, programcode=programcode, calldate=response["CallDate"] if ("CallDate") in response and isnotnull_whitespaceorempty(response["CallDate"]) else "NONE", calltime=response["CallTime"] if ("CallTime") in response and isnotnull_whitespaceorempty(response["CallTime"]) else "NONE", event_datetime=get_utc_epoch(), timestamp=get_timestamp_from_calldate( response["CallDate"], response["CallTime"], ) if (isnotnull_whitespaceorempty(response["CallDate"] if ( "CallDate") in response else None) and isnotnull_whitespaceorempty(response["CallTime"] if ( "CallTime") in response else None)) else datetime.now(), customerfirstname=response["CustomerFirstName"] if ("CustomerFirstName") in response and isnotnull_whitespaceorempty( response["CustomerFirstName"]) else "NONE", customerlastname=response["CustomerLastName"] if ("CustomerLastName") in response and isnotnull_whitespaceorempty( response["CustomerLastName"]) else "NONE", modelyear=response["VehicleYear"] if ("VehicleYear") in response and isnotnull_whitespaceorempty(response["VehicleYear"]) else "NONE", brand=response["Make"] if ("Make") in response and isnotnull_whitespaceorempty(response["Make"]) else "NONE", modelname=response["Model"] if ("Model") in response and isnotnull_whitespaceorempty(response["Model"]) else "NONE", modelcode=response["Make"] if ("Make") in response and isnotnull_whitespaceorempty(response["Make"]) else "NONE", vin=response["VIN"] if ("VIN") in response and isnotnull_whitespaceorempty(response["VIN"]) else "NONE", modelcolor=response["ExteriorColor"] if ("ExteriorColor") in response and isnotnull_whitespaceorempty(response["ExteriorColor"]) else "NONE", phonenumber=response["FromLocationPhoneNo"] if ("FromLocationPhoneNo") in response and isnotnull_whitespaceorempty( response["FromLocationPhoneNo"]) else "NONE", srnumber=response["SRNumber"] if ("SRNumber") in response and isnotnull_whitespaceorempty(response["SRNumber"]) else "NONE", locationaddress=response["FromLocationAddress"] if ("FromLocationAddress") in response and isnotnull_whitespaceorempty( response["FromLocationAddress"]) else "NONE", locationcity=response["FromLocationCity"] if ("FromLocationCity") in response and isnotnull_whitespaceorempty( response["FromLocationCity"]) else "NONE", locationstate=response["FromLocationState"] if ("FromLocationState") in response and isnotnull_whitespaceorempty( response["FromLocationState"]) else "NONE", locationpostalcode=response["FromLocationZip"] if ("FromLocationZip") in response and isnotnull_whitespaceorempty( response["FromLocationZip"]) else "NONE", countrycode=response["FromLocationCountry"] if ("FromLocationCountry") in response and isnotnull_whitespaceorempty( response["FromLocationCountry"]) else "NONE", locationconfidence=response["Location_confidence"] if ("Location_confidence") in response and isnotnull_whitespaceorempty( response["Location_confidence"]) else "NONE", locationtrueness=response["Location_trueness"] if ("Location_trueness") in response and isnotnull_whitespaceorempty( response["Location_trueness"]) else "NONE", cruisingrange=response["Cruising_range"] if ("Cruising_range") in response and isnotnull_whitespaceorempty( response["Cruising_range"]) else "NONE", ismoving=response["Is_moving"] if ("Is_moving") in response and isnotnull_whitespaceorempty(response["Is_moving"]) else False, latitude=response["FromLocationLatitude"] if ("FromLocationLatitude") in response and isnotnull_whitespaceorempty( response["FromLocationLatitude"]) else 0, longitude=response["FromLocationLongitude"] if ("FromLocationLongitude") in response and isnotnull_whitespaceorempty( response["FromLocationLongitude"]) else 0, altitude=response["Altitude"] if ("Altitude") in response and isnotnull_whitespaceorempty(response["Altitude"]) else "NONE", headingdirection=response["Direction_heading"] if ("Direction_heading") in response and isnotnull_whitespaceorempty( response["Direction_heading"]) else "NONE", language=response["Hmi_language"] if ("Hmi_language") in response and isnotnull_whitespaceorempty(response["Hmi_language"]) else "NONE", responsemessage="Successfully retrieved", )
def map_supplementtable( msisdn: str, programcode: ProgramCode, vehicledata: VehicleDataRequest, custom_extension: CustomExtension, tblsupplement: ConnectedVehicleSupplementTable, ): return tblsupplement( msisdn=msisdn, programcode=programcode, request_key="{}-{}".format(programcode, msisdn), timestamp=convert_epoch_to_utc_timestamp(vehicledata.Timestamp), event_datetime=get_utc_epoch(), callcenternumber=vehicledata.Data.callCenterNumber, devicetype=custom_extension.device.deviceType, deviceos=custom_extension.device.deviceOS, headunittype=custom_extension.device.headUnitType, manufacturername=custom_extension.device.manufacturerName, region=custom_extension.device.region, screensize=custom_extension.device.screenSize, tbmserialnum=custom_extension.device.tbmSerialNum, tbmpartnum=custom_extension.device.tbmPartNum, tbmhardwareversion=custom_extension.device.tbmHardwareVersion, tbmsoftwareversion=custom_extension.device.tbmSoftwareVersion, simiccid=int(custom_extension.device.simIccid), simimsi=custom_extension.device.simImsi, nadimei=custom_extension.device.nadImei, nadhardwareversion=custom_extension.device.nadHardwareVersion, nadsoftwareversion=custom_extension.device.nadSoftwareVersion, nadserialnum=custom_extension.device.nadSerialNum, nadpartnum=custom_extension.device.nadPartNum, wifimac=custom_extension.device.wifiMac, huserialnum=custom_extension.device.huSerialNum, hupartnum=custom_extension.device.huPartNum, huhardwareversion=custom_extension.device.huHardwareVersion, husoftwareversion=custom_extension.device.huSoftwareVersion, ishunavigationpresent=custom_extension.device.isHUNavigationPresent, distanceremainingfornextservice=custom_extension. distanceRemainingForNextService, estimatedpositionerror=custom_extension.vehicleInfo.vehicleLocation. estimatedPositionError, estimatedaltitudeerror=custom_extension.vehicleInfo.vehicleLocation. estimatedAltitudeError, isgpsfixnotavailable=custom_extension.vehicleInfo.vehicleLocation. isGPSFixNotAvailable, gpsfixtype=custom_extension.vehicleInfo.vehicleLocation.gpsFixTypeEnum, errortelltale=None if hasattr(custom_extension.errorTellTale, "isOilPressure") else custom_extension.errorTellTale, isoilpressure=custom_extension.errorTellTale.isOilPressure if hasattr( custom_extension.errorTellTale, "isOilPressure") else None, fuelremaining=custom_extension.fuelRemaining, stateofcharge=custom_extension.stateofCharge, tirepressure=None if hasattr(custom_extension.tirePressure, "flTirePressure") else custom_extension.tirePressure, fltirepressure=custom_extension.tirePressure.flTirePressure if hasattr( custom_extension.tirePressure, "flTirePressure") else None, frtirepressure=custom_extension.tirePressure.frTirePressure if hasattr( custom_extension.tirePressure, "frTirePressure") else None, rltirepressure=custom_extension.tirePressure.rlTirePressure if hasattr( custom_extension.tirePressure, "rlTirePressure") else None, rrtirepressure=custom_extension.tirePressure.rrTirePressure if hasattr( custom_extension.tirePressure, "rrTirePressure") else None, rl2tirepressure=custom_extension.tirePressure.rl2TirePressure if hasattr(custom_extension.tirePressure, "rl2TirePressure") else None, rr2tirepressure=custom_extension.tirePressure.rr2TirePressure if hasattr(custom_extension.tirePressure, "rr2TirePressure") else None, fltirests=custom_extension.tirePressure.flTireSts if hasattr( custom_extension.tirePressure, "flTireSts") else None, frtirests=custom_extension.tirePressure.frTireSts if hasattr( custom_extension.tirePressure, "frTireSts") else None, rltirests=custom_extension.tirePressure.rlTireSts if hasattr( custom_extension.tirePressure, "rlTireSts") else None, rrtirests=custom_extension.tirePressure.rrTireSts if hasattr( custom_extension.tirePressure, "rrTireSts") else None, daysremainingfornextservice=custom_extension. daysRemainingForNextService, )