コード例 #1
0
def LoRaRec(data,socket,source_address):
    bandera = 0
    mensaje = b""
    tabla = BaseDatos(mode_print)
    my_lora_address = binascii.hexlify(network.LoRa().mac())
    if (mode_print == 1): 
        #print ("DEBUG Server: Content in reception LoRa", data)    # KN: Enable this print to see the content in reception LoRa in debug mode
        print ("DEBUG Server: Source Address in LoRaRec ", source_address)
    if (source_address == ANY_ADDR):
        content2 = str(data)     # Capturing the data, and changing the format
        IPlora,user_raw = content2.split(",")
        if (IPlora == "b'FFFFFFFraspbsend'") or (IPlora == b'FFFFFFFraspberry'):
            if (mode_print == 1): print ("DEBUG Server: It's the raspberry IP")
        if (mode_print == 1): print ("DEBUG Server: IP Lora: ", str(IPlora))
        lenght = len(user_raw)
        userf = user_raw[:lenght - 1]
        if (userf == "broadcast"):     # Message to all users
            message_broadcast = str(IPlora[2:])
            tabla = BaseDatos(mode_print)
            if (mode_print == 1): print ("DEBUG Server: Message Broadcast received", message_broadcast)
            posthandler.broadcast(message_broadcast, mode_print)    # Function to save the broadcast message
        IPloraf = IPlora[4:]
        if (mode_print == 1): print ("DEBUG Server: User ", userf)
        bandera = posthandler.consultat(userf, mode_print)    # Checking if the user is in the database
        if (mode_print == 1): print ("DEBUG Server: Flag ", bandera)
        if bandera == 1:    # The user is in the database, I'm going to respond
            if (mode_print == 1): print ("DEBUG Server: Lora Address ", IPloraf)
            sent, retrans, sent, notsend = swlp.tsend(my_lora_address, socket, my_lora_address, IPloraf, mode_print)    # Function to send a LoRa Message using the protocol
    elif (source_address == my_lora_address[8:]):    # The message is for me, I'm going to save it
        message_raw = data
        #if (mode_print == 1): print ("DEBUG Server: Message in server", message_raw)      # KN: Enable this print to see the message in server in debug mode
        if (mode_print == 2): print ("Receiving message")
        if (message_raw == b"Failed"):
            print ("Reception Failed, Discarding")
        elif (message_raw != b"") and (message_raw != b"Failed"):
            mensajet = str(message_raw)
            print("XXXYYYraw", message_raw)
            # handling sensors data... there must be a better way to send and receive json
            if (mensajet[-10:-1] == "mqttproxy"):
                aaa = mensajet.find("{")
                zzz = mensajet.find("}")
                user_final = "mqttproxy"
                messagef = str(mensajet[aaa:zzz+1])
                idEmisor = str(mensajet[2:aaa-1])
                if (mode_print == 1):
                    print ("Sender: " + idEmisor)
                    print ("Message: " + messagef)    # KN: Enable this print to see the message in debug mode
                    print ("User: "******",")
	            if (mode_print == 1):
	                print ("Sender: " + str(idEmisor[1:]))
	                #print ("Message: " + str(messagef))    # KN: Enable this print to see the message in debug mode
	                print ("User: " + str(user_final))
	            lenght = len(user_final)
	            userf = user_final[:lenght - 1]
	            tabla.ingreso(idEmisor[2:],userf,messagef)    # Function to save the message in the database
