blob: ad84e5ae6cf6c91c3110fe15b87a365c1f0c13bd [file] [log] [blame]
Piotr Krysik902f4eb2017-09-19 08:04:33 +02001#!/usr/bin/env python2
2# -*- coding: utf-8 -*-
3
4# GR-GSM based transceiver
5# UDP link implementation
6#
7# (C) 2017 by Vadim Yanitskiy <axilirator@gmail.com>
8#
9# All Rights Reserved
10#
11# This program is free software; you can redistribute it and/or modify
12# it under the terms of the GNU General Public License as published by
13# the Free Software Foundation; either version 2 of the License, or
14# (at your option) any later version.
15#
16# This program is distributed in the hope that it will be useful,
17# but WITHOUT ANY WARRANTY; without even the implied warranty of
18# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19# GNU General Public License for more details.
20#
21# You should have received a copy of the GNU General Public License along
22# with this program; if not, write to the Free Software Foundation, Inc.,
23# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24
25import socket
26import select
27
Vadim Yanitskiy873e44e2017-10-17 06:52:01 +070028class udp_link:
Vadim Yanitskiy473b35b2018-08-10 00:20:03 +070029 def __init__(self, remote_addr, remote_port, bind_addr = '0.0.0.0', bind_port = 0):
Piotr Krysik902f4eb2017-09-19 08:04:33 +020030 self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Vadim Yanitskiyb085a2c2018-08-09 19:20:52 +070031 self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Vadim Yanitskiy473b35b2018-08-10 00:20:03 +070032 self.sock.bind((bind_addr, bind_port))
Piotr Krysik902f4eb2017-09-19 08:04:33 +020033 self.sock.setblocking(0)
34
35 # Save remote info
36 self.remote_addr = remote_addr
37 self.remote_port = remote_port
38
Vadim Yanitskiybf6f6ec2018-08-09 19:17:57 +070039 def __del__(self):
40 self.sock.close()
41
Piotr Krysik902f4eb2017-09-19 08:04:33 +020042 def loop(self):
43 r_event, w_event, x_event = select.select([self.sock], [], [])
44
45 # Check for incoming data
46 if self.sock in r_event:
47 data, addr = self.sock.recvfrom(128)
Vadim Yanitskiy0e246372018-08-09 19:30:39 +070048 self.handle_rx(data.decode(), addr)
Piotr Krysik902f4eb2017-09-19 08:04:33 +020049
Vadim Yanitskiy2adbee42018-08-10 00:51:36 +070050 def desc_link(self):
51 (bind_addr, bind_port) = self.sock.getsockname()
52
53 return "L:%s:%u <-> R:%s:%u" \
54 % (bind_addr, bind_port, self.remote_addr, self.remote_port)
55
Vadim Yanitskiy0e246372018-08-09 19:30:39 +070056 def send(self, data, remote = None):
Piotr Krysik902f4eb2017-09-19 08:04:33 +020057 if type(data) not in [bytearray, bytes]:
58 data = data.encode()
59
Vadim Yanitskiy0e246372018-08-09 19:30:39 +070060 if remote is None:
61 remote = (self.remote_addr, self.remote_port)
Piotr Krysik902f4eb2017-09-19 08:04:33 +020062
Vadim Yanitskiy0e246372018-08-09 19:30:39 +070063 self.sock.sendto(data, remote)
64
65 def handle_rx(self, data, remote):
Piotr Krysik902f4eb2017-09-19 08:04:33 +020066 raise NotImplementedError