5bb79f9b7e74b2bd0cecfd07672dc27e43d84583
2 # -*- coding: utf-8 -*-
5 InfoEx <-> NRCS/MesoWest Auto Wx implementation
7 Wylark Mountaineering LLC
9 This program fetches data from either an NRCS SNOTEL site or MesoWest
10 weather station and pushes it to InfoEx using the new automated weather
11 system implementation.
13 It is designed to be run hourly, and it asks for the last three hours
14 of data of each desired type, and selects the most recent one. This
15 lends some resiliency to the process and helps ensure that we have a
16 value to send, but it can lead to somewhat inconsistent/untruthful
17 data if e.g. the HS is from the last hour but the tempPres is from two
18 hours ago because the instrumentation had a hiccup. It's worth
19 considering if this is a bug or a feature.
21 For more information, see file: README
22 For licensing, see file: LICENSE
35 from ftplib
import FTP
36 from argparse
import ArgumentParser
44 import zeep
.transports
48 LOG
= logging
.getLogger(__name__
)
49 LOG
.setLevel(logging
.NOTSET
)
51 urllib3
.disable_warnings()
54 """Return OptionParser for this program"""
55 parser
= ArgumentParser()
57 parser
.add_argument("--version",
61 parser
.add_argument("--config",
64 help="location of config file")
66 parser
.add_argument("--log-level",
69 help="set the log level (debug, info, warning)")
71 parser
.add_argument("--dry-run",
75 help="fetch data but don't upload to InfoEx")
79 def setup_config(config
):
80 """Setup config variable based on values specified in the ini file"""
83 'host': config
['infoex']['host'],
84 'uuid': config
['infoex']['uuid'],
85 'api_key': config
['infoex']['api_key'],
86 'csv_filename': config
['infoex']['csv_filename'],
87 'location_uuid': config
['infoex']['location_uuid'],
88 'wx_data': {}, # placeholder key, values to come later
93 station
['provider'] = config
['station']['type']
95 if station
['provider'] not in ['nrcs', 'mesowest', 'python']:
96 print("Please specify either nrcs or mesowest as the station type.")
99 # massage units config items first
101 # NOTE: custom providers don't require units to be specified
102 # because they can do whatever they please with the units
103 # within their own program
104 if station
['provider'] != "python":
105 station
['units'] = config
['station']['units']
107 if station
['units'] not in ['metric', 'english', 'american']:
108 print("Please specify metric, english, or american for the units.")
111 # if units are specified as "American" then we simply
112 # default to metric for the requests
113 if station
['units'] == 'american':
114 station
['units_requested'] = 'metric'
116 station
['units_requested'] = station
['units']
118 # massage provider config items
119 if station
['provider'] == 'nrcs':
120 #station['source'] = 'https://www.wcc.nrcs.usda.gov/awdbWebService/services?WSDL'
121 station
['source'] = 'https://wcc.sc.egov.usda.gov/awdbWebService/services?WSDL'
123 station
['station_id'] = config
['station']['station_id']
124 station
['desired_data'] = config
['station']['desired_data'].split(',')
126 if station
['provider'] == 'mesowest':
127 station
['source'] = 'https://api.synopticdata.com/v2/stations/timeseries'
128 station
['station_id'] = config
['station']['station_id']
129 station
['desired_data'] = config
['station']['desired_data']
131 # construct full API URL (sans start/end time, added later)
132 station
['source'] = station
['source'] + '?token=' + \
133 config
['station']['token'] + \
134 '&within=60&units=' + station
['units_requested'] + \
135 '&stid=' + station
['station_id'] + \
136 '&vars=' + station
['desired_data']
138 if station
['provider'] == 'python':
139 station
['path'] = config
['station']['path']
141 tz
= 'America/Los_Angeles'
143 if 'tz' in config
['station']:
144 tz
= config
['station']['tz']
147 station
['tz'] = pytz
.timezone(tz
)
148 except pytz
.exceptions
.UnknownTimeZoneError
:
149 LOG
.critical("%s is not a valid timezone", tz
)
152 # By default, fetch three hours of data
154 # If user wants hn24 or wind averaging, then
156 station
['num_hrs_to_fetch'] = 3
159 if 'hn24' in config
['station']:
160 if config
['station']['hn24'] not in ['true', 'false']:
161 raise ValueError("hn24 must be either 'true' or 'false'")
163 if config
['station']['hn24'] == "true":
164 station
['hn24'] = True
165 station
['num_hrs_to_fetch'] = 24
167 station
['hn24'] = False
170 station
['hn24'] = False
173 if 'wind_mode' in config
['station']:
174 if config
['station']['wind_mode'] not in ['normal', 'average']:
175 raise ValueError("wind_mode must be either 'normal' or 'average'")
177 station
['wind_mode'] = config
['station']['wind_mode']
179 if station
['wind_mode'] == "average":
180 station
['num_hrs_to_fetch'] = 24
183 station
['wind_mode'] = "normal"
185 except KeyError as err
:
186 LOG
.critical("%s not defined in configuration file", err
)
188 except ValueError as err
:
189 LOG
.critical("%s", err
)
192 # all sections/values present in config file, final sanity check
194 for key
in config
.sections():
195 for subkey
in config
[key
]:
196 if not config
[key
][subkey
]:
199 LOG
.critical("Config value '%s.%s' is empty", key
, subkey
)
202 return (infoex
, station
)
204 def setup_logging(log_level
):
205 """Setup our logging infrastructure"""
207 from systemd
.journal
import JournalHandler
208 LOG
.addHandler(JournalHandler())
210 ## fallback to syslog
211 #import logging.handlers
212 #LOG.addHandler(logging.handlers.SysLogHandler())
214 handler
= logging
.StreamHandler(sys
.stdout
)
215 formatter
= logging
.Formatter('%(asctime)s.%(msecs)03d '
216 '%(levelname)s %(module)s - '
217 '%(funcName)s: %(message)s',
219 handler
.setFormatter(formatter
)
220 LOG
.addHandler(handler
)
223 if log_level
in [None, 'debug', 'info', 'warning']:
224 if log_level
== 'debug':
225 LOG
.setLevel(logging
.DEBUG
)
226 elif log_level
== 'info':
227 LOG
.setLevel(logging
.INFO
)
228 elif log_level
== 'warning':
229 LOG
.setLevel(logging
.WARNING
)
231 LOG
.setLevel(logging
.NOTSET
)
238 """Main routine: sort through args, decide what to do, then do it"""
239 parser
= get_parser()
240 options
= parser
.parse_args()
242 config
= configparser
.ConfigParser(allow_no_value
=False)
244 if not options
.config
:
246 print("\nPlease specify a configuration file via --config.")
249 config
.read(options
.config
)
251 if not setup_logging(options
.log_level
):
253 print("\nPlease select an appropriate log level or remove the switch (--log-level).")
256 (infoex
, station
) = setup_config(config
)
258 LOG
.debug('Config parsed, starting up')
261 (fmap
, final_data
) = setup_infoex_fields_mapping(infoex
['location_uuid'])
262 iemap
= setup_infoex_counterparts_mapping(station
['provider'])
264 # override units if user selected metric
265 if station
['provider'] != 'python' and station
['units'] == 'metric':
266 final_data
= switch_units_to_metric(final_data
, fmap
)
268 # likewise for "American" units
269 if station
['provider'] != 'python' and station
['units'] == 'american':
270 final_data
= switch_units_to_american(final_data
, fmap
)
272 (begin_date
, end_date
) = setup_time_values(station
)
274 if station
['provider'] == 'python':
275 LOG
.debug("Getting custom data from external Python program")
277 LOG
.debug("Getting %s data from %s to %s (%s)",
278 str(station
['desired_data']),
279 str(begin_date
), str(end_date
), end_date
.tzinfo
.zone
)
281 time_all_elements
= time
.time()
284 if station
['provider'] == 'nrcs':
285 infoex
['wx_data'] = get_nrcs_data(begin_date
, end_date
, station
)
286 elif station
['provider'] == 'mesowest':
287 infoex
['wx_data'] = get_mesowest_data(begin_date
, end_date
,
289 elif station
['provider'] == 'python':
291 spec
= importlib
.util
.spec_from_file_location('custom_wx',
293 mod
= importlib
.util
.module_from_spec(spec
)
294 spec
.loader
.exec_module(mod
)
298 infoex
['wx_data'] = mod
.get_custom_data()
300 if infoex
['wx_data'] is None:
301 infoex
['wx_data'] = []
302 except Exception as exc
:
303 LOG
.error("Python program for custom Wx data failed in "
304 "execution: %s", str(exc
))
307 LOG
.info("Successfully executed external Python program")
309 LOG
.error("Please upgrade to Python 3.3 or later")
311 except FileNotFoundError
:
312 LOG
.error("Specified Python program for custom Wx data "
315 except Exception as exc
:
316 LOG
.error("A problem was encountered when attempting to "
317 "load your custom Wx program: %s", str(exc
))
320 LOG
.info("Time taken to get all data : %.3f sec", time
.time() -
323 LOG
.debug("infoex[wx_data]: %s", str(infoex
['wx_data']))
326 final_end_date
= end_date
.astimezone(station
['tz'])
328 # Now we only need to add in what we want to change thanks to that
329 # abomination of a variable declaration earlier
330 final_data
[fmap
['Location UUID']] = infoex
['location_uuid']
331 final_data
[fmap
['obDate']] = final_end_date
.strftime('%m/%d/%Y')
332 final_data
[fmap
['obTime']] = final_end_date
.strftime('%H:%M')
333 final_data
[fmap
['timeZone']] = station
['tz'].zone
335 for element_cd
in infoex
['wx_data']:
336 if element_cd
not in iemap
:
337 LOG
.warning("BAD KEY wx_data['%s']", element_cd
)
340 if infoex
['wx_data'][element_cd
] is None:
343 # do the conversion before the rounding
344 if station
['provider'] == 'nrcs' and station
['units'] == 'metric':
345 infoex
['wx_data'][element_cd
] = convert_nrcs_units_to_metric(element_cd
, infoex
['wx_data'][element_cd
])
347 if station
['provider'] != 'python' and station
['units'] == 'american':
348 infoex
['wx_data'][element_cd
] = convert_units_to_american(element_cd
, infoex
['wx_data'][element_cd
])
350 # Massage precision of certain values to fit InfoEx's
353 # 0 decimal places: relative humidity, wind speed, wind
354 # direction, wind gust, snow depth
355 # 1 decimal place: air temp, baro
356 # Avoid transforming None values
357 if element_cd
in ['wind_speed', 'WSPD', 'wind_direction',
358 'RHUM', 'relative_humidity', 'WDIR',
359 'wind_gust', 'SNWD', 'snow_depth',
361 infoex
['wx_data'][element_cd
] = round(infoex
['wx_data'][element_cd
])
362 elif element_cd
in ['TOBS', 'air_temp', 'PRES', 'pressure']:
363 infoex
['wx_data'][element_cd
] = round(infoex
['wx_data'][element_cd
], 1)
364 elif element_cd
in ['PREC', 'precip_accum']:
365 infoex
['wx_data'][element_cd
] = round(infoex
['wx_data'][element_cd
], 2)
367 # CONSIDER: Casting every value to Float() -- need to investigate if
368 # any possible elementCds we may want are any other data
371 # Another possibility is to query the API with
372 # getStationElements and temporarily store the
373 # storedUnitCd. But that's pretty network-intensive and
374 # may not even be worth it if there's only e.g. one or two
375 # exceptions to any otherwise uniformly Float value set.
376 final_data
[fmap
[iemap
[element_cd
]]] = infoex
['wx_data'][element_cd
]
378 LOG
.debug("final_data: %s", str(final_data
))
380 if infoex
['wx_data']:
381 if not write_local_csv(infoex
['csv_filename'], final_data
):
382 LOG
.warning('Could not write local CSV file: %s',
383 infoex
['csv_filename'])
386 if not options
.dry_run
:
387 upload_csv(infoex
['csv_filename'], infoex
)
392 # data structure operations
393 def setup_infoex_fields_mapping(location_uuid
):
395 Create a mapping of InfoEx fields to the local data's indexing scheme.
399 This won't earn style points in Python, but here we establish a couple
400 of helpful mappings variables. The reason this is helpful is that the
401 end result is simply an ordered set, the CSV file. But we still may
402 want to manipulate the values arbitrarily before writing that file.
404 Also note that the current Auto Wx InfoEx documentation shows these
405 keys in a graphical table with the "index" beginning at 1, but here we
406 sanely index beginning at 0.
408 # pylint: disable=too-many-statements,multiple-statements,bad-whitespace
409 fmap
= {} ; final_data
= [None] * 29
410 fmap
['Location UUID'] = 0 ; final_data
[0] = location_uuid
411 fmap
['obDate'] = 1 ; final_data
[1] = None
412 fmap
['obTime'] = 2 ; final_data
[2] = None
413 fmap
['timeZone'] = 3 ; final_data
[3] = 'Pacific'
414 fmap
['tempMaxHour'] = 4 ; final_data
[4] = None
415 fmap
['tempMaxHourUnit'] = 5 ; final_data
[5] = 'F'
416 fmap
['tempMinHour'] = 6 ; final_data
[6] = None
417 fmap
['tempMinHourUnit'] = 7 ; final_data
[7] = 'F'
418 fmap
['tempPres'] = 8 ; final_data
[8] = None
419 fmap
['tempPresUnit'] = 9 ; final_data
[9] = 'F'
420 fmap
['precipitationGauge'] = 10 ; final_data
[10] = None
421 fmap
['precipitationGaugeUnit'] = 11 ; final_data
[11] = 'in'
422 fmap
['windSpeedNum'] = 12 ; final_data
[12] = None
423 fmap
['windSpeedUnit'] = 13 ; final_data
[13] = 'mph'
424 fmap
['windDirectionNum'] = 14 ; final_data
[14] = None
425 fmap
['hS'] = 15 ; final_data
[15] = None
426 fmap
['hsUnit'] = 16 ; final_data
[16] = 'in'
427 fmap
['baro'] = 17 ; final_data
[17] = None
428 fmap
['baroUnit'] = 18 ; final_data
[18] = 'inHg'
429 fmap
['rH'] = 19 ; final_data
[19] = None
430 fmap
['windGustSpeedNum'] = 20 ; final_data
[20] = None
431 fmap
['windGustSpeedNumUnit'] = 21 ; final_data
[21] = 'mph'
432 fmap
['windGustDirNum'] = 22 ; final_data
[22] = None
433 fmap
['dewPoint'] = 23 ; final_data
[23] = None
434 fmap
['dewPointUnit'] = 24 ; final_data
[24] = 'F'
435 fmap
['hn24Auto'] = 25 ; final_data
[25] = None
436 fmap
['hn24AutoUnit'] = 26 ; final_data
[26] = 'in'
437 fmap
['hstAuto'] = 27 ; final_data
[27] = None
438 fmap
['hstAutoUnit'] = 28 ; final_data
[28] = 'in'
440 return (fmap
, final_data
)
442 def setup_infoex_counterparts_mapping(provider
):
444 Create a mapping of the NRCS/MesoWest fields that this program supports to
445 their InfoEx counterparts
449 if provider
== 'nrcs':
450 iemap
['PREC'] = 'precipitationGauge'
451 iemap
['TOBS'] = 'tempPres'
452 iemap
['TMAX'] = 'tempMaxHour'
453 iemap
['TMIN'] = 'tempMinHour'
455 iemap
['PRES'] = 'baro'
457 iemap
['WSPD'] = 'windSpeedNum'
458 iemap
['WDIR'] = 'windDirectionNum'
459 # unsupported by NRCS:
462 # NOTE: this doesn't exist in NRCS SNOTEL, we create it in this
463 # program, so add it to the map here
464 iemap
['hn24'] = 'hn24Auto'
465 elif provider
== 'mesowest':
466 iemap
['precip_accum'] = 'precipitationGauge'
467 iemap
['air_temp'] = 'tempPres'
468 iemap
['air_temp_high_24_hour'] = 'tempMaxHour'
469 iemap
['air_temp_low_24_hour'] = 'tempMinHour'
470 iemap
['snow_depth'] = 'hS'
471 iemap
['pressure'] = 'baro'
472 iemap
['relative_humidity'] = 'rH'
473 iemap
['wind_speed'] = 'windSpeedNum'
474 iemap
['wind_direction'] = 'windDirectionNum'
475 iemap
['wind_gust'] = 'windGustSpeedNum'
477 # NOTE: this doesn't exist in MesoWest, we create it in this
478 # program, so add it to the map here
479 iemap
['hn24'] = 'hn24Auto'
480 elif provider
== 'python':
481 # we expect Python programs to use the InfoEx data type names
482 iemap
['precipitationGauge'] = 'precipitationGauge'
483 iemap
['precipitationGaugeUnit'] = 'precipitationGaugeUnit'
484 iemap
['tempPres'] = 'tempPres'
485 iemap
['tempPresUnit'] = 'tempPresUnit'
486 iemap
['tempMaxHour'] = 'tempMaxHour'
487 iemap
['tempMinHour'] = 'tempMinHour'
489 iemap
['hsUnit'] = 'hsUnit'
490 iemap
['baro'] = 'baro'
492 iemap
['windSpeedNum'] = 'windSpeedNum'
493 iemap
['windDirectionNum'] = 'windDirectionNum'
494 iemap
['windGustSpeedNum'] = 'windGustSpeedNum'
498 # provider-specific operations
499 def get_nrcs_data(begin
, end
, station
):
500 """get the data we're after from the NRCS WSDL"""
501 transport
= zeep
.transports
.Transport(cache
=zeep
.cache
.SqliteCache())
502 transport
.session
.verify
= False
503 client
= zeep
.Client(wsdl
=station
['source'], transport
=transport
)
506 # massage begin/end date format
507 begin_date_str
= begin
.strftime('%Y-%m-%d %H:%M:00')
508 end_date_str
= end
.strftime('%Y-%m-%d %H:%M:00')
510 for element_cd
in station
['desired_data']:
511 time_element
= time
.time()
513 # get the last three hours of data for this elementCd/element_cd
514 tmp
= client
.service
.getHourlyData(
515 stationTriplets
=[station
['station_id']],
516 elementCd
=element_cd
,
518 beginDate
=begin_date_str
,
519 endDate
=end_date_str
)
521 LOG
.info("Time to get NRCS elementCd '%s': %.3f sec", element_cd
,
522 time
.time() - time_element
)
524 values
= tmp
[0]['values']
526 # sort and isolate the most recent
528 # NOTE: we do this because sometimes there are gaps in hourly data
529 # in NRCS; yes, we may end up with slightly inaccurate data,
530 # so perhaps this decision will be re-evaluated in the future
532 ordered
= sorted(values
, key
=lambda t
: t
['dateTime'], reverse
=True)
533 remote_data
[element_cd
] = ordered
[0]['value']
535 remote_data
[element_cd
] = None
538 # calc hn24, if applicable
544 if element_cd
== "SNWD":
545 for idx
, _
in enumerate(values
):
549 hn24_values
.append(val
['value'])
551 if len(hn24_values
) > 0:
552 # instead of taking MAX - MIN, we want the first
553 # value (most distant) - the last value (most
556 # if the result is positive, then we have
557 # settlement; if it's not, then we have HN24
558 hn24
= hn24_values
[0] - hn24_values
[len(hn24_values
)-1]
563 # this case represents HS settlement
566 # finally, if user wants hn24 and it's set to None at this
567 # point, then force it to 0.0
573 remote_data
['hn24'] = hn24
577 def get_mesowest_data(begin
, end
, station
):
578 """get the data we're after from the MesoWest/Synoptic API"""
581 # massage begin/end date format
582 begin_date_str
= begin
.strftime('%Y%m%d%H%M')
583 end_date_str
= end
.strftime('%Y%m%d%H%M')
585 # construct final, completed API URL
586 api_req_url
= station
['source'] + '&start=' + begin_date_str
+ '&end=' + end_date_str
589 req
= requests
.get(api_req_url
)
590 except requests
.exceptions
.ConnectionError
:
591 LOG
.error("Could not connect to '%s'", api_req_url
)
597 LOG
.error("Bad JSON in MesoWest response")
601 observations
= json
['STATION'][0]['OBSERVATIONS']
602 except KeyError as exc
:
603 LOG
.error("Unexpected JSON in MesoWest response: '%s'", exc
)
605 except IndexError as exc
:
606 LOG
.error("Unexpected JSON in MesoWest response: '%s'", exc
)
608 LOG
.error("Detailed MesoWest response: '%s'",
609 json
['SUMMARY']['RESPONSE_MESSAGE'])
613 except ValueError as exc
:
614 LOG
.error("Bad JSON in MesoWest response: '%s'", exc
)
617 # pos represents the last item in the array, aka the most recent
618 pos
= len(observations
['date_time']) - 1
620 # while these values only apply in certain cases, init them here
621 wind_speed_values
= []
622 wind_gust_speed_values
= []
623 wind_direction_values
= []
627 wind_speed_avg
= None
628 wind_gust_speed_avg
= None
629 wind_direction_avg
= None
632 for element_cd
in station
['desired_data'].split(','):
633 # sort and isolate the most recent, see note above in NRCS for how and
636 # NOTE: Unlike in the NRCS case, the MesoWest API response contains all
637 # data (whereas with NRCS, we have to make a separate request for
638 # each element we want). This is nice for network efficiency but
639 # it means we have to handle this part differently for each.
641 # NOTE: Also unlike NRCS, MesoWest provides more granular data; NRCS
642 # provides hourly data, but MesoWest can often provide data every
643 # 10 minutes -- though this provides more opportunity for
646 # we may not have the data at all
647 key_name
= element_cd
+ '_set_1'
649 if key_name
in observations
:
650 # val is what will make it into the dataset, after
651 # conversions... it gets defined here because in certain
652 # cases we need to look at all of the data to calculate HN24
653 # or wind averages, but for the rest of the data, we only
654 # take the most recent
657 # loop through all observations for this key_name
658 # record relevant values for wind averaging or hn24, but
659 # otherwise only persist the data if it's the last datum in
661 for idx
, _
in enumerate(observations
[key_name
]):
662 val
= observations
[key_name
][idx
]
668 # mesowest by default provides wind_speed in m/s, but
669 # we specify 'english' units in the request; either way,
671 if element_cd
in ('wind_speed', 'wind_gust'):
674 # mesowest provides HS in mm, not cm; we want cm
675 if element_cd
== 'snow_depth' and station
['units'] == 'metric':
678 # HN24 / wind_mode transformations, once the data has
679 # completed unit conversions
680 if station
['wind_mode'] == "average":
681 if element_cd
== 'wind_speed' and val
is not None:
682 wind_speed_values
.append(val
)
683 elif element_cd
== 'wind_gust' and val
is not None:
684 wind_gust_speed_values
.append(val
)
685 elif element_cd
== 'wind_direction' and val
is not None:
686 wind_direction_values
.append(val
)
688 if element_cd
== 'snow_depth':
689 hn24_values
.append(val
)
691 # again, only persist this datum to the final data if
692 # it's from the most recent date
694 remote_data
[element_cd
] = val
696 # ensure that the data is filled out
697 if not observations
[key_name
][pos
]:
698 remote_data
[element_cd
] = None
700 remote_data
[element_cd
] = None
702 if len(hn24_values
) > 0:
703 # instead of taking MAX - MIN, we want the first value (most
704 # distant) - the last value (most recent)
706 # if the result is positive, then we have settlement; if it's not,
708 hn24
= hn24_values
[0] - hn24_values
[len(hn24_values
)-1]
713 # this case represents HS settlement
717 # finally, if user wants hn24 and it's set to None at this
718 # point, then force it to 0.0
719 if station
['hn24'] and hn24
is None:
722 if len(wind_speed_values
) > 0:
723 wind_speed_avg
= sum(wind_speed_values
) / len(wind_speed_values
)
725 if len(wind_gust_speed_values
) > 0:
726 wind_gust_speed_avg
= sum(wind_gust_speed_values
) / len(wind_gust_speed_values
)
728 if len(wind_direction_values
) > 0:
729 wind_direction_avg
= sum(wind_direction_values
) / len(wind_direction_values
)
733 remote_data
['hn24'] = hn24
735 # overwrite the following with the respective averages, if
737 if wind_speed_avg
is not None:
738 remote_data
['wind_speed'] = wind_speed_avg
740 if wind_gust_speed_avg
is not None:
741 remote_data
['wind_gust'] = wind_gust_speed_avg
743 if wind_direction_avg
is not None:
744 remote_data
['wind_direction'] = wind_direction_avg
748 def switch_units_to_metric(data_map
, mapping
):
749 """replace units with metric counterparts"""
751 # NOTE: to update this, use the fmap<->final_data mapping laid out
752 # in setup_infoex_fields_mapping ()
753 data_map
[mapping
['tempMaxHourUnit']] = 'C'
754 data_map
[mapping
['tempMinHourUnit']] = 'C'
755 data_map
[mapping
['tempPresUnit']] = 'C'
756 data_map
[mapping
['precipitationGaugeUnit']] = 'mm'
757 data_map
[mapping
['hsUnit']] = 'cm'
758 data_map
[mapping
['windSpeedUnit']] = 'm/s'
759 data_map
[mapping
['windGustSpeedNumUnit']] = 'm/s'
760 data_map
[mapping
['dewPointUnit']] = 'C'
761 data_map
[mapping
['hn24AutoUnit']] = 'cm'
762 data_map
[mapping
['hstAutoUnit']] = 'cm'
766 def switch_units_to_american(data_map
, mapping
):
768 replace units with the American mixture of metric and imperial
770 Precip values = metric
771 Wind values = imperial
775 data_map
[mapping
['tempMaxHourUnit']] = 'C'
776 data_map
[mapping
['tempMinHourUnit']] = 'C'
777 data_map
[mapping
['tempPresUnit']] = 'C'
778 data_map
[mapping
['dewPointUnit']] = 'C'
780 data_map
[mapping
['precipitationGaugeUnit']] = 'cm'
781 data_map
[mapping
['hsUnit']] = 'cm'
782 data_map
[mapping
['hn24AutoUnit']] = 'cm'
783 data_map
[mapping
['hstAutoUnit']] = 'cm'
785 data_map
[mapping
['baroUnit']] = 'inHg'
788 data_map
[mapping
['windSpeedUnit']] = 'mph'
789 data_map
[mapping
['windGustSpeedNumUnit']] = 'mph'
793 def convert_nrcs_units_to_metric(element_cd
, value
):
794 """convert NRCS values from English to metric"""
795 if element_cd
== 'TOBS':
796 value
= f_to_c(value
)
797 elif element_cd
== 'SNWD':
798 value
= in_to_cm(value
)
799 elif element_cd
== 'PREC':
800 value
= in_to_mm(value
)
803 def convert_units_to_american(element_cd
, value
):
805 convert value to 'American' units
807 The original unit is always metric.
809 Precip values = metric
810 Wind values = imperial
813 # no need to convert precip values, as they will arrive in metric
814 # units in "American" units mode
816 # if element_cd in ['TMAX', 'TMIN', 'TOBS', 'air_temp', 'air_temp_high_24_hour', 'air_temp_low_24_hour']:
817 # value = c_to_f(value)
819 # mesowest provides HS in mm, not cm; we want cm
820 if element_cd
== 'snow_depth':
821 value
= mm_to_cm(value
)
823 # baro values also arrive in metric, so convert to imperial
824 if element_cd
in ['PRES', 'pressure']:
825 value
= inhg_to_pascal(value
)
827 if element_cd
in ['WSPD', 'wind_speed', 'wind_gust']:
828 value
= ms_to_mph(value
)
833 def write_local_csv(path_to_file
, data
):
834 """Write the specified CSV file to disk"""
835 with
open(path_to_file
, 'w') as file_object
:
836 # The requirement is that empty values are represented in the CSV
837 # file as "", csv.QUOTE_NONNUMERIC achieves that
838 LOG
.debug("writing CSV file '%s'", path_to_file
)
839 writer
= csv
.writer(file_object
, quoting
=csv
.QUOTE_NONNUMERIC
)
840 writer
.writerow(data
)
844 def upload_csv(path_to_file
, infoex_data
):
845 """Upload the specified CSV file to InfoEx FTP and remove the file"""
846 with
open(path_to_file
, 'rb') as file_object
:
847 LOG
.debug("uploading FTP file '%s'", infoex_data
['host'])
848 ftp
= FTP(infoex_data
['host'], infoex_data
['uuid'],
849 infoex_data
['api_key'])
850 ftp
.storlines('STOR ' + path_to_file
, file_object
)
853 os
.remove(path_to_file
)
855 # other miscellaneous routines
856 def setup_time_values(station
):
857 """establish time bounds of data request(s)"""
859 # default timezone to UTC (for MesoWest)
862 # but for NRCS, use the config-specified timezone
863 if station
['provider'] == 'nrcs':
866 # floor time to nearest hour
867 date_time
= datetime
.datetime
.now(tz
=tz
)
868 end_date
= date_time
- datetime
.timedelta(minutes
=date_time
.minute
% 60,
869 seconds
=date_time
.second
,
870 microseconds
=date_time
.microsecond
)
871 begin_date
= end_date
- datetime
.timedelta(hours
=station
['num_hrs_to_fetch'])
872 return (begin_date
, end_date
)
875 """convert Fahrenheit to Celsius"""
876 return (float(f
) - 32) * 5.0/9.0
879 """convert Celsius to Fahrenheit"""
880 return (float(c
) * 1.8) + 32
882 def in_to_cm(inches
):
883 """convert inches to centimeters"""
884 return float(inches
) * 2.54
887 """convert centimeters to inches"""
888 return float(cms
) / 2.54
890 def pascal_to_inhg(pa
):
891 """convert pascals to inches of mercury"""
892 return float(pa
) * 0.00029530
894 def inhg_to_pascal(inhg
):
895 """convert inches of mercury to pascals"""
896 return float(inhg
) / 0.00029530
898 def in_to_mm(inches
):
899 """convert inches to millimeters"""
900 return (float(inches
) * 2.54) * 10.0
903 """convert meters per second to miles per hour"""
907 """convert knots to miles per hour"""
911 """convert millimeters to centimeters"""
914 if __name__
== "__main__":