コード例 #2
0
def run(post_body, socket, mac, sender, flag_broadcast):
    tabla = BaseDatos()
    ufun.set_led_to(BLUE)
    dest_lora_address = b""
    # PM: extracting data to be sent from passed POST body
    blks = post_body.split("&")
    if DEBUG_MODE: print("DEBUG: Data received from the form: ", blks)
    tbs = str(mac)
    for i in blks:
        v = i.split("=")
        tbs += "," + v[1]
    if DEBUG_MODE: print("DEBUG: tbs: ", tbs)
    loramac, receiver, message = tbs.split(",")
    # AM: Checking where to send the message
    start_search_time = utime.ticks_ms()
    if (flag_broadcast == 1):
        receiver = "broadcast"
    dest_lora_address, m_broadcast = reconocimiento(
        socket, receiver, message,
        flag_broadcast)  #Function to look for the user
    search_time = utime.ticks_ms() - start_search_time
    dest_lora_address2 = dest_lora_address[2:]
    if DEBUG_MODE: print("DEBUG: dest lora address: ", dest_lora_address2)
    if DEBUG_MODE:
        print("DEBUG: Search Destination time: %0.10f mseconds." % search_time)
    if (dest_lora_address != b""):
        start_time = utime.ticks_ms()
        aenvio = str(sender) + "," + str(message) + "," + str(
            receiver)  # AM: When you know where to send the message
        if DEBUG_MODE: print("DEBUG: Payload to be sent: ", aenvio)
        sent, retrans, sent = swlp.tsend(aenvio, socket, mac,
                                         dest_lora_address)
        elapsed_time = utime.ticks_ms() - start_time
        if DEBUG_MODE:
            print("DEBUG: Sent OK, Message time: %0.10f mseconds." %
                  elapsed_time)
        if DEBUG_MODE: print("DEBUG: Retransmisions", retrans)
        if DEBUG_MODE: print("DEBUG: Segments sent:", sent)
        ufun.set_led_to(OFF)
        # PM: creating web page to be returned
        r_content = "<h1>Message sent via LoRa</h1>\n"
        r_content += "\n"
        r_content += tbs + "\n"
        r_content += "\n"
        r_content += "<p><a href='/'>Back to home</a></p>\n"
    elif (m_broadcast == 1):
        # AM: Creating Web Page to be returned
        r_content = "<h1>Message sent to all users via LoRa</h1>\n"
        r_content += "\n"
        r_content += tbs + "\n"
        r_content += "\n"
        r_content += "<p><a href='/'>Back to home</a></p>\n"
    else:
        ufun.set_led_to(OFF)
        r_content = "<h1>Destination Not found\n"
        r_content += "<h1><a href='/'>Back To Home</a></h1>\n"
    return r_content
コード例 #3
0
ファイル: server.py プロジェクト: gie-sakura/msnlora
def LoRaRec(data,socket,source_address):
    bandera=0
    mensaje = b""
    tabla=BaseDatos()
    my_lora_address = binascii.hexlify(network.LoRa().mac())
    print("DEBUG: Content in reception LoRa",data)
    if DEBUG_MODE: print("DEBUG: Source Address in LoRaRec ", source_address)
    if (source_address == ANY_ADDR):
        content2 = str(data) #Capturing the data, and changing the format
        IPlora,user_raw = content2.split(",")
        if(IPlora=="b'FFFFFFFraspbsend'") or (IPlora==b'FFFFFFFraspberry'):
            if DEBUG_MODE: print("DEBUG: It's the raspberry IP")
        if DEBUG_MODE: print("DEBUG: IP Lora: ",str(IPlora))
        lenght = len(user_raw)
        userf = user_raw[:lenght-1]
        if(userf=="broadcast"): #Message to all users
            message_broadcast = str(IPlora[2:])
            tabla=BaseDatos()
            if DEBUG_MODE: print("DEBUG: Message Broadcast received",message_broadcast)
            posthandler.broadcast(message_broadcast) #Function to save the broadcast message
        IPloraf = IPlora[4:]
        if DEBUG_MODE: print("DEBUG: User ", userf)
        bandera=posthandler.consultat(userf) #Checking if the user is in the database
        #bandera=tabla.consultaControl(userf)
        if DEBUG_MODE: print("DEBUG: Flag ", bandera)
        if bandera == 1: #The user is in the database, I'm going to respond
            if DEBUG_MODE: print("DEBUG: Lora Address ", IPloraf)
            sent, retrans,sent = swlp.tsend(my_lora_address, socket, my_lora_address, IPloraf)#Function to send a LoRa Message using the protocol
    elif(source_address== my_lora_address[8:]): #The message is for me, I'm going to save it
        message_raw = data
        if DEBUG_MODE: print("DEBUG: message in server", message_raw)
        if(message_raw !=b""):
            mensajet = str(message_raw)
            idEmisor, messagef,user_final = mensajet.split(",")
            print("Sender: "+str(idEmisor[1:]))
            print("Message: "+str(messagef))
            print("User: "+str(user_final))
            lenght = len(user_final)
            userf = user_final[:lenght-1]
            tabla.ingreso(idEmisor[2:],userf,messagef)#Function to save the message in the database
