Exemplo n.º 1
0
def refresh_sensors(credentials):
    # Access to the sensors
    try:
        auth = lnetatmo.ClientAuth(
            clientId=credentials["NETATMO_CLIENT_ID"],
            clientSecret=credentials["NETATMO_CLIENT_SECRET"],
            username=credentials["NETATMO_USERNAME"],
            password=credentials["NETATMO_PASSWORD"],
            scope="read_station")

    except lnetatmo.AuthFailure as e:
        print(e, end=" ")
        print("\nWrong password or username.")
        exit_routine(10)
    except socket.timeout as e:
        print(e, end=" ")
        print("\nA timeout occoured.")
        return None

    try:
        dev = lnetatmo.WeatherStationData(auth)
        stations = dev.stationByName()
        return stations
    except TypeError as e:
        print(e)
        pass
        return None
Exemplo n.º 2
0
def setup(hass, config):
    """Setup the Netatmo devices."""
    if not validate_config(config, {
            DOMAIN:
        [CONF_API_KEY, CONF_USERNAME, CONF_PASSWORD, CONF_SECRET_KEY]
    }, _LOGGER):
        return None

    import lnetatmo

    global NETATMO_AUTH
    try:
        NETATMO_AUTH = lnetatmo.ClientAuth(
            config[DOMAIN][CONF_API_KEY], config[DOMAIN][CONF_SECRET_KEY],
            config[DOMAIN][CONF_USERNAME], config[DOMAIN][CONF_PASSWORD],
            "read_station read_camera "
            "access_camera")
    except HTTPError:
        _LOGGER.error("Connection error "
                      "Please check your settings for NatAtmo API.")
        return False

    for component, discovery_service in (('camera', DISCOVER_CAMERAS),
                                         ('sensor', DISCOVER_SENSORS)):
        discovery.discover(hass,
                           discovery_service,
                           component=component,
                           hass_config=config)

    return True
Exemplo n.º 3
0
def setup(hass, config):
    """Setup the Netatmo devices."""
    if not validate_config(config, {
            DOMAIN:
        [CONF_API_KEY, CONF_USERNAME, CONF_PASSWORD, CONF_SECRET_KEY]
    }, _LOGGER):
        return None

    import lnetatmo

    global NETATMO_AUTH
    try:
        NETATMO_AUTH = lnetatmo.ClientAuth(
            config[DOMAIN][CONF_API_KEY], config[DOMAIN][CONF_SECRET_KEY],
            config[DOMAIN][CONF_USERNAME], config[DOMAIN][CONF_PASSWORD],
            "read_station read_camera "
            "access_camera")
    except HTTPError:
        _LOGGER.error("Connection error "
                      "Please check your settings for NatAtmo API.")
        return False

    for component in 'camera', 'sensor':
        discovery.load_platform(hass, component, DOMAIN, {}, config)

    return True
Exemplo n.º 4
0
    def data_available(self):
        if not self.netatmoDevList:

            if self.natatmoAuthorization == None:
                config = ConfigParser.ConfigParser()
                config.read("netatmo-auth.cfg")

                if config.get("Netatmo_Auth", "clientsecret") == "":
                    raise RuntimeError('Netatmo authentication information are missing in netatmo-auth.cfg')

                self.natatmoAuthorization = lnetatmo.ClientAuth( clientId = config.get("Netatmo_Auth", "clientid"),
                                                                 clientSecret = config.get("Netatmo_Auth", "clientsecret"),
                                                                 username = config.get("Netatmo_Auth", "username"),
                                                                 password = config.get("Netatmo_Auth", "password") )

                if self.natatmoAuthorization == None:
                    print('Netatmo authentication failed')
                    return False
            
            self.netatmoDevList = lnetatmo.DeviceList(self.natatmoAuthorization)

            if self.netatmoDevList == None:
                print('Could not get Netatmo device list')
                return False

        self.humidity = self.netatmoDevList.lastData()[self.netatmoName]['Humidity']
        self.temperature = self.netatmoDevList.lastData()[self.netatmoName]['Temperature']

        return True
