1#!/usr/bin/env python3 2# -*- coding: utf-8 -*- 3""" 4Copyright (c) 2024 Huawei Device Co., Ltd. 5Licensed under the Apache License, Version 2.0 (the "License"); 6you may not use this file except in compliance with the License. 7You may obtain a copy of the License at 8 9 http://www.apache.org/licenses/LICENSE-2.0 10 11Unless required by applicable law or agreed to in writing, software 12distributed under the License is distributed on an "AS IS" BASIS, 13WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14See the License for the specific language governing permissions and 15limitations under the License. 16 17Description: Python Protocol Domain Interfaces 18""" 19 20import sys 21from pathlib import Path 22 23sys.path.append(str(Path(__file__).parent.parent)) # add aw path to sys.path 24 25from customized_types import ProtocolType 26 27 28class ProtocolImpl(object): 29 30 def __init__(self, id_generator, websocket): 31 self.id_generator = id_generator 32 self.class_name = self.__class__.__name__ 33 self.domain = self.class_name[:-4] 34 self.dispatch_table = {} 35 self.websocket = websocket 36 37 async def send(self, protocol_name, connection, params=None): 38 protocol = self._check_and_parse_protocol(protocol_name) 39 if self.dispatch_table.get(protocol) is not None: 40 if self.dispatch_table.get(protocol)[1] != ProtocolType.send: 41 raise AssertionError("{} send ProtocolType inconsistent: Protocol {}, calling {}, should be {}" 42 .format(self.class_name, protocol_name, "send", 43 self.dispatch_table.get(protocol)[1])) 44 message_id = next(self.id_generator) 45 return await self.dispatch_table.get(protocol)[0](message_id, connection, params) 46 47 async def recv(self, protocol_name, connection, params=None): 48 protocol = self._check_and_parse_protocol(protocol_name) 49 if self.dispatch_table.get(protocol) is not None: 50 if self.dispatch_table.get(protocol)[1] != ProtocolType.recv: 51 raise AssertionError("{} recv ProtocolType inconsistent: Protocol {}, calling {}, should be {}" 52 .format(self.class_name, protocol_name, "recv", 53 self.dispatch_table.get(protocol)[1])) 54 return await self.dispatch_table.get(protocol)[0](connection, params) 55 56 def _check_and_parse_protocol(self, protocol_name): 57 res = protocol_name.split('.') 58 if len(res) != 2: 59 raise AssertionError("{} parse protocol name error: protocol_name {} is invalid" 60 .format(self.class_name, protocol_name)) 61 domain, protocol = res[0], res[1] 62 if domain != self.domain: 63 raise AssertionError("{} parse protocol name error: protocol_name {} has the wrong domain" 64 .format(self.class_name, protocol_name)) 65 if protocol not in self.dispatch_table: 66 raise AssertionError("{} parse protocol name error: protocol_name {} has not been defined" 67 .format(self.class_name, protocol_name)) 68 return protocol