コード例 #4
0
def consultat(user):
    tabla = BaseDatos()
    bandera = tabla.consultaControl(user)
    print("Consulta")
    #bandera=1
    return bandera
コード例 #5
0
def broadcast(message):  #Function to save a broadcast message
    tabla = BaseDatos()
    tabla.broadcast_message(message)
    print("received")
コード例 #6
0
 def _wait_for_connections(self, s_left, addr, treq):
     # determine request method  (HEAD and GET are supported) (PM: added support to POST )

     request_method = treq.split(' ')[0]
     if (self.modep == 1):
        print ("Method: ", request_method)
        print ("Full HTTP message: -->")
        print (treq)      # KN: Enable this print to see the value of treq in debug mode
        print ("<--")
     treqhead = treq.split("\r\n\r\n")[0]
     print("treqhead:", treqhead)
     treqbody = treq[len(treqhead):].lstrip()      # PM: makes easier to handle various types of newlines
     if (self.modep == 1):
        print ("only the HTTP body: -->")
        print (treqbody)    # KN: Enable this print to see the value of treqbody in debug mode
        print ("<--")
     # split on space "GET /file.html" -into-> ('GET','file.html',...)
     file_requested = treq.split(' ')
     #if(self.modep==1): print("Debug Server: File Requested: ", file_requested)    # KN: Enable this print to see the file requested in debug mode
     if (file_requested == ''):
        file_requested = '/index.html'
     file_requested = file_requested[1] # get 2nd element
     # Check for URL arguments. Disregard them
     file_requested = file_requested.split('?')[0]  # disregard anything after '?'
     if (file_requested == '/'):  # in case no file is specified by the browser
             file_requested = '/index.html' # load index.html by default
     elif (file_requested == '/favicon.ico'):  # most browsers ask for this file...
             file_requested = '/index.html' # ...giving them index.html instead
     file_requested = self.www_dir + file_requested
     if (self.modep == 1): print ("Serving web page ["+file_requested+"]")

# GET method
     if (request_method == 'GET') | (request_method == 'HEAD') :
     ## Load file content
         if (self.modep == 1): print ("file_requested: ", file_requested)
         try:
             gc.collect()
             if (request_method == 'GET' and file_requested =='/flash/registro'):
                 if (self.modep == 1): print ('Regreso del Usuario',self.userR)
                 tabla = BaseDatos(self.modep)
                 response_content,self.userR = tabla.ingresoRegistro(self.userR,1)
                 if (self.modep == 1): print ('Datos Regreso', response_content)
             else:
                 file_handler = open(file_requested,'rb')
                 if (request_method == 'GET'):      # only read the file when GET
                    response_content = file_handler.read()     # read file content
                 file_handler.close()
             response_headers = self._gen_headers(200)
             if (self.modep == 1): print ('response_headers', response_headers)
         except Exception as e:     # in case file was not found, generate 404 page
             error_str = str(e)
             if (error_str[:24] == 'memory allocation failed'):
                print ("Warning, memory allocation failed. Serving response code 500"+" -> "+error_str)
                response_headers = self._gen_headers(500)
                if (request_method == 'GET'):
                    response_content = b"<html><body><p>Error 500: Memory allocation failed</p><p>Python HTTP server</p><p><a href='/'>Back to home</a></p></body></html>"
                else:
                    print ("Warning, file not found from GET. Serving response code 404\n", e)
                    response_headers = self._gen_headers( 404)
                    if (request_method == 'GET'):
                        response_content = b"<html><head><meta charset='utf-8'><title>LoRa</title></head><body><p>Error 404: File not found</p><p>Python HTTP server</p><p><a href='/'>Back to home</a></p></body></html>"
         server_response =  response_headers.encode()      # return headers for GET and HEAD
         if (request_method == 'GET'):
            server_response +=  response_content      # return additional content for GET only
         s_left.send(server_response)
         if (self.modep == 1): print ("Closing connection with client")
         ufun.set_led_to(OFF)
         s_left.close()

