예제 #1
0
def getinfo(authorization):

    # パラメータを設定
    params = {
        "field1": "",
        "field2": "",
        "field3": "",
        "field4": "",
    }

    weather_station = lnetatmo.WeatherStationData(authorization)
    data = weather_station.lastData()
    ''' 
    dataの中身(sample) ----------------------------------------------
    {'屋内': {'AbsolutePressure': 1020.1, 'Noise': 48, 'Temperature': 25.2, 'temp_trend': 'up', 'Humidity': 32, 'Pressure': 1020.1, 'pressure_trend': 'stable', 'CO2': 1149, 'date_max_temp': 1490859269, 'date_min_temp': 1490823519, 'min_temp': 16.1, 'max_temp': 25.4, 'When': 1490870784, 'wifi_status': 42}, '屋外': {'Temperature': 24.3, 'temp_trend': 'stable', 'Humidity': 35, 'date_max_temp': 1490860768, 'date_min_temp': 1490822573, 'min_temp': 15.8, 'max_temp': 24.7, 'When': 1490870766, 'battery_vp': 6178, 'rf_status': 28}, '風速計': {'WindAngle': -1, 'WindStrength': 0, 'GustAngle': 74, 'GustStrength': 3, 'WindHistoric': [{'WindStrength': 0, 'WindAngle': -1, 'time_utc': 1490867447}, {'WindStrength': 0, 'WindAngle': -1, 'time_utc': 1490867755}, {'WindStrength': 0, 'WindAngle': -1, 'time_utc': 1490868056}, {'WindStrength': 0, 'WindAngle': -1, 'time_utc': 1490868357}, {'WindStrength': 0, 'WindAngle': -1, 'time_utc': 1490868664}, {'WindStrength': 0, 'WindAngle': -1, 'time_utc': 1490868965}, {'WindStrength': 0, 'WindAngle': -1, 'time_utc': 1490869267}, {'WindStrength': 0, 'WindAngle': -1, 'time_utc': 1490869575}, {'WindStrength': 0, 'WindAngle': -1, 'time_utc': 1490869875}, {'WindStrength': 0, 'WindAngle': -1, 'time_utc': 1490870176}, {'WindStrength': 0, 'WindAngle': -1, 'time_utc': 1490870477}, {'WindStrength': 0, 'WindAngle': -1, 'time_utc': 1490870779}], 'date_max_wind_str': 1490805950, 'date_max_temp': 1490799888, 'date_min_temp': 1490799888, 'min_temp': 0, 'max_temp': 0, 'max_wind_angle': 139, 'max_wind_str': 3, 'When': 1490870779, 'battery_vp': 6252, 'rf_status': 63}, '雨量計': {'Rain': 0, 'sum_rain_24': 0, 'sum_rain_1': 0, 'When': 1490870772, 'battery_vp': 6354, 'rf_status': 49}}
{'field1': 25.2, 'field2': 32, 'field3': 1020.1, 'field4': 1149}
    -----------------------------------------------------------------
    '''

    # 拡張可能
    params['field1'] = data['屋内']['Temperature']
    params['field2'] = data['屋内']['Humidity']
    params['field3'] = data['屋内']['Pressure']
    params['field4'] = data['屋内']['CO2']

    return params
예제 #2
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()
        ]
예제 #3
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
예제 #4
0
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)
예제 #5
0
    def _lastWeatherData(self) -> Generator[Tuple[str, str, str], None, None]:
        self._weatherData = lnetatmo.WeatherStationData(self._netatmoAuth)
        for siteId, values in self._weatherData.lastData().items():

            if siteId == 'Wind' or siteId == 'Rain':
                siteId = self.LanguageManager.getStrings('outside')[0]

            for key, value in values.items():
                yield (siteId.lower(), self._telemetryTypes.get(key), value)
예제 #6
0
    def update(self):
        """Call the Netatmo API to update the data."""
        import lnetatmo
        self.station_data = lnetatmo.WeatherStationData(self.auth)

        if self.station is not None:
            self.data = self.station_data.lastData(station=self.station,
                                                   exclude=3600)
        else:
            self.data = self.station_data.lastData(exclude=3600)
