1919from os import path
2020
2121DRIVER_NAME = 'ambientweatherapi'
22- DRIVER_VERSION = '0.0.12'
22+ DRIVER_VERSION = '0.0.13'
23+ log = logging .getLogger (__name__ )
2324
2425
2526def loader (config_dict , engine ):
@@ -34,43 +35,35 @@ def __init__(self, **stn_dict):
3435 rainfile = "%s_%s_rain.txt" % (DRIVER_NAME , DRIVER_VERSION )
3536 self .log_file = stn_dict .get ('log_file' , None )
3637 self .loop_interval = float (stn_dict .get ('loop_interval' , 60 ))
37- self .log_level = stn_dict .get ('log_level' , 'ERROR' )
38-
39- if self .log_file and self .log_level != 'console' :
40- logging .basicConfig (format = '%(asctime)s::%(levelname)s::%(message)s' ,
41- filemode = 'w' ,
42- filename = self .log_file ,
43- level = getattr (logging , self .log_level .upper (), 'ERROR' ))
44-
4538 self .api_url = stn_dict .get ('api_url' , 'https://api.ambientweather.net/v1' )
4639 self .api_key = stn_dict .get ('api_key' )
4740 self .api_app_key = stn_dict .get ('api_app_key' )
4841 self .station_hardware = stn_dict .get ('hardware' , 'Undefined' )
4942 self .safe_humidity = float (stn_dict .get ('safe_humidity' , 60 ))
5043 self .max_humidity = float (stn_dict .get ('max_humidity' , 38 ))
5144 self .use_meteobridge = bool (stn_dict .get ('use_meteobridge' , False ))
52- logging .info ('use_meteobridge: %s' % str (self .use_meteobridge ))
45+ log .info ('use_meteobridge: %s' % str (self .use_meteobridge ))
5346 self .station_mac = stn_dict .get ('station_mac' , '' )
5447 self .use_station_mac = False
5548 if not self .station_mac :
56- logging .info ("No Station MAC specified. The first station will be returned." )
49+ log .info ("No Station MAC specified. The first station will be returned." )
5750 else :
58- logging .info ("Using Station MAC: %s" % self .station_mac )
51+ log .info ("Using Station MAC: %s" % self .station_mac )
5952 self .use_station_mac = True
6053 self .rainfilepath = os .path .join (tempfile .gettempdir (), rainfile )
61- logging .info ('Starting: %s, version: %s' % (DRIVER_NAME , DRIVER_VERSION ))
62- logging .debug ("Exiting init()" )
54+ log .info ('Starting: %s, version: %s' % (DRIVER_NAME , DRIVER_VERSION ))
55+ log .debug ("Exiting init()" )
6356
6457 @property
6558 def hardware_name (self ):
6659 """Returns the type of station."""
67- logging .debug ("calling: hardware_name" )
60+ log .debug ("calling: hardware_name" )
6861 return self .station_hardware
6962
7063 @property
7164 def archive_interval1 (self ):
7265 """Returns the archive internal."""
73- logging .debug ("calling: archive_interval" )
66+ log .debug ("calling: archive_interval" )
7467 return self .loop_interval
7568
7669 def calc_target_humidity (self , external_temp_f ):
@@ -93,45 +86,43 @@ def calc_target_humidity(self, external_temp_f):
9386 def convert_epoch_ms_to_sec (self , epoch_ms ):
9487 """Converts a epoch that's in ms to sec.
9588 AmbientAPI returns the epoch time in ms not sec"""
96- logging .debug ("calling: convert_epoch_ms_to_sec" )
89+ log .debug ("calling: convert_epoch_ms_to_sec" )
9790 utc_epoch_sec = epoch_ms / 1000
9891 return utc_epoch_sec
9992
10093 def print_dict (self , data_dict ):
10194 """Prints a dict."""
102- if logging .DEBUG >= logging .root .level :
103- logging .debug ("calling: print_dict" )
104- for key in data_dict :
105- logging .debug (key + " = " + str (data_dict [key ]))
95+ log .debug ("calling: print_dict" )
96+ for key in data_dict :
97+ log .debug (key + " = " + str (data_dict [key ]))
10698
10799 def get_value (self , data_dict , key ):
108100 """Gets the value from a dict, returns None if the key does not exist."""
109- if logging .DEBUG >= logging .root .level :
110- logging .debug ("calling: get_value" )
101+ log .debug ("calling: get_value" )
111102 return data_dict .get (key , None )
112103
113104 def get_float (self , value ):
114105 """Checks if a value is not, if not it performs a converstion to a float()"""
115- # logging .debug("calling: get_float")
106+ # log .debug("calling: get_float")
116107 if value is None :
117108 return value
118109 else :
119110 return float (value )
120111
121112 def get_battery_status (self , value ):
122113 """Converts the AM API battery status to somthing weewx likes."""
123- # logging .debug("calling: get_battery_status")
114+ # log .debug("calling: get_battery_status")
124115 if value is None :
125116 return None
126117 if (value <= 0 ):
127118 if self .use_meteobridge :
128- logging .debug ("use_meteobridge flip bit to 0.0" )
119+ log .debug ("use_meteobridge flip bit to 0.0" )
129120 return 0.0
130121 else :
131122 return 1.0
132123 else :
133124 if self .use_meteobridge :
134- logging .debug ("use_meteobridge flip bit to 1.0" )
125+ log .debug ("use_meteobridge flip bit to 1.0" )
135126 return 1.0
136127 else :
137128 return 0.0
@@ -141,39 +132,39 @@ def check_rain_rate(self, dailyrainin):
141132 correctedRain = dailyrainin
142133 try :
143134 if path .exists (self .rainfilepath ):
144- logging .debug ('Opening file: %s' % (self .rainfilepath ))
135+ log .debug ('Opening file: %s' % (self .rainfilepath ))
145136 intervalRain = open (self .rainfilepath , 'r' )
146137 try :
147138 lastRain = float (intervalRain .read ())
148139 except ValueError :
149- logging .error ('String value found. Assuming zero interval rain and recording current value' )
140+ log .error ('String value found. Assuming zero interval rain and recording current value' )
150141 lastRain = dailyrainin
151142 intervalRain .close ()
152- logging .debug ('Previous daily rain: %s' % str (lastRain ))
143+ log .debug ('Previous daily rain: %s' % str (lastRain ))
153144 else :
154- logging .debug ('No previous value found for rain, assuming interval of 0 and recording daily value' )
145+ log .debug ('No previous value found for rain, assuming interval of 0 and recording daily value' )
155146 lastRain = dailyrainin
156147
157- logging .debug ('Reported daily rain: %s' % str (dailyrainin ))
148+ log .debug ('Reported daily rain: %s' % str (dailyrainin ))
158149
159150 if lastRain > dailyrainin :
160151 correctedRain = dailyrainin
161- logging .debug ('Recorded rain is more than reported rain; using reported rain' )
152+ log .debug ('Recorded rain is more than reported rain; using reported rain' )
162153 else :
163154 correctedRain = dailyrainin - lastRain
164155 # temp
165- # logging .info('Previous daily rain: %s' % str(lastRain))
166- # logging .info('Reported daily rain: %s' % str(dailyrainin))
167- # logging .info('Calculated interval rain: %s' % str(correctedRain))
156+ # log .info('Previous daily rain: %s' % str(lastRain))
157+ # log .info('Reported daily rain: %s' % str(dailyrainin))
158+ # log .info('Calculated interval rain: %s' % str(correctedRain))
168159
169- logging .debug ('Calculated interval rain: %s' % str (correctedRain ))
160+ log .debug ('Calculated interval rain: %s' % str (correctedRain ))
170161 intervalRain = open (self .rainfilepath , 'w' )
171162 intervalRain .write (str (dailyrainin ))
172163 intervalRain .close ()
173164
174165 except Exception as e :
175- logging .error ("%s driver, function: %s encountered an error." % (DRIVER_NAME , "check_rain_rate" ))
176- logging .error ("Error caught was: %s" % e )
166+ log .error ("%s driver, function: %s encountered an error." % (DRIVER_NAME , "check_rain_rate" ))
167+ log .error ("Error caught was: %s" % e )
177168 finally :
178169 return correctedRain
179170
@@ -280,47 +271,47 @@ def get_packet_mapping(self):
280271 }
281272
282273 def genLoopPackets (self ):
283- logging .debug ("calling: genLoopPackets" )
274+ log .debug ("calling: genLoopPackets" )
284275
285276 while True :
286277 # Query the API to get the latest reading.
287278 try :
288279 error_occured = False
289- logging .debug ("starting getLoopPackets" )
280+ log .debug ("starting getLoopPackets" )
290281
291282 # Adding an extra buffer so the API throttle limit isn't hit
292- logging .debug ("sleeping an extra 3 seconds to not hit API throttle limit." )
283+ log .debug ("sleeping an extra 3 seconds to not hit API throttle limit." )
293284 time .sleep (3 )
294285
295286 # init the API
296287 weather = AmbientAPI (AMBIENT_ENDPOINT = self .api_url ,
297288 AMBIENT_API_KEY = self .api_key ,
298289 AMBIENT_APPLICATION_KEY = self .api_app_key )
299- logging .debug ("Init API call returned" )
290+ log .debug ("Init API call returned" )
300291
301292 # get the first device
302293 devices = weather .get_devices ()
303- logging .debug ("Got weather devices" )
294+ log .debug ("Got weather devices" )
304295 if not devices :
305- logging .error ('AmbientAPI get_devices() returned empty dict' )
296+ log .error ('AmbientAPI get_devices() returned empty dict' )
306297 raise Exception ('AmbientAPI get_devices() returned empty dict' )
307298 else :
308- logging .debug ('Weather get_devices() payload not empty' )
299+ log .debug ('Weather get_devices() payload not empty' )
309300
310301 # get the last report dict for the first station
311302 data = devices [0 ].last_data
312303 # check to see if the user wants a specific MAC
313304 if self .use_station_mac :
314- logging .debug ('Searching for specific Station MAC' )
305+ log .debug ('Searching for specific Station MAC' )
315306 for device in devices :
316307 if device .mac_address == self .station_mac :
317- logging .info ("Found station mac: %s" % self .station_mac )
308+ log .info ("Found station mac: %s" % self .station_mac )
318309 data = device .last_data
319310 break
320311 else :
321- logging .debug ('Specified MAC not found, using first station.' )
312+ log .debug ('Specified MAC not found, using first station.' )
322313 # info = devices[0].info
323- logging .debug ("Got last report" )
314+ log .debug ("Got last report" )
324315
325316 # Convert the epoch to the format weewx wants.
326317 current_observation = self .convert_epoch_ms_to_sec (data ["dateutc" ])
@@ -330,14 +321,14 @@ def genLoopPackets(self):
330321
331322 except Exception as e :
332323 syslog .syslog (DRIVER_NAME + " driver encountered an error." )
333- logging .error (DRIVER_NAME + " driver encountered an error." )
324+ log .error (DRIVER_NAME + " driver encountered an error." )
334325 syslog .syslog ("Error caught was: %s" % e )
335- logging .error ("Error caught was: %s" % e )
326+ log .error ("Error caught was: %s" % e )
336327 error_occured = True
337328
338329 # build the packet data
339330 try :
340- logging .debug ("============Starting Packet Build============" )
331+ log .debug ("============Starting Packet Build============" )
341332 if error_occured :
342333 error_occured = False
343334 raise Exception ('Previous error occured, skipping packet build.' )
@@ -360,29 +351,29 @@ def genLoopPackets(self):
360351 for key , value in mapping .items ():
361352 is_battery = value .startswith ('batt' )
362353 if value in data :
363- logging .debug ("Setting Weewx value: '%s' to: %s using Ambient field: '%s'" %
364- (key , str (data [value ]), value ))
354+ log .debug ("Setting Weewx value: '%s' to: %s using Ambient field: '%s'" %
355+ (key , str (data [value ]), value ))
365356 if is_battery :
366357 _packet [key ] = self .get_battery_status (data [value ])
367358 else :
368359 _packet [key ] = self .get_float (data [value ])
369360 else :
370- logging .debug ("Dropping Ambient value: '%s' from Weewx packet." % (value ))
361+ log .debug ("Dropping Ambient value: '%s' from Weewx packet." % (value ))
371362
372- self .print_dict (_packet )
373- logging .debug ("============Completed Packet Build============" )
363+ # self.print_dict(_packet)
364+ log .debug ("============Completed Packet Build============" )
374365 yield _packet
375- logging .info ("loopPacket Accepted" )
366+ log .info ("loopPacket Accepted" )
376367 except Exception as e :
377368 syslog .syslog (DRIVER_NAME + " driver had an error sending data to weewx." )
378- logging .error (DRIVER_NAME + " driver had an error sending data to weewx." )
369+ log .error (DRIVER_NAME + " driver had an error sending data to weewx." )
379370 syslog .syslog ("Error caught was: %s" % e )
380- logging .error ("Error caught was: %s" % e )
371+ log .error ("Error caught was: %s" % e )
381372
382373 # Sleepy Time
383- logging .debug ("Going to sleep" )
374+ log .debug ("Going to sleep" )
384375 time .sleep (self .loop_interval )
385- logging .debug ("Mom, I'm up!" )
376+ log .debug ("Mom, I'm up!" )
386377
387378
388379if __name__ == "__main__" :
0 commit comments