Skip to content

Commit

Permalink
Merge pull request #3 from mrihtar/master
Browse files Browse the repository at this point in the history
Fixed for python 3.11
  • Loading branch information
MatejKovacic authored Sep 21, 2023
2 parents 99b29b5 + 4724af3 commit ccdb031
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 17 deletions.
26 changes: 18 additions & 8 deletions bluesensor-server.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from tornado import ioloop, gen, websocket, web
import subprocess
from threading import Thread
from multiprocessing.queues import Queue
from multiprocessing import queues, get_context
from collections import deque

import database as db
Expand All @@ -25,23 +25,27 @@

def dump(obj, detailed=False):
sys.stdout.write('obj.type = {}\n'.format(type(obj)))
sys.stdout.flush()
for attr in dir(obj):
try:
value = getattr(obj, attr)
sys.stdout.write('obj.{} = {}\n'.format(attr, value))
sys.stdout.flush()
if detailed and str(value).startswith('<'):
sys.stdout.write(' '); n = 0
for oattr in dir(value):
if n > 0: sys.stdout.write(' ')
sys.stdout.write('{}'.format(oattr)); n += 1
sys.stdout.write('\n')
sys.stdout.flush()
except: pass

def print_exc(f_name, msg=''):
exc_type, exc_obj, exc_tb = sys.exc_info()
exc = traceback.format_exception_only(exc_type, exc_obj)
err = '{}({}): {}'.format(f_name, exc_tb.tb_lineno, msg) + exc[-1].strip()
sys.stderr.write(err + '\n')
sys.stderr.flush()

class MainHandler(web.RequestHandler):
@gen.coroutine
Expand All @@ -51,6 +55,7 @@ def get(self):
with open(graf_template) as f:
html = f.read()
self.write(html)
self.flush()
except:
print_exc(sys._getframe().f_code.co_name, graf_template + ': ')

Expand Down Expand Up @@ -81,7 +86,7 @@ def send_update(measurement):
@gen.coroutine
def update_db(sensor, data):
try:
print('Inserting data into db')
print('Inserting data into db', flush=True)
db.dbInsert(sensor, data)
except: pass

Expand All @@ -102,7 +107,7 @@ def reader(ioloop):
# this subprocess creation with pipes works on Unix and Windows!
proc = subprocess.Popen(cmd, bufsize=1, universal_newlines=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
q = Queue()
q = queues.Queue(ctx=get_context())
t = Thread(target=enque_output, args=(proc.stdout, q))
t.daemon = True; t.start()

Expand All @@ -114,10 +119,10 @@ def reader(ioloop):
yield gen.sleep(1) # wait 1 second
continue # no output yet

print('Got JSON: %r' % line)
print('Got JSON: %r' % line, flush=True)
try:
measurement = json.loads(line)
#print(measurement)
#print(measurement, flush=True)
ioloop.add_callback(send_update, measurement)
if db_use and (tick % db_save) == 0:
ioloop.add_callback(update_db, USBPORT, line)
Expand All @@ -130,9 +135,9 @@ def reader(ioloop):
print_exc(sys._getframe().f_code.co_name)
yield gen.sleep(5) # wait 5 seconds

# 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)
# Reopen stdout and stderr with buffer size 0 (unbuffered) - only in python 2.7
#sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
#sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0)

db_use = False; db_save = DB_SAVE

Expand All @@ -152,6 +157,7 @@ def reader(ioloop):
vf = False
else:
sys.stderr.write('Error: unknown argument \'{}\'\n'.format(arg))
sys.stderr.flush()
vf = False
else:
argv.append(arg)
Expand All @@ -163,6 +169,7 @@ def reader(ioloop):
sys.stderr.write(' for reading data from BlueSensor connected to ttyUSB0\n')
sys.stderr.write('$ python bluesensor-server.py read-dust 1\n')
sys.stderr.write(' for reading data from dust sensor connected to ttyUSB1\n')
sys.stderr.flush()
sys.exit(1)

sensor_name = str(argv[1])
Expand All @@ -176,10 +183,12 @@ def reader(ioloop):

if not os.path.isfile(reader_py):
sys.stderr.write('Error: file "{}" doesn\'t exist\n'.format(reader_py))
sys.stderr.flush()
sys.exit(2)

if len(argv) < 3:
sys.stderr.write('Error: missing USB port number (for example from 0 to 3)\n')
sys.stderr.flush()
sys.exit(3)
else:
sensor_name = str(argv[2])
Expand Down Expand Up @@ -208,6 +217,7 @@ def reader(ioloop):

sys.stdout.write('Starting Sensor web server with {}\n'.format(reader_py))
sys.stdout.write('To connect, open http://localhost:' + str(port_id) + '/\n')
sys.stdout.flush()
ioloop = ioloop.IOLoop.current()
ioloop.add_callback(reader, ioloop)
ioloop.start()
12 changes: 9 additions & 3 deletions read-dust.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ def print_exc(f_name, msg=''):
exc = traceback.format_exception_only(exc_type, exc_obj)
err = '{}({}): {}'.format(f_name, exc_tb.tb_lineno, msg) + exc[-1].strip()
sys.stderr.write(err + '\n')
sys.stderr.flush()

def time_now_ms():
tt = datetime.datetime.now(tz).timetuple()
Expand Down Expand Up @@ -51,9 +52,11 @@ def __init__(self, inport, simulate=False):
print_exc(sys._getframe().f_code.co_name)
sys.exit(1)
sys.stderr.write('Reading DUST data from ' + inport + '...\n')
sys.stderr.flush()
else:
self.serial = None
sys.stderr.write('Reading DUST data from simulated ' + inport + '...\n')
sys.stderr.flush()

def readValue(self):
step = 0
Expand Down Expand Up @@ -117,22 +120,25 @@ def read(self):
data_s = json.dumps(data)

sys.stdout.write(data_s + '\n')
sys.stdout.flush()

time.sleep(1) # wait 1 second
except KeyboardInterrupt:
sys.stderr.write('Quit!\n')
sys.stderr.flush()
sys.exit(0)
except:
print_exc(sys._getframe().f_code.co_name)
time.sleep(1) # wait 1 second

# 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)
# Reopen stdout and stderr with buffer size 0 (unbuffered) - only in python 2.7
#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.stderr.flush()
sys.exit()

if sys.platform.startswith('win'):
Expand Down
12 changes: 9 additions & 3 deletions read-raw-serial.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ def print_exc(f_name, msg=''):
exc = traceback.format_exception_only(exc_type, exc_obj)
err = '{}({}): {}'.format(f_name, exc_tb.tb_lineno, msg) + exc[-1].strip()
sys.stderr.write(err + '\n')
sys.stderr.flush()

def time_now_ms():
tt = datetime.datetime.now(tz).timetuple()
Expand All @@ -37,13 +38,14 @@ def sim_value(n, max, fluc):
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)
# Reopen stdout and stderr with buffer size 0 (unbuffered) - only in python 2.7
#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.stderr.flush()
sys.exit()

