Tuesday, July 28, 2015

Openwrt Synchronized Wifi Hotspot

There are three wireless routers at my home. All run Openwrt. One acts as gateway. The other two are APs. Sometimes, my mother wants to turn off WiFi before sleep. She would power off the gateway router. As a result, all clients will connect to the other two APs, and cannot access the Internet.

I want to make things more elegant. When the two APs detect that the gateway is down, they will turn off their wifi as well, and turn it on when the gateway is online again. Fortunately, the two APs have enough ROM for python. So I need not mess around with shell scripts.


Below is the python code. Save it on the router and add one line in crontab to run it every few minutes.
BTW, "wifi" is a greate command. It returns json format.

#! /usr/bin/python

import subprocess
import socket, sys
from json import JSONDecoder
import time

SERVER_IP = "192.168.1.1"
SERVER_PORT = 80

def turnon(devname):
    subprocess.call(["wifi", "up", devname])

def turnoff(devname):
    subprocess.call(["wifi", "down", devname])

def is_on(devname):
    ret = subprocess.check_output(["wifi", "status"])
    status = JSONDecoder().decode(ret)
    return status[devname]["up"]
     
def is_connected():
    for i in range(5):
        try:
            ss = socket.create_connection((SERVER_IP, SERVER_PORT))
            ss.close()
            return True
        except:
            pass
    return False

online = is_connected()
wifi_on = is_on("ra0")
heading = " ".join((time.strftime("[%Y-%m-%d %H:%M:%S]"), str(online), str(wifi_on)))
sys.stderr.write(heading+'\n')

if online == wifi_on:
    pass
if online and not wifi_on:
    turnon("ra0")
    print heading, "ON"
elif not online and wifi_on:
    turnoff("ra0")
    print heading, "OFF"


No comments:

Post a Comment