예제 #1
0
def subscribe_to_alarms(alarms, settings):
	# Did we subscribe to even one alarm?
	success = False
	# Connect to the server
	t = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	t.settimeout(RESPONSE_TIMEOUT)
	t.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	t.bind((settings['address'], settings['port']))
	t.connect((settings['server_address'], settings['server_port']))

	# Ask the server to subscribe us for each alarm
	for alarm in alarms:
		command_string = Commands.create_command_string(('B', alarm))
		t.send(command_string)
		Log.debug('Subscription request for alarm "%s" sent.' % alarm)
		# Receive data
		command_string = t.recv(BUFFER_SIZE)
		# Print the command
		Log.debug('Got response "%s"' % command_string)
		# Parse the command
		command = Commands.parse_command(command_string)

		if command[0] == 'FB':
			Log.debug('Already subscribed to alarm "%s".' % alarm)
			success = True
		elif command[0] == 'S':
			Log.debug('Successfully subscribed to alarm "%s".' % alarm)
			success = True
		elif command[0] == 'FN':
			Log.error('Server says alarm "%s" does not exist.' % alarm)
		else:
			Log.error('Unable to parse response from server.')

	t.close()
	return success
예제 #2
0
def listen(settings):
	# Create a socket and listen for packets
	sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	sock.bind((settings['address'], settings['port']))
	sock.listen(1)
	Log.debug('Listening on port %i' % settings['port'])
	# This is our main listening thread
	while True:
		# Accept incoming connection
		connection, address = sock.accept()
		server = address[0] + ':' + str(address[1])
		Log.debug('Connection from %s' % server)
		# Receive data
		command_string = connection.recv(BUFFER_SIZE)
		# Print the command
		Log.debug('Received command %s from %s.' % (command_string, server))
		# Parse the command
		command = Commands.parse_command(command_string)
		response = 'E general'
		if command:
			response = Commands.create_command_string(('F', command[1]))
			# Handle the alarm
			if command[0] == 'A':
				Log.debug('Alarm %s triggered.', command[1])
				result = dispatch_alarm(command[1])
				# Success
				if result:
					response = Commands.create_command_string(('S', command[1]))
			# Invalid command
			else:
				Log.error('Invalid command "%s" from server.', command[0])
		# Invalid command
		else:
			Log.error('Invalid command from server.')
		connection.send(response)
		# Close the connection from the server
		connection.close()
	# Close the socket
	sock.close()
예제 #3
0
	def receive(self):
		return Commands.parse_command(self.socket.recv(self.buffer_size))