1 # -*- coding: utf-8 -*-
4 # DATA interface implementation
6 # (C) 2017-2019 by Vadim Yanitskiy <axilirator@gmail.com>
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2 of the License, or
13 # (at your option) any later version.
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
22 from udp_link
import UDPLink
23 from data_msg
import *
25 class DATAInterface(UDPLink
):
26 def __init__(self
, *udp_link_args
):
27 # Default header version (legacy)
30 UDPLink
.__init
__(self
, *udp_link_args
)
31 log
.debug("Init TRXD interface (%s)" % self
.desc_link())
33 def set_hdr_ver(self
, ver
):
34 if not ver
in Msg
.KNOWN_VERSIONS
:
40 def pick_hdr_ver(self
, ver_req
):
41 # Pick a version that is lower or equal to ver_req
42 for ver
in Msg
.KNOWN_VERSIONS
[::-1]:
46 # No suitable version found
49 def match_hdr_ver(self
, msg
):
50 if msg
.ver
== self
._hdr
_ver
:
53 log
.error("(%s) Rx DATA message (%s) with unexpected header "
54 "version %u (!= expected %u), ignoring..."
55 % (self
.desc_link(), msg
.desc_hdr(),
56 msg
.ver
, self
._hdr
_ver
))
59 def recv_raw_data(self
):
60 data
, _
= self
.sock
.recvfrom(512)
63 def recv_tx_msg(self
):
64 # Read raw data from socket
65 data
= self
.recv_raw_data()
67 # Attempt to parse a TRXD Tx message
70 msg
.parse_msg(bytearray(data
))
72 log
.error("Failed to parse a TRXD Tx message "
73 "from R:%s:%u" % (self
.remote_addr
, self
.remote_port
))
76 # Make sure the header version matches
77 # the configured one (self._hdr_ver)
78 if not self
.match_hdr_ver(msg
):
83 def recv_rx_msg(self
):
84 # Read raw data from socket
85 data
= self
.recv_raw_data()
87 # Attempt to parse a TRXD Rx message
90 msg
.parse_msg(bytearray(data
))
92 log
.error("Failed to parse a TRXD Rx message "
93 "from R:%s:%u" % (self
.remote_addr
, self
.remote_port
))
96 # Make sure the header version matches
97 # the configured one (self._hdr_ver)
98 if not self
.match_hdr_ver(msg
):
103 def send_msg(self
, msg
, legacy
= False):
105 # Validate and encode a TRXD message
106 payload
= msg
.gen_msg(legacy
)
107 except ValueError as e
:
108 log
.error("Failed to encode a TRXD message ('%s') "
109 "due to error: %s" % (msg
.desc_hdr(), e
))
110 # TODO: we may want to send a NOPE.ind here