Giter Site home page Giter Site logo

philippelt / netatmo-api-python Goto Github PK

View Code? Open in Web Editor NEW
186.0 38.0 118.0 236 KB

Netatmo connect API python client (for Netatmo information, see https://dev.netatmo.com)

License: GNU General Public License v3.0

Python 100.00%
home-automation netatmo python

netatmo-api-python's Introduction

netatmo-api-python

Simple API to access Netatmo weather station data from any python script For more detailed information see http://dev.netatmo.com

I have no relation with the netatmo company, I wrote this because I needed it myself, and published it to save time to anyone who would have same needs.

There is no longer credential load at library import, credentials are loaded at ClientAuth class initialization and a new parameter credentialFile allow to specify private name and location for the credential file. It is recommended to use this parameter to specify the location of the credential file using absolute path to be able to be independant of the account used to run the program.

Caution

Remember that the program using the library must be able to rewrite the credential file to be able to save the new refresh token that netatmo may provide at the authentication step. Check the file permission according to the account the program is running.

Note

Several users reported that Netatmo is now asking for a DPO (Data Protection Officer) mail address to deliver application credentials. Netatmo is requesting this to comply with RGPD European regulation for the case of your application would be able to access other customers account and you would hold responsibility to protect others potentially confidential informations.
For most users (if not all) of this library, this is totally useless as we are accessing only OUR devices thus are not concerned by RGPD. You can then put your netatmo account email address, just in case some mail would be sent to it.
It is only an information for the Netatmo records, there is absolutely no use of this information by the library.

Install

To install lnetatmo simply run:

python setup.py install

or

pip install lnetatmo

Depending on your permissions you might be required to use sudo.

It is a single file module, on platforms where you have limited access, you just have to clone the repo and take the lnetatmo.py in the same directory than your main program.

Once installed you can simple add lnetatmo to your python scripts by including:

import lnetatmo

For documentation, see usage

netatmo-api-python's People

Contributors

asphotographics avatar aurorevgn avatar cclauss avatar florianbeer avatar fxstein avatar hydrelioxgithub avatar jabesq avatar joebe975 avatar jurgenlb avatar mnin avatar philippelt avatar richieb2b avatar rmkraus avatar sbrunner avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

netatmo-api-python's Issues

JSONDecodeError: Unterminated String

Hello,

I just found this very interesting python library for getting access to my Netatmo devices.
Thank you for this!

Unfortunately, when trying to get access to my home devices, postRequest method returns an exception when trying to return the response in JSON format.

It happens when testing the library from class HomeData tryng to request _GETHOMEDATA_REQ api.

json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 65528 (char 65527)

The returned string is effectively not well formed.

Any idea?

Many thanks in advance for your help!

Nicolas

Value of device_id and module_id in graphLast3Days

Hi,

I'm getting an urllib2.HTTPError 404: Not found when running this script. Any ideas?

I'm using 'name' module_id (in my case indoor) and device_id as station name (in my case aertebjerggaardvej)

support of GetPublicData API

Hello !

I noticed the awesome code you wrote for interacting with netatmo data. Many thanks for that !
However, I need to access the public data through "GetPublicData API" and the code does not (yet) support it.

Do you think someone can provide this ?

As an absolute beginner in development, I'm almost sure you couldn't accept a pull request with my poor code quality. But if someone can check my repo and give some advices, this will be greatly appreciated.

Maybe my work can inspire someone?

no new data with devList.lastData()

I have the following issue.

When I start the program the devList.lastData() function get all the data as expected.
When I redo this function afterwards in 15 Min cycles I got always the same data.

What is my mistake?

RG
Oliver

ValueError: Empty certificate data

Hi!

First of all, thank you so much for this, I have tried it directly on my Raspberry Pi3 it worked like a charm.

I'm a bit lazy and don't really enjoy Raspbian and dev'ing directly on it, so for some reason I have put in my head to make it work with..... Visual Studio 2017

Got everything working, even managed to make it load lnetatmo!

Unfortunately, when trying to

netatmoAuth = lnetatmo.ClientAuth(clientId, clientSecret, username, password)

And deploying to my Raspberry, the execution stops and VS returns me an error saying:

"ValueError: Empty certificate data" or sometimes
"urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:646)>"

I'm not saying this is lnetatmo's problem, but maybe you have a slight idea of what could cause this?

Cheers!

ds['time_utc']can be null

  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/home/pi/ProjectAlice/modules/RedQueen.py", line 45, in airQualityCheck
    data = netatmoModule.getDataFromNetatmo()
  File "/home/pi/ProjectAlice/modules/Netatmo.py", line 201, in getDataFromNetatmo
    return weatherData.lastData()
  File "/home/pi/ProjectAlice/libraries/lnetatmo.py", line 324, in lastData
    if ds['time_utc'] > limit:
KeyError: 'time_utc'

I just plugged a new wind and a new rain module

403 Forbidden error

I am trying to pull data from Netatmo using your library and I was able to do it until now. For some reason my application stopped working with a 403 HTTP error when trying to do this:

weatherData = lnetatmo.WeatherStationData(authorization)

This is the error:

Traceback (most recent call last):
  File "netatmo_test.py", line 9, in <module>
    weatherData = lnetatmo.WeatherStationData(authorization)
  File "/usr/local/lib/python2.7/dist-packages/lnetatmo.py", line 171, in __init__
    resp = postRequest(_GETSTATIONDATA_REQ, postParams)
  File "/usr/local/lib/python2.7/dist-packages/lnetatmo.py", line 546, in postRequest
    resp = urllib2.urlopen(req).read(body_size)
  File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 435, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 548, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 473, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 407, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 556, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden

The authorization variable is well set and everything is configured, like I said, it worked for 2 hours straight. I thought it could the expiration date but it is not as it is set to 15:50 (13:07 now). After a 10 or so minutes it came back to normal and now I am able to pull data again. Have you experienced any of this? I would like to know the cause. Thank you for the library, it is a great work.

no modules

My external module died, so now I have a home station without any modules.
several sections of the code expect there to be at least one module and the code fails if there aren't any.
I was able to get it to work by putting Try/except/pass around the module loops in both init and lastData.

pretty new to Github, so not sure how to upload the code changes, but thought I should mention it.

Thanks for the great code!

-Nils

Fails to retrieve weather data if outdoor module doesn't have a name set

#When I installed my weather station, I didn't end up having a module_name for my outdoor module. It shows up as "noname" on the web config popup and the API returns no module_name field. Hence the error

File "./run.py", line 27, in <module>
    ( devList.lastData()['internal']['Temperature'],
  File "/usr/local/lib/python3.4/dist-packages/lnetatmo.py", line 231, in lastData
    lastD[module['module_name']] = ds.copy()
KeyError: 'module_name'`

Add Homecoach from API

I have put the following code for My HomeCoach devices;

`
Common definitions

 _GETHOMECOACH          = _BASE_URL + "api/gethomecoachsdata"

class HomeCoach:
"""
List the HomeCoach modules
Args:
authData (clientAuth): Authentication information with a working access Token
home : Home name or id of the home who's HomeCoach belongs to
"""

def __init__(self, authData, home=None):
    self.getAuthToken = authData.accessToken
    postParams = {
            "access_token" : self.getAuthToken
            }
    resp = postRequest("HomeCoach", _GETHOMECOACH, postParams)
    self.rawData = resp['body']['devices']
    # homecoach data
    if not self.rawData : raise NoDevice("No HomeCoach available")
    for i in range(len(self.rawData)):
       #
       self.HomecoachDevice = self.rawData[i]
       print (self.HomecoachDevice)
       print (' ')
       print (self.HomecoachDevice['dashboard_data'])
       print (' ')

`

this give me the following data;

`
{'_id': '70:ee:50:25:f3:58', 'station_name': 'Slaapkamer', 'date_setup': 1529696933, 'last_setup': 1529696933, 'type': 'NHC', 'last_status_store': 1695673789, 'firmware': 59, 'last_upgrade': 1529696984, 'wifi_status': 63, 'reachable': True, 'co2_calibrating': False, 'data_type': ['Temperature', 'CO2', 'Humidity', 'Noise', 'Pressure', 'health_idx'], 'place': {'altitude': 65, 'city': 'Bree', 'country': 'BE', 'timezone': 'Europe/Brussels', 'location': [5.58998, 51.121652]}, 'dashboard_data': {'time_utc': 1695673788, 'Temperature': 20.8, 'CO2': 586, 'Humidity': 58, 'Noise': 37, 'Pressure': 1024.8, 'AbsolutePressure': 1017, 'health_idx': 0, 'min_temp': 20.1, 'max_temp': 20.8, 'date_max_temp': 1695659280, 'date_min_temp': 1695593088}}

{'time_utc': 1695673788, 'Temperature': 20.8, 'CO2': 586, 'Humidity': 58, 'Noise': 37, 'Pressure': 1024.8, 'AbsolutePressure': 1017, 'health_idx': 0, 'min_temp': 20.1, 'max_temp': 20.8, 'date_max_temp': 1695659280, 'date_min_temp': 1695593088}
`

I'm not sure on how to handle the rest of the code but I'm willing to assist

Kind regards

Netatmo API changes on November 30th.

Today I received the following mail from Netatmo:

Switch to Getthermostatsdata, Gethomedata and Getstationsdata by November 30th.

Friendly reminder: Getthermstate, Getuser and Devicelist will move from deprecated to shut down. On November 30th, we are proceeding to a structural change to make our APIs faster and more powerful. Unfortunately, old and deprecated API methods won’t be supported anymore. Make sure you amend your code and start using newer methods as soon as possible for a smooth transition:

Replace Getthermstate with Getthermostatdata
Replace Getuser with Getthermostatdata, Gethomedata or Getstationsdata
Replace Devicelist with Getthermostatdata or Getstationsdata

Question: is this module compatible with the changes in the Netatmo API?

Python Package Index

It would be nice if you publish releases at PyPI.

netatmo-api-python is a dependency of Home Assistant and since there are no archives of releases available it makes it hard to track changes.

Thanks.

At same home, two stations with same name

I'm running Netatmo Weather since 2015 now. By some reason I had to replace my first station by a new one (2017) but kept the data of the first one at Netatmo. Somehow I was able to give the second on the same name like the first one. Now in every interface (web/app) I see two stations with same name where I can chose either. The first one does not show me any recent data, the second one does. This means in the web/app interface there is a way to differentiate (N.B. when I try to rename, I rename always both at the same time, so somewhat frustrated by this). I'm using grafana to record the data myself. This was working fine until the recent change concerning REFRESH_TOKEN.
After updating lnetatmo I always select the old one (with no data returned) and the simpleLastData script fails by an error (as selecting the wrong station for default). I'm not able to address the station by station="station_name" as both stations share the same name.

Would it be an option to additionally have the station key "_id" as a further selector? This mac address is unique and is an intrinsic selector identifying the hardware.
Thanks

I took the User class to find the different _id strings for the stations.

Further looking around, the lnetatmo is organized around the names, even building the raw_data hides one of the duplicates because station_name is used for key. So a potential change looks to become bigger effort as not only the station_name would have to be replaced by _id , the same applies for all modules which may have same names as well... I wonder how common the issue is, whether it might be more simple to delete my netatmo account fully and rebuild it again.

How to know if the boiler is working? (thermostat)

Hi,

I am trying to measure of how much time the boiler is working each month. The thing is that I cannot find in the thermostat response ( thermostat.getThermostat()) any data that says is working. I compared tow different responses, one while the boiler was working and other while not. The only difference I found was in the timestamp datas...

Do you know if I am missing something?

Thanks for your help

Error after updating to 2.0.0

Hello!
I have an issue after updating to 2.0.0.

I updated my code with the following, because I have 2 homes linked to my Netatmo account, and 1 station in each home :

    devList = lnetatmo.WeatherStationData(authorization, home='Home A', station=None)
    externalTemperature = round(devList.lastData('Home A')['Exterieur']['Temperature'],1)
    externalHumidity = devList.lastData('Home A')['Home A']['Humidity']
    internalPressure = round(devList.lastData('Homa A')['Appart']['Pressure'],1)
    expirationdelay=1800
    someLost = devList.checkNotUpdated(station='Home A',delay=expirationdelay)
    if someLost and 'Exterieur' in someLost:
        currentTemperature = "--"
        currentHumidity = "--"
        currentPressure = "--"
    else:
        currentTemperature = str(externalTemperature)
        currentHumidity = str(externalHumidity)
        currentPressure = str(internalPressure)
    return (currentTemperature,currentHumidity,currentPressure)

Then, it gives me the following result:

Traceback (most recent call last):
File "netamo.py", line 52, in
main()
File "netamo.py", line 46, in main
currentTemperature,currentHumidity,currentPressure = getCurrentWeatherData()
File "netamo.py", line 26, in getCurrentWeatherData
externalTemperature = round(devList.lastData('Home A')['Exterieur']['Temperature'],1)
File "/home/pi/.local/lib/python2.7/site-packages/lnetatmo.py", line 374, in lastData
limit = (time.time() - exclude) if exclude else 0
TypeError: unsupported operand type(s) for -: 'float' and 'str'

Did I miss something?
Thanks for your help!

error since import lnetatmo

Hi!

I don't why this error :
(pyenv) X:\Prog\Netatmo\My.camera>python
Python 3.10.1 (tags/v3.10.1:2cd268a, Dec 6 2021, 19:10:37) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

import lnetatmo
Traceback (most recent call last):
File "", line 1, in
File "X:\Prog\Netatmo\My.camera\pyenv\lib\site-packages\lnetatmo.py", line 73, in
cred.update({k.upper():v for k,v in json.loads(f.read()).items()})
File "c:\python\python310\lib\json_init_.py", line 346, in loads
return _default_decoder.decode(s)
File "c:\python\python310\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "c:\python\python310\lib\json\decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 13 column 5 (char 641)

Is it my error or is it a really bug under python 3.10 ?

Thanks

Accessing to /homestatus

Hi!

Thank you for your great work!
Thanks to it, I can access to my Netatmo weather station and log its data to my Grafana :-)

I have some other Netatmo w/ Legrand devices such as Smarther Thermostat (score "read_smarther") and power outlet, cable outlet, light micromodule, .... (scope "read_magellan"). These data are readable with https://api.netatmo.com/api/homestatus

I tried HomeData function but I have "lnetatmo.NoDevice: No camera available in default home" and it's quite logical, I don't have any camera.

With your great script I didn't find how to access to homestatus. Did I miss something? How can I access to them?

Thanks,

KeyError: 'dashboard_data' when device hasn't been reached

Apparently my netatmo weather station was unable to connect to the netatmo cloud for a while, and now my scripts crash with a KeyError: 'dashboard_data' error.

This is new: I'm pretty sure that in the past I got a more decent error.

The documentation at https://dev.netatmo.com/en-US/resources/technical/reference/weather/getstationsdata indeed states that dashboard_data is unavailable when the station is unreachable, but it could be that this is a recent change on the side of netatmo.

It would be nice if a more decent error was returned in this case, or if simply an empty dataset was returned.

Unfortunately I've made my station reconnect in the mean time, so I can't provide a tested patch, but I have the feeling that replacing the two dict accesses in lastData() with .get('dashboard_data', {}) would solve the issue.

Implement API to Weewx

Hi.

I've found your python API and I would like to integrate to Weewx. Is it possible to use your git with mentions ?

Regards,

Add Netatmo radiator

Hi

I wanted to add my Netatmo radiator in the Home Assistant, and that didn't work. After the search it turned out that the radiator cannot currently be included in the Home Assistant. I found your contribution in GitHub and I noticed that it still contains outdated code components. Unfortunately my programming skills are not so good otherwise I would help you rewrite that.

https://dev.netatmo.com/resources/technical/reference/deprecated

And the values I got back from the Dev Netatmo website might help you. If there's anything else I can do to help you, just say it.

body:

homes:
	id: "5a99870413475d3a118c5386"
	name: "Home"
	altitude: 000
	coordinates:[...]
	country: "DE"
	timezone: "Europe/Bananaland"
	rooms:
		id: "1703702957"
		name: "Bedroom"
		type: "bedroom"
		module_ids:
			"09:00:00:00:93:02"
		measure_offset_NAPlug_temperature: 0
		measure_offset_NAPlug_estimated_temperature: 0
		id: "2331965531"
		name: "Living room"
		type: "livingroom"
		module_ids:
			"09:00:00:00:8d:cc"
		measure_offset_NAPlug_temperature: 0
		measure_offset_NAPlug_estimated_temperature: 0
	modules:
		[Object]
			id: "70:ee:50:0e:85:d4"
			type: "NAPlug"
			name: "Relay"
			setup_date: 1520011012
			modules_bridged:
				"09:00:00:00:8d:cc"
				"09:00:00:00:93:02"
		[Object]
			id: "09:00:00:00:8d:cc"
			type: "NRV"
			name: "Heater Living room"
			setup_date: 1520011025
			room_id: "2331965531"
			bridge: "70:ee:50:0e:85:d4"
		[Object]
			id: "09:00:00:00:93:02"
			type: "NRV"
			name: "HeaterBedroom"
			setup_date: 1520011025
			room_id: "1703702957"
			bridge: "70:ee:50:0e:85:d4"
	schedules:[...]
	therm_schedules:[...]
	therm_setpoint_default_duration: 60
	therm_mode: "schedule"

New commits to lnetatmo.py break existing functionality

I have a working python script that uses lnetatmo.py successfully to query two netatmo stations. Up until (eab2766) it worked flawlessly. The referenced commit was done for: #50 (comment).

Now with the current version: Update lnetatmo.py it is no longer working, it throws an exception during execution. There were more commits in between. I can't tell which commit really broke it. Here is the scenario (I am showing only the relevant code):

weatherData = lnetatmo.WeatherStationData(authorization)

for station in weatherData.stations:
    station_data = []
    module_data  = []
    station      = weatherData.stationById(station)
    pprint.pprint(station)
    station_name = station['station_name']

When I run this, I get:

None
Traceback (most recent call last):
  File "/home/baiti/newest_netatmo/./netatmo_influx.py", line 51, in <module>
    station_name = station['station_name']
                   ~~~~~~~^^^^^^^^^^^^^^^^
TypeError: 'NoneType' object is not subscriptable

I would conclude that weatherData.stationById(station) returns nothing. I would further conclude that the commits to this file after the one referenced above, are not just new functions, they break existing functionality.

exceptions when no homes

Thanks for the module, I belive I just found a bug whilst only using netatmo station and you do not use the camera, it looks like the rawData does not have homes setup
285 self.homes = { d['id'] : d for d in self.rawData['homes'] }

{u'homes': [], u'user': {u'lang': u'es-ES', u'reg_locale': u'es-ES', u'country': u'ES_ES'}, u'global_info': {u'show_tags': True}}

and therefore there's an out of range exception:

Traceback (most recent call last):
File "lnetatmo.py", line 562, in
Camera = WelcomeData(authorization)
File "lnetatmo.py", line 307, in init
self.default_home = list(self.homes.values())[0]['name']
IndexError: list index out of range

'lastData(station=station, exclude=0)' no longer works when iterating through multiple stations

until recently I have used code from grafana-netamo like this:

for station in weatherData.stations:
    for module, moduleData in weatherData.lastData(station=station_name, exclude=0).items():

Now after an authentication related update of lnetatmo the code above (taken from sample code shown in grafana-netatmo) no longer works, it throws a TypeError

Traceback (most recent call last):
File "./netatmo_influx.py", line 46, in
for module, moduleData in weatherData.lastData(station=station, exclude=0).items():
TypeError: lastData() got an unexpected keyword argument 'station'
I got it back working by just dropping that station agrument.

Looking at the lnetatmo.py source makes it clear, that parameter station no longer exists. Of course I can jusrt remove that parameter in the for loop above, however, then, when iterating more than one station, I fetch one and the same set of measurements and values for all stations. It must be possible somehow, to reference that lastData by station. Can anybody shed some light into this?

KeyError: 'events' when initializing HomeData(authorization)

Hi,
I use lnetatmo already some time, but it stopped working for me. First I thought there is a problem with my authorization but that wasn't the case.

I could connect using the same authorization directly and get data back. Then I noticed one thing. I had two homes in my output data and the second one was quite empty.

      {
         "id":"xxxxxxxxxxxxxxxx",
         "name":"xxxxxx",
         "persons":[],
         "place":{
            "city":"xxxxxx",
            "country":"CZ",
            "timezone":"Europe/Prague"
         },
         "cameras":[],
         "smokedetectors":[ ]
      }

The important thing is there are no events! I have no clue why the second home is there at all, I cannot see it in my profile or settings. But it is there. And I cannot get rid of it. But I would like to continue using the lnetatmo.

Would it be possible to do something like below, in the class HomeData? Adding the If condition to make sure it will work even in the scenarion described above.

            if 'events' in curHome.keys():
                for e in curHome['events']:
                    if e['camera_id'] not in self.events:
                        self.events[ e['camera_id'] ] = dict()
                    self.events[ e['camera_id'] ][ e['time'] ] = e

Thanks!
Lubo

script problems

Hi, when I'm using simpleLastData, I got the following error:
pi@pfupfweb:~/netatmo-api-python/samples $ python simpleLastData
Traceback (most recent call last):
File "simpleLastData", line 12, in
authorization = lnetatmo.ClientAuth()
File "/usr/local/lib/python2.7/dist-packages/lnetatmo.py", line 157, in init
if not resp: raise AuthFailure("Authentication request rejected")
lnetatmo.AuthFailure: Authentication request rejected

the access is working with php...

self signed certificate in certificate chai

I loved your program ... been using for years. Now it quit a few days ago.
Trying to get the new version with client_id, client_secret and refresh_token to work.

In lnetatmo.py I changed just 3 things .... client_id , client_secret, refresh_token

python3 lnetatmo.py ( on mac computer using terminal )

urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:727)

error3.txt

Sporadic error when getting weather data

Hello all,

I am facing an issue which is hapenning quite many times recently.
Installed is lnetatmo==1.4.3 and I am calling once every hour the following code:

def getCurrentWeatherData():
try:
authorization = lnetatmo.ClientAuth(clientId = "xxx", clientSecret = "xxx", username = "xxx", password = "xxx")
devList = lnetatmo.WeatherStationData(authorization)
externalTemperature = round(devList.lastData('Brest')['Exterieur']['Temperature'],1)
externalHumidity = devList.lastData('Brest')['Exterieur']['Humidity']
internalPressure = round(devList.lastData('Brest')['Appart']['Pressure'],1)
expirationdelay=1800
someLost = devList.checkNotUpdated(station='Brest',delay=expirationdelay)
if someLost and 'Exterieur' in someLost:
currentTemperature = "--"
currentHumidity = "--"
currentPressure = "--"
print ("Error handled: Could not get data from External module")
else:
currentTemperature = str(externalTemperature)
currentHumidity = str(externalHumidity)
currentPressure = str(internalPressure)
return (currentTemperature,currentHumidity,currentPressure)
except:
print ("Error handled: Could not get weather data from Netatmo server")
return ("--","--","--")

It is working most of the time, since years. But sometimes, once every 2 days, I get the following error:

Exception in thread Thread-12:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "webcam.py", line 193, in run
currentTemperature,currentHumidity,currentPressure = getCurrentWeatherData()
File "webcam.py", line 355, in getCurrentWeatherData
devList = lnetatmo.WeatherStationData(authorization)
File "/home/pi/.local/lib/python2.7/site-packages/lnetatmo.py", line 203, in init
resp = postRequest(_GETSTATIONDATA_REQ, postParams)
File "/home/pi/.local/lib/python2.7/site-packages/lnetatmo.py", line 650, in postRequest
resp = urllib2.urlopen(req, timeout=timeout)
File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 429, in open
response = self._open(req, data)
File "/usr/lib/python2.7/urllib2.py", line 447, in _open
'_open', req)
File "/usr/lib/python2.7/urllib2.py", line 407, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 1241, in https_open
context=self._context)
File "/usr/lib/python2.7/urllib2.py", line 1201, in do_open
r = h.getresponse(buffering=True)
File "/usr/lib/python2.7/httplib.py", line 1121, in getresponse
response.begin()
File "/usr/lib/python2.7/httplib.py", line 438, in begin
version, status, reason = self._read_status()
File "/usr/lib/python2.7/httplib.py", line 394, in _read_status
line = self.fp.readline(_MAXLINE + 1)
File "/usr/lib/python2.7/socket.py", line 480, in readline
data = self._sock.recv(self._rbufsize)
File "/usr/lib/python2.7/ssl.py", line 766, in recv
return self.read(buflen)
File "/usr/lib/python2.7/ssl.py", line 653, in read
v = self._sslobj.read(len)
SSLError: ('The read operation timed out',)

Could you please tell me what I am doing wring? Is it an authentication issue? Or a network issue?

Many thanks in advance :)
Genfersee

lnetatmo runs into an error after some hours (2)

Hello,
i wrote this in issue #21, but nothing i did, worked for me.

Here is my Code:
`channel_id = 325338 # PUT CHANNEL ID HERE
write_key = 'RZxxxxxx...' # PUT YOUR WRITE KEY HERE
read_key = 'P9N........' # PUT YOUR READ KEY HERE

DEBUG = False

while True:
authorization = lnetatmo.ClientAuth()
weatherData = lnetatmo.WeatherStationData(authorization)
theData = weatherData.lastData()

tempWZ = theData['Wohnzimmer']['Temperature']
co2WZ = theData['Wohnzimmer']['CO2']

#. lautWZ = theData['Wohnzimmer']['Noise']
tempStudio = theData['Studio']['Temperature']
co2Studio = theData['Studio']['CO2']
tempAussen = theData['Außen']['Temperature']
rain24 = theData['Regensensor']['sum_rain_24']
lastDa = theData['Wohnzimmer']['When']
lastTime = time.strftime("%H:%M:%S",time.localtime(lastDa))

if DEBUG:
    print(weatherData.lastData())
    print('Available modules : ', theData.keys() )
    print ('Temperatur im WZ : ', tempWZ )
    print('CO2 im WZ : ', co2WZ )

#. print('Lautst. im WZ : ', lautWZ )
print('Temperatur im Studio : ', tempStudio )
print('Temperatur draußen : ', tempAussen )
print('Regen : ', rain24 )
print ('letzte Daten im WZ : ', lastTime, lastDa )

# Send the data to Thingspeak
r = requests.post('https://api.thingspeak.com/update.json', data = {'api_key':write_key, 'field1':tempWZ, 'field2':co2WZ, 'field3':tempStudio, 'field4':co2Studio, 'field5':tempAussen, 'field7':rain24, 'field8':lastTime})
# entnommen: 'field6':lautWZ,

# wait 15 min.
time.sleep (1800)

`
and after some time, i get this error:
_**Traceback (most recent call last):
File "/home/pi/netatmo-api-python/write_NetAtmo_to_ThingSpeak_debug.py", line 14, in
weatherData = lnetatmo.WeatherStationData(authorization)
File "/home/pi/netatmo-api-python/lnetatmo.py", line 260, in init
self.rawData = resp['body']['devices']
TypeError: 'NoneType' object is not subscriptable

**_

My authentications are hardcodet in lnetatmo AND expoted in environment-variables.

Thermostat not working

Is there anyone who is using the "Thermostat" Class ?
For me this was not working.
I have changed some of the code and now I can use the data from Relay and Thermostat.

#        self.thermostatData = filter_home_data(self.rawData, home)
#        if not self.thermostatData : raise NoHome("No home %s found" % home)
        # OLD API
        # Standard the first Relaystation and Thermostat is returned   
        # self.rawData is list all station
        for Relay in self.rawData:
            self.Relay_Plug = Relay     # only last will be returnd
            for thermostat in Relay['modules']:
                self.thermostat
        self.defaultThermostat = thermostat['module_name']  #self.the$
        self.defaultThermostatId = thermostat['_id']
#        self.defaultModule = thermostat['modules'][0]

I think it is even better to do
` def Relay_Plug(self):
for Relay in self.rawData:
return Relay

def Thermostat_Data(self):    
        for thermostat in self.Relay_Plug['modules']:
            return thermostat

`
maybe there is even some checking necessary

I find it strange that the 'keywords' are different, but that is possible because of multiple kinds of thermostat

Kind regards

printThermostat: Authentication request rejected

Hi,

I am trying to use your API to retrieve info from my thermostat.

I downloaded your code from github, hardcode my credentials in the file ".netatmo.credentials", copy the printThermostat.py in the same folder than lnetatmo.py and run in Python 3.7 in Windows 10.

I got an error when calling:

authorization = lnetatmo.ClientAuth()

This is the output of the error:

File "E:\Python\netatmo-api-python\lnetatmo.py", line 187, in __init__ if not resp: raise AuthFailure("Authentication request rejected") lnetatmo.AuthFailure: Authentication request rejected

Am I doing something wrong?

Thanks in advance and thanks for your work!

Netatmo API authentication update

Some days ago I have received a mail from Netatmo that they will remove the authentication via username and password from the API. From Oktober 2022 there will be only the oauth2 process.

Question to @philippelt and all users of the netatmo-api-python:
What do we need to do?
Is it possible to patch the code to support oauth2?

Using samples/weather2file to download old data returns Device not found

trying to use weather2file to try to download old data seems it is not working. even if the {module_name} is properly identified it seems it returns ERROR: code=404, reason=Not Found, body=b'{"error":{"code":9,"message":"Device not found"}}'

PYTHONPATH=. ./samples/weather2file --format csv
 INFO: Previous file ./weatherdata.csv not found. Setting empty DataFrame
 INFO: Timezone Europe/Bucharest extracted from data.
 INFO: Processing MasterBedroom...
 INFO: Collecting data for MasterBedroom...
 ERROR: code=404, reason=Not Found, body=b'{"error":{"code":9,"message":"Device not found"}}'
 WARNING: None received. Aborting data collection from module MasterBedroom
 INFO: Collected data from MasterBedroom contains 0 samples.
Traceback (most recent call last):
  File "./samples/weather2file", line 642, in <module>
    main()
  File "./samples/weather2file", line 613, in main
    df_handler.append(
  File "./samples/weather2file", line 150, in append
    self.df = self.df.append(df).reset_index(drop=True)
  File "/usr/local/lib/python3.8/dist-packages/pandas/core/generic.py", line 5989, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'append'

it seems that the issue is from here, but i am not an expert on python

            # Get new data from Netatmo
            d = self._get_field_dict(station_mac,
                               module_data_overview['_id'],
                               module_data_overview['data_type'],
                               module_start_date_timestamp,
                               end_date_timestamp)
            
            retreived_module_data = self._get_measurement(d) 

is there something that i do wrong?

lnetatmo stops after running some hours / days

Hello, and thank you for your work.
but I have a problem with the software, which I can't solve.

Afer some hours or some days lnetatmo stops his work with the following message:

Python 3.5.3 (default, Jan 19 2017, 14:11:04)
[GCC 6.3.0 20170124] on linux
Type "copyright", "credits" or "license()" for more information.

========== RESTART: /home/pi/netatmo/write_NetAtmo_to_ThingSpeak.py ==========
Traceback (most recent call last):
File "/home/pi/netatmo/write_NetAtmo_to_ThingSpeak.py", line 11, in
authorization = lnetatmo.ClientAuth()
File "/home/pi/netatmo/lnetatmo.py", line 157, in init
if not resp: raise AuthFailure("Authentication request rejected")
lnetatmo.AuthFailure: Authentication request rejected

My authorization for NetAtmo is hard codet in lnetatmo.py.

Regards
Juergen

Http Error 400 Bad Request

Hello
The program does not work anymore. I get from the urllib the error message 400, but I have not changed anything. The log file from the app also says nothing. Any ideas?

thanks for your help

Entering post mortem debugging...
****************************************
  648 class HTTPDefaultErrorHandler(BaseHandler):
1   649     def http_error_default(self, req, fp, code, msg, hdrs):
--> 650      raise HTTPError(req.full_url, code, msg, hdrs, fp)
   651 
   652 class HTTPRedirectHandler(BaseHandler):

KeyError: 'home_name'

I was testing your python script with my Thermostat and got a
KeyError: 'home_name'
on line 308
self.thermostatData['name'] = self.thermostatData['home_name']
and line 311
self.defaultThermostat = self.thermostatData['home_name']

I changed it to ['station_name'] and now it give no Error's more.
This is the name for the Relaisstation,
Was this the intended "name" or do you mean the name of the thermostat ?

I see another reference on line 350 but I think there it is OK

Error 403 Code 13

Thank you for updating, but I get this while trying to use the library:

chris@mars kindleNetatmo % python3 lnetatmo.py
lnetatmo - ERROR: code=403, reason=Forbidden, body=b'{"error":{"code":13,"message":"Application does not have the good scope rights"}}'

Maybe you have a hint for me!

Unable to pull temperature from Netatmo weatherstation

Hello there. I'm sorry if this turns out to be a support ticket, but I'm kind of at a loss here.

Before the Netatmo API auth changes, I was able to use a simple bash script to pull indoors and outdoors temperature data from my weatherstation. When that broke, I didn't have the energy to troubleshoot, so I figured I'd try to find something that had already been written, and I stumbled on this project.

I cloned your repository, created a new token in my pre-existing app, populated ~/.netatmo.credentials, installed your library with pip and made an attempt to run some of your sample scripts. The one I was interested in, in particular, was samples/simpleLastData as it appears to show the values I'm after, but when I run it, I get:

$ ./samples/simpleLastData 
Traceback (most recent call last):
  File "/home/daniel/source/netatmo-api-python/./samples/simpleLastData", line 16, in <module>
    ( devList.lastData()['internal']['Temperature'],
      ^^^^^^^^^^^^^^^^^^
  File "/home/daniel/.local/lib/python3.11/site-packages/lnetatmo.py", line 348, in lastData
    lastD[s['module_name']] = ds.copy()
          ~^^^^^^^^^^^^^^^
KeyError: 'module_name'

Sadly, I don't know anything about Python programming, so I don't even know where to start troubleshooting this, but it seems to at least authenticate properly though, because if I run the samples/printAllLastData script, it does print correct values at the top, before spitting out the traceback:

$ ./samples/printAllLastData 
Station owner :  <my@email>
Data units    :  metric

STATION : <correct street address>

Traceback (most recent call last):
  File "/home/daniel/source/netatmo-api-python/./samples/printAllLastData", line 30, in <module>
    for module, moduleData in weather.lastData(station=station, exclude=3600).items() :
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: WeatherStationData.lastData() got an unexpected keyword argument 'station'

In my bash script, I was able to pull the values and populate an array with:

mapfile -t temp_data < <(curl -s --get "$stat_url" \
	-d access_token="$access_token" \
	-d device_id="$device_id" |jq -r \
	'"\(.body.devices[0].dashboard_data.Temperature)
\(.body.devices[0].modules[0].dashboard_data.Temperature)
\(.body.devices[0].modules[0].dashboard_data.temp_trend)"')

Any ideas why things are breaking with your library?

standard environment variable USERNAME on windows

I was using this great module on Linux for a while, but then had the necessity to get the data on windows. I got an authentication error and found that this was due to the standard environment variable USERNAME on windows. This overwrites the given credentials. Don't know the best way how to fix this, I locally changed USERNAME/PASSWORD to NA_USERNAME/NA_PASSWORD in the code. The rest seems running fine.

Authentication request rejected

Hello,

Firstly, thank you for your assistance.

I've been facing challenges with the authentication process. Every time I attempt to authenticate, I receive the error "Authentication request rejected." I've set up my configuration using the .netatmo.credentials method.

I've created the Refresh-Token through Netatmo, but on a reload, it's no longer visible. Oddly, when I recreate it, I get the same token value. Is this the intended behavior?

Below is the error I encounter:

Bildschirmfoto 2023-07-21 um 17 24 19

Your guidance would be much appreciated.

Run on Raspberry Pi3

Hi,

Thank you for the python script to read the data from netatmo. After the installation of lnetatmo.py I want to import the script in a new python code but I get the following message:
lnetatmo.py : warning, no home available for testing
lnetatmo.py : OK

Do you know this problem? I updated the client_id,secret and my username and password, respective.

Thanks in advance

try/except URLError in postRequest() may be over-general

postRequest is the workhorse in lnetatmo, and it uses a try/except urllib.error.URLError around the urlopen() call and returns None in case of errors. This will cause the caller to raise what it feels is the correct lnetatmo error, for example AuthFailure.

Unfortunately this masks networking errors. The case I ran in to was that my certificates were mis-configured (a common occurrence on OSX with Python urllib.request, unfortunately) and this showed up as AuthFailure: Authentication request rejected. This is rather difficult to debug.

I think catching only urllib.error.HTTPError in postRequest may be better: the netatmo-reported errors would still cause the None return and raise the correct lnetatmo error, but underlying network errors (such as certificate errors, but also network connectivity problems and other issues that have nothing to do with netatmo) would let the URLError pass through.

No foreign station access (GetPublicData)

weatherData = lnetatmo.WeatherStationData(auth)
This line throws an error that there are no weather stations in any homes. What does it mean? I was using patatmo module (or library?), and retrieved data for a longer time period by creating a client, authorizing it with client credentials, and using Getpublicdata() to get a list of stations available. It was working well before the new authorization method last week. Thanks to @philippelt, I found their repo to do the authorization part. I want to get the information on all available stations in the API and the documentation says to use Getpublicdata(), but I don't know how to access this function in lnetatmo library. Can somebody please help me with this?

pip setup

Would you mind integrating the pull request #2 submitted a while ago ?

I found this useful and would like to benefit from it without having to create another fork :-)

Thank you !

Option to return data in imperial or metric

Hi,

Thank you for your work on this project, it has benefited me greatly! Netatmo has to option to return the data in imperial or metric values. (unit : 0 -> metric system, 1 -> imperial system)

Is it possible to modify the lnetatmo.py code to have the option? Or, if it's not something that you think other people would want, can you point me in the right direction in your code where to change it?

Again, thank you for your work, it's greatly appreciated.

Richard

TypeError: 'NoneType' object is not subscriptable

Hi,

When running the simple sample I get the following error...

Traceback (most recent call last):
File "samples/simpleLastData", line 12, in
authorization = lnetatmo.ClientAuth()
File "/usr/local/lib/python3.5/dist-packages/lnetatmo.py", line 153, in init
self._accessToken = resp['access_token']
TypeError: 'NoneType' object is not subscriptable

I have set up the app and inserted credentials. Not sure what the issue is?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.