<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2017 <NAME>
---------------

Graphical interface program that allows the user to communicate with an
Arduino or other piece of hardware via a serial port.

Requires wxWidgets 2.8 or newer. To install on Ubuntu Linux:
    apt-get install python-wxgtk2.8 python-wxtools wx2.8-i18n libwxgtk2.8-dev libgtk2.0-dev

GUI built with wxFormbuilder 3.5.1 (https://github.com/wxFormBuilder/wxFormBuilder)
To install on Ubuntu Linux:
    add-apt-repository ppa:wxformbuilder/release
    apt-get install wxformbuilder

Tested on Ubuntu 14.04 with Pyton 2.7.6

---------------
Distributed under the MIT licence:

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import serialMonitorBaseClasses

import wx, string
import os, sys, time
import serial
import glob
import logging

# Set the module version consistent with pip freeze.
import pkg_resources as pkg
__version__=pkg.get_distribution("SerialMonitor").version.lstrip('-').rstrip('-')

# Create a logger for the application.
logger=logging.getLogger("SMLog") # It stands for Serial Monitor, right ;)
logger.setLevel(logging.INFO)
handler=logging.StreamHandler() # Will output to STDERR.
formatter=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
handler.setLevel(logging.INFO)
logger.addHandler(handler)
#TODO Attach the handler to the logger later, when user specifies the level.

class serialMonitorGuiMainFrame( serialMonitorBaseClasses.mainFrame ):

    #============================
    # CONSTRUCTOR
    #============================

    def __init__(self):
        """ Create the main frame, deriving from a baseline object which has all the panels, buttons, etc.
        already defined. """
        # initialise the underlying object
        serialMonitorBaseClasses.mainFrame.__init__( self, None, __version__ )
        
        # File logger name.
        self.fileLoggerName=None # Overwrite with a file name when user chooses to log to a file.

        # serial communication
        self.portOpen = False # indicates if the serial communication port is open
        self.currentPort = 'None' # currently chosen port
        self.arduinoSerialConnection = 0 # holds the serial connection object once it has been initialised
        self.arduinoOutputBuffer = '' # buffer for storing inbound data if it arrives in chunks

        # set default values
        self.readDelay = int(self.readDelayTxtCtrl.GetValue())
        self.BaudRate = int(self.baudRateTxtCtrl.GetValue())

        # initialise the timing function for receiving the data from the serial port at a specific interval
        self.parseOutputsTimer.Start(int(self.readDelay))

        # update the ports available at start-up
        self.updatePorts(suppressWarn=True)
        self.portChoice.SetSelection(0)

        self.Layout() # Make sure everything is nicely located in the sizers on startup.

    #============================
    # EVENT HANDLING FUNCTIONS
    #============================

    def onClose(self, event):
        """ close the serial port before terminating, need to make sure it isn't left hanging """
        if self.portOpen:
            self.arduinoSerialConnection.close()
            logger.info('Disconnected from port before shutdown.')
        self.Destroy()

    def onSendInput(self, event):
        """ pass the message from the txtControl to the message parsing method that
        links with the comms protocol. """
        self.sendMessage( self.inputTextControl.GetLineText(0) )
        self.inputTextControl.Clear()

    def onChoseSerialPort(self, event):
        """ picks up the newly selected port and attempts to connect to a peripheral device via it """
        # ignore the None option
        if self.portChoice.GetStringSelection() != 'None':
            try:
                # don't re-open a working stream
                if self.portChoice.GetStringSelection() != self.currentPort:
                    # close any open ports if present
                    if self.portOpen:
                        self.arduinoSerialConnection.close()

                    self.arduinoSerialConnection = serial.Serial(self.portChoice.GetStringSelection(),
                                                                 self.BaudRate, timeout = 2)

                    if self.checkConnection():
                        self.portOpen = True
                        self.currentPort = self.portChoice.GetStringSelection()
                        logger.info('Connected to port {}'.format(self.currentPort))

            except:
                wx.MessageBox('Unknown problem occurred while establishing connection using the chosen port!', 'Error',
                          wx.OK | wx.ICON_ERROR)
                self.arduinoSerialConnection = 0
                self.portOpen = False
                self.updatePorts()<commit_msg>Started preparing to enable larger control of the serial connection details.<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2017 <NAME>
---------------

Graphical interface program that allows the user to communicate with an
Arduino or other piece of hardware via a serial port.

Requires wxWidgets 2.8 or newer. To install on Ubuntu Linux:
    apt-get install python-wxgtk2.8 python-wxtools wx2.8-i18n libwxgtk2.8-dev libgtk2.0-dev

GUI built with wxFormbuilder 3.5.1 (https://github.com/wxFormBuilder/wxFormBuilder)
To install on Ubuntu Linux:
    add-apt-repository ppa:wxformbuilder/release
    apt-get install wxformbuilder

Tested on Ubuntu 14.04 with Pyton 2.7.6

---------------
Distributed under the MIT licence:

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import serialMonitorBaseClasses

import wx, string
import os, sys, time
import serial
import glob
import logging

# Set the module version consistent with pip freeze.
import pkg_resources as pkg
__version__=pkg.get_distribution("SerialMonitor").version.lstrip('-').rstrip('-')

# Create a logger for the application.
logger=logging.getLogger("SMLog") # It stands for Serial Monitor, right ;)
logger.setLevel(logging.INFO)
handler=logging.StreamHandler() # Will output to STDERR.
formatter=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
handler.setLevel(logging.INFO)
logger.addHandler(handler)
#TODO Attach the handler to the logger later, when user specifies the level.

class serialMonitorGuiMainFrame( serialMonitorBaseClasses.mainFrame ):

    #============================
    # CONSTRUCTOR
    #============================

    def __init__(self):
        """ Create the main frame, deriving from a baseline object which has all the panels, buttons, etc.
        already defined. """
        # initialise the underlying object
        serialMonitorBaseClasses.mainFrame.__init__( self, None, __version__ )
        
        # File logger name.
        self.fileLoggerName=None # Overwrite with a file name when user chooses to log to a file.

        # serial communication
        self.portOpen = False # indicates if the serial communication port is open
        self.currentPort = 'None' # currently chosen port
        self.arduinoSerialConnection = 0 # holds the serial connection object once it has been initialised
        self.arduinoOutputBuffer = '' # buffer for storing inbound data if it arrives in chunks

        # set default values
        self.readDelay = int(self.readDelayTxtCtrl.GetValue())
        self.BaudRate = int(self.baudRateTxtCtrl.GetValue())

        # initialise the timing function for receiving the data from the serial port at a specific interval
        self.parseOutputsTimer.Start(int(self.readDelay))

        # update the ports available at start-up
        self.updatePorts(suppressWarn=True)
        self.portChoice.SetSelection(0)

        self.Layout() # Make sure everything is nicely located in the sizers on startup.

    #============================
    # EVENT HANDLING FUNCTIONS
    #============================

    def onClose(self, event):
        """ close the serial port before terminating, need to make sure it isn't left hanging """
        if self.portOpen:
            self.arduinoSerialConnection.close()
            logger.info('Disconnected from port before shutdown.')
        self.Destroy()

    def onSendInput(self, event):
        """ pass the message from the txtControl to the message parsing method that
        links with the comms protocol. """
        self.sendMessage( self.inputTextControl.GetLineText(0) )
        self.inputTextControl.Clear()

    def onChoseSerialPort(self, event):
        """ picks up the newly selected port and attempts to connect to a peripheral device via it """
        # ignore the None option
        if self.portChoice.GetStringSelection() != 'None':
            try:
                # don't re-open a working stream
                if self.portChoice.GetStringSelection() != self.currentPort:
                    # close any open ports if present
                    if self.portOpen:
                        self.arduinoSerialConnection.close()

                    #TODO should also define parity and stopbits, and possibly bytesize in the Serial initialiser.
                    self.arduinoSerialConnection = serial.Serial(port=self.portChoice.GetStringSelection(),
                                                                 baudrate=self.BaudRate,
                                                                 timeout=2,
                                                                 stopbits=serial.STOPBITS_ONE, #TODO override default value
                                                                 parity=serial.PARITY_NONE, #TODO override default value
                                                                 bytesize=serial.EIGHTBITS) #TODO override default value

                    if self.checkConnection():
                        self.portOpen = True
                        self.currentPort = self.portChoice.GetStringSelection()
                        logger.info('Connected to port {}'.format(self.currentPort))

            except:
                wx.MessageBox('Unknown problem occurred while establishing connection using the chosen port!', 'Error',
                          wx.OK | wx.ICON_ERROR)
                self.arduinoSerialConnection = 0
                self.portOpen = False
                self.updatePorts()
{'fraction_non_alphanumeric': 0.09082856912794911, 'fraction_numerical': 0.0051533939930751265, 'mean_word_length': 2.684366656778404, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2727056', 'n_tokens_mistral': 3129, 'n_tokens_neox': 2958, 'n_words': 1167}