macco_cl (Normal User)
Rookie
Messaggi: 34
Iscritto: 27/02/2007
|
Ciao a tutti!
Ho sviluppato due semplici Script Server/Client, illustro in breve il funzionamento in modo che sia più chiaro il mio problema:
Il server rimane sempre in ascolto sul socket in attesa che il client gli invii un messaggio, a messaggio ricevuto si deve solo preoccupare di elaborare il messaggio e inserirlo in un DB.
Il client invece si occupa di testare il funzionamento di una porta seriale e di effettuare una lettura da un dispositivo esterno, se i dati che avevo in precedenza sono cambiati rispetto la lettura attuale allora devo inviare tali dati al server tramite socket.
I due script sembrerebbero essere funzionanti, infatti quando lancio il server e successivamente il client i messaggi inviati dal client arrivano correttamente a server, il problema che ho è che se per 2 minuti (o più tempo) il client non invia nessun dato, perché le letture del dispositivo non hanno subito variazioni dallo stato precedete, e improvvisamente ottengo una lettura con un cambiamento, il client si blocca dandomi errore sul socket di tipo timeout.
Premesso che so che il modo migliore per fare un Client/Server che faccia le cose di cui ho bisogno sarebbe necessario usare i thread vi pregherei ugualmente di aiutarmi.
Sto letteralmente impazzendo dietro questo semplice codice, spero che possiate veramente aiutarmi perché non so proprio capire dove sto sbagliando.
Server:
Codice sorgente - presumibilmente Python |
import socket import json import time import Config_mio import packet import sqlite3 as lite if __name__ == "__main__": """Main function that starts the server""" # Creates TCP socket in the specified IP address and port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((Config_mio.IP_Server_Add, Config_mio.ws_port)) # Starts server, up to 10 clients are queued s.listen(Config_mio.Max_Num_Clients) while True: #try: con = lite.connect('test.db') #print "sono prima di mettermi in ascolto" conn, addr = s.accept() #print "sono dopo ascolto" msg = conn.recv(1024) print "Data value:",msg msg = msg.split(",") if msg[0] == "c": # msg type identification if request_type is c we have a counter people msg print "counter msg" timestamp = msg[1] RbPiId = msg[2] people_in = msg[3] people_out = msg[4] #print msg[2] #print msg[3] #print msg[4] with con: cur = con.cursor() def dataEntry(): cur.execute("CREATE TABLE IF NOT EXISTS Data_Occupancy (ID, TimeStamp, In_Count, Out_Count)") cur.execute("CREATE TABLE IF NOT EXISTS Dynamic_occupancy (ID TEXT PRIMARY KEY, In_Count, Out_Count, sqltime TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL)") cur.execute("CREATE TABLE IF NOT EXISTS Inertial_Data (Platform_Id, Gyro_X_Axis, Gyro_Y_Axis, Gyro_Z_Axis, Acc_X_Axis, Acc_Y_Axis, Acc_Z_Axis, Magn_X_Axis, Magn_Y_Axis, Magn_Z_Axis, Temperature, Pressure, Humidity, Timestamp)") cur.execute("INSERT INTO Data_Occupancy (ID, TimeStamp, In_Count, Out_Count) VALUES(?, ?, ?, ?)",(RbPiId, timestamp, people_in, people_out)) cur.execute("INSERT OR REPLACE INTO Dynamic_Occupancy VALUES (?, ?, ?, CURRENT_TIMESTAMP) ", (RbPiId, people_in, people_out)) #cur.execute("DELETE FROM Dynamic_occupancy WHERE sqltime < datetime('now', '-60 seconds')") con.commit() dataEntry() # Entry data con.close() elif msg[0] == "r": print "range msg",msg[1],msg[2],msg[5] timestamp_r = msg[1] RbPiId_r = msg[2] ranging = msg[5] with con: cur = con.cursor() def dataEntry(): cur.execute("CREATE TABLE IF NOT EXISTS Inertial_Data (Platform_Id, Gyro_X_Axis, Gyro_Y_Axis, Gyro_Z_Axis, Acc_X_Axis, Acc_Y_Axis, Acc_Z_Axis, Magn_X_Axis, Magn_Y_Axis, Magn_Z_Axis, Temperature, Pressure, Humidity, Timestamp)") cur.execute("CREATE TABLE IF NOT EXISTS Ranging (ID, TimeStamp, Ranging_Data_Meters)") cur.execute("CREATE TABLE IF NOT EXISTS Ranging_Dynamic (ID TEXT PRIMARY KEY , TimeStamp, Ranging_Data_Meters, sqltime TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL)") cur.execute("INSERT OR REPLACE INTO Ranging_Dynamic VALUES (?, ?, ?, CURRENT_TIMESTAMP) ", (RbPiId_r, timestamp_r, ranging)) cur.execute("DELETE FROM Ranging_Dynamic WHERE sqltime < datetime('now', '-1 minutes')") con.commit() dataEntry() # Entry data con.close() #except: # print "Errore di connessione" conn.close()
|
Client:
Codice sorgente - presumibilmente Python |
import time, socket, struct, array, json import Client_Axis import sys import serial import os import datetime import re import packet import Config_mio usbport = '/dev/ttyAMA0' h = "/r/n" if __name__=="__main__": """Main function that starts the server""" curr_value = "0000000000" prev_value = "" line = '111111111111111' error_counter = 0 people_in = 0 people_out = 0 txtDate = "" no_updates_counter = 0 while True: ser = None try: # print('1') ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=1) # ser.open() # print('2') for line in ser.read(): line = ser.readline() print(line[6:10]) curr_value = line except: print('Serial error') # print('3') pass finally: if ser: ser.close() try: error_counter += 1 # print('1') response = Client_Axis.Read_Axis_Camera_Occupancy() code = response.code print "CODE VALUE:",code if (code == 200): content = response.read() fields = content.split(",") people_in_refresh = int(re.search(r'\d+', fields[3]).group()) people_out_refresh = int(re.search(r'\d+', fields[4]).group()) # print('2') error_flag = 0 if people_in != people_in_refresh or people_out != people_out_refresh: people_in = people_in_refresh people_out = people_out_refresh try: # Creates TCP socket in the specified IP address and port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect client to the server s.connect((Config_mio.IP_Server_Add, Config_mio.ws_port)) # Create message and send it to server timestamp = str(time.time()) msg = "c"+","+str(timestamp)+","+str(Config_mio.RbPi_Id)+","+str(people_in)+","+str(people_out)+","+"None" s.send(msg) print "sent msg" except socket.error, exc: print "Server connection error 1: %s" % exc pass finally: s.close() else: print "CODE WRONG" except: error_msg = "Error retrieving occupancy from: " + Config_mio.IP_AXIS_Add error_flag = 1 if (error_flag == 1): no_updates_counter = 0 print "Error detected: %s \r\n" % error_msg print error_counter if (error_counter > 200): os.system("sudo reboot") elif (line[6:10] != '1111' and prev_value != curr_value): try: # Creates TCP socket in the specified IP address and port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect client to the server s.connect((Config_mio.IP_Server_Add, Config_mio.ws_port)) timestamp = str(time.time()) # Create message and send it to server msg = "r"+","+str(timestamp)+","+str(Config_mio.RbPi_Id)+","+"None"+","+"None"+","+str(line[6:10]) s.send(msg) print "Message : %s" % msg except socket.error, exc: print "Server connection error 2: %s" % exc pass finally: s.close() else: no_updates_counter += 1 # Send message despite there are no changes in value # This is a heartbeat message of 10 min if (no_updates_counter > 200): no_updates_counter = 0 AXIS_occup = "" prev_value = curr_value # Reboot device every day - routine # We have 4 cases incase we miss few seconds txtDate = str(datetime.datetime.fromtimestamp(time.time())) if (txtDate[11:19] == "00:00:00"): os.system("sudo reboot") if (txtDate[11:19] == "00:00:01"): os.system("sudo reboot") if (txtDate[11:19] == "00:00:02"): os.system("sudo reboot") if (txtDate[11:19] == "00:00:03"): os.system("sudo reboot") # Kill time - 1 sec: Remove it for high speed localisation time.sleep(1)
|
|