From c8d1dfab56432d5a0c489f1224675bd29e9dba9e Mon Sep 17 00:00:00 2001 From: James Harrison Date: Tue, 24 Mar 2015 15:00:12 +0000 Subject: [PATCH 1/3] Python PEP8/indentation fixes --- emitter/sniffer/write_wifi_data.py | 88 +++++++------- emitter/trigger/trigger.py | 188 +++++++++++++++-------------- 2 files changed, 143 insertions(+), 133 deletions(-) diff --git a/emitter/sniffer/write_wifi_data.py b/emitter/sniffer/write_wifi_data.py index 5ee9d35..e6e8502 100755 --- a/emitter/sniffer/write_wifi_data.py +++ b/emitter/sniffer/write_wifi_data.py @@ -1,6 +1,7 @@ #!/usr/bin/python # read from stdin -# Usage: sudo airodump-ng mon0 --channel 11 --berlin 2 2>&1 | ./send_wifi_data.py 2>&1 > airodump.log & +# Usage: sudo airodump-ng mon0 --channel 11 --berlin 2 2>&1 | +# ./send_wifi_data.py 2>&1 > airodump.log & import fileinput import re @@ -14,12 +15,13 @@ import json source = socket.gethostname() - + print source script_path = os.path.dirname(os.path.realpath(__file__)) -config_file = open(os.path.join(script_path, "..", "..", "shared", "config.json"), "r").read() +config_file = open( + os.path.join(script_path, "..", "..", "shared", "config.json"), "r").read() config = json.loads(config_file) data_file_path = config["sniffer"]["dataFilename"] @@ -42,54 +44,56 @@ pass if(re.search(' \w\w\:\w\w', line)): - try: - arr = re.split(' ',line) - #sys.stdout.write( "arr "+ "\t".join(arr)) - power = arr[2].strip() - aps = "" - if(re.search('[a-zA-Z]', arr[10])): - aps = arr[10].strip() - #sys.stdout.write( "aps "+ aps) + try: + arr = re.split(' ', line) + # sys.stdout.write( "arr "+ "\t".join(arr)) + power = arr[2].strip() + aps = "" + if(re.search('[a-zA-Z]', arr[10])): + aps = arr[10].strip() + # sys.stdout.write( "aps "+ aps) this_id = str(arr[1].strip()) tt = int(time.time()) - if(power!="" and int(power) > power_threshold and int(power)!=-1): - - if (this_id in exclusions): - #print "do nothing, excluded" - sys.stdout.write('-') - else: - sys.stdout.write('.') - #print "found "+str(this_id)+" power "+str(power) - #print "updating last seen anything to "+str(tt) - to_send_power[this_id] = str(power) - to_send_time[this_id] = str(tt) - to_send_aps[this_id] = str(aps) - last_seen_anything = tt + + if(power != "" and int(power) > power_threshold and int(power) != -1): + if (this_id in exclusions): + # print "do nothing, excluded" + sys.stdout.write('-') + else: + sys.stdout.write('.') + # print "found "+str(this_id)+" power "+str(power) + # print "updating last seen anything to "+str(tt) + to_send_power[this_id] = str(power) + to_send_time[this_id] = str(tt) + to_send_aps[this_id] = str(aps) + last_seen_anything = tt if(len(to_send_power) > 0 and int(time.time()) - last_time_seen > 10): - # send data every few seconds, to make sure we capture multiple devices - if(int(time.time()) - last_seen_anything < time_threshold): - print "\nsaving data because "+str(time.time() - last_seen_anything) - data = [] - count = 0 - for item in to_send_time: - item_ob = item[0:12]+"XX:XX" - list_item = {'source':source,'id':item_ob, 'time': to_send_time[item], 'power': to_send_power[item], 'aps': to_send_aps[item]} - data.append(list_item) - data_sorted = sorted(data, key=lambda k: k['power']) - all_data = {'data':data_sorted} - data_str = json.dumps(all_data) - - # save the data - file_ = open(data_file_path, 'w') - file_.write(data_str) - file_.close() + # send data every few seconds, to make sure we capture multiple + # devices + if(int(time.time()) - last_seen_anything < time_threshold): + print "\nsaving data because " + str(time.time() - last_seen_anything) + data = [] + count = 0 + for item in to_send_time: + item_ob = item[0:12] + "XX:XX" + list_item = {'source': source, 'id': item_ob, 'time': to_send_time[ + item], 'power': to_send_power[item], 'aps': to_send_aps[item]} + data.append(list_item) + data_sorted = sorted(data, key=lambda k: k['power']) + all_data = {'data': data_sorted} + data_str = json.dumps(all_data) + + # save the data + file_ = open(data_file_path, 'w') + file_.write(data_str) + file_.close() # update time last seen something last_time_seen = int(time.time()) - except Exception, e: + except Exception, e: print e pass diff --git a/emitter/trigger/trigger.py b/emitter/trigger/trigger.py index 5228e90..65aeb27 100644 --- a/emitter/trigger/trigger.py +++ b/emitter/trigger/trigger.py @@ -12,7 +12,8 @@ script_path = os.path.dirname(os.path.realpath(__file__)) -config_file = open(os.path.join(script_path, "..", "..", "shared", "config.json"), "r").read() +config_file = open( + os.path.join(script_path, "..", "..", "shared", "config.json"), "r").read() config = json.loads(config_file) host = config['collector']['host'] @@ -25,105 +26,110 @@ distance_threshold_cm = config['trigger']['distanceThresholdCm'] + def log(msg): - print msg - sys.stdout.flush() + print msg + sys.stdout.flush() + def setup(): - GPIO.setmode(GPIO.BOARD) + GPIO.setmode(GPIO.BOARD) - GPIO.setwarnings(False) + GPIO.setwarnings(False) - # point the software to the GPIO pins the sensor is using - # change these values to the pins you are using - # GPIO output = the pin that's connected to "Trig" on the sensor - # GPIO input = the pin that's connected to "Echo" on the sensor - GPIO.setup(trigger_pin,GPIO.OUT) - GPIO.setup(echo_pin,GPIO.IN) - GPIO.output(trigger_pin, GPIO.LOW) + # point the software to the GPIO pins the sensor is using + # change these values to the pins you are using + # GPIO output = the pin that's connected to "Trig" on the sensor + # GPIO input = the pin that's connected to "Echo" on the sensor + GPIO.setup(trigger_pin, GPIO.OUT) + GPIO.setup(echo_pin, GPIO.IN) + GPIO.output(trigger_pin, GPIO.LOW) + + # found that the sensor can crash if there isn't a delay here + # no idea why. If you have odd crashing issues, increase delay + time.sleep(0.3) - # found that the sensor can crash if there isn't a delay here - # no idea why. If you have odd crashing issues, increase delay - time.sleep(0.3) def read(): - # libby - signaloff = time.time() + # libby + signaloff = time.time() + # sensor manual says a pulse ength of 10Us will trigger the + # sensor to transmit 8 cycles of ultrasonic burst at 40kHz and + # wait for the reflected ultrasonic burst to be received - # sensor manual says a pulse ength of 10Us will trigger the - # sensor to transmit 8 cycles of ultrasonic burst at 40kHz and - # wait for the reflected ultrasonic burst to be received + # to get a pulse length of 10Us we need to start the pulse, then + # wait for 10 microseconds, then stop the pulse. This will + # result in the pulse length being 10Us. - # to get a pulse length of 10Us we need to start the pulse, then - # wait for 10 microseconds, then stop the pulse. This will - # result in the pulse length being 10Us. + # start the pulse on the GPIO pin + # change this value to the pin you are using + # GPIO output = the pin that's connected to "Trig" on the sensor + GPIO.output(trigger_pin, True) - # start the pulse on the GPIO pin - # change this value to the pin you are using - # GPIO output = the pin that's connected to "Trig" on the sensor - GPIO.output(trigger_pin, True) + # wait 10 micro seconds (this is 0.00001 seconds) so the pulse + # length is 10Us as the sensor expects + time.sleep(0.00001) - # wait 10 micro seconds (this is 0.00001 seconds) so the pulse - # length is 10Us as the sensor expects - time.sleep(0.00001) + # stop the pulse after the time above has passed + # change this value to the pin you are using + # GPIO output = the pin that's connected to "Trig" on the sensor + GPIO.output(trigger_pin, False) - # stop the pulse after the time above has passed - # change this value to the pin you are using - # GPIO output = the pin that's connected to "Trig" on the sensor - GPIO.output(trigger_pin, False) + # listen to the input pin. 0 means nothing is happening. Once a + # signal is received the value will be 1 so the while loop + # stops and has the last recorded time the signal was 0 + # change this value to the pin you are using + # GPIO input = the pin that's connected to "Echo" on the sensor + while GPIO.input(echo_pin) == 0: + signaloff = time.time() - # listen to the input pin. 0 means nothing is happening. Once a - # signal is received the value will be 1 so the while loop - # stops and has the last recorded time the signal was 0 - # change this value to the pin you are using - # GPIO input = the pin that's connected to "Echo" on the sensor - while GPIO.input(echo_pin) == 0: - signaloff = time.time() + # listen to the input pin. Once a signal is received, record the + # time the signal came through + # change this value to the pin you are using + # GPIO input = the pin that's connected to "Echo" on the sensor + while GPIO.input(echo_pin) == 1: + signalon = time.time() - # listen to the input pin. Once a signal is received, record the - # time the signal came through - # change this value to the pin you are using - # GPIO input = the pin that's connected to "Echo" on the sensor - while GPIO.input(echo_pin) == 1: - signalon = time.time() + # work out the difference in the two recorded times above to + # calculate the distance of an object in front of the sensor + timepassed = signalon - signaloff - # work out the difference in the two recorded times above to - # calculate the distance of an object in front of the sensor - timepassed = signalon - signaloff + # we now have our distance but it's not in a useful unit of + # measurement. So now we convert this distance into centimetres + distance = timepassed * 17000 - # we now have our distance but it's not in a useful unit of - # measurement. So now we convert this distance into centimetres - distance = timepassed * 17000 + # return the distance of an object in front of the sensor in cm + return distance - # return the distance of an object in front of the sensor in cm - return distance def teardown(): - log('Cleaning up GPIO...') - GPIO.cleanup() + log('Cleaning up GPIO...') + GPIO.cleanup() + def send_trigger_message(): - log("Send trigger message") - msg = '{"channel":"/trigger","data":{}}' - headers = { "Content-type": "application/json" } - - try: - conn = httplib.HTTPConnection(host, port) - conn.request("POST", "/faye", msg, headers) - response = conn.getresponse() - log(str(response.status) + " " + response.reason) - data = response.read() - except httplib.HTTPException, e: - log("Error making HTTP request") - finally: - conn.close() + log("Send trigger message") + msg = '{"channel":"/trigger","data":{}}' + headers = {"Content-type": "application/json"} + + try: + conn = httplib.HTTPConnection(host, port) + conn.request("POST", "/faye", msg, headers) + response = conn.getresponse() + log(str(response.status) + " " + response.reason) + data = response.read() + except httplib.HTTPException, e: + log("Error making HTTP request") + finally: + conn.close() + def handleSigTERM(): - teardown() - log('...exit') - sys.exit() + teardown() + log('...exit') + sys.exit() signal.signal(signal.SIGTERM, handleSigTERM) @@ -135,24 +141,24 @@ def handleSigTERM(): # Main loop while True: - distance = math.ceil( read() ) + distance = math.ceil(read()) - # Log if distance has changed - if log_distance and (distance != last_distance): - log(distance) - last_distance = distance + # Log if distance has changed + if log_distance and (distance != last_distance): + log(distance) + last_distance = distance - # If within distance threshold ... - if distance < distance_threshold_cm: - log("Within distance threshold") + # If within distance threshold ... + if distance < distance_threshold_cm: + log("Within distance threshold") # ... and not in triggered state if has_triggered == False: - log("Triggering") - send_trigger_message() - has_triggered = True - # else outside of distance threshold and in triggered state - elif has_triggered == True: - log("Outside of distance threshold...reset") - has_triggered = False - - time.sleep(0.5) + log("Triggering") + send_trigger_message() + has_triggered = True + # else outside of distance threshold and in triggered state + elif has_triggered == True: + log("Outside of distance threshold...reset") + has_triggered = False + + time.sleep(0.5) From 626f52ba618dce47bcdfcc56a3fe390aa1f09313 Mon Sep 17 00:00:00 2001 From: James Harrison Date: Tue, 24 Mar 2015 15:01:21 +0000 Subject: [PATCH 2/3] Couple of final PEP8/style tweaks --- emitter/trigger/trigger.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/emitter/trigger/trigger.py b/emitter/trigger/trigger.py index 65aeb27..9f74549 100644 --- a/emitter/trigger/trigger.py +++ b/emitter/trigger/trigger.py @@ -120,7 +120,7 @@ def send_trigger_message(): response = conn.getresponse() log(str(response.status) + " " + response.reason) data = response.read() - except httplib.HTTPException, e: + except httplib.HTTPException as e: log("Error making HTTP request") finally: conn.close() @@ -152,12 +152,12 @@ def handleSigTERM(): if distance < distance_threshold_cm: log("Within distance threshold") # ... and not in triggered state - if has_triggered == False: + if not has_triggered: log("Triggering") send_trigger_message() has_triggered = True # else outside of distance threshold and in triggered state - elif has_triggered == True: + elif has_triggered: log("Outside of distance threshold...reset") has_triggered = False From eb067ff5934b9e23511f29e6911a560f7e8b51ac Mon Sep 17 00:00:00 2001 From: James Harrison Date: Tue, 24 Mar 2015 15:07:16 +0000 Subject: [PATCH 3/3] Removed some unused imports, fixed python3 compatibility, indentation fixes --- emitter/sniffer/write_wifi_data.py | 95 +++++++++++++++--------------- emitter/trigger/trigger.py | 6 +- 2 files changed, 48 insertions(+), 53 deletions(-) diff --git a/emitter/sniffer/write_wifi_data.py b/emitter/sniffer/write_wifi_data.py index e6e8502..973a231 100755 --- a/emitter/sniffer/write_wifi_data.py +++ b/emitter/sniffer/write_wifi_data.py @@ -5,18 +5,15 @@ import fileinput import re -import subprocess import os -import glob import time import sys import socket -import urllib import json source = socket.gethostname() -print source +print(source) script_path = os.path.dirname(os.path.realpath(__file__)) @@ -26,7 +23,7 @@ data_file_path = config["sniffer"]["dataFilename"] -print "Will save data to: " + data_file_path +print("Will save data to: " + data_file_path) to_send_power = {} to_send_time = {} @@ -53,47 +50,47 @@ aps = arr[10].strip() # sys.stdout.write( "aps "+ aps) - this_id = str(arr[1].strip()) - tt = int(time.time()) - - if(power != "" and int(power) > power_threshold and int(power) != -1): - if (this_id in exclusions): - # print "do nothing, excluded" - sys.stdout.write('-') - else: - sys.stdout.write('.') - # print "found "+str(this_id)+" power "+str(power) - # print "updating last seen anything to "+str(tt) - to_send_power[this_id] = str(power) - to_send_time[this_id] = str(tt) - to_send_aps[this_id] = str(aps) - last_seen_anything = tt - - if(len(to_send_power) > 0 and int(time.time()) - last_time_seen > 10): - - # send data every few seconds, to make sure we capture multiple - # devices - if(int(time.time()) - last_seen_anything < time_threshold): - print "\nsaving data because " + str(time.time() - last_seen_anything) - data = [] - count = 0 - for item in to_send_time: - item_ob = item[0:12] + "XX:XX" - list_item = {'source': source, 'id': item_ob, 'time': to_send_time[ - item], 'power': to_send_power[item], 'aps': to_send_aps[item]} - data.append(list_item) - data_sorted = sorted(data, key=lambda k: k['power']) - all_data = {'data': data_sorted} - data_str = json.dumps(all_data) - - # save the data - file_ = open(data_file_path, 'w') - file_.write(data_str) - file_.close() - - # update time last seen something - last_time_seen = int(time.time()) - - except Exception, e: - print e - pass + this_id = str(arr[1].strip()) + tt = int(time.time()) + + if(power != "" and int(power) > power_threshold and int(power) != -1): + if (this_id in exclusions): + # print("do nothing, excluded") + sys.stdout.write('-') + else: + sys.stdout.write('.') + # print("found "+str(this_id)+" power "+str(power)) + # print("updating last seen anything to "+str(tt)) + to_send_power[this_id] = str(power) + to_send_time[this_id] = str(tt) + to_send_aps[this_id] = str(aps) + last_seen_anything = tt + + if(len(to_send_power) > 0 and int(time.time()) - last_time_seen > 10): + + # send data every few seconds, to make sure we capture multiple + # devices + if(int(time.time()) - last_seen_anything < time_threshold): + print("\nsaving data because " + str(time.time() - last_seen_anything)) + data = [] + count = 0 + for item in to_send_time: + item_ob = item[0:12] + "XX:XX" + list_item = {'source': source, 'id': item_ob, 'time': to_send_time[ + item], 'power': to_send_power[item], 'aps': to_send_aps[item]} + data.append(list_item) + data_sorted = sorted(data, key=lambda k: k['power']) + all_data = {'data': data_sorted} + data_str = json.dumps(all_data) + + # save the data + file_ = open(data_file_path, 'w') + file_.write(data_str) + file_.close() + + # update time last seen something + last_time_seen = int(time.time()) + + except Exception as e: + print(e) + pass diff --git a/emitter/trigger/trigger.py b/emitter/trigger/trigger.py index 9f74549..69032e5 100644 --- a/emitter/trigger/trigger.py +++ b/emitter/trigger/trigger.py @@ -6,7 +6,6 @@ import math import httplib -import urllib import RPi.GPIO as GPIO @@ -28,7 +27,7 @@ def log(msg): - print msg + print(msg) sys.stdout.flush() @@ -119,8 +118,7 @@ def send_trigger_message(): conn.request("POST", "/faye", msg, headers) response = conn.getresponse() log(str(response.status) + " " + response.reason) - data = response.read() - except httplib.HTTPException as e: + except httplib.HTTPException: log("Error making HTTP request") finally: conn.close()