Exemplo n.º 5
0
    def __init__(self,
                 device_metadata: Dict[str, Any] = None,
                 username: str = None,
                 password: str = None,
                 client_id: str = None,
                 client_secret: str = None) -> None:
        """Represent the metadata for all devices, modules and measurements in a Netatmo Login. Can accept either the
        actual metadata (device_metadata) or the login information for an account so the information is fetched from
        the Netatmo Api."""
        if not (device_metadata or
                (username and password and client_id and client_secret)):
            raise NetatmoDomainError(
                f'{NetatmoDomain.__name__} needs either device_metadata directly or complete'
                f'login information.')

        if device_metadata:
            metadata = device_metadata
        else:
            auth = lnetatmo.ClientAuth(clientId=client_id,
                                       clientSecret=client_secret,
                                       username=username,
                                       password=password,
                                       scope='read_station')
            device_data = lnetatmo.WeatherStationData(auth)

            metadata = device_data.stations

        self.metadata: Dict[str, Any] = metadata

        self.stations: List[NetatmoStation] = [
            NetatmoStation(**station) for station in metadata.values()
        ]
Exemplo n.º 6
0
def parcours(bouton):
    authorization = lnetatmo.ClientAuth()
    devList = lnetatmo.WeatherStationData(authorization)
    
    device = tingbot.app.settings['Module']["P"+str(bouton)][3]
    logo = tingbot.app.settings['Module']["P"+str(bouton)][2]
    titre = tingbot.app.settings['Module']["P"+str(bouton)][1]
    value = devList.lastData('MeteoNicho')[tingbot.app.settings['Module']["P"+str(bouton)][3]][tingbot.app.settings['Module']["P"+str(bouton)][4]]
    value_prec = tingbot.app.settings['Module']["P"+str(bouton)][6]
    temp = str(devList.lastData('MeteoNicho')[tingbot.app.settings['Module']["P"+str(bouton)][3]][tingbot.app.settings['Module']["P"+str(bouton)][4]]) + " " + tingbot.app.settings['Module']["P"+str(bouton)][5]
    

        
    if tingbot.app.settings['Module']["P"+str(bouton)][4] == "Temperature":
        if value > 20:
            couleur = "red"
        else:
            couleur = "green"
        
    if tingbot.app.settings['Module']["P"+str(bouton)][4] == "Humidity":
        if value > 80:
            couleur = "red"
        elif value < 40:
            couleur = "green"
        else:
            couleur = "orange"
    
    screen.fill(color='white')
    
    # Partie concernant la variation de temperature par rapport a la precedente
    
    #screen.text(str(value) + str(value_prec['prec']), xy=(190,180), font_size=25, color='black')
    
    if value > value_prec['prec']:
        screen.image("monte.png", xy=(220,180), max_width=120, max_height=120)
    elif value < value_prec['prec']:
        screen.image("descend.png", xy=(220,180), max_width=120, max_height=120)
    else:
        screen.image("stable.png", xy=(220,180), max_width=120, max_height=120)
    
    value_prec['prec'] = value
    #tingbot.app.settings['Module']["P"+str(bouton)][6] = "{'prec' : "+int(value)+"}"
    
    screen.image(logo,xy=(130,180),max_width=60,max_height=100)
    screen.text(titre,xy=(160,20),color='black', font_size=25)
    screen.text(temp,xy=(155,100),color=couleur,font_size=80)
    
    temps = time.gmtime()
    #local_time = time.ctime(seconds)
    screen.update()
    
    screen.text("Update : " + str(temps.tm_mday) + "/" + str(temps.tm_mon) + " " + str(temps.tm_hour+2) + "h" + str(temps.tm_min) , color='blue',xy=(255,235),font_size=10)
    
    screen.text(' A propos de NetAtmoTingBot',xy=(70,235),font_size=10, color='red')
    screen.update()
Exemplo n.º 7
0
    def __init__(self):
        # NETATMOの認証情報を設定
        self.authorization = lnetatmo.ClientAuth(
                        clientId = "NETATMO Client id",
                        clientSecret = "NETATMO Client secret",
                        username = "******",
                        password = "******",
        )

        # ThingSpeakのWrite_API_Keyを設定
        self.apikey = "ThingSpeak Write API Key"