# POST method
     elif (request_method == 'POST'):
             ## Load file content
         try:
             if (file_requested.find("execposthandler") != -1):
                 if (self.modep == 1):
                    print ("... PM: running python code")
                    print ("DEBUG Server: lenght message:", len(treqbody))
                 if (len(treqbody) > 25):
                     self.form = treqbody
                     response_content, self.dest_lora_address = posthandler.run(treqbody,self.s_right,self.loramac,self.userR,0, self.modep)
                 else:
	                 if (self.modep == 1): print ("... PM: empty POST received")
	                 response_content = b"<html><body><p>Error: EMPTY FORM RECEIVED, Please Check Again</p><p>Python HTTP server</p><p><a href='/'>Back to home</a></p></body></html>"
             elif (file_requested.find("tabla") != -1):                 
                 if (self.modep == 1): print ("DEBUG Server: Checking Messages")
                 if (self.modep == 2): print ("Checking Messages")
                 if (self.modep == 3): print ("Checking messages")
                 gc.collect()
                 tabla = BaseDatos(self.modep)
                 response_content = tabla.consulta(self.userR)
             elif (file_requested.find("registro") != -1):
                 if (self.modep == 1): 
                    print ("DEBUG Server: Register")
                    print ("DEBUG Server: lenght user:"******"DEBUG Server: treqbody:", treqbody)
                 tabla = BaseDatos(self.modep)
                 if (len(treqbody) > 12 ):
                     response_content,self.userR = tabla.ingresoRegistro(treqbody,0)
                     gc.collect()
                     print ("Register Ok")
                 else:
                     print ("... PM: empty POST received")
                     response_content = b"<html><body><p>Error: Please Choose a username</p><p>Python HTTP server</p><p><a href='/'>Back to home</a></p></body></html>"

             # Handling sensors data: START
             elif (file_requested.find("mqttproxypush") != -1):
                 if (self.modep == 1): 
                    print ("DEBUG Server: MqttProxy PUSH request")
                    print ("DEBUG Server: lenght user:"******"DEBUG Server: treqbody:", treqbody)
                 if (len(treqbody) > 10 ):  # to be adapted!!!
                     print ("MqttProxy PUSH request Ok")
                     response_content = b"<html><body><p>MqttProxy PUSH request</p><p>Python HTTP server</p><p><a href='/'>Back to home</a></p></body></html>"
                 else:
                     print ("MqttProxy request ERROR")
                     response_content = b"<html><body><p>ERROR MqttProxy PUSH request</p><p>Python HTTP server</p><p><a href='/'>Back to home</a></p></body></html>"
                 # value 3 in "broadcast field" indicates that is anycasting, that is the closest with the service    
                 response_content, self.dest_lora_address = posthandler.run(treqbody,self.s_right,self.loramac,self.userR,3, self.modep)
             elif (file_requested.find("mqttproxypop") != -1):                 
                 if (self.modep == 1): 
                    print ("DEBUG Server: MqttProxy POP request")
                    print ("DEBUG Server: lenght user:"******"DEBUG Server: treqbody:", treqbody)
                 if (len(treqbody) > 10 ):  # to be adapted!!!
                     print ("MqttProxy POP request Ok")
                     response_content = b"<html><body><p>MqttProxy POP request</p><p>Python HTTP server</p><p><a href='/'>Back to home</a></p></body></html>"
                 else:
                     print ("MqttProxy request ERROR")
                     response_content = b"<html><body><p>ERROR MqttProxy POP request</p><p>Python HTTP server</p><p><a href='/'>Back to home</a></p></body></html>"
                 gc.collect()
                 tabla = BaseDatos(self.modep)
                 response_content = tabla.consulta("mqttproxy")
             # Handling sensors data: END

             elif (file_requested.find("broadcast") != -1):
                if (self.modep == 1 | self.modep ==2 ): print ("AM: Sending Message Broadcast")
                if (self.modep == 3): print ("Message Broadcast sent")
                gc.collect()
                tabla = BaseDatos(self.modep)
                response_content, self.dest_lora_address = posthandler.run(treqbody,self.s_right,self.loramac,self.userR,1, self.modep)
             elif (file_requested.find("telegram") != -1):
                print ("AM: Telegram Message")
                tabla = BaseDatos(self.modep)
                if (self.modep == 1): print ("DEBUG Server: lenght message:", len(treqbody))
                if (len(treqbody) > 25):
                    response_content, self.dest_lora_address = posthandler.run(treqbody,self.s_right,self.loramac,self.userR,2, self.modep)
                else:
                    print ("... AM: empty POST received")
                    response_content = b"<html><body><p>Error: EMPTY FORM RECEIVED, Please Check Again</p><p>Python HTTP server</p><p><a href='/'>Back to home</a></p></body></html>"
             elif (file_requested.find("resend") != -1):
                    if (self.modep == 1): print ("DEBUG Server: Resending message")
                    response_content = posthandler.resend(self.form, self.s_right, self.loramac, self.userR, self.dest_lora_address, self.modep)
             else:
                 file_handler = open(file_requested,'rb')
                 response_content = file_handler.read()     # read file content
                 file_handler.close()
             response_headers = self._gen_headers(200)
         except Exception as e:      # in case file was not found, generate 404 page
             print ("Warning, file not found. Serving response code 404\n", e)
             response_headers = self._gen_headers(404)
             response_content = b"<html><body><p>Error 404: File not found</p><p>Python HTTP server</p><p><a href='/'>Back to home</a></p></body></html>"

         server_response =  response_headers.encode()       # return headers
         server_response +=  response_content       # return additional content
         s_left.send(server_response)
         if (self.modep == 1): print ("Closing connection with client")
         ufun.set_led_to(OFF)
         s_left.close()
     else:
         print ("Unknown HTTP request method:", request_method)
