Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update to add MacOS logging and FTDI driver detection #41

Merged
merged 2 commits into from
Feb 10, 2017
Merged
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
94 changes: 94 additions & 0 deletions BlocklyHardware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import os
import logging
from sys import platform
from subprocess import Popen, PIPE, check_output, CalledProcessError

# Define platform constants
PLATFORM_MACOS = 'darwin'
PLATFORM_UBUNTU = 'linux2'

# Define error constants
FTDI_DRIVER_NOT_INSTALLED = 201
FTDI_DRIVER_NOT_LOADED = 202
PLATFORM_UNKNOWN = 2

# Enable logging
__module_logger = logging.getLogger('blockly')


def init():
result = is_module_installed()
if result != 0:
return result

result = is_module_loaded()
if result != 0:
return result


def is_module_installed():
if platform == PLATFORM_MACOS:
return __is_module_installed_macos()
elif platform == PLATFORM_UBUNTU:
return __is_module_installed_ubuntu()
else:
return PLATFORM_UNKNOWN


def is_module_loaded():
if platform == PLATFORM_MACOS:
return __is_module_loaded_macos()
elif platform == PLATFORM_UBUNTU:
return __is_module_loaded_ubuntu()
else:
return PLATFORM_UNKNOWN


# Ubuntu implementation
def __is_module_installed_ubuntu():
try:
process = Popen(['cat', '/proc/modules'], stdout=PIPE, stderr=PIPE)
output = check_output(('grep', 'ftdi'), stdin=process.stdout)
__module_logger.debug('FTDI module load state')
__module_logger.debug(output)
return 0
except CalledProcessError:
__module_logger.warning('No FTDI modules detected.')
return FTDI_DRIVER_NOT_INSTALLED


def __is_module_loaded_ubuntu():
try:
process = Popen(['dmesg', '-H', '-x'], stdout=PIPE, stderr=PIPE)
output = check_output(('grep', 'ftdi'), stdin=process.stdout)
process.wait()
__module_logger.debug(output)
return 0
except CalledProcessError:
__module_logger.warning('Serial port is not assigned.')
return FTDI_DRIVER_NOT_LOADED


# MacOS implementation
def __is_module_installed_macos():
try:
# Does the log directory exist
os.stat('/Library/Extensions/FTDIUSBSerialDriver.kext')
__module_logger.info('FTDI driver is installed')
return 0

except OSError:
__module_logger.error('Cannot find FTDI installation')
return FTDI_DRIVER_NOT_INSTALLED


def __is_module_loaded_macos():
try:
process = Popen(['kextstat'], stdout=PIPE, stderr=PIPE)
output = check_output(('grep', 'FTDI'), stdin=process.stdout)
__module_logger.debug('FTDI module load state')
__module_logger.debug(output)
return 0
except CalledProcessError:
__module_logger.warning('No FTDI modules detected.')
return 1
118 changes: 66 additions & 52 deletions BlocklyLogger.py
Original file line number Diff line number Diff line change
@@ -1,71 +1,85 @@
""""
BlocklyPropLogger manages the application logging process.


"""

import os
import logging
from sys import platform
from subprocess import Popen, PIPE, check_output, CalledProcessError

__author__ = 'Jim Ewald'

# Constants
PLATFORM_MACOS = 'darwin'

path = None

# Logging path
try: # Python 2.7+
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
def init(filename = 'BlocklyPropClient.log'):
global path

logging.getLogger(__name__).addHandler(NullHandler())
# Set a default log file name
logfile_name = filename

# Create a logger
logger = logging.getLogger('blockly')
logger.setLevel(logging.DEBUG)
# Set correct log file location
if platform == PLATFORM_MACOS:
logfile_name = __set_macos_logpath(filename)
if logfile_name is None:
return 1

# create a file handler to log events to the debug level. Log file
# is overwritten each time the app runs.
handler = logging.FileHandler('BlocklyPropClient.log', mode='w')
#handler = logging.FileHandler('BlocklyPropClient.log')
handler.setLevel(logging.DEBUG)
path = logfile_name