Exemplo n.º 8
0
    def create_netatmo_connection(self) -> ty.Tuple[lnetatmo.WeatherStationData, NetatmoDomain]:
        """Refresh the netatmo connection."""
        auth = lnetatmo.ClientAuth(clientId=self.client_id,
                                   clientSecret=self.client_secret,
                                   username=self.username,
                                   password=self.password,
                                   scope='read_station')
        device_data = lnetatmo.WeatherStationData(auth)
        domain = NetatmoDomain(device_data.stations)

        return device_data, domain
Exemplo n.º 9
0
def get_measurement(location, debug=False, test_fail_netatmo=False):

    name = location.name2
    try:
        authorization = lnetatmo.ClientAuth()

        # 2 : Get devices list
        weather_data = lnetatmo.WeatherStationData(authorization)
        if debug:
            print(weather_data.stationByName(name))
            print(weather_data.rawData)

        weather_data = get_netatmo_station_data(weather_data.rawData, location.home_id, debug=debug)

        # Inddor
        if debug:
            print("Inddor data:")

        indoor_values = get_netatmo_indoor_data(weather_data, debug=debug)
        if debug:
            print(indoor_values)

        # Outdoor
        if debug:
            print("Outddor data:")
        outdoor_values = get_netatmo_module_data(weather_data, "Temperature")
        if debug:
            print(outdoor_values)

        # Rain
        if debug:
            print("Rain data")
        rain_values = get_netatmo_module_data(weather_data, "Rain")
        if debug:
            print(rain_values)

        if debug:
            print(indoor_values)
            print(outdoor_values)
            print(rain_values)

        if test_fail_netatmo:
            raise Exception("test_fail_netatmo")

        return indoor_values, outdoor_values, rain_values
    except:
        print("Could not access and get all Netatmo station data")
        raise
Exemplo n.º 10
0
def setup(hass, config):
    """Set up the Netatmo devices."""
    import lnetatmo

    global NETATMO_AUTH
    try:
        NETATMO_AUTH = lnetatmo.ClientAuth(
            config[DOMAIN][CONF_API_KEY], config[DOMAIN][CONF_SECRET_KEY],
            config[DOMAIN][CONF_USERNAME], config[DOMAIN][CONF_PASSWORD],
            'read_station read_camera access_camera')
    except HTTPError:
        _LOGGER.error("Unable to connect to Netatmo API")
        return False

    for component in 'camera', 'sensor':
        discovery.load_platform(hass, component, DOMAIN, {}, config)

    return True
Exemplo n.º 11
0
    def _auth(self) -> bool:
        try:
            self._netatmoAuth = lnetatmo.ClientAuth(
                clientId=self.getConfig('clientId'),
                clientSecret=self.getConfig('clientSecret'),
                username=self.getConfig('username'),
                password=self.getConfig('password'),
                scope='read_station')
        except Exception:
            self._authTries += 1
            if self._authTries >= 3:
                self.logWarning('Tried to auth 3 times, giving up now')
                raise ModuleStartingFailed
            else:
                time.sleep(1)
                return self._auth()

        return True
Exemplo n.º 12
0
    def _auth(self) -> bool:
        try:
            self._netatmoAuth = lnetatmo.ClientAuth(
                clientId=self.getConfig('clientId'),
                clientSecret=self.getConfig('clientSecret'),
                username=self.getConfig('username'),
                password=self.getConfig('password'),
                scope='read_station')
        except lnetatmo.AuthFailure:
            self._authTries += 1
            if self._authTries >= 3:
                self._logger.warning(
                    f'[{self.name}] Tried to auth 3 times, giving up now')
                return False
            else:
                time.sleep(1)
                return self._auth()

        return True
