def run_application(self): AppSettings.load_settings() VocableManager.load_vocables() self.xld_main_window = XLDMainWindow() Gtk.main()
def get_attribute_value_list_from_string(cls, string): attribute_value_separator = AppSettings.get_setting_by_name(AppSettings.ATTRIBUTE_VALUE_SEPARATOR_SETTING_NAME) stripped_characters = AppSettings.get_setting_by_name(AppSettings.STRIPPED_CHARACTERS_SETTING_NAME) value_list = string.split(sep=attribute_value_separator, maxsplit=-1) # stripped_value_list = [value.strip(stripped_characters) for value in value_list] # return stripped_value_list return value_list
def load_vocables(cls): xml_file_path = AppSettings.get_setting_by_name( AppSettings.XML_VOCABLE_FILE_PATH_SETTING_NAME) xsd_file_path = AppSettings.get_setting_by_name( AppSettings.XSD_VOCABLE_FILE_PATH_SETTING_NAME) VocableManager.vocables = FileManager.load_vocables( xml_file_path, xsd_file_path) VocableManager.search_result = VocableManager.vocables
def get_attribute_value_list_from_string(cls, string): attribute_value_separator = AppSettings.get_setting_by_name( AppSettings.ATTRIBUTE_VALUE_SEPARATOR_SETTING_NAME) stripped_characters = AppSettings.get_setting_by_name( AppSettings.STRIPPED_CHARACTERS_SETTING_NAME) value_list = string.split(sep=attribute_value_separator, maxsplit=-1) # stripped_value_list = [value.strip(stripped_characters) for value in value_list] # return stripped_value_list return value_list
def exit_application(self, widget, event): strtrue = str(True) save_vocables = AppSettings.get_setting_by_name( AppSettings.SAVE_VOCABLES_ON_EXIT_SETTING_NAME) == strtrue show_dialog = AppSettings.get_setting_by_name( AppSettings.DIALOG_SHOW_SAVE_VOCABLES_CONFIRMATION_SETTING_NAME ) == strtrue if show_dialog and VocableManager.vocables_changed: save_vocables_confirmation_dialog = SaveVocablesBeforeExitConfirmationDialog( self) save_vocables = save_vocables_confirmation_dialog.run( ) == Gtk.ResponseType.YES AppSettings.change_setting_by_name( AppSettings.SAVE_VOCABLES_ON_EXIT_SETTING_NAME, save_vocables) save_vocables_confirmation_dialog.destroy() if save_vocables: VocableManager.save_vocables(VocableManager.vocables) exit_on_exit_confirmation = AppSettings.get_setting_by_name( AppSettings.EXIT_ON_EXIT_SETTING_NAME) == strtrue show_exit_confirmation = AppSettings.get_setting_by_name( AppSettings.DIALOG_SHOW_EXIT_CONFIRMATION_SETTING_NAME) if show_exit_confirmation == strtrue: ExitConfirmationDialog.__init__ = timefunction( ExitConfirmationDialog.__init__) # decoration exit_confirmation_dialog = ExitConfirmationDialog(self) exit_confirmation_dialog.run = timefunction( exit_confirmation_dialog.run) # decoration exit_on_exit_confirmation = exit_confirmation_dialog.run( ) == Gtk.ResponseType.YES AppSettings.change_setting_by_name( AppSettings.EXIT_ON_EXIT_SETTING_NAME, exit_on_exit_confirmation) exit_confirmation_dialog.destroy() if exit_on_exit_confirmation: # print("Clicked YES") AppSettings.save_settings() Gtk.main_quit() sys.exit() else: # print("Clicked NO") pass return GTKSignal.DO_NOT_PROPAGATE
def save_vocables(cls, vocable_list, xml_file_path, xsd_file_path): delimiter = AppSettings.get_setting_by_name(AppSettings.ATTRIBUTE_VALUE_SEPARATOR_SETTING_NAME) xml_parser = XMLParser() new_xml_root = etree.Element("list") for vocable in vocable_list: vocable_node = FileManager.create_vocable_xml_node(new_xml_root, vocable, delimiter) # # test print # rough_string = etree.tostring(new_xml_root, encoding='unicode') # reparsed = minidom.parseString(rough_string) # pretty_printed = reparsed.toprettyxml(indent='\t', encoding='utf-8') # print(pretty_printed[:600]) # with open('/home/xiaolong/testfile.xml', 'w') as file: # file.write(str(pretty_printed)) # # end if xml_parser.validate_tree(xsd_file_path, new_xml_root): xml_parser.write_xml_file(xml_file_path, new_xml_root) else: raise XMLInvalidException( "The XML is not valid. Could not write vocables to file: " + xml_file_path + " validating against XSD: " + xsd_file_path )
def test_xml_file_invariance(self): # get file content xml_file_content = None xml_file_path = AppSettings.get_setting_by_name(AppSettings.XML_VOCABLE_FILE_PATH_SETTING_NAME) with open(xml_file_path, mode='rb') as vocable_file: xml_file_content = vocable_file.read() # check if file content is still the same new_xml_file_content = None xml_file_path = AppSettings.get_setting_by_name(AppSettings.XML_VOCABLE_FILE_PATH_SETTING_NAME) with open(xml_file_path, mode='rb') as vocable_file: new_xml_file_content = vocable_file.read() assert xml_file_content == new_xml_file_content, \ 'Loading and saving the vocables leads to changes in the XML vocable file, ' \ 'although the vocables didn\'t change. These changes might be whitespace character differences.'
def create_sortable_vocable_tree_view_model(self): vocable_tree_view_model = Gtk.ListStore( str, str, str, str, str) # index, fl, flps, slps, sl displayed_vocable_attributes_list = [] delimiter = AppSettings.get_setting_by_name( AppSettings.ATTRIBUTE_VALUE_SEPARATOR_SETTING_NAME) for vocable in VocableManager.search_result: displayed_vocable_attributes_list.append( (delimiter.join(vocable.first_language_translations), delimiter.join(vocable.first_language_phonetic_scripts), delimiter.join(vocable.second_language_phonetic_scripts), delimiter.join(vocable.second_language_translations))) for list_index, vocable in enumerate( displayed_vocable_attributes_list): string_index = zero_fill( str(list_index), len_of_number(len(displayed_vocable_attributes_list))) row = [string_index] for attribute in vocable: row.append(attribute) vocable_tree_view_model.append(row) # vocable_tree_view_model.append(Vocable('fl','flps','sl','slps','t','c','ll','rl','d')) # This does not work because of number of columns issue # make it sortable sortable_vocable_tree_view_model = Gtk.TreeModelSort( model=vocable_tree_view_model) return sortable_vocable_tree_view_model
def save_vocables(cls, vocable_list, xml_file_path, xsd_file_path): delimiter = AppSettings.get_setting_by_name( AppSettings.ATTRIBUTE_VALUE_SEPARATOR_SETTING_NAME) xml_parser = XMLParser() new_xml_root = etree.Element('list') for vocable in vocable_list: vocable_node = FileManager.create_vocable_xml_node( new_xml_root, vocable, delimiter) # # test print # rough_string = etree.tostring(new_xml_root, encoding='unicode') # reparsed = minidom.parseString(rough_string) # pretty_printed = reparsed.toprettyxml(indent='\t', encoding='utf-8') # print(pretty_printed[:600]) # with open('/home/xiaolong/testfile.xml', 'w') as file: # file.write(str(pretty_printed)) # # end if xml_parser.validate_tree(xsd_file_path, new_xml_root): xml_parser.write_xml_file(xml_file_path, new_xml_root) else: raise XMLInvalidException( 'The XML is not valid. Could not write vocables to file: ' + xml_file_path + ' validating against XSD: ' + xsd_file_path)
def initialize_widgets(self): self.label = Gtk.Label('There are changes to the vocables of the currently opened dictionary.' '\nDo you wish to save those changes?') self.remember_decision_checkbutton = Gtk.CheckButton('Remember my decision.') self.remember_decision_checkbutton.set_active( not bool(AppSettings.get_setting_by_name(AppSettings.DIALOG_SHOW_SAVE_VOCABLES_CONFIRMATION_SETTING_NAME)) )
def create_vocable_list(self): AppSettings.load_settings() list_of_vocables = [] for index in range(10): vocable_not_in_list = self.create_random_vocable() while any( item for item in list_of_vocables if item.first_language_translations == vocable_not_in_list.first_language_translations ): vocable_not_in_list = self.create_random_vocable() list_of_vocables.append(vocable_not_in_list) return list_of_vocables
def initialize_widgets(self): self.label = Gtk.Label( 'Do you really want to exit Xiaolong Dictionary?') self.remember_decision_checkbutton = Gtk.CheckButton( 'Remember my decision.') self.remember_decision_checkbutton.set_active(not bool( AppSettings.get_setting_by_name( AppSettings.DIALOG_SHOW_EXIT_CONFIRMATION_SETTING_NAME)))
def test_xml_file_invariance(self): # get file content xml_file_content = None xml_file_path = AppSettings.get_setting_by_name( AppSettings.XML_VOCABLE_FILE_PATH_SETTING_NAME) with open(xml_file_path, mode='rb') as vocable_file: xml_file_content = vocable_file.read() # check if file content is still the same new_xml_file_content = None xml_file_path = AppSettings.get_setting_by_name( AppSettings.XML_VOCABLE_FILE_PATH_SETTING_NAME) with open(xml_file_path, mode='rb') as vocable_file: new_xml_file_content = vocable_file.read() assert xml_file_content == new_xml_file_content, \ 'Loading and saving the vocables leads to changes in the XML vocable file, ' \ 'although the vocables didn\'t change. These changes might be whitespace character differences.'
def exit_application(self, widget, event): strtrue = str(True) save_vocables = AppSettings.get_setting_by_name(AppSettings.SAVE_VOCABLES_ON_EXIT_SETTING_NAME) == strtrue show_dialog = AppSettings.get_setting_by_name( AppSettings.DIALOG_SHOW_SAVE_VOCABLES_CONFIRMATION_SETTING_NAME ) == strtrue if show_dialog and VocableManager.vocables_changed: save_vocables_confirmation_dialog = SaveVocablesBeforeExitConfirmationDialog(self) save_vocables = save_vocables_confirmation_dialog.run() == Gtk.ResponseType.YES AppSettings.change_setting_by_name(AppSettings.SAVE_VOCABLES_ON_EXIT_SETTING_NAME, save_vocables) save_vocables_confirmation_dialog.destroy() if save_vocables: VocableManager.save_vocables(VocableManager.vocables) exit_on_exit_confirmation = AppSettings.get_setting_by_name(AppSettings.EXIT_ON_EXIT_SETTING_NAME) == strtrue show_exit_confirmation = AppSettings.get_setting_by_name(AppSettings.DIALOG_SHOW_EXIT_CONFIRMATION_SETTING_NAME) if show_exit_confirmation == strtrue: ExitConfirmationDialog.__init__ = timefunction(ExitConfirmationDialog.__init__) # decoration exit_confirmation_dialog = ExitConfirmationDialog(self) exit_confirmation_dialog.run = timefunction(exit_confirmation_dialog.run) # decoration exit_on_exit_confirmation = exit_confirmation_dialog.run() == Gtk.ResponseType.YES AppSettings.change_setting_by_name(AppSettings.EXIT_ON_EXIT_SETTING_NAME, exit_on_exit_confirmation) exit_confirmation_dialog.destroy() if exit_on_exit_confirmation: # print("Clicked YES") AppSettings.save_settings() Gtk.main_quit() sys.exit() else: # print("Clicked NO") pass return GTKSignal.DO_NOT_PROPAGATE
def __init__(self, model=None): super().__init__(model=model) for index, column_title in enumerate(self.columns_titles): # create Gtk.TreeViewColumns self.columns.append(Gtk.TreeViewColumn(title=column_title)) # add Gtk.TreeViewColumns to the TreeView self.append_column(self.columns[-1]) # create Gtk.CellRendererTexts self.cell_renderers.append(Gtk.CellRendererText()) # style the CellRendererTexts self.cell_renderers[-1].set_alignment(xalign=0.0, yalign=0.0) # ??? self.columns[-1].pack_start(self.cell_renderers[-1], self.column_expand[index]) self.columns[-1].add_attribute( cell_renderer=self.cell_renderers[-1], attribute='text', column=index) self.set_search_column(index) self.columns[-1].set_sort_column_id(index) self.columns[-1].set_reorderable(True) self.columns[-1].set_resizable(True) # setting the width for all columns except the index column to 100 initial_width = -1 try: initial_width = AppSettings.get_setting_by_name( AppSettings.INITIAL_TREEVIEW_COLUMN_WIDTH) initial_width = int(initial_width, base=10) except SettingUnknownException: print('ERROR: SETTING NOT FOUND!') initial_width = 100 except ValueError: print('Could not convert string to integer value.') initial_width = 100 for column_index in range(4): self.columns[column_index + 1].set_fixed_width(initial_width) self.get_selection().set_mode(Gtk.SelectionMode.MULTIPLE) self.connect_signal_handlers() self.connect_selection_signal_handlers() # popup menu on right click self.popup_menu_ui = PopupMenuProvider.get_vocable_treeview_popup_menu( )
def test_xml_settings_file_invariance(self): xml_settings_file_path = get_full_path('res/settings', 'settings.xml') settings_file_content_1 = None with open(xml_settings_file_path, 'rb') as settings_file: settings_file_content_1 = settings_file.read() AppSettings.load_settings() settings_1 = AppSettings.settings AppSettings.save_settings() settings_file_content_2 = None with open(xml_settings_file_path, 'rb') as settings_file: settings_file_content_2 = settings_file.read() AppSettings.load_settings() settings_2 = AppSettings.settings # equality does not work, since dictionaries do not have an invariant order of access, # but something weaker might work # assert settings_file_content_1 == settings_file_content_2, \ # 'Loading and saving the settings causes changes in the XML settings file, ' \ # 'although the settings didn\'t change. These changes might be whitespace character differences.' assert len(settings_file_content_1) == len(settings_file_content_2), \ 'The settings file contents differ in length.' for character in settings_file_content_1: assert character in settings_file_content_2, \ 'There is content in one settings file, which is not in the other.' for character in settings_file_content_2: assert character in settings_file_content_1, \ 'There is content in one settings file, which is not in the other.' characters_1 = {} for character in settings_file_content_1: if character in characters_1: characters_1[character] += 1 else: characters_1[character] = 1 characters_2 = {} for character in settings_file_content_2: if character in characters_2: characters_2[character] += 1 else: characters_2[character] = 1 assert characters_1 == characters_2, \ 'The settings files do not contain the same characters.' assert settings_1 == settings_2, \ 'Loading and saving the settings causes changes in the settings, ' \ 'although were not intentionally changed.'
def __init__(self, model=None): super().__init__(model=model) for index, column_title in enumerate(self.columns_titles): # create Gtk.TreeViewColumns self.columns.append(Gtk.TreeViewColumn(title=column_title)) # add Gtk.TreeViewColumns to the TreeView self.append_column(self.columns[-1]) # create Gtk.CellRendererTexts self.cell_renderers.append(Gtk.CellRendererText()) # style the CellRendererTexts self.cell_renderers[-1].set_alignment(xalign=0.0, yalign=0.0) # ??? self.columns[-1].pack_start(self.cell_renderers[-1], self.column_expand[index]) self.columns[-1].add_attribute( cell_renderer=self.cell_renderers[-1], attribute='text', column=index ) self.set_search_column(index) self.columns[-1].set_sort_column_id(index) self.columns[-1].set_reorderable(True) self.columns[-1].set_resizable(True) # setting the width for all columns except the index column to 100 initial_width = -1 try: initial_width = AppSettings.get_setting_by_name(AppSettings.INITIAL_TREEVIEW_COLUMN_WIDTH) initial_width = int(initial_width, base=10) except SettingUnknownException: print('ERROR: SETTING NOT FOUND!') initial_width = 100 except ValueError: print('Could not convert string to integer value.') initial_width = 100 for column_index in range(4): self.columns[column_index+1].set_fixed_width(initial_width) self.get_selection().set_mode(Gtk.SelectionMode.MULTIPLE) self.connect_signal_handlers() self.connect_selection_signal_handlers() # popup menu on right click self.popup_menu_ui = PopupMenuProvider.get_vocable_treeview_popup_menu()
def __init__(self, first_language_translations=[], first_language_phonetic_scripts=[], second_language_translations=[], second_language_phonetic_scripts=[], topics=[], chapters=[], learn_level='0', relevance_level='0', description='---'): self.first_language_translations = first_language_translations self.first_language_phonetic_scripts = first_language_phonetic_scripts self.second_language_translations = second_language_translations self.second_language_phonetic_scripts = second_language_phonetic_scripts self.topics = topics self.chapters = chapters self.learn_level = learn_level self.relevance_level = relevance_level self.description = description Vocable.delimiter = AppSettings.get_setting_by_name( AppSettings.ATTRIBUTE_VALUE_SEPARATOR_SETTING_NAME)
def __init__( self, first_language_translations=[], first_language_phonetic_scripts=[], second_language_translations=[], second_language_phonetic_scripts=[], topics=[], chapters=[], learn_level='0', relevance_level='0', description='---' ): self.first_language_translations = first_language_translations self.first_language_phonetic_scripts = first_language_phonetic_scripts self.second_language_translations = second_language_translations self.second_language_phonetic_scripts = second_language_phonetic_scripts self.topics = topics self.chapters = chapters self.learn_level = learn_level self.relevance_level = relevance_level self.description = description Vocable.delimiter = AppSettings.get_setting_by_name(AppSettings.ATTRIBUTE_VALUE_SEPARATOR_SETTING_NAME)
def test_get_setting_by_name(self): """ To test the get_setting_by_name method, we have to assert the following: 1. trying to access a setting, which does not exist raises the appropriate exception 2. trying to access a setting, which does exist, will return the correct settings value To assert 2., we can set a settings value using the change_setting_by_name or add_setting_by_name. """ # make sure we have a string, which is not a key in the dictionary random_word_length = 10 random_word = RandomStringCreator.randomword(random_word_length) while random_word in AppSettings.settings: random_word_length += 1 random_word = RandomStringCreator.randomword(random_word_length) # check for 1. (does it throw the correct exception?) try: AppSettings.get_setting_by_name(random_word) assert False, 'Could get a value for a not existing setting.' except SettingUnknownException: assert random_word not in AppSettings.settings, \ 'The method AppSettings.get_setting_by_name falsely throws exception SettingUnknownException.' # check for 2. if len(AppSettings.settings.keys()) == 0: test_setting_name = 'test_setting_name' test_setting_value = 'test_setting_value' AppSettings.add_setting_by_name(test_setting_name, test_setting_value) assert AppSettings.get_setting_by_name(test_setting_name) == test_setting_value, \ 'The method AppSettings.get_setting_by_name does not return the correct value.' else: existing_dictionary_key = list(AppSettings.settings.keys())[0] try: returned_value = AppSettings.get_setting_by_name( existing_dictionary_key) expected_value = AppSettings.settings[existing_dictionary_key] assert returned_value == expected_value, \ 'The method AppSettings.get_setting_by_name does not return the correct value.' except SettingUnknownException: assert False, 'Exception raised although the accessed key existed in the settings dictionary.'
def test_get_setting_by_name(self): """ To test the get_setting_by_name method, we have to assert the following: 1. trying to access a setting, which does not exist raises the appropriate exception 2. trying to access a setting, which does exist, will return the correct settings value To assert 2., we can set a settings value using the change_setting_by_name or add_setting_by_name. """ # make sure we have a string, which is not a key in the dictionary random_word_length = 10 random_word = RandomStringCreator.randomword(random_word_length) while random_word in AppSettings.settings: random_word_length += 1 random_word = RandomStringCreator.randomword(random_word_length) # check for 1. (does it throw the correct exception?) try: AppSettings.get_setting_by_name(random_word) assert False, 'Could get a value for a not existing setting.' except SettingUnknownException: assert random_word not in AppSettings.settings, \ 'The method AppSettings.get_setting_by_name falsely throws exception SettingUnknownException.' # check for 2. if len(AppSettings.settings.keys()) == 0: test_setting_name = 'test_setting_name' test_setting_value = 'test_setting_value' AppSettings.add_setting_by_name(test_setting_name, test_setting_value) assert AppSettings.get_setting_by_name(test_setting_name) == test_setting_value, \ 'The method AppSettings.get_setting_by_name does not return the correct value.' else: existing_dictionary_key = list(AppSettings.settings.keys())[0] try: returned_value = AppSettings.get_setting_by_name(existing_dictionary_key) expected_value = AppSettings.settings[existing_dictionary_key] assert returned_value == expected_value, \ 'The method AppSettings.get_setting_by_name does not return the correct value.' except SettingUnknownException: assert False, 'Exception raised although the accessed key existed in the settings dictionary.'
import os import sys import datetime sys.path.append(os.getcwd() + "/Settings") sys.path.append(os.getcwd() + "/WebApis") sys.path.append(os.getcwd() + "/Database") sys.path.append(os.getcwd() + "/Data") from flask import Flask, request, jsonify from flask_cors import CORS from AppSettings import AppSettings from Server import Server appSettings = AppSettings() server = Server(appSettings) app = Flask(__name__) CORS(app) #All events come in through POST requests @app.route("/", methods=["POST"]) def Event(): #Initial error checking, ensure type of message is JSON and we have base data needed to continue if not request.json: return jsonify({"error": "Invalid payload type, only json permitted"}), 400 if not "token" in request.json: return jsonify({"error": "missing required value, token"}), 400 if not "type" in request.json:
def load_vocables(cls): xml_file_path = AppSettings.get_setting_by_name(AppSettings.XML_VOCABLE_FILE_PATH_SETTING_NAME) xsd_file_path = AppSettings.get_setting_by_name(AppSettings.XSD_VOCABLE_FILE_PATH_SETTING_NAME) VocableManager.vocables = FileManager.load_vocables(xml_file_path, xsd_file_path) VocableManager.search_result = VocableManager.vocables
def load_settings(self): AppSettings.load_settings()
def test_change_setting_by_name(self): """ To test the method AppSettings.change_setting_by_name, we have to assert the following: 1.Trying to change a setting, which does not exist should throw a SettingUnknownException. 2.Trying to change a setting, which does exist, should result in the setting having the changed value. """ # make sure we have a string, which is not a key in the dictionary random_word_length = 10 random_word = RandomStringCreator.randomword(random_word_length) while random_word in AppSettings.settings: random_word_length += 1 random_word = RandomStringCreator.randomword(random_word_length) # check for 1. (Does the method throw the correct exception?) try: AppSettings.change_setting_by_name(random_word, 'abc') assert False, 'Could change a not existing setting.' except SettingUnknownException: assert random_word not in AppSettings.settings, \ 'The method AppSettings.change_setting_by_name falsely throws exception SettingUnknownException.' # check for 2. (Does the method set the correct value for the setting?) if len(AppSettings.settings.keys()) == 0: test_setting_name = 'test_setting_name' test_setting_value = 'test_setting_value' new_value = test_setting_value + '_1' AppSettings.add_setting_by_name(test_setting_name, test_setting_value) AppSettings.change_setting_by_name(test_setting_name, new_value) assert AppSettings.get_setting_by_name(test_setting_name) == new_value, \ 'The method AppSettings.change_setting_by_name not set the correct value.' else: existing_dictionary_key = list(AppSettings.settings.keys())[0] try: old_value = AppSettings.get_setting_by_name(existing_dictionary_key) new_value = old_value + '_1' AppSettings.change_setting_by_name(existing_dictionary_key, new_value) assert AppSettings.get_setting_by_name(existing_dictionary_key) == new_value, \ 'The method AppSettings.change_setting_by_name does change to the correct value.' except SettingUnknownException: assert False, 'AppSettings.change_setting_by_name a SettingUnknownException, ' \ 'although the accessed key existed in the settings dictionary.'
def load_app_settings(self): print('loading app settings ...') AppSettings.load_settings() # TODO: use test settings
def test_change_setting_by_name(self): """ To test the method AppSettings.change_setting_by_name, we have to assert the following: 1.Trying to change a setting, which does not exist should throw a SettingUnknownException. 2.Trying to change a setting, which does exist, should result in the setting having the changed value. """ # make sure we have a string, which is not a key in the dictionary random_word_length = 10 random_word = RandomStringCreator.randomword(random_word_length) while random_word in AppSettings.settings: random_word_length += 1 random_word = RandomStringCreator.randomword(random_word_length) # check for 1. (Does the method throw the correct exception?) try: AppSettings.change_setting_by_name(random_word, 'abc') assert False, 'Could change a not existing setting.' except SettingUnknownException: assert random_word not in AppSettings.settings, \ 'The method AppSettings.change_setting_by_name falsely throws exception SettingUnknownException.' # check for 2. (Does the method set the correct value for the setting?) if len(AppSettings.settings.keys()) == 0: test_setting_name = 'test_setting_name' test_setting_value = 'test_setting_value' new_value = test_setting_value + '_1' AppSettings.add_setting_by_name(test_setting_name, test_setting_value) AppSettings.change_setting_by_name(test_setting_name, new_value) assert AppSettings.get_setting_by_name(test_setting_name) == new_value, \ 'The method AppSettings.change_setting_by_name not set the correct value.' else: existing_dictionary_key = list(AppSettings.settings.keys())[0] try: old_value = AppSettings.get_setting_by_name( existing_dictionary_key) new_value = old_value + '_1' AppSettings.change_setting_by_name(existing_dictionary_key, new_value) assert AppSettings.get_setting_by_name(existing_dictionary_key) == new_value, \ 'The method AppSettings.change_setting_by_name does change to the correct value.' except SettingUnknownException: assert False, 'AppSettings.change_setting_by_name a SettingUnknownException, ' \ 'although the accessed key existed in the settings dictionary.'
class IOServiceHandler(BaseHTTPRequestHandler): ## IO board abstracion driver. __board = IOBoard.IOBoard() ## Application settings. __settings = AppSettings.AppSettings('/home/pi/PiCons/settings.ini') ## KIOSK browser settings. __kioskSettings = KioskSettings.KioskSettings( '/home/pi/.config/autostart/autoChromium.desktop') ## Page body. __the_page = 'OK' ## MIME type of the response. __mime_type = '' ## Relay 1 command key. Value: 1 or 0 __RELAY_1 = 'Relay1' ## Relay 2 command key. Value: 1 or 0 __RELAY_2 = 'Relay2' ## Relay 3 command key. Value: 1 or 0 __RELAY_3 = 'Relay3' ## Relay 4 command key. Value: 1 or 0 __RELAY_4 = 'Relay4' ## Toggle relay 1 command key. Value: 1 __TOGGLE_RELAY_1 = 'ToggleRelay1' ## Toggle relay 2 command key. Value: 1 __TOGGLE_RELAY_2 = 'ToggleRelay2' ## Toggle relay 3 command key. Value: 1 __TOGGLE_RELAY_3 = 'ToggleRelay3' ## Toggle relay 4 command key. Value: 1 __TOGGLE_RELAY_4 = 'ToggleRelay4' ## Pulse relay 4 command key. Value: 1 to 60[s] __PULSE_RELAY_1 = 'PulseRelay1' ## Pulse relay 4 command key. Value: 1 to 60[s] __PULSE_RELAY_2 = 'PulseRelay2' ## Pulse relay 4 command key. Value: 1 to 60[s] __PULSE_RELAY_3 = 'PulseRelay3' ## Pulse relay 4 command key. Value: 1 to 60[s] __PULSE_RELAY_4 = 'PulseRelay4' ## Address of the KIOSK browser in BASE64. __KIOSK_ADDRESS = 'KioskAddress' ## Preset the default settings of the browser. __KIOSK_DEFAULT = 'KioskDefault' ## Relay outputs descriptor. __RO = { 'key': "RelayOutputs", 'name': 'RelayOutput', 'unit': 'LogicLevel', 'id': { '1': '0', '2': '1', '3': '2', '4': '3' } } ## Digital inputs descriptor. __DI = { 'key': "DigitalInputs", 'name': 'DigitalInput', 'unit': 'LogicLevel', 'id': { '1': '4', '2': '5', '3': '6', '4': '7', '5': '8', '6': '9' } } ## Counters inputs descriptor. __CI = { 'key': "CounterInputs", 'name': 'CounterInput', 'unit': 'Count', 'id': { '1': '10', '2': '11' } } ## Analog inputs descriptor. __AI = { 'key': "AnalogInputs", 'name': 'AnalogInput', 'unit': 'V', 'id': { '1': '12', '2': '13', '3': '14', '4': '15', '5': '16', '6': '17', '7': '18', '8': '19' } } ## Electronic scales descriptor. __ES = { 'key': "ElectronicScales", 'name': 'ElectronicScale', 'id': { '1': '20' } } ## Protocol version. __PROTOCOL_VERSION = '16.11.0.1' ## Text representation of logic level 0. __STATE_LOW = '0' ## Text representation of logic level 1. __STATE_HIGH = '1' ## Get the key. ## Handler for the GET requests. # @param self The object pointer. def do_GET(self): # Get the key. key = self.__settings.get_credentials_as_b64() # Check if it home IP or authorized client respons it. if (self.headers.getheader('Authorization') == 'Basic ' + key) or (self.client_address[0] == '127.0.0.1'): # Just pass and proseed. pass # Else redirect to authorize. elif (self.headers.getheader('Authorization') == None): self.do_AUTHHEAD() self.wfile.write('no auth header received') pass # Else redirect to authorize. else: self.do_AUTHHEAD() self.wfile.write(self.headers.getheader('Authorization')) self.wfile.write('not authenticated') pass # Parse the URL path. parsed_url = urlparse(self.path) # Check is there arguments. if (parsed_url.query != None and parsed_url.query != ""): # Create the response. self.__the_page = self.__create_get_response(parsed_url.query) else: # Create XML structure. container = dict() container['ProtocolVersion'] = self.__PROTOCOL_VERSION container['Entrys'] = None xml = dicttoxml.dicttoxml(container, custom_root='Monitor', attr_type=False) # Create the response. self.__the_page = xml # ============================================ self.send_response(200) self.send_header('Content-type', self.__mime_type) self.send_header( "Access-Control-Allow-Origin", "*" ) # This may be usefull as a settings. Only the central server can call the IO device. #self.send_header("Access-Control-Allow-Methods", "GET") # This may be usefull only with get method to access the device. self.end_headers() # Send the page self.wfile.write(self.__the_page) return ## Handler for the authorization. # @param self The object pointer. def do_AUTHHEAD(self): # Set MIME. self.__mime_type = "text/xml" self.send_response(401) self.send_header('WWW-Authenticate', 'Basic realm=\"Test\"') self.send_header('Content-type', self.__mime_type) self.end_headers() ## Translate relative path to absolute. # @param self The object pointer. # @param url_path relative path from the request. def __from_realative_to_absolute(self, url_path): curent_path = os.path.dirname(os.path.realpath(__file__)) full_path = curent_path + url_path if (os.name == 'nt'): full_path = full_path.replace('/', '\\') if (os.path.isdir(full_path) == True): full_path = os.path.join(full_path, self.__default_file_name) elif (os.path.isfile(full_path) == True): full_path = full_path return full_path ## Get the content from the file. # @param self The object pointer. # @param file_path file path that wil get the content. def __get_content(self, file_path): content = '' # Open the file. page_file = open(file_path, 'rb') # Read page file content. content = page_file.read() # Close the content. page_file.close() return content ## Returns MIME type. # @param self The object pointer. # @param url_path URL path. def __get_mime(self, url_path): split_string = url_path.split('.') extention = '' mime_type = '' split_count = len(split_string) if (split_count >= 2): extention = split_string[split_count - 1] if (extention == 'css'): mime_type = "text/css" elif (extention == "jpg"): mime_type = "image/jpeg" elif (extention == "jpeg"): mime_type = "image/jpeg" elif (extention == "png"): mime_type = "image/png" elif (extention == "bmp"): mime_type = "image/bmp" elif (extention == "gif"): mime_type = "image/gif" elif (extention == "emf"): mime_type = "image/emf" elif (extention == "ico"): mime_type = "image/ico" elif (extention == "csv"): mime_type = "text/csv" elif (extention == "html"): mime_type = "text/html" elif (extention == "js"): mime_type = "text/javascript" elif (extention == "xml"): mime_type = "text/xml" else: mime_type = "text/html" return mime_type ## Generate entry. # @param self The object pointer. # @param units Units of the mesurment in the entry. # @param id ID of the entry. # @param name Name of the entry. # @param value Value of the mesurment. def __generate_entry(self, units, id, name, value): entry = dict() entry['Unit'] = units entry['ID'] = id entry['Name'] = name entry['Value'] = value return entry ## Create XML response. # @param self The object pointer. # @param url_query URL path. def __create_get_response(self, url_query): query_dict = dict() # Entrys container list. entries = [] if (url_query != None): #query = urllib.unquote(url_query).decode('utf8') ucq_dict = parse_qs(url_query) query_dict = dict([(str(key), str(value[0])) for key, value in ucq_dict.items()]) # If relay 1 is in the arguments prse it. if (self.__RELAY_1 in query_dict): state = query_dict[self.__RELAY_1] if (state == "0"): self.__board.set_output(0, False) if (state == "1"): self.__board.set_output(0, True) # If relay 2 is in the arguments prse it. if (self.__RELAY_2 in query_dict): state = query_dict[self.__RELAY_2] if (state == "0"): self.__board.set_output(1, False) if (state == "1"): self.__board.set_output(1, True) # If relay 3 is in the arguments prse it. if (self.__RELAY_3 in query_dict): state = query_dict[self.__RELAY_3] if (state == "0"): self.__board.set_output(2, False) if (state == "1"): self.__board.set_output(2, True) # If relay 4 is in the arguments prse it. if (self.__RELAY_4 in query_dict): state = query_dict[self.__RELAY_4] if (state == "0"): self.__board.set_output(3, False) if (state == "1"): self.__board.set_output(3, True) # If toggle relay 1 is in the arguments prse it. if (self.__TOGGLE_RELAY_1 in query_dict): state = str(query_dict[self.__TOGGLE_RELAY_1][0]) if (state == "1"): state = not self.__board.get_output(0) self.__board.set_output(0, state) # If toggle relay 2 is in the arguments prse it. if (self.__TOGGLE_RELAY_2 in query_dict): state = query_dict[self.__TOGGLE_RELAY_2] if (state == "1"): state = not self.__board.get_output(1) self.__board.set_output(1, state) # If toggle relay 3 is in the arguments prse it. if (self.__TOGGLE_RELAY_3 in query_dict): state = query_dict[self.__TOGGLE_RELAY_3] if (state == "1"): state = not self.__board.get_output(2) self.__board.set_output(2, state) # If toggle relay 4 is in the arguments prse it. if (self.__TOGGLE_RELAY_4 in query_dict): state = query_dict[self.__TOGGLE_RELAY_4] if (state == "1"): state = not self.__board.get_output(3) self.__board.set_output(3, state) # If pulse relay 1 is in the arguments prse it. if (self.__PULSE_RELAY_1 in query_dict): sTime = query_dict[self.__PULSE_RELAY_1] try: fTime = float(sTime) self.__board.timed_output_set(0, fTime) except: pass # If pulse relay 2 is in the arguments prse it. if (self.__PULSE_RELAY_2 in query_dict): sTime = query_dict[self.__PULSE_RELAY_2] try: fTime = float(sTime) self.__board.timed_output_set(1, fTime) except: pass # If pulse relay 3 is in the arguments prse it. if (self.__PULSE_RELAY_3 in query_dict): sTime = query_dict[self.__PULSE_RELAY_3] try: fTime = float(sTime) self.__board.timed_output_set(2, fTime) except: pass # If pulse relay 4 is in the arguments prse it. if (self.__PULSE_RELAY_4 in query_dict): sTime = query_dict[self.__PULSE_RELAY_4] try: fTime = float(sTime) self.__board.timed_output_set(3, fTime) except: pass # If kiosk browser address is in the arguments prse it. if (self.__KIOSK_ADDRESS in query_dict): b64address = query_dict[self.__KIOSK_ADDRESS] try: address = base64.b64decode(str(b64address)) self.__kioskSettings.update_address(address) except e: print e pass # If kiosk browser default settings is in the arguments prse it. if (self.__KIOSK_DEFAULT in query_dict): value = query_dict[self.__KIOSK_DEFAULT] try: self.__kioskSettings.create_default_settings() except e: print e pass # Check if the relay outputs key is in the list. if (self.__RO['key'] in query_dict): indexes = query_dict[self.__RO['key']] relay_outputs = self.__board.get_outputs() # If the key is all then get all relay outputs. if (indexes == 'all'): for index in range(len(self.__RO['id'])): # Get ID of the entry item. id = self.__RO['id'][str(index + 1)] # Get value of the entry item. value = self.__STATE_HIGH if relay_outputs[ index] else self.__STATE_LOW # Create nama of the entry item. name = self.__RO['name'] + str(index + 1) # Generate entry item. entry = self.__generate_entry(self.__RO['unit'], id, name, value) # Add entry item to entries. entries.append(entry) # If the key is array. elif (indexes <> ''): # Split by coma. indexes_splited = indexes.split(',') # Remove dublicates and sort. indexes_splited = sorted(list(set(indexes_splited))) # If the length is grater then one. for index in range(len(indexes_splited)): if (indexes_splited[index] in self.__RO['id']): # Get ID of the entry item. id = self.__RO['id'][indexes_splited[index]] # Get value of the entry item. value = self.__STATE_HIGH if relay_outputs[ index] else self.__STATE_LOW # Create name of the entry item. name = self.__RO['name'] + indexes_splited[index] # Generate entry item. entry = self.__generate_entry(self.__RO['unit'], id, name, value) # Add entry item to entries. entries.append(entry) # Check if the digital inputs key is in the list. if (self.__DI['key'] in query_dict): # Get content from the arguments. indexes = query_dict[self.__DI['key']] # Read inputs. digital_inputs = self.__board.get_inputs() # If the key is all then get all relay inputs. if (indexes == 'all'): for index in range(len(self.__DI['id'])): # Get ID of the entry item. id = self.__DI['id'][str(index + 1)] # Get value of the entry item. value = self.__STATE_HIGH if digital_inputs[ index] else self.__STATE_LOW # Create nama of the entry item. name = self.__DI['name'] + str(index + 1) # Generate entry item. entry = self.__generate_entry(self.__DI['unit'], id, name, value) # Add entry item to entries. entries.append(entry) # If the key is array. elif (indexes <> ''): # Split by coma. indexes_splited = indexes.split(',') # Remove dublicates and sort. indexes_splited = sorted(list(set(indexes_splited))) # If the length is grater then one. for index in range(len(indexes_splited)): if (indexes_splited[index] in self.__DI['id']): # Get ID of the entry item. id = self.__DI['id'][indexes_splited[index]] # Get value of the entry item. value = self.__STATE_HIGH if digital_inputs[ index] else self.__STATE_LOW # Create nama of the entry item. name = self.__DI['name'] + indexes_splited[index] # Generate entry item. entry = self.__generate_entry(self.__DI['unit'], id, name, value) # Add entry item to entries. entries.append(entry) # Check if the counter inputs key is in the list. if (self.__CI['key'] in query_dict): # Get content from the arguments. indexes = query_dict[self.__CI['key']] # Read counters_inputs. cnt_get1 = self.__board.get_counter1() cnt_get2 = self.__board.get_counter2() self.__settings.add_counters(cnt_get1, cnt_get2) self.__board.reset_counter1() self.__board.reset_counter2() (cnt_get1, cnt_get2) = self.__settings.get_counters() counters_inputs = (cnt_get1, cnt_get2) # If the key is all then get all counters_inputs. if (indexes == 'all'): for index in range(len(self.__CI['id'])): # Get ID of the entry item. id = self.__CI['id'][str(index + 1)] # Get value of the entry item. value = counters_inputs[index] # Create name of the entry item. name = self.__CI['name'] + str(index + 1) # Generate entry item. entry = self.__generate_entry(self.__CI['unit'], id, name, value) # Add entry item to entries. entries.append(entry) # If the key is array. elif (indexes <> ''): # Split by coma. indexes_splited = indexes.split(',') # Remove dublicates and sort. indexes_splited = sorted(list(set(indexes_splited))) # If the length is grater then one. for index in range(len(indexes_splited)): if (indexes_splited[index] in self.__CI['id']): # Get ID of the entry item. id = self.__CI['id'][indexes_splited[index]] # Get value of the entry item. value = counters_inputs[index] # Create name of the entry item. name = self.__CI['name'] + indexes_splited[index] # Generate entry item. entry = self.__generate_entry(self.__CI['unit'], id, name, value) # Add entry item to entries. entries.append(entry) # Check if the analog inputs key is in the list. if (self.__AI['key'] in query_dict): # Get content from the arguments. indexes = query_dict[self.__AI['key']] # Read analog alaog inputs. alaog_inputs = self.__board.get_analogs() # If the key is all then get all relay alaog inputs. if (indexes == 'all'): for index in range(len(self.__AI['id'])): # Get ID of the entry item. id = self.__AI['id'][str(index + 1)] # Get value of the entry item. value = alaog_inputs[index] # Create nama of the entry item. name = self.__AI['name'] + str(index + 1) # Generate entry item. entry = self.__generate_entry(self.__AI['unit'], id, name, value) # Add entry item to entries. entries.append(entry) # If the key is array. elif (indexes <> ''): # Split by coma. indexes_splited = indexes.split(',') # Remove dublicates. indexes_splited = list(set(indexes_splited)) # If the length is grater then one. for index in range(len(indexes_splited)): if (indexes_splited[index] in self.__AI['id']): # Get ID of the entry item. id = self.__AI['id'][indexes_splited[index]] # Get value of the entry item. value = alaog_inputs[index] # Create nama of the entry item. name = self.__AI['name'] + str(index + 1) # Generate entry item. entry = self.__generate_entry(self.__AI['unit'], id, name, value) # Add entry item to entries. entries.append(entry) # Check if the electronic scale key is in the list. if (self.__ES['key'] in query_dict): # Get content from the arguments. indexes = query_dict[self.__ES['key']] mesurment = None # Read the electronic scale. try: mesurment = ElectronicScale.ElectronicScale.static_get_weight( '/dev/serial0') # '/dev/serial0' # Catch exception. except Exception as exception: error_text = str(exception.args[0]) mesurment = ElectronicScale.Measurement.Measurement( error_text, '') print "Electronic scale exception: " + error_text # TODO: Log the error for a week. #print type(exception) # the exception instance #print exception.args[0] # arguments stored in .args #print exception # __str__ allows args to be printed directly pass # Data container. es_inputs = [] es_inputs.append(mesurment) # If the key is all then get all electronic scales. if (indexes == 'all'): for index in range(len(self.__ES['id'])): # Get ID of the entry item. id = self.__ES['id'][str(index + 1)] # Create nama of the entry item. name = self.__ES['name'] + str(index + 1) # Tmporal fields. value = '' unit = '' # Get value of the entry item. if (es_inputs[index] != None): if (es_inputs[index].isValid()): value = es_inputs[index].getValue() unit = es_inputs[index].getUnit() # Generate entry item. es_entry = self.__generate_entry(unit, id, name, value) # Add entry item to entries. entries.append(es_entry) # If the key is array. elif (indexes <> ''): # Split by coma. indexes_splited = indexes.split(',') # Remove dublicates and sort. indexes_splited = sorted(list(set(indexes_splited))) # If the length is grater then one. for index in range(len(indexes_splited)): if (indexes_splited[index] in self.__ES['id']): # Get ID of the entry item. id = self.__ES['id'][indexes_splited[index]] # Create nama of the entry item. name = self.__ES['name'] + indexes_splited[index] # Tmporal fields. value = '' unit = '' # Get value of the entry item. if (es_inputs[index] != None and es_inputs[index].isValid()): value = es_inputs[index].getValue() unit = es_inputs[index].getUnit() # Generate entry item. es_entry = self.__generate_entry(unit, id, name, value) # Add entry item to entries. entries.append(es_entry) # Create XML structure. device = dict() device['Entries'] = entries device['Name'] = key = self.__settings.get_device_name() devices = [] devices.append(device) container = dict() container['Devices'] = devices container['ProtocolVersion'] = self.__PROTOCOL_VERSION xml = dicttoxml.dicttoxml(container, custom_root='Monitor', attr_type=False) return xml
def save_vocables(cls, vocable_list): xml_file_path = AppSettings.get_setting_by_name( AppSettings.XML_VOCABLE_FILE_PATH_SETTING_NAME) xsd_file_path = AppSettings.get_setting_by_name( AppSettings.XSD_VOCABLE_FILE_PATH_SETTING_NAME) FileManager.save_vocables(vocable_list, xml_file_path, xsd_file_path)
def create_xld_main_window(self): AppSettings.load_settings() # TODO: use test settings VocableManager.load_vocables() # TODO: use text vocables self.xld_main_window = XLDMainWindow() self.xld_main_window.show_all() GTKGUITestHelper.refresh_gui()
def save_settings(self, widget): AppSettings.change_setting_by_name( AppSettings.DIALOG_SHOW_SAVE_VOCABLES_CONFIRMATION_SETTING_NAME, not self.remember_decision_checkbutton.get_active() )
def main(): cwd = os.getcwd() settings = AppSettings.AppSettings(cwd + '/settings.ini') settings.reset_counters(0, 0)
def save_vocables(cls, vocable_list): xml_file_path = AppSettings.get_setting_by_name(AppSettings.XML_VOCABLE_FILE_PATH_SETTING_NAME) xsd_file_path = AppSettings.get_setting_by_name(AppSettings.XSD_VOCABLE_FILE_PATH_SETTING_NAME) FileManager.save_vocables(vocable_list, xml_file_path, xsd_file_path)