Denne artikel er en støtteartikel til serien om GDS-IOT, indeholdende kildekode.
status.py
Dette program styrer status-lysdioden. Hvis der ikke er forbindelse til routeren lyser LED rød, ellers grøn.
#/* # * ----------------------------------------------------------------------------------- # * "THE BEER-WARE LICENSE" (Revision 42): # * <steen@ieee.org> wrote this file. As long as you retain this notice you # * can do whatever you want with this stuff. If we meet some day, and you think # * this stuff is worth it, you can buy me a beer in return. Steen Garbers Enevoldsen # * ----------------------------------------------------------------------------------- # */ import os import RPi.GPIO as GPIO import socket, struct import time GPIO.setmode(GPIO.BCM) GPIO.setup(9, GPIO.OUT) # Green LED GPIO.setup(10, GPIO.OUT) # Blue LED GPIO.setup(11, GPIO.OUT) # Red LED # Initialize: All LEDs off. GPIO.output(9, GPIO.LOW) GPIO.output(10, GPIO.LOW) GPIO.output(11, GPIO.LOW) # Start: LED is red GPIO.output(11, GPIO.HIGH) # Find default gateway, geeky method: read and parse directly from /proc/net/route # If you know in advance, it's easier to just set hostname="IPaddress" with open("/proc/net/route") as fh: for line in fh: fields = line.strip().split() if fields[1] != '00000000' or not int(fields[3], 16) & 2: continue hostname = socket.inet_ntoa(struct.pack("<L", int(fields[2], 16))) while True: time.sleep(1) response = os.system("ping -c 1 " + hostname) if response == 0: # Network is reachable, LED=Green GPIO.output(11, GPIO.LOW) GPIO.output(9, GPIO.HIGH) else: # Network is NOT reachable, LED=Red GPIO.output(11, GPIO.HIGH) GPIO.output(9, GPIO.LOW)