8 self
.InputStream
= False
12 def setBuffer(self
, Buffer
):
13 self
.InputStream
= True
19 return self
.InputStream
21 def serialUInt8(self
, val
=b
""):
23 val
= ord(self
.Buffer
[self
.Pos
])
27 self
.Buffer
+= bytes([val
& 0xFF])
30 def serialUInt32(self
, val
=b
""):
32 val
= ord(self
.Buffer
[self
.Pos
])
34 val
+= ord(self
.Buffer
[self
.Pos
])*256
36 val
+= ord(self
.Buffer
[self
.Pos
])*256*256
38 val
+= ord(self
.Buffer
[self
.Pos
])*256*256*256
42 self
.Buffer
+= bytes([val
& 0xFF])
43 self
.Buffer
+= bytes([(val
>>8) & 0xFF])
44 self
.Buffer
+= bytes([(val
>>16) & 0xFF])
45 self
.Buffer
+= bytes([(val
>>24) & 0xFF])
48 def serialString(self
, val
=b
""):
50 size
= self
.serialUInt32()
51 val
= self
.Buffer
[self
.Pos
:self
.Pos
+size
]
56 #Convert to bytes if need
57 val
= val
.encode("utf-8")
58 except AttributeError:
61 self
.serialUInt32(valLen
)
65 def serialEnum(self
, val
=""):
69 class CMessage(CMemStream
):
74 def setName(self
, name
):
78 class CCallbackClient():
83 def connect(self
, addr
, port
, res
):
88 self
.ConSock
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
90 self
.ConSock
.connect((addr
, port
))#, $errno, $errstr, $SockTimeOut)
92 print("Connection failed...")
95 print("Connection enabled!")
98 #TODO: set time out on the socket to 2 secondes
99 #stream_set_timeout(self.ConSock, $SockTimeOut)
106 def sendMessage(self
, message
):
108 hd
.serialUInt32(self
.MsgNum
) #number the packet
111 hd
.serialUInt8(messageType
)
112 hd
.serialString(message
.MsgName
)
114 size
= hd
.Pos
+ message
.Pos
115 Buffer
= chr((size
>>24)&0xFF)
116 Buffer
+= chr((size
>>16)&0xFF)
117 Buffer
+= chr((size
>>8)&0xFF)
118 Buffer
+= chr(size
&0xFF)
119 Buffer
= Buffer
.encode("iso-8859-1")
121 Buffer
+= message
.Buffer
123 print(Buffer
.decode("utf-8", errors
="replace"))
124 sent
= self
.ConSock
.send(Buffer
)
126 raise RuntimeError("socket connection broken")
128 def waitMessage(self
):
130 val
= self
.ConSock
.recv(1)
132 size
= ord(val
) << 24
136 val
= self
.ConSock
.recv(1)
138 size
= ord(val
) << 16
142 val
= self
.ConSock
.recv(1)
143 size
+= ord(val
) << 8
145 val
= self
.ConSock
.recv(1)
148 fake
= self
.ConSock
.recv(5)
149 size
-= 5 #remove the fake
152 while size
> 0 and len(Buffer
) != size
:
153 Buffer
+= self
.ConSock
.recv(size
- len(Buffer
)).decode("utf-8", errors
="replace")
156 msgin
.setBuffer(Buffer
)
160 name
= msgin
.serialString(name
)
162 logging
.info("Message name = '%s'" % name
)
165 message
.setBuffer(msgin
.Buffer
[msgin
.Pos
:])
166 message
.setName(name
)