Exemplo n.º 13
0
def getNetatmoData():
    authorization = lnetatmo.ClientAuth()
    devList = lnetatmo.WeatherStationData(authorization)

    when = datetime.fromtimestamp(int(devList.lastData()['Balcon']['When']))

    string = str(
        devList.lastData()['Balcon']['Temperature']) + " °C at " + str(
            datetime.fromtimestamp(int(devList.lastData()['Balcon']['When'])).
            strftime('%d-%m-%Y %H:%M:%S'))

    rss.items = [
        PyRSS2Gen.RSSItem(title=string,
                          link="",
                          description=string,
                          pubDate=when)
    ]

    rss.lastBuildDate = when
    rss.write_xml(open("/pyrss2gen.xml", "w"))
Exemplo n.º 14
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """ Get the NetAtmo sensor. """

    if not validate_config({
            DOMAIN: config
    }, {DOMAIN: [CONF_API_KEY, CONF_USERNAME, CONF_PASSWORD, CONF_SECRET_KEY]},
                           _LOGGER):
        return None

    import lnetatmo

    authorization = lnetatmo.ClientAuth(config.get(CONF_API_KEY, None),
                                        config.get(CONF_SECRET_KEY, None),
                                        config.get(CONF_USERNAME, None),
                                        config.get(CONF_PASSWORD, None))

    if not authorization:
        _LOGGER.error("Connection error "
                      "Please check your settings for NatAtmo API.")
        return False

    data = NetAtmoData(authorization)

    dev = []
    try:
        # Iterate each module
        for module_name, monitored_conditions in config[ATTR_MODULE].items():
            # Test if module exist """
            if module_name not in data.get_module_names():
                _LOGGER.error('Module name: "%s" not found', module_name)
                continue
            # Only create sensor for monitored """
            for variable in monitored_conditions:
                if variable not in SENSOR_TYPES:
                    _LOGGER.error('Sensor type: "%s" does not exist', variable)
                else:
                    dev.append(NetAtmoSensor(data, module_name, variable))
    except KeyError:
        pass

    add_devices(dev)
Exemplo n.º 15
0
def setup(hass, config):
    """Set up the Netatmo devices."""
    import lnetatmo

    global NETATMO_AUTH
    try:
        NETATMO_AUTH = lnetatmo.ClientAuth(
            config[DOMAIN][CONF_API_KEY], config[DOMAIN][CONF_SECRET_KEY],
            config[DOMAIN][CONF_USERNAME], config[DOMAIN][CONF_PASSWORD],
            'read_station read_camera access_camera '
            'read_thermostat write_thermostat '
            'read_presence access_presence', config[DOMAIN][CONF_APP_VERSION],
            config[DOMAIN][CONF_USER_PREFIX])

    except HTTPError:
        _LOGGER.error("Unable to connect to Netatmo API")
        return False

    if config[DOMAIN][CONF_DISCOVERY]:
        discovery.load_platform(hass, 'climate', DOMAIN, {}, config)

    return True
Exemplo n.º 16
0
    def pull(self, token=None, callerToken=None):
        authentication = self.pluginData.get('authentication', {})
        if not authentication.get('clientId'):
            return self.igor.app.raiseHTTPError(
                "400 Plugindata authentication does not contain clientId")
        if not authentication.get('clientSecret'):
            return self.igor.app.raiseHTTPError(
                "400 Plugindata authentication does not contain clientSecret")
        if not authentication.get('username'):
            return self.igor.app.raiseHTTPError(
                "400 Plugindata authentication does not contain username")
        if not authentication.get('password'):
            return self.igor.app.raiseHTTPError(
                "400 Plugindata authentication does not contain password")
        # xxxjack could also honor `scope` parameter here...
        try:
            authorization = lnetatmo.ClientAuth(**authentication)
        except lnetatmo.AuthFailure as e:
            return self.igor.app.raiseHTTPError("502 netatmo: {}".format(
                str(e)))

        # xxxjack could also add `station` parameter here for multiple weather statiosn
        # xxxjack could also add other types, such as ThermostatData
        weatherDataAccessor = lnetatmo.WeatherStationData(authorization)
        weatherData = weatherDataAccessor.lastData()
        for stationName in weatherData:
            path = '/data/sensors/{}/{}'.format(self.pluginName, stationName)
            data = weatherData[stationName]
            rv = self.igor.databaseAccessor.put_key(
                path,
                'text/plain',
                None,
                data,
                'application/x-python-object',
                token,
                replace=True)

        return 'ok\n'
