Skip to content

Commit

Permalink
Enhanced simulation
Browse files Browse the repository at this point in the history
  • Loading branch information
mrihtar committed Feb 14, 2018
1 parent 011f691 commit bb52e97
Show file tree
Hide file tree
Showing 4 changed files with 107 additions and 45 deletions.
15 changes: 10 additions & 5 deletions bluesensor-server.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,16 +86,18 @@ def enque_output(out, queue):
def reader(ioloop):
while True:
try:
cmd = [sys.executable, reader_py, sensor_name, '1']
cmd = [sys.executable, reader_py, sensor_name]
if simulate: cmd.append('simulate')
# this subprocess creation with pipes works on Unix and Windows!
proc = subprocess.Popen(cmd, bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
proc = subprocess.Popen(cmd, bufsize=1, universal_newlines=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
q = Queue()
t = Thread(target=enque_output, args=(proc.stdout, q))
t.daemon = True; t.start()

while True:
try:
line = q.get_nowait() # get next line from subprocess
line = q.get_nowait().strip() # get next line from subprocess
except:
yield gen.sleep(1) # wait 1 second
continue # no output yet
Expand All @@ -114,8 +116,9 @@ def reader(ioloop):
print_exc(sys._getframe().f_code.co_name)
yield gen.sleep(5) # wait 5 seconds

# Reopen sys.stdout with buffer size 0 (unbuffered)
# Reopen stdout and stderr with buffer size 0 (unbuffered)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0)

if len(sys.argv) == 1:
sys.stderr.write('This application must be called with parameters specifying reader and port number.\n')
Expand Down Expand Up @@ -146,6 +149,8 @@ def reader(ioloop):
sensor_name = str(sys.argv[2])
port_id = int('808' + sensor_name) # set port number according to sensor number

simulate = len(sys.argv) > 3

STATIC_PATH = os.path.join(os.path.dirname(__file__), 'static')
app = web.Application([
(r"/", MainHandler),
Expand All @@ -154,7 +159,7 @@ def reader(ioloop):
])
app.listen(port_id) # webserver listening TCP port

sys.stdout.write('Starting Tornado web server...\n')
sys.stdout.write('Starting Tornado web server with {}\n'.format(reader_py))
sys.stdout.write('To connect, open http://localhost:' + str(port_id) + '/\n')
ioloop = ioloop.IOLoop.current()
ioloop.add_callback(reader, ioloop)
Expand Down
39 changes: 29 additions & 10 deletions read-dust.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,32 @@

import sys, os
import traceback
import datetime, time
import datetime, time, pytz
from pprint import pprint
import serial
import json
import random

tz = pytz.timezone('Europe/Ljubljana')
va = [None]*2

def time_now_ms():
tt = datetime.datetime.now(tz).timetuple()
now = time.mktime(tt) + 3600 # WTF?!
if tt.tm_isdst: now += 3600
return int(now)*1000

def sim_value(n, max, fluc):
global va
plus = random.random() > 0.5
diff = random.random()*(max*fluc/100)
if va[n] is None: va[n] = max/2
if plus: va[n] += diff
else: va[n] -= diff
if va[n] > max: va[n] -= 2*diff
elif va[n] < 0: va[n] += 2*diff
return va[n]

class SDS021_Reader:
def __init__(self, inport, simulate=False):
self.simulate = simulate
Expand Down Expand Up @@ -60,10 +81,10 @@ def read(self):
values = self.readValue()
else:
values = []
values.append(random.random()*25)
values.append(random.random()*50)
values.append(sim_value(0, 25, 10))
values.append(sim_value(1, 50, 10))

t = int((time.time() - time.altzone)*1000)
t = time_now_ms()
species[0].append(values[0])
species[1].append(values[1])

Expand Down Expand Up @@ -99,24 +120,22 @@ def read(self):
sys.stderr.write(err + '\n')
time.sleep(1) # wait 1 second

# Reopen sys.stdout with buffer size 0 (unbuffered)
# Reopen stdout and stderr with buffer size 0 (unbuffered)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0)

if len(sys.argv) == 1:
sys.stderr.write('This application must be called with parameter specifying ID of a USB port where BlueSensor is conneccted.\n')
sys.stderr.write('For example: "read-serial.py 0" for reading from device connected to /dev/ttyUSB0.\n')
sys.exit()

USBNUM = str(sys.argv[1])
if (sys.argv[1].isdigit()):
if sys.argv[1].isdigit():
USBPORT = "/dev/ttyUSB" + USBNUM
else:
USBPORT = "/dev/ttyUSB0"

if (len(sys.argv) > 2):
simulate = True
else:
simulate = False
simulate = len(sys.argv) > 2

reader = SDS021_Reader(USBPORT, simulate)
while True:
Expand Down
51 changes: 35 additions & 16 deletions read-raw-serial.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,48 @@

import sys, os
import traceback
import datetime, time
import datetime, time, pytz
from pprint import pprint
import serial
import json
import random

# Reopen sys.stdout with buffer size 0 (unbuffered)
tz = pytz.timezone('Europe/Ljubljana')
va = [None]*6

def time_now_ms():
tt = datetime.datetime.now(tz).timetuple()
now = time.mktime(tt) + 3600 # WTF?!
if tt.tm_isdst: now += 3600
return int(now)*1000

def sim_value(n, max, fluc):
global va
plus = random.random() > 0.5
diff = random.random()*(max*fluc/100)
if va[n] is None: va[n] = max/2
if plus: va[n] += diff
else: va[n] -= diff
if va[n] > max: va[n] -= 2*diff
elif va[n] < 0: va[n] += 2*diff
return va[n]

# Reopen stdout and stderr with buffer size 0 (unbuffered)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0)

if len(sys.argv) == 1:
sys.stderr.write('This application must be called with parameter specifying USB port.\n')
sys.stderr.write('Use 0 for /dev/ttyUSB0, 1 for /dev/ttyUSB1, etc.\n')
sys.exit()

USBNUM = str(sys.argv[1])
if (sys.argv[1].isdigit()):
if sys.argv[1].isdigit():
USBPORT = "/dev/ttyUSB" + USBNUM
else:
USBPORT = "/dev/ttyUSB0"

if (len(sys.argv) > 2):
simulate = True
else:
simulate = False
simulate = len(sys.argv) > 2

if not simulate:
ser = serial.Serial(port=USBPORT, baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)
Expand All @@ -46,14 +65,14 @@
values.append('Raw sensor')
values.append('RAW1')
values.append('IJS')
values.append('Gas 1'); values.append(random.random())
values.append('Gas 2'); values.append(random.random())
values.append('Hum 1'); values.append(random.random()*100)
values.append('Temp 1'); values.append(random.random()*35)
values.append('Temp 2'); values.append(random.random()*35)
values.append('Temp 3'); values.append(random.random()*35)
values.append('Gas 1'); values.append(sim_value(0, 10, 20))
values.append('Gas 2'); values.append(sim_value(1, 10, 20))
values.append('Hum 1'); values.append(sim_value(2, 100, 5))
values.append('Temp 1'); values.append(sim_value(3, 50, 2))
values.append('Temp 2'); values.append(sim_value(4, 50, 2))
values.append('Temp 3'); values.append(sim_value(5, 50, 2))

t = int((time.time() - time.altzone)*1000)
t = time_now_ms()

data = {
"metadata": {
Expand All @@ -71,8 +90,8 @@
},
"time": t,
"data": {
"gas1": [round(values[4], 2), 0],
"gas2": [round(values[6], 2), 0],
"gas1": [round(values[4], 2), 10],
"gas2": [round(values[6], 2), 10],
"humidity": [round(values[8], 2), 100],
"temp1": [round(values[10], 2), 50],
"temp2": [round(values[12], 2), 50],
Expand Down
47 changes: 33 additions & 14 deletions read-serial.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,48 @@

import sys, os
import traceback
import datetime, time
import datetime, time, pytz
from pprint import pprint
import serial
import json
import random

# Reopen sys.stdout with buffer size 0 (unbuffered)
tz = pytz.timezone('Europe/Ljubljana')
va = [None]*6

def time_now_ms():
tt = datetime.datetime.now(tz).timetuple()
now = time.mktime(tt) + 3600 # WTF?!
if tt.tm_isdst: now += 3600
return int(now)*1000

def sim_value(n, max, fluc):
global va
plus = random.random() > 0.5
diff = random.random()*(max*fluc/100)
if va[n] is None: va[n] = max/2
if plus: va[n] += diff
else: va[n] -= diff
if va[n] > max: va[n] -= 2*diff
elif va[n] < 0: va[n] += 2*diff
return va[n]

# Reopen stdout and stderr with buffer size 0 (unbuffered)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0)

if len(sys.argv) == 1:
sys.stderr.write('This application must be called with parameter specifying ID of a USB port where BlueSensor is conneccted.\n')
sys.stderr.write('For example: "read-serial.py 0" for reading from device connected to /dev/ttyUSB0.\n')
sys.exit()

USBNUM = str(sys.argv[1])
if (sys.argv[1].isdigit()):
if sys.argv[1].isdigit():
USBPORT = "/dev/ttyUSB" + USBNUM
else:
USBPORT = "/dev/ttyUSB0"

if (len(sys.argv) > 2):
simulate = True
else:
simulate = False
simulate = len(sys.argv) > 2

if not simulate:
ser = serial.Serial(port=USBPORT, baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)
Expand Down Expand Up @@ -57,17 +76,17 @@
},
"time": 0,
"data": {
"gas1": [round(random.random(), 2), 0],
"gas2": [round(random.random(), 2), 0],
"humidity": [round(random.random()*100, 2), 100],
"temp1": [round(random.random()*35, 2), 50],
"temp2": [round(random.random()*35, 2), 50],
"temp3": [round(random.random()*35, 2), 50]
"gas1": [round(sim_value(0, 10, 20), 2), 10],
"gas2": [round(sim_value(1, 10, 20), 2), 10],
"humidity": [round(sim_value(2, 100, 5), 2), 100],
"temp1": [round(sim_value(3, 50, 2), 2), 50],
"temp2": [round(sim_value(4, 50, 2), 2), 50],
"temp3": [round(sim_value(5, 50, 2), 2), 50]
}
}
data_s = json.dumps(data)

t = int((time.time() - time.altzone)*1000)
t = time_now_ms()

data = json.loads(data_s)
if data['time'] is None or data['time'] == 0:
Expand Down

0 comments on commit bb52e97

Please sign in to comment.