コード例 #7
0
lora = LoRa(mode=LoRa.LORA,
        frequency=freq,         
        tx_power=tx_pow,               
        bandwidth=band,    
        sf=spreadf,                       
        preamble=prea,               
        coding_rate=cod_rate,
        power_mode=pow_mode,  
        tx_iq=tx_iq_inv,                
        rx_iq=rx_iq_inv,                
        adr=ada_dr,                  
        public=pub,       
        tx_retries=tx_retr,
        region=LoRa.EU868,              
        device_class=dev_class)

# The lopy is configured as an Access Point and HTTP server
my_lora_address = binascii.hexlify(network.LoRa().mac())
lopy_name = "messenger_" + my_lora_address.decode()[-3:]
print ("Network Name: " + lopy_name)
wlan = WLAN()
wlan.init(mode=WLAN.STA_AP, ssid=lopy_name, auth=None, channel=7, antenna=WLAN.INT_ANT)

tabla = BaseDatos(mode_print)    # Instance Class Database

print ("Starting web server")
s = Server(80, mode_print)    # Construct server object
s.activate_server()    # Acquire the socket
s.connectionLoRa()     # Acquire Socket LoRa

s.conexion()
コード例 #8
0
def consultat(user, mode):
    tabla = BaseDatos(mode)
    bandera = tabla.consultaControl(user)
    if DEBUG_MODE: print("Consulta")
    return bandera
コード例 #9
0
def broadcast(message, mode):  # Function to save a broadcast message
    tabla = BaseDatos(mode)
    tabla.broadcast_message(message)
    if DEBUG_MODE: print("received")
    if (VERBOSE_MODE | NORMAL_MODE):
        print("Posthandler: Message Broadcast received")
