blob: 736c9435d99944d74b9e347a0377fabb2132370b [file] [log] [blame]
Neels Hofmeyr3531a192017-03-28 14:30:28 +02001
2# osmo_gsm_tester: specifics for running a sysmoBTS
3#
4# Copyright (C) 2016-2017 by sysmocom - s.f.m.c. GmbH
5#
6# Author: Neels Hofmeyr <neels@hofmeyr.de>
7#
8# This program is free software: you can redistribute it and/or modify
9# it under the terms of the GNU Affero General Public License as
10# published by the Free Software Foundation, either version 3 of the
11# License, or (at your option) any later version.
12#
13# This program is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16# GNU Affero General Public License for more details.
17#
18# You should have received a copy of the GNU Affero General Public License
19# along with this program. If not, see <http://www.gnu.org/licenses/>.
20
21import socket
22import struct
23
24from . import log
25
26class CtrlInterfaceExn(Exception):
27 pass
28
29class OsmoCtrl(log.Origin):
30
31 def __init__(self, host, port):
32 self.set_name('Ctrl', host=host, port=port)
33 self.set_log_category(log.C_BUS)
34 self.host = host
35 self.port = port
36 self.sck = None
37
38 def prefix_ipa_ctrl_header(self, data):
39 if isinstance(data, str):
40 data = data.encode('utf-8')
41 s = struct.pack(">HBB", len(data)+1, 0xee, 0)
42 return s + data
43
44 def remove_ipa_ctrl_header(self, data):
45 if (len(data) < 4):
46 raise CtrlInterfaceExn("Answer too short!")
47 (plen, ipa_proto, osmo_proto) = struct.unpack(">HBB", data[:4])
48 if (plen + 3 > len(data)):
49 self.err('Warning: Wrong payload length', expected=plen, got=len(data)-3)
50 if (ipa_proto != 0xee or osmo_proto != 0):
51 raise CtrlInterfaceExn("Wrong protocol in answer!")
52 return data[4:plen+3], data[plen+3:]
53
54 def connect(self):
55 self.dbg('Connecting')
56 self.sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
57 self.sck.connect((self.host, self.port))
58 self.sck.setblocking(1)
59
60 def disconnect(self):
61 self.dbg('Disconnecting')
62 if self.sck is not None:
63 self.sck.close()
64
65 def _send(self, data):
66 self.dbg('Sending', data=data)
67 data = self.prefix_ipa_ctrl_header(data)
68 self.sck.send(data)
69
70 def receive(self, length = 1024):
71 return self.sck.recv(length)
72
73 def do_set(self, var, value, id=0):
74 setmsg = "SET %s %s %s" %(id, var, value)
75 self._send(setmsg)
76
77 def do_get(self, var, id=0):
78 getmsg = "GET %s %s" %(id, var)
79 self._send(getmsg)
80
81 def __enter__(self):
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +020082 super().__enter__()
Neels Hofmeyr3531a192017-03-28 14:30:28 +020083 self.connect()
84 return self
85
86 def __exit__(self, *exc_info):
87 self.disconnect()
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +020088 super().__exit__(*exc_info)
Neels Hofmeyr3531a192017-03-28 14:30:28 +020089
90# vim: expandtab tabstop=4 shiftwidth=4