Module: AutomateEm::DatagramServer

Defined in:
lib/automate-em/device/datagram_server.rb

Instance Method Summary collapse

Instance Method Details

#add_device(scheme, device) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/automate-em/device/datagram_server.rb', line 85

def add_device(scheme, device)

	res = ResolverJob.new(scheme.ip)
	res.callback {|ip|
		@devices["#{ip}:#{scheme.port}"] = device
		@ips["#{scheme.ip}:#{scheme.port}"] = ip
	}
	res.errback {|error|
		@devices["#{scheme.ip}:#{scheme.port}"] = device
		@ips["#{scheme.ip}:#{scheme.port}"] = scheme.ip
		
		EM.defer do
			System.logger.info error.message + " adding UDP #{scheme.dependency.actual_name} @ #{scheme.ip} in #{scheme.control_system.name}"
		end
	}

end

#do_send_data(scheme, data) ⇒ Object

Additional controls



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/automate-em/device/datagram_server.rb', line 59

def do_send_data(scheme, data)
	res = ResolverJob.new(scheme.ip)
	res.callback {|ip|
		
		#
		# Just in case the address is a domain name we want to ensure the
		#	IP lookups are always correct and we are always sending to the
		#	specified device
		#
		text = "#{scheme.ip}:#{scheme.port}"
		old_ip = @ips[text]
		if old_ip != ip
			device = @devices.delete("#{old_ip}:#{scheme.port}")
			@ips[text] = ip
			@devices["#{ip}:#{scheme.port}"] = device
		end
		
		send_datagram(data, ip, scheme.port)
	}
	res.errback {|error|
		EM.defer do
			System.logger.info error.message + " calling UDP send for #{scheme.dependency.actual_name} @ #{scheme.ip} in #{scheme.control_system.name}"
		end
	}
end

#initialize(*args) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/automate-em/device/datagram_server.rb', line 23

def initialize *args
	super
	
	if !$datagramServer.nil?
		return
	end
	
	$datagramServer = self
	@devices = {}
	@ips = {}
	
	EM.defer do
		System.logger.info 'datagram server is now running'
	end
end

#receive_data(data) ⇒ Object

Eventmachine callbacks



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/automate-em/device/datagram_server.rb', line 43

def receive_data(data)
	#ip = get_peername[2,6].unpack "nC4"
	port, ip = Socket.unpack_sockaddr_in(get_peername)
	begin
		@devices["#{ip}:#{port}"].do_receive_data(data)
	rescue => e
		EM.defer do
			System.logger.info e.message + "\nDatagram receive failed..."
		end
	end
end

#remove_device(scheme) ⇒ Object



103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/automate-em/device/datagram_server.rb', line 103

def remove_device(scheme)
	EM.schedule do
		begin
			ip = @ips.delete("#{scheme.ip}:#{scheme.port}")
			@devices.delete("#{ip}:#{scheme.port}")
		rescue => e
			EM.defer do
				System.logger.info e.message + " removing UDP #{scheme.dependency.actual_name} @ #{scheme.ip} in #{scheme.control_system.name}"
			end
		end
	end
end