Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 60 additions & 59 deletions emitter/sniffer/write_wifi_data.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,29 @@
#!/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
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__))

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"]

print "Will save data to: " + data_file_path
print("Will save data to: " + data_file_path)

to_send_power = {}
to_send_time = {}
Expand All @@ -42,54 +41,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)

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
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(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
190 changes: 97 additions & 93 deletions emitter/trigger/trigger.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@
import math

import httplib
import urllib

import RPi.GPIO as GPIO

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']
Expand All @@ -25,105 +25,109 @@

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)
except httplib.HTTPException:
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)
Expand All @@ -135,24 +139,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)
if not has_triggered:
log("Triggering")
send_trigger_message()
has_triggered = True
# else outside of distance threshold and in triggered state
elif has_triggered:
log("Outside of distance threshold...reset")
has_triggered = False

time.sleep(0.5)