Passed
Push — master ( e96c3d...44474a )
by Ian
06:20
created

build.rsudp.c_forward   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 47
dl 0
loc 75
rs 10
c 0
b 0
f 0
wmc 14

2 Methods

Rating   Name   Duplication   Size   Complexity  
B Forward.__init__() 0 27 8
B Forward.run() 0 28 6
1
import os, sys
2
import socket as s
3
from rsudp import printM, printW, printE
4
import rsudp.raspberryshake as rs
5
6
class Forward(rs.ConsumerThread):
7
	"""
8
	Single-destination data forwarding. This consumer reads
9
	queue messages from the :class:`rsudp.c_consumer.Consumer`
10
	and forwards those messages to a specified address and port.
11
12
	:param str addr: IP address to pass UDP data to
13
	:param str port: network port to pass UDP data to (at specified address)
14
	:param cha: channel(s) to forward. others will be ignored.
15
	:type cha: str or list
16
	:param queue.Queue q: queue of data and messages sent by :class:`rsudp.c_consumer.Consumer`
17
	"""
18
19
	def __init__(self, addr, port, cha, q):
20
		"""
21
		Initializes data forwarding module.
22
		
23
		"""
24
		super().__init__()
25
26
		self.sender = 'Forward'
27
		self.queue = q
28
		self.addr = addr
29
		self.port = port
30
		self.chans = []
31
		cha = rs.chns if (cha == 'all') else cha
32
		cha = list(cha) if isinstance(cha, str) else cha
33
		l = rs.chns
34
		for c in l:
35
			n = 0
36
			for uch in cha:
37
				if (uch.upper() in c) and (c not in str(self.chans)):
38
					self.chans.append(c)
39
				n += 1
40
		if len(self.chans) < 1:
41
			self.chans = rs.chns
42
		self.running = True
43
		self.alive = True
44
45
		printM('Starting.', self.sender)
46
47
	def run(self):
48
		"""
49
		Gets and distributes queue objects to another address and port on the network.
50
		"""
51
		printM('Opening socket...', sender=self.sender)
52
		socket_type = s.SOCK_DGRAM if os.name in 'nt' else s.SOCK_DGRAM | s.SO_REUSEADDR
53
		sock = s.socket(s.AF_INET, socket_type)
54
55
		printM('Forwarding %s data to %s:%s' % (self.chans, self.addr, self.port),
56
			   sender=self.sender)
57
58
		try:
59
			while self.running:
60
				p = self.queue.get()	# get a packet
61
				self.queue.task_done()	# close the queue
62
63
				if 'TERM' in str(p):	# shutdown if there's a TERM message on the queue
64
					self.alive = False
65
					printM('Exiting.', self.sender)
66
					sys.exit()
67
68
				if rs.getCHN(p) in self.chans:
69
					sock.sendto(p, (self.addr, self.port))
70
71
		except Exception as e:
72
			self.alive = False
73
			printE('%s' % e, sender=self.sender)
74
			sys.exit(2)
75
76