Skip to content

Commit

Permalink
Merge pull request schodet#132 from feinstaub/master
Browse files Browse the repository at this point in the history
Fix nxt_test when --verbose option is NOT given
  • Loading branch information
GoldSloth authored Apr 24, 2018
2 parents 86ebdf2 + 7fb8332 commit 9851bee
Show file tree
Hide file tree
Showing 7 changed files with 85 additions and 57 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
build/

80 changes: 49 additions & 31 deletions nxt/locator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# Copyright (C) 2006, 2007 Douglas P Lau
# Copyright (C) 2009 Marcus Wanner
# Copyright (C) 2013 Dave Churchill, Marcus Wanner
# Copyright (C) 2015, 2016, 2017, 2018 Multiple Authors
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
Expand All @@ -18,9 +19,11 @@
class BrickNotFoundError(Exception):
pass


class NoBackendError(Exception):
pass


class Method():
"""Used to indicate which comm backends should be tried by find_bricks/
find_one_brick. Any or all can be selected."""
Expand All @@ -30,6 +33,7 @@ def __init__(self, usb=True, bluetooth=True, device=False):
self.bluetooth = bluetooth
self.device = device


def find_bricks(host=None, name=None, silent=False, method=Method()):
"""Used by find_one_brick to look for bricks ***ADVANCED USERS ONLY***"""
methods_available = 0
Expand Down Expand Up @@ -87,7 +91,7 @@ def find_one_brick(host=None, name=None, silent=False, strict=None, debug=False,
information will be read from if no brick location directives (host,
name, strict, or method) are provided."""
if debug and silent:
silent=False
silent = False
print("silent and debug can't both be set; giving debug priority")

conf = read_config(confpath, debug)
Expand All @@ -98,41 +102,53 @@ def find_one_brick(host=None, name=None, silent=False, strict=None, debug=False,
method = eval('Method(%s)' % conf.get('Brick', 'method'))
if not strict: strict = True
if not method: method = Method()

if debug:
print("Host: %s Name: %s Strict: %s" % (host, name, str(strict)))
print("USB: {} BT: {}".format(method.usb, method.bluetooth))

for s in find_bricks(host, name, silent, method):
try:
if host and 'host' in dir(s) and s.host != host:
if debug:
print("Warning: the brick found does not match the host provided (s.host).")
if strict: continue
b = s.connect()
info = b.get_device_info()
print(info)
strict = False
if host and info[1] != host:
if debug:
print("Warning: the brick found does not match the host provided (get_device_info).")
if strict:
s.close()
continue
info = list(info)
info[0] = str(info[0])
info[0] = info[0][2:(len(info[0])-1)]
info[0] = info[0].strip('\\x00')
if info[0] != name:
if debug:
print("Warning; the brick found does not match the name provided.")
if strict:
s.close()
continue
return b
except:
for s in find_bricks(host, name, silent, method):
try:
if host and 'host' in dir(s) and s.host != host:
if debug:
traceback.print_exc()
print("Failed to connect to possible brick")
print("Warning: the brick found does not match the host provided (s.host).")
if strict: continue
b = s.connect()
info = b.get_device_info()
if debug:
print("info: " + str(info))

strict = False

if host and info[1] != host:
if debug:
print("Warning: the brick found does not match the host provided (get_device_info).")
print(" host:" + str(host))
print(" info[1]:" + info[1])
if strict:
s.close()
continue

info = list(info)
info[0] = str(info[0])
info[0] = info[0][2:(len(info[0])-1)]
info[0] = info[0].strip('\\x00')

if info[0] != name:
if debug:
print("Warning; the brick found does not match the name provided.")
print(" host:" + str(host))
print(" info[0]:" + info[0])
print(" name:" + str(name))
if strict:
s.close()
continue

return b
except:
if debug:
traceback.print_exc()
print("Failed to connect to possible brick")

print("""No brick was found.
Is the brick turned on?
Expand All @@ -146,6 +162,7 @@ def server_brick(host, port = 2727):
sock = ipsock.IpSock(host, port)
return sock.connect()


def device_brick(filename):
from . import devsock
sock = devsock.find_bricks(filename=filename)
Expand All @@ -161,6 +178,7 @@ def read_config(confpath=None, debug=False):
conf.add_section('Brick')
return conf


def make_config(confpath=None):
conf = configparser.RawConfigParser()
if not confpath: confpath = os.path.expanduser('~/.nxt-python')
Expand Down
2 changes: 1 addition & 1 deletion nxt/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ def get_device_info(opcode):

def _parse_get_device_info(tgram):
tgram.check_status()
name = tgram.parse_string(15)
name = tgram.parse_string(15).decode('utf-8').split('\0')[0]
a0 = tgram.parse_u8()
a1 = tgram.parse_u8()
a2 = tgram.parse_u8()
Expand Down
2 changes: 1 addition & 1 deletion nxt/telegram.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def add_string(self, n_bytes, v):
self.pkt.write(pack('%ds' % n_bytes, v.encode('windows-1252')))

def add_filename(self, fname):
self.pkt.write(pack('20s', fname))
self.pkt.write(pack('20s', fname.encode('utf-8')))

def add_s8(self, v):
self.pkt.write(pack('<b', v))
Expand Down
10 changes: 9 additions & 1 deletion scripts/nxt_test
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@ import nxt.locator
import nxt.brick

debug = False
if '--verbose' in sys.argv:
if '--verbose' in sys.argv or '--debug' in sys.argv:
debug = True
print('debug = True')

b = None
try:
print('Find brick...', flush=True)
b = nxt.locator.find_one_brick(debug=debug)
name, host, signal_strength, user_flash = b.get_device_info()
print('NXT brick name: %s' % name)
Expand All @@ -33,6 +35,12 @@ try:
print('Firmware version %s.%s' % fw_version)
millivolts = b.get_battery_level()
print('Battery level %s mV' % millivolts)
print('Play test sound...', end='', flush=True)
b.play_tone_and_wait(300, 50)
b.play_tone_and_wait(400, 50)
b.play_tone_and_wait(500, 50)
b.play_tone_and_wait(600, 50)
print('done')
b.sock.close()
except:
print("Error while running test:")
Expand Down
44 changes: 22 additions & 22 deletions scripts/nxtfilemgr
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env python
#
# nxt_filemgr program -- Updated from nxt_filer
# nxt_filemgr program -- Updated from nxt_filer
# Based on: nxt_filer program -- Simple GUI to manage files on a LEGO Mindstorms NXT
# Copyright (C) 2006 Douglas P Lau
# Copyright (C) 2010 rhn
Expand Down Expand Up @@ -68,12 +68,12 @@ def run_program(b, fname):
if DEBUG:
print("Running %s" % fname)
b.start_program(fname)

def delete_file(b, fname):
b.delete(fname)
if DEBUG:
print("Deleted %s" % fname)

def read_file(b, fname):
with FileReader(b, fname) as r:
with open(fname, 'wb') as f:
Expand Down Expand Up @@ -124,7 +124,7 @@ def write_file(b, fname, data):
system_error_dialog()
except USBError:
raise

def write_files(b, names):
for fname in names.split('\r\n'):
if fname:
Expand All @@ -150,7 +150,8 @@ class NXTListing(Gtk.ListStore):

def populate(self, brick, pattern):
f = FileFinder(brick, pattern)
for (fname, size) in f:
for (fname_b, size) in f:
fname = fname_b.decode('utf-8')
self.append((fname, str(size)))


Expand All @@ -167,7 +168,7 @@ class NXT_FileMgr(Gtk.Window):
self.selected_file = None
self.brick_info_str = CONNECT_STRING
self.nxt_filelist = NXTListing()

h = Gtk.Grid()
h.set_orientation(Gtk.Orientation.VERTICAL)
self.brick_button = Gtk.Button(label=self.brick_info_str)
Expand Down Expand Up @@ -211,12 +212,12 @@ class NXT_FileMgr(Gtk.Window):
return tv

def make_file_panel(self):
v = Gtk.Box(Gtk.Orientation.VERTICAL, 0)
v = Gtk.Box(Gtk.Orientation.VERTICAL, 0)
tv = self.make_file_view()
tv.set_model(self.nxt_filelist)
select = tv.get_selection()
select.connect("changed", self.on_tree_selection_changed)

s = Gtk.ScrolledWindow()
s.set_min_content_width(FILELIST_MINWIDTH)
s.set_max_content_width(min(FILENAME_MAXWIDTH+FILESIZE_MAXWIDTH, FILELIST_MAXWIDTH))
Expand All @@ -228,12 +229,12 @@ class NXT_FileMgr(Gtk.Window):
return v

def make_button_panel(self):
vb = Gtk.Box(Gtk.Orientation.HORIZONTAL, 0)
vb = Gtk.Box(Gtk.Orientation.HORIZONTAL, 0)

self.about_button = Gtk.Button(label="?")
self.about_button.connect("clicked", self.about)
vb.pack_start(self.about_button, True, True, 10)

self.delete_button = Gtk.Button(label="Remove")
self.delete_button.connect("clicked", self.remove_file)
vb.pack_start(self.delete_button, True, True, 10)
Expand All @@ -251,7 +252,7 @@ class NXT_FileMgr(Gtk.Window):
self.brick.sock.close()
self.brick = None
self.selected_file = None

def reload_filelist(self, widget):
if DEBUG:
print("Reloading filelist...")
Expand All @@ -274,7 +275,7 @@ class NXT_FileMgr(Gtk.Window):
self.nxt_filelist.clear()
if self.brick != None:
self.nxt_filelist.populate(self.brick, '*.*')

def get_brick_info(self):
if self.brick != None:
print("Reading from NXT..."),
Expand All @@ -283,17 +284,16 @@ class NXT_FileMgr(Gtk.Window):
if prot_version == PROTOCOL_VER:
brick_name, brick_hostid, brick_signal_strength, brick_user_flash = self.brick.get_device_info()
connection_type = str(self.brick.sock)
brick_name_str = brick_name.split('\0')[0]
if DEBUG:
print("Brick Info: ", connection_type, brick_name_str, brick_hostid, brick_signal_strength, fw_version, brick_user_flash)
self.brick_info_str = "%s ==> %s [%s]\tFirmware: v%s.%s\tFreespace: %s" % (connection_type, brick_name_str, brick_hostid, fw_version[0], fw_version[1], brick_user_flash)
print("Brick Info: ", connection_type, brick_name, brick_hostid, brick_signal_strength, fw_version, brick_user_flash)
self.brick_info_str = "%s ==> %s [%s]\tFirmware: v%s.%s\tFreespace: %s" % (connection_type, brick_name, brick_hostid, fw_version[0], fw_version[1], brick_user_flash)
else:
print("Invalid Protocol version! Closing connection.")
self.do_housekeeping()
else:
self.brick_info_str = CONNECT_STRING
sys.stdout.flush()

def choose_files(self):
dialog = Gtk.FileChooserNative();
dialog.new("Add File", self, Gtk.FileChooserAction.OPEN, None, None)
Expand Down Expand Up @@ -324,7 +324,7 @@ class NXT_FileMgr(Gtk.Window):
self.selected_file = model[treeiter][0]
else:
self.selected_file = None

def drag_data_get_data(self, treeview, context, selection, target_id,
etime):
treeselection = treeview.get_selection()
Expand Down Expand Up @@ -369,15 +369,15 @@ class NXT_FileMgr(Gtk.Window):
self.do_housekeeping()
self.update_view()
else:
print("Can't execute '*.%s' files" % ext)
print("Can't execute '*.%s' files" % ext)
except ValueError:
print("No file extension (unknown file type)")
except USBError:
'Cannot recover, close connection'
usb_error_dialog()
self.do_housekeeping()
self.update_view()

def remove_file(self, widget):
if self.selected_file != None:
warning_str = "Do you really want to remove %s?" % self.selected_file
Expand All @@ -402,15 +402,15 @@ class NXT_FileMgr(Gtk.Window):
elif response == Gtk.ResponseType.CANCEL:
if DEBUG:
print("CANCEL Delete File")

def add_file(self, widget):
if self.brick != None:
if DEBUG:
print("Adding file...")
self.choose_files()
self.selected_file = None
self.update_view()

def quit(self, w):
'Quit the program'
if self.brick != None:
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@
url='https://github.com/Eelviny/nxt-python/',
license='Gnu GPL v3',
packages=['nxt', 'nxt.sensor'],
scripts=['scripts/nxt_push', 'scripts/nxt_test', 'scripts/nxt_server'],
scripts=['scripts/nxt_push', 'scripts/nxt_test', 'scripts/nxt_server', 'scripts/nxtfilemgr'],
long_description=ldesc
)

0 comments on commit 9851bee

Please sign in to comment.