#! /usr/bin/env python3
#-*- coding: utf-8 -*-
#----------------------------------------------------------------------
# python3 /home/scripts_python_tests_capteurs/UDP_server/AQCM05_UDP_server.py
#----------------------------------------------------------------------
from subprocess  import *
import socket
import time

#----------------------------------------------------------------------
def run_cmd(cmd):
	global run_cmd
	try :
		p = Popen(cmd, shell = True, stdout = PIPE, stderr = PIPE)
		
		cmd_retour    = p.communicate()[0]
		chaine_retour = cmd_retour.decode()
		
		p.wait()
		
		run_cmd_return_code = p.returncode
		if ( run_cmd_return_code != 0 ) :
			chaine_retour = "NOK!!!"
			
	except :
		chaine_retour = "NOK!!!"
	
	finally :	
		return chaine_retour

#----------------------------------------------------------------------
def get_only_IP_MAC():
	try:
		cmd1 = "ip addr show wlan0 | grep inet       | awk '{print $2}'"
		ip_str_0 = run_cmd(cmd1)
		if ( ip_str_0 != "NOK!!!" ) :
			ip_str = ip_str_0[0:ip_str_0.index('/')]
			ip_str = ip_str.strip()
			ip_str = ip_str.replace(" ", "")
		else :
			ip_str = "001.002.003.004"
			
	except:
		ip_str = "004.003.002.001"

	try:
		cmd2 = "ip addr show wlan0 | grep link/ether | awk '{print $2}'"
		cmd2 = "cat /sys/class/net/wlan0/address"
		mac_str_0 = run_cmd(cmd2)
		if ( mac_str_0 != "NOK!!!" ) :
			mac_str = mac_str_0.strip()
			mac_str = mac_str.replace(" ", "")
		else :
			mac_str = "01:02:03:04:05:06"
			
	except:
		mac_str = "06:05:04:03:02:01"

	return [ip_str, mac_str]
	
#----------------------------------------------------------------------
localIP     = ""
localPort   = 31559
bufferSize  = 1024

msg_from_scanner = "AQCM05"

IP_MAC = get_only_IP_MAC()
My_IP  = IP_MAC[0]
My_MAC = IP_MAC[1]
My_IP_MAC = IP_MAC[0] + "|" + IP_MAC[1]


UDP_Sonde_Socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)

UDP_Sonde_Socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)


# Bind to address and ip

UDP_Sonde_Socket.bind((localIP, localPort))

print("le serveur UDP de la sonde est actif...")

while(True):

	bytesAddressPair = UDP_Sonde_Socket.recvfrom(bufferSize)

	message = bytesAddressPair[0].decode('utf-8')
	address = bytesAddressPair[1]
	
	if message == msg_from_scanner :
	
		print( My_IP + " -> " + str(address) )
		bytesToSend = str.encode( My_IP_MAC )
		UDP_Sonde_Socket.sendto(bytesToSend, address)
		
	time.sleep(0.100)
	