Exemplo n.º 17
0
# encoding: utf-8
import time
import lnetatmo
import os
from slackclient import SlackClient
import schedule
import time

module_name = os.getenv("NETATOMO_MODULE_NAME")
authorization = lnetatmo.ClientAuth(
    clientId=os.getenv("NETATOMO_CLIENT_ID"),
    clientSecret=os.getenv("NETATOMO_CLIENT_SECRET"),
    username=os.getenv("NETATOMO_USER_NAME"),
    password=os.getenv("NETATOMO_PASS"),
    scope="read_station")

slack_token = os.getenv("SLACK_TOKEN")
slack_user_id = os.getenv("SLACK_USER_ID")
slack_user_name_prefix = os.getenv("SLACK_USER_NAME_PREFIX")
client = SlackClient(slack_token)


def job():
    weather_station = lnetatmo.WeatherStationData(authorization)
    ppm = weather_station.lastData()[module_name]['CO2']
    display_name = f'{slack_user_name_prefix}{ppm}ppm'
    client.api_call("users.profile.set",
                    user=slack_user_id,
                    profile={'display_name': display_name})
    print(display_name)
Exemplo n.º 18
0
def get_weather(device_id,
                client_id,
                client_secret,
                username,
                password,
                station_id=None):
    weather = {}
    weather['wind_direction'] = '...'
    weather['wind_speed'] = '...'
    weather['gust'] = '...'
    weather['temperature'] = '...'
    weather['rain_1hr'] = '...'
    weather['rain_24hr'] = '...'
    weather['rain_midnight'] = '...'
    weather['humidity'] = '..'
    weather['pressure'] = '.....'

    authorization = lnetatmo.ClientAuth(client_id, client_secret, username,
                                        password)

    device_list = lnetatmo.DeviceList(authorization)
    if not device_id in device_list.stations:
        return

    device_data = device_list.stations[device_id]
    place_data = device_data['place']

    # Select between Station ('Indoor' v 'Outdoor') and Dashboard Data.
    if station_id is not None:
        readings = device_list.lastData()[station_id]
        last_reading = readings['When']
    else:
        readings = device_data['dashboard_data']
        last_reading = readings['time_utc']

    # Humidity is an acceptable format for APRS:
    weather['humidity'] = readings['Humidity']

    # Convert C to F for APRS:
    weather['temperature'] = netatmoaprs.c2f(readings['Temperature'])

    # Convert float to APRS format:
    if 'Pressure' in readings:
        weather['pressure'] = str(readings['Pressure']).replace('.', '')

    # Convert UTC Epoch to DHM Zulu:
    weather['timestamp'] = time.strftime('%d%H%M', time.gmtime(last_reading))

    # Get location data and convert to APRS format:
    weather['latitude'] = aprs.geo_util.dec2dm_lat(place_data['location'][1])
    weather['longitude'] = aprs.geo_util.dec2dm_lng(place_data['location'][0])

    frame = "@%sz%s/%s_%s/%sg%st%03dr%sp%sP%sh%02db%sNttm" % (
        weather['timestamp'],
        weather['latitude'],
        weather['longitude'],
        weather['wind_direction'][:3],
        weather['wind_speed'][:3],
        weather['gust'][:3],
        weather['temperature'],
        weather['rain_1hr'][:3],
        weather['rain_24hr'][:3],
        weather['rain_midnight'][:3],
        weather['humidity'],
        weather['pressure'],
    )
    return frame
Exemplo n.º 19
0
def netatmoIndoor(sonde):
    authorization = lnetatmo.ClientAuth()
    devList = lnetatmo.WeatherStationData(authorization)
    msg = (sonde + " current temperature : %s C" %
           (devList.lastData()[sonde]['Temperature']))
    return msg
Exemplo n.º 20
0
def create_json_stub(measurementName, tagkey, tagvalue):
    json_item = {}
    json_item.update({"measurement": measurementName})
    json_item.update({"tags": {tagkey: tagvalue}})
    json_item.update({"fields": {}})
    return json_item


# Connect to InfluxDB
client = InfluxDBClient(influxcred['Host'], influxcred['Port'],
                        influxcred['Username'], influxcred['Password'],
                        influxcred['Database'])

# Connect to netatmo
authorization = lnetatmo.ClientAuth()
weatherData = lnetatmo.WeatherStationData(authorization)

# Preparing JSON for InfluxDB request
json_body = []

# Iterate over stations
for station in weatherData.stations:
    # print (station)
    json_item = create_json_stub(influxcred['Measurement'], "station", station)
    for sensor in weatherData.stationById(station)['data_type']:
        json_item['fields'].update({
            sensor:
            weatherData.stationById(station)['dashboard_data'][sensor]
        })
        # print (sensor)
Exemplo n.º 21
0
import lnetatmo
import requests
import time
import json
import datetime
import pyodbc
from password.password import *

# Netatmoの認証情報
authorization = lnetatmo.ClientAuth(clientId=NETA_ID,
                                    clientSecret=NETA_PW,
                                    username=STD_EMAIL,
                                    password=STD_PW,
                                    scope="")

# Netatmoからのデータ取得
devList = lnetatmo.WeatherStationData(authorization)
outdoors_temp = devList.lastData()['Outdoor']['Temperature']
outdoors_humi = devList.lastData()['Outdoor']['Humidity']

#HANAのタイムスタンプへの変換
posttime = time.time()
print(posttime)
posttime = posttime * 1000
print(posttime)
posttime = posttime + 32400000
print(posttime)
posttime = str(posttime)
print(posttime)
posttime = posttime[0:13]
print(posttime)
Exemplo n.º 22
0
import lnetatmo  # Netatmo library
from time import sleep  # Not sure why
import serial  # Arduino

#---------------------------------------------------------------------GET NETATMO DATA----------------------------------------------------------------------------
#Authenticate netatmo
authorization = lnetatmo.ClientAuth(
    clientId="Enter CLIENT ID here",
    clientSecret="Enter CLIENT SECRET here",
    username="******",
    password="******",
    scope="read_station")

#Get devices list
weatherData = lnetatmo.WeatherStationData(authorization)

#Access most fresh data directly

#---------------------------------------------------------------------------ARDUINO CODE--------------------------------------------------------------------------

COM = 'COM3'  #Change Value depending on Arduino Port

ser = serial.Serial(COM, 9600)  # Establish the connection on a specific port
counter = 32  # Below 32 everything in ASCII is gibberish
while True:

    co2 = (weatherData.lastData()['Netatmo02']['CO2']
           )  #Collect CO2 reading from Netatmo					#
    print("Current CO2 reading(T100): %s ppm\t ,sending to Arduino..." %
          (co2))  #Print CO2 reading on console
    #counter +=1
Exemplo n.º 23
0
ssm_client = boto3.client("ssm")
parameters = ssm_client.get_parameters_by_path(Path="/netatmo",
                                               Recursive=True,
                                               WithDecryption=True)
params = {}
print("Loading parameters")
for param in parameters["Parameters"]:
    param_name = param["Name"].split("/")[-1].upper().replace("-", "_")
    print("... {}".format(param_name))
    params[param_name] = param["Value"]

cloudwatch_client = boto3.client("cloudwatch")
auth = lnetatmo.ClientAuth(
    clientId=params["CLIENT_ID"],
    clientSecret=params["CLIENT_SECRET"],
    username=params["NETATMO_USERNAME"],
    password=params["NETATMO_PASSWORD"],
)


def post_metrics(metric_data):
    """Send prepared metric data to CloudWatch"""
    cloudwatch_client.put_metric_data(Namespace="netatmo",
                                      MetricData=metric_data)