예제 #7
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()
예제 #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
예제 #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
예제 #10
0
    def onStart(self) -> list:
        super().onStart()
        if not self.getConfig('password'):
            raise ModuleStartingFailed(moduleName=self.name,
                                       error='No credentials provided')

        if not self._auth():
            raise ModuleStartingFailed(moduleName=self.name,
                                       error='Authentication failed')

        try:
            self._weatherData = lnetatmo.WeatherStationData(self._netatmoAuth)
        except lnetatmo.NoDevice:
            raise ModuleStartingFailed(moduleName=self.name,
                                       error='No Netatmo device found')

        return self.supportedIntents
예제 #11
0
def main():
    """Fetch data from Netatmo and interate through it, posting to CloudWatch
    Metrics"""
    try:
        weather_data = lnetatmo.WeatherStationData(auth)
        last_data = weather_data.lastData(params["NETATMO_STATION"])
    except TypeError:
        print("Caught error from letnatmo, aborting")
        post_error_metric()
        return
    if not last_data:
        # lnetatmo eats the Exception and returns None if there's a problem
        print("Failed to get data from Netatmo, aborting")
        post_error_metric()
        return
    # Init metric_data with our API success status
    metric_data = [{
        "MetricName": "apierror",
        "Timestamp": time.time(),
        "Value": 0,
        "Unit": "Count",
    }]
    for device in last_data.keys():
        device_data = last_data[device]
        when = device_data["When"]
        del device_data["When"]
        for name, value in last_data[device].items():
            if isinstance(value, str):
                continue
            metric = {
                "MetricName": name,
                "Dimensions": [{
                    "Name": "Device",
                    "Value": device
                }],
                "Timestamp": when,
                "Value": value,
            }
            metric_data.append(metric)
            if len(metric_data) > 19:
                post_metrics(metric_data)
                metric_data = []
    if len(metric_data):
        post_metrics(metric_data)
예제 #12
0
    def onStart(self) -> list:
        super().onStart()
        if not self.getConfig('password'):
            raise ModuleStartingFailed(
                moduleName=self.name,
                error=f'[{self.name}] No credentials provided')

        if not self._auth():
            raise ModuleStartingFailed(
                moduleName=self.name,
                error=f'[{self.name}] Authentication failed')

        try:
            self._weatherData = lnetatmo.WeatherStationData(self._netatmoAuth)
        except lnetatmo.NoDevice:
            raise ModuleStartingFailed(
                moduleName=self.name,
                error=f'[{self.name}] No Netatmo device found')
        else:
            return self._SUPPORTED_INTENTS
예제 #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"))
예제 #14
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'
예제 #15
0
#!/usr/bin/python3
# encoding=utf-8

# 2014-01 : [email protected]

# Just connect to a Netatmo account, and print all last informations available for
# station and modules of the user account
# (except if module data is more than one hour old that usually means module lost
#  wether out of radio range or battery exhausted thus information is no longer
#  significant)

import time
import lnetatmo

authorization = lnetatmo.ClientAuth()
devList = lnetatmo.WeatherStationData(authorization)

# For each available module in the returned data that should not be older than one hour (3600 s) from now
for module, moduleData in devList.lastData(exclude=3600).items():

    # Name of the module (or station embedded module), the name you defined in the web netatmo account station management
    print(module)

    # List key/values pair of sensor information (eg Humidity, Temperature, etc...)
    for sensor, value in moduleData.items():
        # To ease reading, print measurement event in readable text (hh:mm:ss)
        if sensor == "When":
            value = time.strftime("%H:%M:%S", time.localtime(value))
        print("%30s : %s" % (sensor, value))

# OUTPUT SAMPLE :
예제 #16
0
def netatmoIndoor(sonde):
    authorization = lnetatmo.ClientAuth()
    devList = lnetatmo.WeatherStationData(authorization)
    msg = (sonde + " current temperature : %s C" %
           (devList.lastData()[sonde]['Temperature']))
    return msg
예제 #17
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)
    # print (json_item)
예제 #18
0
 def _lastWeatherData(self) -> Generator[Tuple[str, str, str], None, None]:
     self._weatherData = lnetatmo.WeatherStationData(self._netatmoAuth)
     for siteId, values in self._weatherData.lastData().items():
         for key, value in values.items():
             yield (siteId, self._telemetryTypes.get(key), value)