# create a console handler for error-level events
console = logging.StreamHandler()
console.setLevel(logging.ERROR)
# Logging path
try: # Python 2.7+
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass

# create a logging format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
console.setFormatter(formatter)
logging.getLogger(__name__).addHandler(NullHandler())

# add the handlers to the logger
logger.addHandler(handler)
logger.addHandler(console)
# Create a logger
logger = logging.getLogger('blockly')
logger.setLevel(logging.DEBUG)

# create a file handler to log events to the debug level. Log file
# is overwritten each time the app runs.
__log_file_location = logfile_name
handler = logging.FileHandler(logfile_name, mode='w')
handler.setLevel(logging.DEBUG)

# create a console handler for error-level events
console = logging.StreamHandler()
console.setLevel(logging.ERROR)

# create a logging format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
console.setFormatter(formatter)

# add the handlers to the logger
logger.addHandler(handler)
logger.addHandler(console)

def init():
logger.info("Logger has been started.")
if platform == 'linux2':
if is_module_loaded() != 0:
return

if check_system_messages() != 0:
return

def __set_macos_logpath(filename):
user_home = os.path.expanduser('~')
log_path = user_home + '/Library/Logs/Parallax'

def is_module_loaded():
# Does the log directory exist
try:
process = Popen(['cat', '/proc/modules'], stdout=PIPE, stderr=PIPE)
output = check_output(('grep', 'ftdi'), stdin=process.stdout)
logger.debug('FTDI module load state')
logger.debug(output)
return 0
except CalledProcessError:
logger.warning('No FTDI modules detected.')
return 1
os.stat(log_path)
return log_path + '/' + filename

except OSError:
# Create a new log path
try:
os.makedirs(log_path)

def check_system_messages():
try:
process = Popen(['dmesg', '-H', '-x'], stdout=PIPE, stderr=PIPE)
output = check_output(('grep', 'ftdi'), stdin=process.stdout)
process.wait()
logger.debug(output)
return 0
except CalledProcessError:
logger.warning('Serial port is not assigned.')
return 1
except OSError:
return None

return log_path + '/' + filename
63 changes: 51 additions & 12 deletions BlocklyPropClient.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
"""
BlocklyProp Client

"""
import Tkinter as tk
import ttk as ttk
import tkMessageBox
Expand All @@ -13,22 +17,30 @@
import logging
import BlocklyServer
import BlocklyLogger
import BlocklyHardware


__author__ = 'Michel & Vale'

PORT = 6009
VERSION = "0.5.1"


# Enable logging for functions outside of the class definition
module_logger = logging.getLogger('blockly')


class BlocklyPropClient(tk.Tk):
def __init__(self, *args, **kwargs):

# Enable application logging
BlocklyLogger.init()
self.logger = logging.getLogger('blockly.main')
self.logger.info('Creating logger.')

BlocklyHardware.init()

# Init Tk
tk.Tk.__init__(self, *args, **kwargs)

# initialize values
Expand All @@ -43,6 +55,7 @@ def __init__(self, *args, **kwargs):
self.ip_address = tk.StringVar()
self.port = tk.StringVar()
self.trace_log = tk.IntVar()
self.logfile = tk.StringVar()

# Default trace to enabled or logging level 1, not sure which it is
self.trace_log.set(1)
Expand All @@ -59,51 +72,73 @@ def __init__(self, *args, **kwargs):

self.initialize()
self.initialize_menu()
# Verify the hardware is connected and available

def set_version(self, version):
self.logger.info('Application version is %s', version)
self.version = version

def initialize(self):
self.logger.info('Initializing the UI')

# Display the client screen
self.grid()

# IP address label
self.lbl_ip_address = ttk.Label(self, anchor=tk.E, text='IP Address :')
self.lbl_ip_address.grid(column=0, row=0, sticky='nesw')

self.ent_ip_address = ttk.Entry(self, state='readonly', textvariable=self.ip_address)
self.ent_ip_address.grid(column=1, row=0, sticky='nesw', padx=3, pady=3)

