Commit 30e187f8 authored by Federico Sismondi's avatar Federico Sismondi

Update() of weather scripts for posting and getting raw weather data

parent 0d0d8f1f
#!/usr/bin/env python3
"""
Creates entity in IoT platform, and loops for ever sending updates on the weather data for Carouge
"""
import time
import logging
from weather_api import *
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# Create entity in case it doesnt exist
create_weather_entity_in_platform()
# Send updates in a loop
while True:
time.sleep(POST_DATA_PERIOD)
post_weather_data_to_platform()
#!/usr/bin/env python3
import logging
from weather_api import *
from pprint import pprint
logger = logging.getLogger()
logger.setLevel(logging.INFO)
pprint(get_all_raw_weather_data_from_platform())
\ No newline at end of file
#!/usr/bin/env python3
"""
Implements API calls related to weather use case
NOTES:
- id and type of message sent should follow convention defined for URN in spreadsheet
https://telecombretagneeu-my.sharepoint.com/:x:/g/personal/federico_sismondi_telecom-bretagne_eu/Ebw_b9iHempGoSPEz__sYCcB_qPu0pwxDAgAeKXFoMu6cA?e=6uuUGD
"""
import os
import json
import requests
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
# config environment
URL_weather_service = 'https://www.prevision-meteo.ch/services/json/carouge'
POST_DATA_PERIOD = int(os.getenv('POST_DATA_PERIOD', default='300')) # in seconds
URL_BASE = 'http://{}:1026'.format(os.getenv('ORION_HOST', default='localhost'))
dump_keys = ['city_info', 'current_condition']
# see note above about id and type
fiware_data = {
'id': 'urn:ngsi-ld:WeatherRawData:carouge_weather_observed_raw',
'type': 'WeatherRawData'
}
# build header for POST
http_header_post = {
'Fiware-Service': 'carouge',
'Fiware-ServicePath': '/Carouge/Weather/Raw',
'Content-Type': 'application/json',
'Accept': 'application/json',
}
# build header for GET
http_header_get = http_header_post.copy()
http_header_get.pop('Content-Type')
logger.info('Config: \n\tPERIOD: {} seconds \n\tURL: {}'.format(POST_DATA_PERIOD, URL_BASE))
def get_data_from_weather_service():
logger.info('Querying weather service..')
try:
r = requests.get(
url=URL_weather_service,
timeout=90,
)
except (requests.exceptions.ConnectTimeout, requests.exceptions.ConnectionError):
logger.info('Could not weather reach service')
return None
weather_data = {k: v for k, v in r.json().items() if k in dump_keys}
return weather_data
def create_weather_entity_in_platform():
weather_data = get_data_from_weather_service()
assert weather_data, 'Weather data not defined'
logger.info('Creating entity')
response = None
try:
entity = {**weather_data, **fiware_data}
with open('weather_raw_last_data.json', encoding='utf-8', mode='w') as f:
json.dump(
obj=entity,
fp=f
)
response = requests.post(
url=URL_BASE + '/v2/entities?options=keyValues',
headers=http_header_post,
json=entity
)
logger.info('Got {}'.format(response.status_code))
except (requests.exceptions.ConnectTimeout, requests.exceptions.ConnectionError):
logger.error('IoT Platform at {} seems unreachable'.format(URL_BASE))
if response and response.ok:
return True
else:
logger.error('Operation failed, got message: {}'.format(response.json()))
return False
def post_weather_data_to_platform():
weather_data = get_data_from_weather_service()
assert weather_data, 'Weather data not defined'
logger.info('Posting weather data to platform')
response = None
try:
entity = {**weather_data}
with open('weather_raw_last_data.json', encoding='utf-8', mode='w') as f:
json.dump(
obj=entity,
fp=f
)
response = requests.put(
url=URL_BASE + '/v2/entities/{}/attrs?options=keyValues'.format(fiware_data['id']),
headers=http_header_post,
json=entity
)
logger.info('Got {}'.format(response.status_code))
except (requests.exceptions.ConnectTimeout, requests.exceptions.ConnectionError):
logger.error('IoT Platform at {} seems unreachable'.format(URL_BASE))
if response and response.ok:
return True
else:
logger.error('Operation failed, got message: {}'.format(response.json()))
return False
def get_all_raw_weather_data_from_platform():
logger.info('Getting all RAW weather data from platform')
response = None
try:
response = requests.get(
url=URL_BASE + '/v2/entities/?options=keyValues&type={}'.format(fiware_data['type']),
headers=http_header_get,
)
logger.info('Got {}'.format(response.status_code))
except (requests.exceptions.ConnectTimeout, requests.exceptions.ConnectionError):
logger.error('IoT Platform at {} seems unreachable'.format(URL_BASE))
if response and response.ok:
return response.json()
else:
logger.error('Operation failed, got message: {}'.format(response.json()))
return False
__all__ = [
'URL_weather_service',
'POST_DATA_PERIOD',
'URL_BASE',
'post_weather_data_to_platform',
'get_data_from_weather_service',
'create_weather_entity_in_platform',
'get_all_raw_weather_data_from_platform'
]
{"city_info": {"name": "Carouge", "country": "Suisse", "latitude": "46.1838613", "longitude": "6.1385878", "elevation": "388", "sunrise": "05:56", "sunset": "21:06"}, "current_condition": {"date": "18.05.2020", "hour": "14:00", "tmp": 23, "wnd_spd": 17, "wnd_gust": 27, "wnd_dir": "NE", "pressure": 1017.6, "humidity": 45, "condition": "Ensoleill\u00e9", "condition_key": "ensoleille", "icon": "https://www.prevision-meteo.ch/style/images/icon/ensoleille.png", "icon_big": "https://www.prevision-meteo.ch/style/images/icon/ensoleille-big.png"}}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment