예제 #1
0
 def test_accounts_get_set(self, account_list, unused_tcp_port):
     """Test the account getting and setting."""
     siac = SIAClient(
         host="",
         port=unused_tcp_port,
         accounts=account_list,
         function=(lambda ev: print(ev)),
     )
     assert siac.accounts == account_list
     acc_list2 = [
         SIAAccount(account_id=ACCOUNT, key=KEY, allowed_timeband=(None, None)),
         SIAAccount(account_id="1112", key=KEY, allowed_timeband=(None, None)),
     ]
     siac.accounts = acc_list2
     assert siac.accounts == acc_list2
예제 #2
0
    async def test_context(self, account_list, unused_tcp_port_factory, sync):
        """Test the context manager functions."""
        if sync:
            with patch.object(SIAClient, "stop") as client:
                with SIAClient(
                    HOST,
                    unused_tcp_port_factory(),
                    account_list,
                    function=get_func("sync"),
                ) as cl:
                    assert cl.accounts == account_list
                client.assert_called_once()

        else:
            with patch.object(SIAClientA, "stop") as client:
                with patch("asyncio.start_server"):
                    # test Async
                    async with SIAClientA(
                        HOST,
                        unused_tcp_port_factory(),
                        account_list,
                        function=get_func("aio"),
                    ) as cl:
                        assert cl.accounts == account_list
                client.assert_awaited_once()
예제 #3
0
 def test_func_errors(
     self,
     account_list,
     unused_tcp_port_factory,
     sync_client,
     sync_func,
 ):
     """Test the function setting."""
     error_type = TypeError if sync_client != sync_func else None
     try:
         if sync_client:
             SIAClient(
                 HOST,
                 unused_tcp_port_factory(),
                 account_list,
                 get_func("sync" if sync_func else "aio"),
             )
         else:
             SIAClientA(
                 HOST,
                 unused_tcp_port_factory(),
                 account_list,
                 get_func("sync" if sync_func else "aio"),
             )
         assert error_type is None
     except Exception as e:
         if isinstance(e, error_type):
             assert True
         else:
             assert False
예제 #4
0
 def test_sia_key_account_errors(self, key, account, port, error):
     """Test sia client behaviour."""
     try:
         SIAClient(
             host="",
             port=port,
             accounts=[SIAAccount(account_id=account, key=key)],
             function=func,
         )
         assert False if error else True
     except Exception as exp:
         assert isinstance(exp, error)
예제 #5
0
 def test_sia_account_setup(
     self, unused_tcp_port_factory, key, account_id, error_type
 ):
     """Test sia client behaviour."""
     try:
         SIAAccount.validate_account(account_id, key)
         SIAClient(
             host="",
             port=unused_tcp_port_factory(),
             accounts=[SIAAccount(account_id=account_id, key=key)],
             function=get_func("sync"),
         )
         assert True if error_type is None else False
     except Exception as exp:
         assert isinstance(exp, error_type)
예제 #6
0
    def test_parse_and_check(
        self,
        unused_tcp_port_factory,
        event_handler,
        key,
        code,
        msg_type,
        alter_key,
        wrong_event,
        response,
    ):
        """Test the server parsing."""
        if msg_type in ("ADM-CID", "NULL") and code == "ZX":
            pytest.skip(
                "Unknown code is not usefull to test in ADM-CID and NULL messages."
            )
            return
        if alter_key and key is None:
            pytest.skip("Alter key is not usefull to test when not encrypted.")
            return

        siac = SIAClient(
            HOST, unused_tcp_port_factory(), [SIAAccount(ACCOUNT, key)], event_handler
        )
        line = create_test_line(
            account=ACCOUNT,
            key=key,
            code=code,
            msg_type=msg_type,
            wrong_event=wrong_event,
            alter_key=alter_key,
        )

        _LOGGER.warning("Line to parse: %s", line)
        event = siac.sia_server.parse_and_check_event(line)
        _LOGGER.warning("Event received: %s", event)

        assert event.response == response
        if wrong_event or alter_key:
            assert isinstance(event, NAKEvent)
        else:
            assert event.account == ACCOUNT
            assert event.code == "RP" if msg_type == "NULL" else code
예제 #7
0
def create_client(
    unused_tcp_port_factory,
    event_handler,
    async_event_handler,
    bad_handler,
    async_bad_handler,
    key,
    good,
    protocol,
    sync,
):
    """Fixture to create a SIA Client."""
    config = {
        "host": HOST,
        "port": unused_tcp_port_factory(),
        "account_id": ACCOUNT,
        "key": key,
        "protocol": protocol,
    }

    if sync:
        client = SIAClient(
            host=config["host"],
            port=config["port"],
            accounts=[SIAAccount(config["account_id"], config["key"])],
            function=event_handler if good else bad_handler,
            protocol=config["protocol"],
        )
    else:
        client = SIAClientA(
            host=config["host"],
            port=config["port"],
            accounts=[SIAAccount(config["account_id"], config["key"])],
            function=async_event_handler if good else async_bad_handler,
            protocol=config["protocol"],
        )
    return (client, config, good, sync)
예제 #8
0
파일: run.py 프로젝트: fcoach66/pysiaalarm
from pysiaalarm import SIAEvent

logging.basicConfig(level=logging.DEBUG)

events = []


def func(event: SIAEvent):
    events.append(event)


with open("unencrypted_config.json", "r") as f:
    config = json.load(f)

account = [SIAAccount(config["account_id"], config["key"])]
client = SIAClient(config["host"], config["port"], account, function=func)
sleep_time = 120

client.start()

time.sleep(20)
print(f"Client started... adding extra account")
accounts = client.accounts
accounts.append(SIAAccount("FFFFFFFFF", config["key"]))
client.accounts = accounts
print("--------------------------------------------------")
print(f"Running for another {sleep_time} seconds")
time.sleep(sleep_time)
print(f"Client will stop now...")
print("--------------------------------------------------")
client.stop()
예제 #9
0
    def test_client(self, config_file):
        """Test the client.

        Arguments:
            config_file {str} -- Filename of the config.

        """
        try:
            with open(config_file, "r") as f:
                config = json.load(f)
        except:  # noqa: E722
            config = {
                "host": HOST,
                "port": PORT,
                "account_id": ACCOUNT,
                "key": None
            }

        events = []

        def func_append(event: SIAEvent):
            events.append(event)

        siac = SIAClient(
            host="",
            port=config["port"],
            accounts=[
                SIAAccount(account_id=config["account_id"], key=config["key"])
            ],
            function=func_append,
        )
        siac.start()

        tests = [
            {
                "code": False,
                "crc": False,
                "account": False,
                "time": False
            },
            {
                "code": True,
                "crc": False,
                "account": False,
                "time": False
            },
            {
                "code": False,
                "crc": True,
                "account": False,
                "time": False
            },
            {
                "code": False,
                "crc": False,
                "account": True,
                "time": False
            },
            {
                "code": False,
                "crc": False,
                "account": False,
                "time": True
            },
        ]

        t = threading.Thread(target=client_program,
                             name="test_client",
                             args=(config, 1, tests))
        t.daemon = True
        t.start()  # stops after the five events have been sent.

        # run for 30 seconds
        time.sleep(30)

        siac.stop()
        assert siac.counts == {
            "events": 5,
            "valid_events": 1,
            "errors": {
                "crc": 1,
                "timestamp": 1,
                "account": 1,
                "code": 1,
                "format": 0,
                "user_code": 0,
            },
        }
        assert len(events) == 1
예제 #10
0
import logging
import time

from pysiaalarm import SIAAccount, SIAClient, SIAEvent

logging.basicConfig(level=logging.DEBUG)

events = []


def func(event: SIAEvent):
    events.append(event)


with open("local_config.json", "r") as f:
    config = json.load(f)
print("Config: ", config)
account = [SIAAccount(config["account_id"], config["key"])]
sleep_time = 1200
with SIAClient(config["host"], config["port"], account, function=func) as client:
    time.sleep(sleep_time)
    counts = client.counts

# for ev in events:
#     print(ev)

print("--------------------------------------------------")
print("Number of events: ", len(events))
print("Counts: ", counts)
print("--------------------------------------------------")