コード例 #10
0
def run(post_body, socket, mac, sender, flag_broadcast, mode):
    gc.enable()
    gc.collect()
    #    print ("---->mem_free: ", gc.mem_free())
    tabla = BaseDatos(mode)
    DEBUG_MODE, VERBOSE_MODE, NORMAL_MODE = swlp.choose_mode(mode)
    ufun.set_led_to(BLUE)
    dest_lora_address = b""

    # handling mqttproxy data
    if (flag_broadcast == 3):
        loramac = str(mac)
        receiver = "mqttproxy"  # There may be various but we want to get to the closest one (anycasting)
        message = "'" + post_body + "'"
        flag_broadcast = 0  # resetting for unicast
    else:
        # PM: extracting data to be sent from passed POST body
        blks = post_body.split("&")
        print("blks", blks)
        #if DEBUG_MODE: print("DEBUG Posthandler: Data received from the form: ", blks)       # KN: Enable this print to see the value of blks in debug mode
        tbs = str(mac)
        for i in blks:
            v = i.split("=")
            tbs += "," + v[1]
        #if DEBUG_MODE: print("DEBUG Posthandler: tbs: ", tbs)     # KN: Enable this print to see the value of tbs in debug mode
        loramac, receiver, message = tbs.split(",")

    # AM: Checking where to send the message
    start_search_time = utime.ticks_ms()
    if (flag_broadcast == 1):
        receiver = "broadcast"
    dest_lora_address, m_broadcast = reconocimiento(
        socket, receiver, message, flag_broadcast,
        mode)  # Function to look for the user
    search_time = utime.ticks_ms() - start_search_time
    dest_lora_address2 = dest_lora_address[2:]
    if DEBUG_MODE:
        print("DEBUG Posthandler: dest lora address: ", dest_lora_address2)
        print("DEBUG Posthandler: Search Destination time: %0.10f mseconds." %
              search_time)
    if (dest_lora_address != b""):
        start_time = utime.ticks_ms()
        aenvio = str(sender) + "," + str(message) + "," + str(
            receiver)  # AM: When you know where to send the message
        #if DEBUG_MODE: print("DEBUG Posthandler: Payload to be sent: ", aenvio)      # KN: Enable this print to see the value of aenvio in debug mode
        if VERBOSE_MODE:
            print("Destination found")
            print("Sending message")
        sent, retrans, sent, notsend = swlp.tsend(aenvio, socket, mac,
                                                  dest_lora_address, mode)
        elapsed_time = utime.ticks_ms() - start_time
        if notsend == 1:
            if DEBUG_MODE:
                print("DEBUG Posthandler: Message can't be sent. Try again")
            if (VERBOSE_MODE | NORMAL_MODE):
                print("Message can't be sent. Try again")
            ufun.set_led_to(OFF)
            # KN: creating web page to be returned
            r_content = "<h1>Message can't be sent. Try again</h1>\n"
            r_content += "\n"
            r_content += '<form class="form-horizontal well" action="" method="post"><div class="button"><button id="btn" type="submit" onclick=this.form.action="resend.html";document.getElementById("oculta").style.visibility="visible">Resend</button></div>'
            r_content += "\n"
            r_content += '<div id="oculta" style="visibility:hidden">Resending...</div>'
            r_content += "\n"
            r_content += "<p><a href='/registro'>Back to home</a></p>\n"
        else:
            if DEBUG_MODE:
                print(
                    "DEBUG Posthandler: Sent OK, Message time: %0.10f mseconds."
                    % elapsed_time)
                print("DEBUG Posthandler: Retransmisions", retrans)
                print("DEBUG Posthandler: Segments sent:", sent)
            if VERBOSE_MODE: print("Sent OK")
            if NORMAL_MODE: print("Message sent")
            ufun.set_led_to(OFF)
            # PM: creating web page to be returned
            r_content = "<h1>Message sent via LoRa</h1>\n"
            r_content += "\n"
            r_content += tbs + "\n"
            r_content += "\n"
            r_content += "<p><a href='/registro'>Back to home</a></p>\n"
    elif (m_broadcast == 1):
        # AM: Creating Web Page to be returned
        r_content = "<h1>Message sent to all users via LoRa</h1>\n"
        r_content += "\n"
        r_content += tbs + "\n"
        r_content += "\n"
        r_content += "<p><a href='/registro'>Back to home</a></p>\n"
    else:
        ufun.set_led_to(OFF)
        r_content = "<h1>Destination Not found\n"
        r_content += "<h1><a href='/registro'>Back To Home</a></h1>\n"
    return r_content, dest_lora_address