if sys.platform.startswith('win'):
Expand All @@ -63,9 +65,11 @@ def sim_value(n, max, fluc):
print_exc(sys._getframe().f_code.co_name)
sys.exit(1)
sys.stderr.write('Reading RAW data from ' + USBPORT + '...\n')
sys.stderr.flush()
else:
ser = None
sys.stderr.write('Reading RAW data from simulated ' + USBPORT + '...\n')
sys.stderr.flush()

while True:
try:
Expand Down Expand Up @@ -113,10 +117,12 @@ def sim_value(n, max, fluc):
data_s = json.dumps(data)

sys.stdout.write(data_s + '\n')
sys.stdout.flush()

time.sleep(1) # wait 1 second
except KeyboardInterrupt:
sys.stderr.write('Quit!\n')
sys.stderr.flush()
sys.exit(0)
except:
print_exc(sys._getframe().f_code.co_name)
Expand Down
12 changes: 9 additions & 3 deletions read-serial.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ def print_exc(f_name, msg=''):
exc = traceback.format_exception_only(exc_type, exc_obj)
err = '{}({}): {}'.format(f_name, exc_tb.tb_lineno, msg) + exc[-1].strip()
sys.stderr.write(err + '\n')
sys.stderr.flush()

def time_now_ms():
tt = datetime.datetime.now(tz).timetuple()
Expand All @@ -37,13 +38,14 @@ def sim_value(n, max, fluc):
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)
# Reopen stdout and stderr with buffer size 0 (unbuffered) - only in python 2.7
#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.stderr.flush()
sys.exit()

if sys.platform.startswith('win'):
Expand All @@ -63,9 +65,11 @@ def sim_value(n, max, fluc):
print_exc(sys._getframe().f_code.co_name)
sys.exit(1)
sys.stderr.write('Reading JSON data from ' + USBPORT + '...\n')
sys.stderr.flush()
else:
ser = None
sys.stderr.write('Reading JSON data from simulated ' + USBPORT + '...\n')
sys.stderr.flush()

while True:
try:
Expand Down Expand Up @@ -106,10 +110,12 @@ def sim_value(n, max, fluc):
data_s = json.dumps(data)

sys.stdout.write(data_s + '\n')
sys.stdout.flush()

time.sleep(1) # wait 1 second
except KeyboardInterrupt:
sys.stderr.write('Quit!\n')
sys.stderr.flush()
sys.exit(0)
except:
print_exc(sys._getframe().f_code.co_name)
Expand Down

0 comments on commit ccdb031

Please sign in to comment.