def post_error_metric():
    post_metrics([{
        "MetricName": "apierror",
        "Timestamp": time.time(),
        "Value": 1,
Exemplo n.º 24
0
 def __init__(self, clientId, clientSecret, user, password, verbose=True):
     self.devList = WeatherStationData(lnetatmo.ClientAuth(clientId, clientSecret, user, password))
Exemplo n.º 25
0
    if len(sys.argv) > 1:
        fh = open(sys.argv[1], "w")

    print(data, file=fh)

    if len(sys.argv) > 1:
        fh.close()


secrets = load_secrets()

try:
    authorization = lnetatmo.ClientAuth(clientId=secrets.get('CLIENT_ID', ''),
                                        clientSecret=secrets.get(
                                            'CLIENT_SECRET', ''),
                                        username=secrets.get('USERNAME', ''),
                                        password=secrets.get('PASSWORD', ''))

    weatherData = lnetatmo.WeatherStationData(authorization)

    #pprint(weatherData.__dict__)

    output = build_json(weatherData)

    json_data = json.dumps(output)

    dump_json(json_data)
except HTTPError as err:
    print("Fetch error {err.code} - {err.msg}".format(err=err),
          file=sys.stderr)
Exemplo n.º 26
0
import lnetatmo
import requests
import time
import json
import datetime
import pyodbc
from password import *

authorization = lnetatmo.ClientAuth(clientId=neta_id,
                                    clientSecret=neta_pw,
                                    username=email,
                                    password=std_pw,
                                    scope="")

devList = lnetatmo.WeatherStationData(authorization)

outdoors_temp = devList.lastData()['Outdoor']['Temperature']
outdoors_humi = devList.lastData()['Outdoor']['Humidity']

# print (time.time())
# print (time.time() * 1000)

posttime = time.time() * 1000
posttime = posttime + 32400000
posttime = str(posttime)
posttime = posttime[0:13]
posttime = '/Date(' + posttime + ")/"

datetime = datetime.datetime.now()
datetime = str(datetime)
datetime = datetime[0:19]
Exemplo n.º 27
0
def main():
    # Main program block
    # Initialise display
    lcd_init()

    napis = "Opakovani n="

    while True:
        #           12345678901234567890
        lcd_string("Getting tempture1...", LCD_LINE_1)
        lcd_string("From NetAtmo and ", LCD_LINE_2)
        lcd_string("From DS18B20 sensor", LCD_LINE_3)
        lcd_string("Dvorek,puda,pudicka", LCD_LINE_4)
        #req = "Teplota 00 :-("
        datumcas = datetime.datetime.now().strftime("Cas: %Y-%m-%d %H:%M:%S")
        dvorek = "000"
        puda = "000"

        try:
            reqt = requests.get('http://www.t1.cz/puda.temp', timeout=10)
            esp8266 = reqt.text.rstrip()
            tlak = esp8266.split(' ')
            akt = float(tlak[0][:-2])
            atm = float(tlak[1][:-3])
            # Math Expression to count pressure to the sea level:
            # ( pressure * 9.80665 * meters_above_sea ) / (273 + actual_temperature + (meters_above_sea/400)) + pressure
            vypocet = (atm * 9.80665 * mnm) / (287 * (273 + akt +
                                                      (mnm / 400))) + atm
            tlak_hladina = int(round(vypocet))
            esp_line = "ESP: " + str(akt) + "C, " + str(tlak_hladina) + "hPa"
        except requests.exceptions.RequestException as reqt:
            print datumcas
            print reqt
            esp8266 = "ESP nejede"

        try:
            # 1 : Authenticate NetAtmo
            authorization = lnetatmo.ClientAuth()
            # 2 : Get devices list
            devList = lnetatmo.DeviceList(authorization)
        except IOError:
            print "IOError"

        dvorek = devList.lastData("Plzenska")['dvorek']['Temperature']
        puda = devList.lastData("Plzenska")['puda']['Temperature']
        netatmo = str(dvorek) + ", " + str(puda)
        datum = datetime.datetime.now().strftime("Date: %Y-%m-%d")
        fo = open(TEMPERFILE, "w")
        fo.write(netatmo)
        fo.close()
        for i in range(REVOL):
            if (GPIO.input(19)):
                LCD_BACKLIGHT = 0x08  # On
            else:
                LCD_BACKLIGHT = 0x00  # Off

            #print("LCD Backlight")
            #print(LCD_BACKLIGHT)
            #lcd_byte(0x0C, LCD_CMD)

            cas = datetime.datetime.now().strftime("%H:%M:%S %d.%m.%Y")
            lcd_string("Venku: " + str(dvorek) + "C..W" + str(i), LCD_LINE_1)
            lcd_string(" Puda: " + str(puda) + "C", LCD_LINE_2)
            lcd_string(esp_line, LCD_LINE_3)
            lcd_string(cas, LCD_LINE_4)

            time.sleep(SLEEPTIME)
Exemplo n.º 28
0
#!/usr/bin/python35

import json, lnetatmo

creds = json.loads(open('.netatmo.credentials').read())
authorization = lnetatmo.ClientAuth(clientId=creds['CLIENT_ID'],
                                    clientSecret=creds['CLIENT_SECRET'],
                                    username=creds['USERNAME'],
                                    password=creds['PASSWORD'])
wsdata = lnetatmo.WeatherStationData(authorization)

print("Current temperature (inside/outside): %s / %s C, Wind: %s km/h" %
      (wsdata.lastData()['Indoor']['Temperature'],
       wsdata.lastData()['Outdoor']['Temperature'],
       wsdata.lastData()['Veranda']['GustStrength']))

data = wsdata.lastData(exclude=3600)
print('--- all JSON data ------------------------')
print(data)
print('--- variables in modules -----------------')
for module_name in data.keys():
    for variable in data[module_name]:
        print('module %s: var %s' % (module_name, variable))

print('--- monitored conditions -----------------')
for module_name in data.keys():
    for variable in wsdata.monitoredConditions(module_name):
        print('module %s: var %s' % (module_name, variable))

#for name in data.keys():
#	print(wsdata.moduleByName(name)['dashboard_data'])
# settings from EnvionmentValue
netatmo_clientId = os.getenv('NETATMO_CLIENT_ID', "")
netatmo_clientSecret = os.getenv('NETATMO_CLIENT_SECRET', "")
netatmo_username = os.getenv('NETATMO_USERNAME')
netatmo_password = os.getenv('NETATMO_PASSWORD')
#
influxdb_host = os.getenv('INFLUXDB_HOST', "")
influxdb_port = int(os.getenv('INFLUXDB_PORT', "8086"))
influxdb_username = os.getenv('INFLUXDB_USERNAME', "")
influxdb_password = os.getenv('INFLUXDB_PASSWORD', "")
influxdb_database = os.getenv('INFLUXDB_DATABASE', "")

# netatmo
authorization = lnetatmo.ClientAuth(clientId=netatmo_clientId,
                                    clientSecret=netatmo_clientSecret,
                                    username=netatmo_username,
                                    password=netatmo_password)
devList = lnetatmo.WeatherStationData(authorization)
# influxdb
client = InfluxDBClient(influxdb_host, influxdb_port, influxdb_username,
                        influxdb_password, influxdb_database)

# these keys are float
keylist = [
    'Temperature', 'min_temp', 'max_temp', 'Pressure', 'AbsolutePressure'
]


def send_data(ds):
    #
    senddata = {}
Exemplo n.º 30
0
#!/usr/bin/env python3
# encoding=utf-8

import lnetatmo
from influxdb import InfluxDBClient

CLIENT_ID = ''
CLIENT_SECRET = ''
USERNAME = ''
PASSWORD = ''

authorization = lnetatmo.ClientAuth(clientId=CLIENT_ID,
                                    clientSecret=CLIENT_SECRET,
                                    username=USERNAME,
                                    password=PASSWORD,
                                    scope='read_station')

weatherData = lnetatmo.WeatherStationData(authorization)

client = InfluxDBClient()
if {'name': 'netatmo'} not in client.get_list_database():
    client.create_database('netatmo')

for station in weatherData.stations:
    station_data = []
    module_data = []
    station = weatherData.stationById(station)
    station_name = station['station_name']
    altitude = station['place']['altitude']
    country = station['place']['country']
    timezone = station['place']['timezone']