コード例 #11
0
ファイル: server.py プロジェクト: gie-sakura/msnlora
 def _wait_for_connections(self,s_left,addr,treq):
     #determine request method  (HEAD and GET are supported) (PM: added support to POST )
     request_method = treq.split(' ')[0]
     print ("Method: ", request_method)
     print ("Full HTTP message: -->")
     print (treq)
     print ("<--")
     treqhead = treq.split("\r\n\r\n")[0]
     treqbody = treq[len(treqhead):].lstrip() # PM: makes easier to handle various types of newlines
     print ("only the HTTP body: -->")
     print (treqbody)
     print ("<--")

         # split on space "GET /file.html" -into-> ('GET','file.html',...)
     file_requested = treq.split(' ')
     if DEBUG_MODE: print("File Requested: ", file_requested)
     if(file_requested==''):
        file_requested = '/index.html'
     file_requested = file_requested[1] # get 2nd element

         #Check for URL arguments. Disregard them
     file_requested = file_requested.split('?')[0]  # disregard anything after '?'

     if (file_requested == '/'):  # in case no file is specified by the browser
             file_requested = '/index.html' # load index.html by default
     elif (file_requested == '/favicon.ico'):  # most browsers ask for this file...
             file_requested = '/index.html' # ...giving them index.html instead
     file_requested = self.www_dir + file_requested
     print ("Serving web page [",file_requested,"]")

# GET method
     if (request_method == 'GET') | (request_method == 'HEAD') :
    ## Load file content
         try:
             gc.collect()
             print("mem_free: ", gc.mem_free())
             file_handler = open(file_requested,'rb')
             if (request_method == 'GET'):  #only read the file when GET
                 response_content = file_handler.read() # read file content
             file_handler.close()
             response_headers = self._gen_headers( 200)
         except Exception as e: #in case file was not found, generate 404 page
             error_str = str(e)
             if (error_str[:24] == 'memory allocation failed'):
                print ("Warning, memory allocation failed. Serving response code 500"+" -> "+error_str)
                response_headers = self._gen_headers(500)
                if (request_method == 'GET'):
                    response_content = b"<html><body><p>Error 500: Memory allocation failed</p><p>Python HTTP server</p><p><a href='/'>Back to home</a></p></body></html>"
                else:
                    print ("Warning, file not found from GET. Serving response code 404\n", e)
                    response_headers = self._gen_headers( 404)
                    if (request_method == 'GET'):
                        response_content = b"<html><head><meta charset='utf-8'><title>LoRa</title></head><body><p>Error 404: File not found</p><p>Python HTTP server</p><p><a href='/'>Back to home</a></p></body></html>"
         server_response =  response_headers.encode() # return headers for GET and HEAD
         if (request_method == 'GET'):
             server_response +=  response_content  # return additional conten for GET only
         s_left.send(server_response)
         print ("Closing connection with client")
         ufun.set_led_to(OFF)
         s_left.close()

