[AETHER-3121] - On-demand probing

Change-Id: I573d3d17ba73b4c1f06b7bc28a10c4a6018d72c6
diff --git a/app.py b/app.py
index 1b2c075..4a53c31 100644
--- a/app.py
+++ b/app.py
@@ -21,6 +21,8 @@
 
 devices = {} # dict imsi:device
 lock = threading.Lock()
+probe_start = threading.Event()
+probe_stop = threading.Event()
 
 
 @app.route("/devices")
@@ -52,12 +54,25 @@
                 unreachable[device.imsi_id] = {'ip':device.ip, 'imsi':device.imsi, 'last_reachable':'{:%Y-%m-%d %H:%M:%S}'.format(device.last_reachable)}
     return unreachable
 
+@app.route("/probe")
+def probe():
+    update_and_probe()
+    return get_devices_reachable()
+
 @app.route("/config")
 def config():
-    global args
+    global args, probe_stop
     period = request.args.get('period')
     if period is not None:
-        args.period = int(period)
+        period = int(period)
+        if period == 0:
+            log.info("Stopping probes...")
+            args.period = period
+            probe_stop.set()
+        else:
+            log.info("Starting probes...")
+            args.period = period
+            probe_start.set()
     config = vars(args)
     config.pop('token', None)
     config.pop('user', None)
@@ -111,15 +126,25 @@
             device.reachable = False
             log.info("{}/{}/{} - unreachable".format(device.imsi_id, device.imsi, device.ip))
 
-def work_thread(roc, prom):
-    global devices, lock, args
-    while True:
-        new = update(roc, prom, devices)
-        probe(new)
-        with lock:
-            devices = new
+def update_and_probe():
+    global devices, lock
+    new = update(roc, prom, devices)
+    probe(new)
+    with lock:
+        devices = new
 
-        time.sleep(args.period)
+def work_thread(roc, prom):
+    global args
+    while True:
+        probe_start.wait()
+        probe_start.clear()
+        log.info("Probing started")
+        while True:
+            update_and_probe()
+            if probe_stop.wait(timeout=args.period):
+                log.info("Probing stopped")
+                probe_stop.clear()
+                break
 
 if __name__ == '__main__':
 
@@ -138,5 +163,6 @@
 
     t = threading.Thread(target=work_thread, args=(roc, prom,))
     t.start()
+    probe_start.set()
 
     app.run('0.0.0.0', args.port)