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 20from aw.types import ProtocolType 21 22 23class ProtocolImpl(object): 24 25 def __init__(self, id_generator, websocket): 26 self.id_generator = id_generator 27 self.class_name = self.__class__.__name__ 28 self.domain = self.class_name[:-4] 29 self.dispatch_table = {} 30 self.websocket = websocket 31 32 async def send(self, protocol_name, connection, params=None): 33 protocol = self._check_and_parse_protocol(protocol_name) 34 if self.dispatch_table.get(protocol) is not None: 35 if self.dispatch_table.get(protocol)[1] != ProtocolType.send: 36 raise AssertionError("{} send ProtocolType inconsistent: Protocol {}, calling {}, should be {}" 37 .format(self.class_name, protocol_name, "send", 38 self.dispatch_table.get(protocol)[1])) 39 message_id = next(self.id_generator) 40 return await self.dispatch_table.get(protocol)[0](message_id, connection, params) 41 42 async def recv(self, protocol_name, connection, params=None): 43 protocol = self._check_and_parse_protocol(protocol_name) 44 if self.dispatch_table.get(protocol) is not None: 45 if self.dispatch_table.get(protocol)[1] != ProtocolType.recv: 46 raise AssertionError("{} recv ProtocolType inconsistent: Protocol {}, calling {}, should be {}" 47 .format(self.class_name, protocol_name, "recv", 48 self.dispatch_table.get(protocol)[1])) 49 return await self.dispatch_table.get(protocol)[0](connection, params) 50 51 def _check_and_parse_protocol(self, protocol_name): 52 res = protocol_name.split('.') 53 if len(res) != 2: 54 raise AssertionError("{} parse protocol name error: protocol_name {} is invalid" 55 .format(self.class_name, protocol_name)) 56 domain, protocol = res[0], res[1] 57 if domain != self.domain: 58 raise AssertionError("{} parse protocol name error: protocol_name {} has the wrong domain" 59 .format(self.class_name, protocol_name)) 60 if protocol not in self.dispatch_table: 61 raise AssertionError("{} parse protocol name error: protocol_name {} has not been defined" 62 .format(self.class_name, protocol_name)) 63 return protocol