Sensor values CLI in Python (macOS, Linux)

Moderator: Telldus

Post Reply
atchoo
Posts: 21
Joined: Fri Mar 17, 2023 9:45 am
Location: Oslo, Norway
Contact:

Sensor values CLI in Python (macOS, Linux)

Post by atchoo »

Hello,

I wrote a small script in Python to get values of all sensors. This will run from macOS Terminal or a Linux/Unix command line (CLI).

The reason I made this in Python, was because I wanted to connect my Flic bluetooth button to Telldus Live, and there is no such pre-configured option in their Mac app (which in my opinion seems like a sloppy 3 nights job).

However, a cool feature about that Flic app is that it has rather extended support for user plugins. I believe these will generally work regardless of programming language, as long as
  • you provide a JSON dictionary, as described in their plugins support page
  • the plugin can be executed "inside" their app, client-side (Python, Applescript, Bash, Powershell, even some clever Javascript)
  • it returns some value/values that can (and will) get mangled by their non configurable widget view
Long story short: I figured my safest bet was to use Python, which was a good exercise for me. This will run fine "standalone" too, of course.
As you can see, Python is not exactly my first language, but I think it turned out pretty decent in the end.

sensors.py

Code: Select all

# -*- coding: utf-8 -*-
#!/usr/bin/env python

#  
# This is where to insert your generated API keys (http://api.telldus.com/keys/generatePrivate)

pubkey = "ABCDEFGH12345678"  # Public Key
privkey = "ABCDEFGH12345678" # Private Key
token = "123456789abcdefgh" # Token
secret = "123456789abcdefgh" # Token Secret 

import requests, json, hashlib
import time, math, random
m = time.time()
localtime = time.localtime(time.time())
ts = int(time.mktime(localtime))
ts2= str(ts)
sec = math.floor(m)
usec = math.floor(1000000 * (m - sec))
lcg = random.random()
the_uniqid = "%08x%05x%.8F" % (sec, usec, lcg * 10)
nonce = hashlib.md5(the_uniqid).hexdigest()
oauthSignature = (privkey + "%26" + secret)

response = requests.get(
	url="https://pa-api.telldus.com/json/sensors/list",
	params={
		"includeIgnored": "0",
		"includeValues": "1",
		"includeScale": "1",
		"includeUnit": "1",
	},
	headers={
		"Authorization": "OAuth oauth_consumer_key=\"" + pubkey +"\", oauth_nonce=\"" + nonce +"\", oauth_signature=\"" + oauthSignature + "\", oauth_signature_method=\"PLAINTEXT\", oauth_timestamp=\"" + ts2 + "\", oauth_token=\"" + token + "\", oauth_version=\"1.0\"",
		},
	)
	
data = json.loads(response.content)

for x in range(len(data['sensor'])):
	sensor = (data['sensor'][x])
	sensorName = (data['sensor'][x]['name']).encode('utf-8')
	print("\n\n" + sensorName + ":\n")
	for y in range(len(sensor['data'])):
		sensorType = (data['sensor'][x]['data'][y]['name']).encode('utf-8')
		sensorValue = (data['sensor'][x]['data'][y]['value']).encode('utf-8')
		sensorUnit = (data['sensor'][x]['data'][y]['unit']).encode('utf-8')
		if sensorType == 'temp':
			stp = 'Temperature'
		elif sensorType == 'humidity':
			stp = 'Humidity'
		elif sensorType == 'wdir':
			stp = 'Wind Dir.'
		elif sensorType == 'dewp':
			stp = 'Dew Point'
		elif sensorType == 'wavg':
			stp = 'Avg. Wind'
		elif sensorType == 'wgust':
			stp = 'Wind Gust'
		elif sensorType == 'barpress':
			stp = 'Bar Pressure'
		else:
			stp = sensorType 
		print(stp + ": " + sensorValue + sensorUnit)
Works on Python 2 & 3. Paste code into a new file, name it "sensors.py" and run it with

Code: Select all

python sensors.py
bergetun
Posts: 35
Joined: Fri Mar 17, 2023 9:45 am

Re: Sensor values CLI in Python (macOS, Linux)

Post by bergetun »

Tusen takk for dette.

Vet du om scriptet ditt fungerer enda ? JEg sliter med å få det til da jeg får feilemdlinger.

Code: Select all

pi@raspberrypi:~ $ python2 sensors.py 
Traceback (most recent call last):
  File "sensors.py", line 42, in <module>
    sensorName = (data['sensor'][x]['name']).encode('utf-8')
AttributeError: 'NoneType' object has no attribute 'encode'
pi@raspberrypi:~ $ 
bergetun
Posts: 35
Joined: Fri Mar 17, 2023 9:45 am

Re: Sensor values CLI in Python (macOS, Linux)

Post by bergetun »

Om det er andre som har problemer, så er det greit å legge til en check om den er null (none)

if data['sensor'][x]['name'] is None:
continue
atchoo
Posts: 21
Joined: Fri Mar 17, 2023 9:45 am
Location: Oslo, Norway
Contact:

Re: Sensor values CLI in Python (macOS, Linux)

Post by atchoo »

bergetun wrote: Mon Dec 02, 2019 11:12 am Om det er andre som har problemer, så er det greit å legge til en check om den er null (none)

if data['sensor'][x]['name'] is None:
continue
Ooops, helt rett. Utfordringen min er ofte at jeg blir så entusiastisk når jeg får til nye ting, at jeg bare vil fortelle alle om det med en gang - også går alle eventualiteter som jeg ikke tenker på der og da i bakleksa. Får det som oftest i retur på et eller annet tidspunkt, og det er nok meningen jeg skal lære noe av det, tenker jeg :roll:

Er forøvriig ganske praktisk å bruke "methods" for å sjekke hva slags egenskaper enheten har.

Husker ikke nøyaktig syntaks i hodet akkurat nå, men det er noe ala:

Code: Select all

if Device.TURNON or Device.TURNOFF in methods:
	checkSensor()
	
func checkifSensor() {
if Device.Bell not in methods elif deviceId != XYZ:
	doNotRingTheBell == True
	print("It's not a door bell, I presume.)
exit()
Skikkelig pseudokode her altså, men det var bare for å forklare sånn halvveis hva jeg mente. Ikke bruk det mot meg..hahah.

Peace. Andreas
Post Reply