From 3379efcb4dfacc3af72e67b319e560d7271d7750 Mon Sep 17 00:00:00 2001 From: AxelC Date: Mon, 25 Nov 2019 23:13:36 +0100 Subject: [PATCH] Use config in main app. Add some tests --- box.py | 49 +++++++------------ modules/cards_bdd/AppConfig.py | 15 ++++++ modules/cards_bdd/CardsRead_test.py | 40 +++++++++++++++ .../{cards_test.py => CardsWrite_test.py} | 6 +-- modules/cards_bdd/ConfigRead_test.py | 42 ++++++++++++++++ modules/cards_bdd/DbCreatorCard.py | 4 +- modules/cards_bdd/DbCreatorConfig.py | 4 +- modules/cards_bdd/DbManager.py | 37 +++++++++----- .../{serviceAccountKey.json => ReadKey.json} | 0 modules/cards_bdd/WriteKey.json | 12 +++++ 10 files changed, 159 insertions(+), 50 deletions(-) create mode 100644 modules/cards_bdd/CardsRead_test.py rename modules/cards_bdd/{cards_test.py => CardsWrite_test.py} (97%) create mode 100644 modules/cards_bdd/ConfigRead_test.py rename modules/cards_bdd/{serviceAccountKey.json => ReadKey.json} (100%) create mode 100644 modules/cards_bdd/WriteKey.json diff --git a/box.py b/box.py index e70d826..fd439b9 100755 --- a/box.py +++ b/box.py @@ -14,40 +14,25 @@ import requests from modules.rfid_reader.Reader import Reader from modules.card_memory.CardMemory import CardMemory from modules.cards_bdd.Card import Card +from modules.cards_bdd.AppConfig import AppConfig from modules.cards_bdd.DbManager import DbManager +from modules.tools import get_serial -import config as cfg # Get config from file def main(): - # Get config - try: - # Get it from config - memory_duration = cfg.previousCardTimeout - except AttributeError: - # Default value - memory_duration = 30 - UPDATE_PERIOD = 60 reader = Reader() - bdd = DbManager('https://bipbipzizik.firebaseio.com/', 'cards', 'modules/cards_bdd/serviceAccountKey.json') - previous_card = CardMemory(memory_duration) + database = DbManager('https://bipbipzizik.firebaseio.com/', 'prod', 'modules/cards_bdd/serviceAccountKey.json') + app_serial = get_serial() + cfg = database.get_config(app_serial) + cfg.print() #TODO investigate why config db is empty sometimes if no print is done + + previous_card = CardMemory(cfg.cfg_card_timeout) last_update_time = time() - # Create address path - address = cfg.ip + ':' + cfg.port - - # Create command line - if cfg.roomName == '': - # Command for global playing - addr_with_room = address + '/' - else: - # Command for local playing - addr_with_room = address + '/' + cfg.roomName + '/' - - while True: print('Ready: place a card on top of the reader') @@ -57,11 +42,11 @@ def main(): try: print('Read card : ', read_id) - # Find the card in bdd - card = bdd.get_card(read_id) + # Find the card in database + card = database.get_card(read_id) if card is None: - print('Failed to read card from bdd') + print('Failed to read card from database') else: # Card execution @@ -71,7 +56,7 @@ def main(): print('Command : ', command) print('Modes : ', mode) - if (previous_card.get() == read_id) and ("cancel" == cfg.multiReadMode) and (not card.is_command()): + if (previous_card.get() == read_id) and ("cancel" == cfg.cfg_multi_read_mode) and (not card.is_command()): # Cancel the read print('Multi read : card canceled') else: @@ -79,22 +64,22 @@ def main(): previous_card.set(read_id) if card.has_mode("ClearQueue"): - command_line = "http://" + addr_with_room + "clearqueue" + command_line = cfg.get_sonos_cmd("clearqueue") print(command_line) response = requests.get(command_line) print(response.text) if command is not None: - command_line = "http://" + addr_with_room + command + command_line = cfg.get_sonos_cmd(command) print(command_line) response = requests.get(command_line) print(response.text) - # Update the bdd periodically + # Update the database periodically if (time() - last_update_time) > UPDATE_PERIOD: - bdd.update() + database.update() last_update_time = time() - # TODO Write last update time on config bdd + # TODO Write last update time on config database except OSError as e: print("Execution failed:" + e.strerror) diff --git a/modules/cards_bdd/AppConfig.py b/modules/cards_bdd/AppConfig.py index b45c979..a31adfe 100644 --- a/modules/cards_bdd/AppConfig.py +++ b/modules/cards_bdd/AppConfig.py @@ -37,6 +37,21 @@ class AppConfig: # Previous card memory duration in second self.cfg_card_timeout = card_timeout + def get_sonos_cmd(self, command): + + # Create address path + sonos_addr = "http://" + self.cfg_sonos_server_ip + ':' + self.cfg_sonos_server_port + + # Create command line + if self.cfg_room_name == '': + # Command for global playing + addr_with_room = sonos_addr + '/' + else: + # Command for local playing + addr_with_room = sonos_addr + '/' + self.cfg_room_name + '/' + + return addr_with_room + command + def print(self): """ Function that print the application config diff --git a/modules/cards_bdd/CardsRead_test.py b/modules/cards_bdd/CardsRead_test.py new file mode 100644 index 0000000..76dac85 --- /dev/null +++ b/modules/cards_bdd/CardsRead_test.py @@ -0,0 +1,40 @@ +# +# BIPBIPZIZIK +# Unit test for Card and FirebaseBdd classes +# It test the read of cards on production database with a public key +# + +import unittest + +from modules.cards_bdd.Card import Card +from modules.cards_bdd.DbManager import DbManager + + +class CardsRead(unittest.TestCase): + + @classmethod + def setUpClass(cls): + + cls.bdd = DbManager('https://bipbipzizik.firebaseio.com/', 'prod', 'ReadKey.json') + + # def setUp(self): + # nothing yet + + def test_read_card(self): + card_expected = {"user": "user", + "name": "name", + "comment": "comment", + "ids": "template", + "mode": "mode", + "action": "action", + "data": "data"} + + card = self.bdd.get_card("template") + + self.assertEqual(card.parameters, card_expected) + + +if __name__ == '__main__': + + unittest.main() + diff --git a/modules/cards_bdd/cards_test.py b/modules/cards_bdd/CardsWrite_test.py similarity index 97% rename from modules/cards_bdd/cards_test.py rename to modules/cards_bdd/CardsWrite_test.py index cff7bc1..67f3444 100644 --- a/modules/cards_bdd/cards_test.py +++ b/modules/cards_bdd/CardsWrite_test.py @@ -10,13 +10,13 @@ from modules.cards_bdd.Card import Card from modules.cards_bdd.DbManager import DbManager -class CardLisTest(unittest.TestCase): +class CardsWrite(unittest.TestCase): @classmethod def setUpClass(cls): - cls.bdd = DbManager('https://bipbipzizik.firebaseio.com/', 'cards_test', 'serviceAccountKey.json') - cls.bdd.delete() + cls.bdd = DbManager('https://bipbipzizik.firebaseio.com/', 'test', 'WriteKey.json') + cls.bdd.delete("cards_test") cls.bdd.write_card(user="user1", name="name1", comment="comment1", diff --git a/modules/cards_bdd/ConfigRead_test.py b/modules/cards_bdd/ConfigRead_test.py new file mode 100644 index 0000000..c9bce3f --- /dev/null +++ b/modules/cards_bdd/ConfigRead_test.py @@ -0,0 +1,42 @@ +# +# BIPBIPZIZIK +# Unit test for Card and FirebaseBdd classes +# It test the read of cards on production database with a public key +# + +import unittest + +from modules.cards_bdd.Card import Card +from modules.cards_bdd.DbManager import DbManager + + +class ConfigRead(unittest.TestCase): + + @classmethod + #def setUpClass(cls): + + #cls.bdd = DbManager('https://bipbipzizik.firebaseio.com/', 'prod', 'ReadKey.json') + + # def setUp(self): + # nothing yet + + def test_read_config(self): + card_expected = {"app_name": "For test purpose", + "app_owner": "axel", + "app_id": "template", + "sonos_server_ip": "HHH.UUU.GGG.OOO", + "sonos_server_port": "2017", + "room_name": "Ginette", + "multi_read_mode": "none", + "card_timeout": "42"} + self.database = DbManager('https://bipbipzizik.firebaseio.com/', 'prod', 'ReadKey.json') + config = self.database.get_config("template") + config.print() + self.assertEqual(config.cfg_sonos_server_port, "2017") + self.assertEqual(config.cfg_app_name, "For test purpose") + + +if __name__ == '__main__': + + unittest.main() + diff --git a/modules/cards_bdd/DbCreatorCard.py b/modules/cards_bdd/DbCreatorCard.py index 7dca016..85ff825 100644 --- a/modules/cards_bdd/DbCreatorCard.py +++ b/modules/cards_bdd/DbCreatorCard.py @@ -3,8 +3,8 @@ from modules.cards_bdd.DbManager import DbManager -data_base = DbManager('https://bipbipzizik.firebaseio.com/', 'cards', 'config', 'serviceAccountKey.json') -data_base.delete('cards') +data_base = DbManager('https://bipbipzizik.firebaseio.com/', 'prod', 'WriteKey.json') +data_base.delete('cards_prod') # CARDS # Test diff --git a/modules/cards_bdd/DbCreatorConfig.py b/modules/cards_bdd/DbCreatorConfig.py index 836fd26..03bfe34 100644 --- a/modules/cards_bdd/DbCreatorConfig.py +++ b/modules/cards_bdd/DbCreatorConfig.py @@ -3,8 +3,8 @@ from modules.cards_bdd.DbManager import DbManager -data_base = DbManager('https://bipbipzizik.firebaseio.com/', 'cards', 'config', 'serviceAccountKey.json') -data_base.delete('config') +data_base = DbManager('https://bipbipzizik.firebaseio.com/', 'prod', 'WriteKey.json') +data_base.delete('config_prod') # CARDS # Command cards diff --git a/modules/cards_bdd/DbManager.py b/modules/cards_bdd/DbManager.py index 6dea59c..adffbda 100644 --- a/modules/cards_bdd/DbManager.py +++ b/modules/cards_bdd/DbManager.py @@ -9,23 +9,24 @@ import firebase_admin from firebase_admin import credentials from firebase_admin import db -from Card import Card -from AppConfig import AppConfig +from .Card import Card +from .AppConfig import AppConfig + +from time import sleep class DbManager: - def __init__(self, bdd_addr, card_bdd_name, config_bdd_name, path_to_key_file): + def __init__(self, bdd_addr, bdd_name, path_to_key_file): """ Card reader constructor. :param bdd_addr: - :param card_bdd_name: - :param config_bdd_name: + :param bdd_name: :param path_to_key_file: """ - self.card_bdd_name = card_bdd_name - self.config_bdd_name = config_bdd_name + self.config_bdd_name = "config_" + bdd_name + self.card_bdd_name = "cards_" + bdd_name try: # Fetch the service account key JSON file contents @@ -38,8 +39,10 @@ class DbManager: # Initialize the app with a service account, granting admin privileges firebase_admin.initialize_app(credential, {'databaseURL': bdd_addr}) - self.config_db = db.reference(config_bdd_name) - self.cards_db = db.reference(card_bdd_name) + self.config_db = db.reference(self.config_bdd_name) + self.cards_db = db.reference(self.card_bdd_name) + + # Todo stop the app with error if db is empty self.cards_db_python = {} self.config_db_python = {} @@ -55,7 +58,7 @@ class DbManager: self.config_db_python = self.config_db.get() self.cards_db_python = self.cards_db.get() - def count(self): + def count_cards(self): """ Function that return the number of cards in th bdd :return: the number of cards @@ -63,6 +66,14 @@ class DbManager: return self.cards_db_python.__len__() + def count_configs(self): + """ + Function that return the number of configs in th bdd + :return: the number of configs + """ + + return self.config_db_python.__len__() + def get_card(self, card_id): """ Function that get a dict of a searched card @@ -122,7 +133,7 @@ class DbManager: sonos_server_port=config.get("sonos_server_port"), room_name=config.get("room_name"), multi_read_mode=config.get("multi_read_mode"), - card_timeout=config.get("card_timeout") + card_timeout=int(config.get("card_timeout")) ) # Config not found, return None @@ -160,9 +171,13 @@ class DbManager: :return: """ if bdd_name == self.card_bdd_name: + print("Delete database: " + bdd_name) print(self.cards_db.delete()) elif bdd_name == self.config_bdd_name: + print("Delete database: " + bdd_name) print(self.config_db.delete()) + else: + print("Delete Canceled: Database not recognized") def print(self): """ diff --git a/modules/cards_bdd/serviceAccountKey.json b/modules/cards_bdd/ReadKey.json similarity index 100% rename from modules/cards_bdd/serviceAccountKey.json rename to modules/cards_bdd/ReadKey.json diff --git a/modules/cards_bdd/WriteKey.json b/modules/cards_bdd/WriteKey.json new file mode 100644 index 0000000..42211e5 --- /dev/null +++ b/modules/cards_bdd/WriteKey.json @@ -0,0 +1,12 @@ +{ + "type": "service_account", + "project_id": "bipbipzizik", + "private_key_id": "b535ec4e6c0a1d168ebe66e6d8e66a18078063ae", + "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQClJDDZLRxonFzM\nNfd1a0VJo11tIKdgeURdk+CYanW6bQm6E+4e1xwV38DlMl0FUBvxeLovxYQ+xILP\nUC73vFOMhPlsWCXZhSbfVVH76lvYNonhgVe8ffnvR0wz54IQnsN00TQaZlpl3n5V\ni4W75PxkCP8RqujV5sCB7fOsdijkfz+g8w8o/Ts+RsfTuMwLo4Bc8R4jOcZCDq5v\nLgcaR6hwYSfKdg0MyOM182oIU2FueSzLAGDrZydVs/vhfyEx55GwpC8StXAdFjnD\nGVb/iLJXiXQ6UoqhGAgQUETjog00xEEUwT5zNpDiRLqvZDdVdkaTL5ZuFH6N6DXl\nqDAE4/k/AgMBAAECggEAEFfylavHQfsnm/ZDVVWWd+E5H9G5fuzBfVljQvJWUGr2\nKXpLeLXlS6znVEeVuS7idRVzp8Kugd/E6muPGmmDA0ctwDFBHbP10uiIwpvBFzbe\nknjQjBETqUCvI/vnfWmZAnip5Wr3y1knu6OhSqUw7V2OkNsPTAwYRUOdeBYBmgtt\nN2zD9w4VQI61nE7iw2Hdy9Lxe4DZlYpUkLlAiLq4byAa6ipypXao+euafVW8yIlq\nRpxpL0LSGObSMXXDEcPQ8qD5jYTQSD65nXKEaEESVRYsGbUX2wIPbg4KhfeqW5T/\nGTHy0seRpLIW4C9dt5TIHyJ5dPG+dRN5urswviUccQKBgQDPp1bl0KkGpQ8e0/2o\nLjv0utxpNlsd3eXZ5Sw5SNWEWTAx8pyp2V9byN4pBoLR9hTXTP1Ix3GFa7Ir4CIS\nQEd4Dwql7JBGiQWpPTZ2ZpAqdj6Y8BIHc2Cp/63qfCnaw5UzKi1jVR4DH0KBb8cn\ndo2tvi+2X07SuU90gqDvInGwwwKBgQDLlwP9nqlynpY5Bd5iN17Qy8+BH51VBBgD\nElej5vJfEHXLNIyMLH4xmKJ1x8kOeQP++UnAxIWQZol3RDoRQHNkcrZ/0I+AXql5\ns+cRHV9dj/cOIbWEhDyttcvF/3/DKt/Z93t2hSzTD1p+oBFX56axx7bVRBZzHqT1\njrlwq0YN1QKBgQCX8Fh8BaZ3rzSWGQVEFrhWBJgb/+LBwshZG/+01p8snNnP4jZR\nbTUCAsLTf+ke2hE7zCCULSLaPgf7ZJ9pfVEN/uuKpsKWadITmC+OiNM5zpVU8Gww\nuXJkUSmfJkS1xmAYNOdLBE/WdvwBm5k8PdnC5CMjLS+Ornr9xEsfTrOjYwKBgCbV\njpBRNHdFotgLs4i+kRp41gMGWcd+uWnUlN0Rz4espxt00Z5nWkbxm4Ol8UcOdGGt\ngZEAq42I0Y3reLwTtC8j5oXo7YaKB//L/jZ4iNla/cA3U92ML9rew5joDKHYysxT\n9bv82TkFQ7jFpalD6bsdolV54GJjJQomCF9ifEFlAoGAbmnhMtUcwT/T7aa3lq72\nGkm7OOMo4+SnNjfjBLIGQlqp484LNTjKPjR8Q9oPhJ9gZq9QXdbxjLl5UgMn/vjh\nmzV+d08ULEf18BgNQ7VYXeRznBnAzB+VyhqDAN3vplk8k0FJlOntlma9tNZQGw9w\n7sQHn4gGeCQ9Q8PRC15nw2E=\n-----END PRIVATE KEY-----\n", + "client_email": "firebase-adminsdk-ez386@bipbipzizik.iam.gserviceaccount.com", + "client_id": "103271275966889207260", + "auth_uri": "https://accounts.google.com/o/oauth2/auth", + "token_uri": "https://oauth2.googleapis.com/token", + "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", + "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-ez386%40bipbipzizik.iam.gserviceaccount.com" +}