Skip to content

Instantly share code, notes, and snippets.

@andialbrecht
Created January 11, 2014 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andialbrecht/8372574 to your computer and use it in GitHub Desktop.
Save andialbrecht/8372574 to your computer and use it in GitHub Desktop.
Weekend fun project. I've copied wlandevices.sh via FTP to my FritzBox, copied the other two scripts to my Raspberry and added a cron that runs fetch_wlanlist.py (sorry for the name) every 5 minutes. The script checks if known devices are close to the wlan router which is located in our living room and greets the (supposed) user with a warm welc…
#!/usr/bin/env python3
import json
import os
from urllib.request import urlopen
URL = 'http://api.openweathermap.org/data/2.5/weather?id=2953398&lang=de'
def fetch_weatherdata():
response = urlopen(URL)
return json.loads(response.read().decode('utf-8'))
def _format_temp(temp):
temp = temp - 273.15
temp = '{:.2}'.format(temp)
return temp.replace('.', ',')
def convert_to_text(data):
text = ['Das Wetter heute:']
text.append(data['weather'][0]['description'])
text.append('bei Temperaturen zwischen')
text.append(_format_temp(data['main']['temp_min']))
text.append('und')
text.append(_format_temp(data['main']['temp_max']))
text.append('Grad.')
return ' '.join(text)
if __name__ == '__main__':
text = convert_to_text(fetch_weatherdata())
os.system('espeak -v mb-de5 -s 100 "{}"'.format(text))
#!/usr/bin/env python3
import json
import os
import telnetlib
SERVER = 'fritz.box'
PASSWORD = 'secret'
# Location of wlandevices.sh on FritzBox
SCRIPT_PATH = '/var/media/ftp/Kingston-DataTraveler2-0-01/wlandevices.sh'
SCRIPT_DIR = os.path.dirname(__file__)
STATE_FILE = os.path.join(SCRIPT_DIR, 'wlan.state')
TRACKED_DEVICES = {
'00:00:00:00:00:00': 'andi',
'00:00:00:00:00:01': 'andi',
'00:00:00:00:00:02': 'andi',
}
def fetch_raw():
client = telnetlib.Telnet(SERVER)
try:
client.read_until(b'password: ')
client.write(PASSWORD.encode() + b'\n')
client.read_until(b'# ')
client.write(SCRIPT_PATH.encode() + b'\n')
client.read_until(b'\n')
return client.read_until(b'# ').decode()[:-2]
finally:
client.close()
def parse(raw):
parsed = {}
for line in raw.splitlines():
data = {}
for entry in line.split(' '):
key, value = entry.split('=', 1)
if key in ('state', 'speed', 'quality', 'wlandevice'):
value = int(value)
data[key] = value
mac = data.pop('mac')
parsed[mac] = data
return parsed
def retrieve_wlan_devices():
return parse(fetch_raw())
def read_state_file():
if not os.path.exists(STATE_FILE):
return {}
else:
with open(STATE_FILE, 'r') as f:
return json.load(f)
def save_state_file(state):
with open(STATE_FILE, 'w') as f:
json.dump(state, f)
def process_updates(oldstate, newstate):
old_users = oldstate.get('users', {})
old_devices = oldstate.get('devices', {})
new_users = {}
for mac in newstate:
old_quality = old_devices.get(mac, {'quality': 0})['quality']
if old_quality > 90:
continue
elif old_quality <= 90 and newstate[mac]['quality'] > 90:
user = TRACKED_DEVICES.get(mac, None)
if user is not None:
new_users[user] = True
for new_user in set(new_users).difference(set(old_users)):
greet_user(new_user)
return {'users': new_users, 'devices': newstate}
def greet_user(user):
os.system('espeak -v mb-de5 -s 100 "Hallo %s. Schön, dass du da bist."' % user)
if __name__ == '__main__':
prevstate = read_state_file()
newstate = retrieve_wlan_devices()
newstate = process_updates(prevstate, newstate)
save_state_file(newstate)
#!/bin/sh
i=0
count_devices=`ctlmgr_ctl r wlan settings/wlanlist/count`
while [ $i -lt $count_devices ]
do
device="wlandevice="$i
#for command in mac UID state speed rssi quality is_turbo is_guest is_ap ap_state mode wmm_active cipher powersave is_repeater channel freq flags flags_set
for command in mac state speed quality hostname
do
output="`ctlmgr_ctl r wlan settings/wlanlist$i/$command`"
device=$device" "$command"="$output
done
echo $device
let i="i + 1"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment