1#!/usr/bin/env python 2 3# Copyright JS Foundation and other contributors, http://js.foundation 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16 17import struct 18 19MAX_BUFFER_SIZE = 256 20 21class RawPacket(object): 22 """ Simplified transmission layer. """ 23 def __init__(self, protocol): 24 self.protocol = protocol 25 self.data_buffer = b"" 26 27 def connect(self, config_size): 28 """ Create connection. """ 29 self.protocol.connect() 30 self.data_buffer = b"" 31 32 # It will return with the Network configurations, which has the following struct: 33 # header [1] - size[1] 34 # configuration [config_size] 35 len_expected = config_size + 1 36 37 while len(self.data_buffer) < len_expected: 38 self.data_buffer += self.protocol.receive_data() 39 40 expected = struct.pack("B", config_size) 41 42 if self.data_buffer[0:1] != expected: 43 raise Exception("Unexpected configuration") 44 45 result = self.data_buffer[1:len_expected] 46 self.data_buffer = self.data_buffer[len_expected:] 47 48 return result 49 50 def close(self): 51 """ Close connection. """ 52 self.protocol.close() 53 54 def send_message(self, _, data): 55 """ Send message. """ 56 msg_size = len(data) 57 58 while msg_size > 0: 59 bytes_send = self.protocol.send_data(data) 60 if bytes_send < msg_size: 61 data = data[bytes_send:] 62 msg_size -= bytes_send 63 64 def get_message(self, blocking): 65 """ Receive message. """ 66 67 # Connection was closed 68 if self.data_buffer is None: 69 return None 70 71 while True: 72 if len(self.data_buffer) >= 1: 73 size = ord(self.data_buffer[0]) 74 if size == 0: 75 raise Exception("Unexpected data frame") 76 77 if len(self.data_buffer) >= size + 1: 78 result = self.data_buffer[1:size + 1] 79 self.data_buffer = self.data_buffer[size + 1:] 80 return result 81 82 if not blocking and not self.protocol.ready(): 83 return b'' 84 85 received_data = self.protocol.receive_data(MAX_BUFFER_SIZE) 86 87 if not received_data: 88 return None 89 90 self.data_buffer += received_data 91