|
| 1 | +""" |
| 2 | +Fetch data from fueleconomy.gov |
| 3 | +(c) Copyright 2016 Dan Kegel <[email protected]> |
| 4 | +License: AGPL v3.0 |
| 5 | +""" |
| 6 | + |
| 7 | +# Note: client app may wish to 'import requests_cache' and install a cache |
| 8 | +# to avoid duplicate fetches |
| 9 | +import requests |
| 10 | +import requests_cache |
| 11 | +# Cache responses for 7 days to be kind to nhtsa's server |
| 12 | +requests_cache.install_cache('libvin_tests_cache', expire_after=7*24*60*60) |
| 13 | +import itertools |
| 14 | +import json |
| 15 | +import xmltodict |
| 16 | + |
| 17 | +# Local |
| 18 | +from decoding import Vin |
| 19 | +from nhtsa import * |
| 20 | + |
| 21 | +class EPAVin(Vin): |
| 22 | + |
| 23 | + # Public interfaces |
| 24 | + |
| 25 | + def __init__(self, vin): |
| 26 | + super(EPAVin, self).__init__(vin) |
| 27 | + |
| 28 | + self.__nhtsa = nhtsa_decode(vin) |
| 29 | + self.__model = self.__get_model() |
| 30 | + self.__id = self.__get_id() |
| 31 | + self.__eco = self.__get_vehicle_economy() |
| 32 | + |
| 33 | + @property |
| 34 | + def nhtsa(self): |
| 35 | + ''' |
| 36 | + NHTSA info dictionary for this vehicle. |
| 37 | + ''' |
| 38 | + return self.__nhtsa |
| 39 | + |
| 40 | + @property |
| 41 | + def nhtsaModel(self): |
| 42 | + ''' |
| 43 | + NHTSA model name for this vehicle. |
| 44 | + ''' |
| 45 | + return self.nhtsa['Model'] |
| 46 | + |
| 47 | + @property |
| 48 | + def model(self): |
| 49 | + ''' |
| 50 | + EPA model name for this vehicle. |
| 51 | + ''' |
| 52 | + return self.__model |
| 53 | + |
| 54 | + @property |
| 55 | + def id(self): |
| 56 | + ''' |
| 57 | + EPA id for this vehicle. |
| 58 | + ''' |
| 59 | + return self.__id |
| 60 | + |
| 61 | + @property |
| 62 | + def eco(self): |
| 63 | + ''' |
| 64 | + EPA fuel economy info dictionary for this vehicle. |
| 65 | + Fields of interest: |
| 66 | + - co2TailpipeGpm - present for most vehicles |
| 67 | + - co2TailpipeAGpm - present for some vehicles, matches EPA website |
| 68 | + ''' |
| 69 | + return self.__eco |
| 70 | + |
| 71 | + # Private interfaces |
| 72 | + |
| 73 | + def __get_possible_models(self): |
| 74 | + ''' |
| 75 | + Return list of possible models for given year of given make. |
| 76 | + The models are those needed by get_vehicle_ids(). |
| 77 | + ''' |
| 78 | + |
| 79 | + models = [] |
| 80 | + url = 'http://www.fueleconomy.gov/ws/rest/vehicle/menu/model?year=%s&make=%s' % (self.year, self.make) |
| 81 | + try: |
| 82 | + r = requests.get(url) |
| 83 | + except requests.Timeout: |
| 84 | + print "epa:__get_possible_models: connection timed out" |
| 85 | + return None |
| 86 | + except requests.ConnectionError: |
| 87 | + print "epa:__get_possible_models: connection failed" |
| 88 | + return None |
| 89 | + try: |
| 90 | + content = r.content |
| 91 | + # You can't make this stuff up. I love xml. |
| 92 | + for item in xmltodict.parse(content).popitem()[1].items()[0][1]: |
| 93 | + models.append(item.popitem()[1]) |
| 94 | + except AttributeError: |
| 95 | + print "epa:__get_possible_models: no models for year %s, make %s" % (self.year, self.make) |
| 96 | + return None |
| 97 | + except ValueError: |
| 98 | + print "epa:__get_possible_models: could not parse result" |
| 99 | + return None |
| 100 | + return models |
| 101 | + |
| 102 | + def __get_model(self): |
| 103 | + ''' |
| 104 | + Given a decoded vin and its nhtsa data, look up its epa model name |
| 105 | + ''' |
| 106 | + models = self.__get_possible_models() |
| 107 | + if models == None: |
| 108 | + return None |
| 109 | + |
| 110 | + # Get candidate modifier strings |
| 111 | + modifiers = [] |
| 112 | + driveType = self.nhtsa['DriveType'] |
| 113 | + if 'AWD' in driveType or '4WD' in driveType or '4x4' in driveType: |
| 114 | + modifiers.append("4WD") |
| 115 | + modifiers.append("AWD") |
| 116 | + # Special cases |
| 117 | + if self.make == 'GMC' and self.nhtsaModel == 'Sierra': |
| 118 | + modifiers.append("K15") |
| 119 | + elif 'Front' in driveType or 'FWD' in driveType or '4x2' in driveType: |
| 120 | + modifiers.append("2WD") |
| 121 | + modifiers.append("FWD") |
| 122 | + # Special cases |
| 123 | + if self.make == 'GMC' and self.nhtsaModel == 'Sierra': |
| 124 | + modifiers.append("C15") |
| 125 | + else: |
| 126 | + # special cases |
| 127 | + if self.make == 'Ford' and self.nhtsaModel == 'Focus': |
| 128 | + modifiers.append("FWD") |
| 129 | + if 'Trim' in self.nhtsa and self.nhtsa['Trim'] != "": |
| 130 | + modifiers.append(self.nhtsa['Trim']) |
| 131 | + if 'BodyClass' in self.nhtsa and self.nhtsa['BodyClass'] != "": |
| 132 | + modifiers.append(self.nhtsa['BodyClass']) |
| 133 | + if 'Series' in self.nhtsa and self.nhtsa['Series'] != "": |
| 134 | + modifiers.append(self.nhtsa['Series']) |
| 135 | + |
| 136 | + # Throw them against the wall and see what sticks |
| 137 | + # FIXME: pick model with highest number of matches regardless of order |
| 138 | + for L in range(len(modifiers)+1, 0, -1): |
| 139 | + for subset in itertools.permutations(modifiers, L): |
| 140 | + modified_model = self.nhtsaModel + " " + " ".join(subset) |
| 141 | + if modified_model in models: |
| 142 | + return modified_model |
| 143 | + |
| 144 | + if self.nhtsaModel in models: |
| 145 | + return self.nhtsaModel |
| 146 | + |
| 147 | + print "epa:__get_model: Failed to find model for %s" % self.vin |
| 148 | + return None |
| 149 | + |
| 150 | + def __get_possible_ids(self): |
| 151 | + ''' |
| 152 | + Return dictionary of id -> vehicle trim string from fueleconomy.gov, or None on error. |
| 153 | + The id's are those needed by get_vehicle_economy(). |
| 154 | + ''' |
| 155 | + |
| 156 | + id2trim = dict() |
| 157 | + url = 'http://www.fueleconomy.gov/ws/rest/vehicle/menu/options?year=%s&make=%s&model=%s' % (self.year, self.make, self.model) |
| 158 | + try: |
| 159 | + r = requests.get(url) |
| 160 | + except requests.Timeout: |
| 161 | + print "epa:__get_possible_ids: connection timed out" |
| 162 | + return None |
| 163 | + except requests.ConnectionError: |
| 164 | + print "epa:__get_possible_ids: connection failed" |
| 165 | + return None |
| 166 | + try: |
| 167 | + content = r.content |
| 168 | + # You can't make this stuff up. I love xml. |
| 169 | + parsed = xmltodict.parse(content) |
| 170 | + innards = parsed.popitem()[1].items()[0][1] |
| 171 | + # special case for N=1 |
| 172 | + if not isinstance(innards, list): |
| 173 | + innards = [ innards ] |
| 174 | + for item in innards: |
| 175 | + id = item.popitem()[1] |
| 176 | + trim = item.popitem()[1] |
| 177 | + id2trim[id] = trim |
| 178 | + except ValueError: |
| 179 | + print "epa:__get_possible_ids: could not parse result" |
| 180 | + return None |
| 181 | + return id2trim |
| 182 | + |
| 183 | + def __get_id(self): |
| 184 | + ''' |
| 185 | + Given a decoded vin, look up its epa id, or return None on failure |
| 186 | + ''' |
| 187 | + if self.model == None: |
| 188 | + return None |
| 189 | + id2trim = self.__get_possible_ids() |
| 190 | + |
| 191 | + # If only one choice, return it |
| 192 | + if (len(id2trim) == 1): |
| 193 | + key, value = id2trim.popitem() |
| 194 | + return key |
| 195 | + |
| 196 | + # Filter by engine displacement |
| 197 | + displacement = '%s L' % self.nhtsa['DisplacementL'] |
| 198 | + matches = [key for key, value in id2trim.items() if displacement in value.upper()] |
| 199 | + if (len(matches) == 1): |
| 200 | + return matches[0] |
| 201 | + |
| 202 | + # Filter by transmission |
| 203 | + tran = None |
| 204 | + if 'Manual' in self.nhtsa['TransmissionStyle']: |
| 205 | + tran = 'MAN' |
| 206 | + if 'Auto' in self.nhtsa['TransmissionStyle']: |
| 207 | + tran = 'AUTO' |
| 208 | + if tran != None: |
| 209 | + matches = [key for key, value in id2trim.items() if tran in value.upper()] |
| 210 | + if (len(matches) == 1): |
| 211 | + return matches[0] |
| 212 | + |
| 213 | + print "epa:__get_id: Failed to match trim for %s" % self.vin |
| 214 | + return None |
| 215 | + |
| 216 | + def __get_vehicle_economy(self): |
| 217 | + ''' |
| 218 | + Return dictionary of a particular vehicle's economy data from fueleconomy.gov, or None on error. |
| 219 | + id is from __get_vehicle_ids(). |
| 220 | + ''' |
| 221 | + |
| 222 | + url = 'http://www.fueleconomy.gov/ws/rest/vehicle/%s' % self.id |
| 223 | + try: |
| 224 | + r = requests.get(url) |
| 225 | + except requests.Timeout: |
| 226 | + print "epa:__get_vehicle_economy: connection timed out" |
| 227 | + return None |
| 228 | + except requests.ConnectionError: |
| 229 | + print "epa:__get_vehicle_economy: connection failed" |
| 230 | + return None |
| 231 | + try: |
| 232 | + content = r.content |
| 233 | + return xmltodict.parse(content).popitem()[1] |
| 234 | + except ValueError: |
| 235 | + print "epa:__get_vehicle_economy: could not parse result" |
| 236 | + return None |
| 237 | + return None |
0 commit comments