# TCP port number label
self.lbl_port = ttk.Label(self, anchor=tk.E, text='Port :')
self.lbl_port.grid(column=0, row=1, sticky='nesw')

# Log file label
self.lbl_logfile = ttk.Label(self, anchor=tk.E, text='Log File :')
self.lbl_logfile.grid(column=0, row=2, sticky='nesw')

# Open browser button
self.btn_open_browser = ttk.Button(self, text='Open Browser', command=self.handle_browser)
self.btn_open_browser.grid(column=0, row=2, sticky='nesw', padx=3, pady=3)
self.btn_open_browser.grid(column=0, row=3, sticky='nesw', padx=3, pady=3)

# Trace label
self.lbl_log = ttk.Label(self, anchor=tk.W, text='Trace :')
self.lbl_log.grid(column=0, row=4, sticky='nesw', padx=3, pady=3)

# Trace log display window
self.ent_log = ScrolledText.ScrolledText(self, state='disabled')
self.ent_log.grid(column=0, row=5, columnspan=2, sticky='nesw', padx=3, pady=3)


# IP address text box
self.ent_ip_address = ttk.Entry(self, state='readonly', textvariable=self.ip_address)
self.ent_ip_address.grid(column=1, row=0, sticky='nesw', padx=3, pady=3)

# TCP port text box
self.ent_port = ttk.Entry(self, textvariable=self.port)
self.ent_port.grid(column=1, row=1, sticky='nesw', padx=3, pady=3)

# Log file text box
self.ent_logfile = ttk.Entry(self, textvariable=self.logfile)
self.ent_logfile.grid(column=1, row=2, sticky='nesw', padx=3, pady=3)


# Connect to device button
self.btn_connect = ttk.Button(self, text='Connect', command=self.handle_connect)
self.btn_connect.grid(column=1, row=2, sticky='nesw', padx=3, pady=3)
self.btn_connect.grid(column=1, row=3, sticky='nesw', padx=3, pady=3)

#self.lbl_current_code = ttk.Label( self, anchor=tk.E, text='Code most recently compiled :' )
#self.lbl_current_code.grid(column=0, row=5, sticky='nesw', padx=3, pady=3)

#self.current_code = ScrolledText.ScrolledText( self, state='disabled')
#self.current_code.grid(column=0, row=6, columnspan=2, sticky='nesw', padx=3, pady=3)

self.lbl_log = ttk.Label(self, anchor=tk.W, text='Log :')
self.lbl_log.grid(column=0, row=3, sticky='nesw', padx=3, pady=3)
self.check_log_trace = tk.Checkbutton(self, anchor=tk.E, text='Trace logging', variable=self.trace_log, offvalue=1, onvalue=0)
self.check_log_trace.grid(column=1, row=4, sticky='nesw', padx=3, pady=3)

self.ent_log = ScrolledText.ScrolledText(self, state='disabled')
self.ent_log.grid(column=0, row=4, columnspan=2, sticky='nesw', padx=3, pady=3)

#s = ttk.Style()
#s.configure('Right.TCheckbutton', anchor='e')
#self.check_log_trace = ttk.Checkbutton(self, style='Right.TCheckbutton', text='Trace logging', variable=self.trace_log)
self.check_log_trace = tk.Checkbutton(self, anchor=tk.E, text='Trace logging', variable=self.trace_log, offvalue=1, onvalue=0)
self.check_log_trace.grid(column=1, row=3, sticky='nesw', padx=3, pady=3)

#self.btn_log_checkbox = ttk.Button(self, text='Low level logging: Currently False', command=self.handle_lowlevel_logging)
#self.btn_log_checkbox.grid(column=1, row=3, sticky='nesw', padx=3, pady=3)

Expand All @@ -121,6 +156,10 @@ def initialize(self):

self.port.set(PORT)
self.logger.info('Port number is: %s', self.port.get())

self.logfile.set(BlocklyLogger.path)
self.logger.info('Disk log file location is: %s', BlocklyLogger.path)

self.server_process = None

self.q = multiprocessing.Queue()
Expand Down