services.py 文件源码

python
阅读 29 收藏 0 点赞 0 评论 0

项目:dsmr-reader 作者: dennissiemensma 项目源码 文件源码
def read_weather():
    """ Reads the current weather state, if enabled, and stores it. """
    # Only when explicitly enabled in settings.
    if not should_sync():
        return

    # For backend logging in Supervisor.
    print(' - Performing temperature reading at Buienradar.')

    weather_settings = WeatherSettings.get_solo()

    # Fetch XML from API.
    request = urllib.request.urlopen(BUIENRADAR_API_URL)
    response_bytes = request.read()
    request.close()
    response_string = response_bytes.decode("utf8")

    # Use simplified xPath engine to extract current temperature.
    root = ET.fromstring(response_string)
    xpath = BUIENRADAR_XPATH.format(
        weather_station_id=weather_settings.buienradar_station
    )
    temperature_element = root.find(xpath)
    temperature = temperature_element.text
    print(' - Read temperature: {}'.format(temperature))

    # Gas readings trigger these readings, so the 'read at' timestamp should be somewhat in sync.
    # Therefor we align temperature readings with them, having them grouped by hour that is..
    read_at = timezone.now().replace(minute=0, second=0, microsecond=0)

    try:
        TemperatureReading.objects.create(read_at=read_at, degrees_celcius=Decimal(temperature))
    except:
        # Try again in 5 minutes.
        weather_settings.next_sync = timezone.now() + timezone.timedelta(minutes=5)
    else:
        # Push next sync back for an hour.
        weather_settings.next_sync = read_at + timezone.timedelta(hours=1)

    weather_settings.save()
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号