Skip to content

Weather Underground (wunderground)

henfri edited this page Jan 2, 2015 · 1 revision

Item

Mandatory:

[Wetter]
    [[wunderground_url]]
        type = str
        value = http://api.wunderground.com/api/13f6a0e88a00bfa5/conditions/forecast/astronomy/lang:DL/q/Germany/Bremen.xml

The items are identified by an xml_string, e.g wind_degrees. Create an Item with a parameter xmlstring

[Anything]
    [[Windrichtung]]
        type = num
        xmlstring = wind_degrees
        knx_send = 7/7/15
        knx_dpt = 9

Code

Put this into logics/wunderground.py

#!/usr/bin/python3.2
# Version 2.1
# Version 2.2:  fixed clean for negative values
#		works with stings now if item is of type str

import xml.etree.ElementTree as ET
from urllib.request import urlopen

weatheritems=sh.Wetter
url=weatheritems.wunderground_url()



def clean(v):
  try:
   import re 
   non_decimal = re.compile(r'[^-?\d*\.{0,1}\d+$]')
   w=float(non_decimal.sub('', v))
   if v.find('%')>0:
         w=w/100
   return w
  except:
   return -99999

#response= urllib2.urlopen('http://api.wunderground.com/weatherstation/WXCurrentObXML.asp?ID=INIEDERS60')
#response= urlopen('http://api.wunderground.com/api/13f6a0e88a00bfa5/conditions/forecast/astronomy/lang:DL/q/Germany/Bremen.xml')
#xml=response.read()

#url='http://api.wunderground.com/api/13f6a0e88a00bfa5/conditions/forecast/astronomy/lang:DL/q/Germany/Bremen.xml'

xml = sh.tools.fetch_url(url)
#xml=minidom.parseString(xml)
tree=ET.fromstring(xml)


logger.debug('[Wunderground] xml heruntergeladen {0}'.format(xml))

for item in sh.find_children(weatheritems, 'xmlstring'):
 try:
  s=item.conf['xmlstring']
  if len(s)>0:
   logger.debug('[Wunderground] Behandle jetzt Item {0} mit xmlstring {1}'.format(item,s))
   val=tree.findall('*/'+s)
   if len(val)==0:
     val=tree.findall(s)
   if len(val)>0:
     val=val[0].text
     logger.debug('[Wunderground] Wert {0} in xml gefunden'.format(val))
     if not isinstance(item(), str):
        val=clean(val)
     if val!=-99999:
       item(val)
       logger.debug('[Wunderground] Wert {0} ins item geschrieben'.format(val))
     else:
       logger.debug('[Wunderground] WARNUNG: Wert konnte nicht gecleaned werden. Kein Wert ins item geschrieben')  
   else:
    logger.warning('[Wunderground] returned empty value for item {0}'.format(item))   
 except KeyError:
   logger.debug('[Wunderground] xmlstring is empty or not existent for item {0}'.format(item))
   pass