# POST method
     elif (request_method == 'POST'):
             ## Load file content
         try:
             if (file_requested.find("execposthandler") != -1):
                 print("... PM: running python code")
                 if DEBUG_MODE: print("DEBUG: lenght message:",len(treqbody))
                 if (len(treqbody) > 25):
                     response_content = posthandler.run(treqbody,self.s_right,self.loramac,self.userR,0)
                 else:
	                 print("... PM: empty POST received")
	                 response_content = b"<html><body><p>Error: EMPTY FORM RECEIVED, Please Check Again</p><p>Python HTTP server</p><p><a href='/'>Back to home</a></p></body></html>"
             elif (file_requested.find("tabla") != -1):
                 print("AM: Checking Messages")
                 tabla=BaseDatos()
                 response_content = tabla.consulta(self.userR)
             elif (file_requested.find("registro") != -1):
                 print("AM: Register")
                 if DEBUG_MODE: print("DEBUG: lenght user:"******"DEBUG: treqbody:",treqbody)
                 tabla=BaseDatos()
                 if (len(treqbody) > 12 ):
                     response_content,self.userR = tabla.ingresoRegistro(treqbody)
                     print("Register Ok")
                 else:
                     print("... PM: empty POST received")
                     response_content = b"<html><body><p>Error: Please Choose a username</p><p>Python HTTP server</p><p><a href='/'>Back to home</a></p></body></html>"
             elif (file_requested.find("broadcast") != -1):
                print("AM: Sending Message Broadcast")
                tabla=BaseDatos()
                response_content = posthandler.run(treqbody,self.s_right,self.loramac,self.userR,1)
             elif (file_requested.find("telegram") != -1):
                print("AM: Telegram Message")
                tabla=BaseDatos()
                if DEBUG_MODE: print("DEBUG: lenght message:",len(treqbody))
                if (len(treqbody) > 25):
                    response_content = posthandler.run(treqbody,self.s_right,self.loramac,self.userR,2)
                else:
                    print("... AM: empty POST received")
                    response_content = b"<html><body><p>Error: EMPTY FORM RECEIVED, Please Check Again</p><p>Python HTTP server</p><p><a href='/'>Back to home</a></p></body></html>"

             else:
                 file_handler = open(file_requested,'rb')
                 response_content = file_handler.read() # read file content
                 file_handler.close()

             response_headers = self._gen_headers(200)
         except Exception as e: #in case file was not found, generate 404 page
             print ("Warning, file not found. Serving response code 404\n", e)
             response_headers = self._gen_headers(404)
             response_content = b"<html><body><p>Error 404: File not found</p><p>Python HTTP server</p><p><a href='/'>Back to home</a></p></body></html>"

         server_response =  response_headers.encode() # return headers
         server_response +=  response_content  # return additional content
         s_left.send(server_response)
         print ("Closing connection with client")
         ufun.set_led_to(OFF)
         s_left.close()

     else:
         print("Unknown HTTP request method:", request_method)
コード例 #12
0
ファイル: server.py プロジェクト: gie-sakura/msnlora
sd = SD()
os.mount(sd, '/sd')
print("SD Card Enabled")
#Starting LoRa
lora = LoRa(mode=LoRa.LORA,
        frequency=freq,         
        tx_power=tx_pow,               
        bandwidth=band,    
        sf=spreadf,                       
        preamble=prea,               
        coding_rate=cod_rate,
        power_mode=pow_mode,  
        tx_iq=tx_iq_inv,                
        rx_iq=rx_iq_inv,                
        adr=ada_dr,                  
        public=pub,       
        tx_retries=tx_retr,              
        device_class=dev_class)
# AM: Se configura la lopy como punto de Acceso y servidor HTTP
# PM: choosing random name for lopy
lopy_name = "messenger"+str(ufun.random_in_range())
wlan = WLAN(mode=WLAN.STA_AP, ssid=lopy_name)
wlan.init(mode=WLAN.STA_AP, ssid=lopy_name, auth=None, channel=7, antenna=WLAN.INT_ANT)
print("Red Name: "+str(lopy_name))
print ("Starting web server")
tabla=BaseDatos() #Instanciamiento Clase Base de Datos
s = Server(80)  # construct server object
my_lora_address = binascii.hexlify(network.LoRa().mac())
s.activate_server() # Acquire the socket
s.connectionLoRa() #Acquire Socket LoRa
s.conexion()