Commit 4ff18cab authored by Philipp Gast's avatar Philipp Gast
Browse files

syncFigFormatRawData also implementet now. now let the bug hunting begin...

parent db624575
......@@ -3,27 +3,44 @@ import pickle
from .signal import Signal,Query,Status,Answer
debug = True
from . import DBUG,WARN,SPCE,SEVR,INFO
class MplClient2():
def __init__(self,con):
self.host,self.port = con # give (IP,PORT)
self.currentRemoteData = []
def __init__(self):
self.sock = socket(AF_INET,SOCK_STREAM)
self.sock.connect(con)
self.host,self.port = (None,None)
# just a list of names
self.currentRemoteData = []
#~ def reset_connection(self,new_con=(self.host,self.port)):
#~ # shutdown
#~ self.sock.shutdown()
#~ self.sock.close()
#~ # start-up
#~ self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#~ self.sock.connect(con)
def connect(self,con):
self.host,self.port = con # give (IP,PORT)
self.sock = socket(AF_INET,SOCK_STREAM)
self.sock.connect(con)
self.connected = True
def disconnect(self):
''' shutdown socket. Warning: If server and client are local the client can not shut down the port because the server has still a handle on it'''
print('closing the connection...')
#~ self.sock.shutdown(socket.SHUT_WR)
self.sock.close()
self.connected = False
print('closing the connection... DONE')
def reset_connection(self,new_con = None):
self.disconnect()
if new_con is not None :
self.connect(con)
else : # try to use the old values
if (self.host is not None) and (self.port is not None) :
self.connect((self.host,self.port))
else :
print('connection not initialized with correct values:')
print('please provide host,port. currently host: ',self.host,' , port:',self.port)
def send(self,sig):
# pickel the signal
# send the str
......@@ -80,32 +97,26 @@ class MplClient2():
statusSig = self.waitForSignal()
return self.testStatusSig(query,statusSig)
def listRemoteData(self):
""" The server retuns a list with the content of its G_RAWDATA """
pass
def newSyncFigure(self, figname, dataname,*args,**kwargs) :
'''
Send a query NEWSYNCFIGURE to the server
wait for the status.
if status ok then sync.
'''
# create a Signal of type Query with args
query = Query(Query.NEWSYNCFIGURE,{'figClassName' : figname, "dataName" : dataname, 'args' : args, 'kwargs' : kwargs})
status = self.send(query)
if not status :
'''
Send a query NEWSYNCFIGURE to the server
wait for the status.
if status ok then sync.
'''
# create a Signal of type Query with args
query = Query(Query.NEWSYNCFIGURE,{'figClassName' : figname.__name__, "dataName" : dataname, 'args' : args, 'kwargs' : kwargs})
status = self.send(query)
if not status :
print('something went wrong with the sending of newSincFigure request...')
statusSig = self.waitForSignal()
return self.testStatusSig(query,statusSig)
#~ if statusSig.value :
#~ # create Figure with args
#~ if created
#~ # create a signal of type status (True)
#~ status = Status(True)
#~ else:
#~ # create a signal of type status (False)
#~ status = Status(False)
#~ sendSignal(status)
#~ else:
#~ # do not create the figure.
#~ print statusSig.error
statusSig = self.waitForSignal()
if self.testStatusSig(query,statusSig) :
fig = figname(dataname,*args,**kwargs)
return fig
#~ def updateSyncFigure()
#~ '''
......@@ -145,19 +156,38 @@ class MplClient2():
#~ # delete local figure.
#~ else:
#~ print statusSig.error
#~
#~ def formatSyncFigure()
#~ '''
#~ Send a FORMAT_SYNC_FIGURE query to the server.
#~ wait for the answer
#~ if answer not empty then set data to answer's value.
#~ '''
#~ # create signal with args
#~ query = Query(Query.FORMAT_SYNC_FIGURE)
#~ sendSignal(query)
#~ answerSig = waitForSIgnal()
#~ if answerSig.value is not None:
#~ # set the figure data to answerSig.value
#~ else:
#~ # print answerSig.error
#~
# SYNC FIGURE FORMAT RAWDATA ---------------------------------------
def syncFigFormatRawData(self, syncID):
''' Send a FORMAT_SYNC_FIGURE query to the server.
wait for the answer
if answer not empty then set data to answer's value.
'''
# Send the signal with syncID
signal = Query(Query.SYNCFIGFORMATRAWDATA,syncID)
status = self.send(signal)
if debug:
if not status:
print(INFO+'Sent Signal')
formatedData = self.waitForSignal()
if not isinstance(formatedData,Answer) :
print(WARN + 'The server could not format the rawdata.')
if isinstance(formatedData,Status) :
if formatedData.value :
print('This should not happen')
else :
print('instead if answer a error was received')
datas = (None,)
else :
status = self.send(Signal(True,'Answer received'))
if status :
rt = self.waitForSignal()
# set the figure data to answerSig.value
return datas
......@@ -454,7 +454,7 @@ class MplServer():
datas = ()
for ax in fig.get_axes():
# ax.data is any user defined object
# ax.packFormatteata returns it's string representation
# ax.packFormattedData returns it's string representation
# to be unpacked by ax.unpackFormattedData
# datas.append(ax.packFormattedData(ax.data))
datas = datas + (ax.data,)
......
......@@ -6,16 +6,25 @@ from .signal import Signal,Status,Query,Answer
from . import SERVER_IOFUNCTIONS
from . import SERVER_FIGURES
from . import MyFig
from . import DBUG,WARN,SPCE,SEVR,INFO
G_RAWDATA = dict()
G_FIGURES = dict()
DEBUG = True
debug = True
class MplHandler(SocketServer.StreamRequestHandler):
def servPrint(self,x) :
def servPrint(self,x) : # This should be replaced with a proper implementation (s.b.) ?
print("SERVER: "+x)
def dprint(*args): #likewise for WARN,SPCE,SEVR,INFO :wprint,sprint,sevprint,iprint ?
argsl = list(args)
if type(argsl[0]) is str :
argsl[0] = DBUG + argsl[0]
print(''.join([repr(arg) for arg in argsl]))
def treatReadData(self,content):
'''Treat signals of type readData.
......@@ -53,7 +62,9 @@ class MplHandler(SocketServer.StreamRequestHandler):
FigClass = SERVER_FIGURES[content.get('figClassName')]
args = content.get('args')
kwargs = content.get('kwargs')
datas = content.get('dataName')
datanames = content.get('dataName')
datas = [G_RAWDATA[name] for name in datanames]
# Generate an FigID
FigID = '26042017'
......@@ -62,22 +73,100 @@ class MplHandler(SocketServer.StreamRequestHandler):
G_FIGURES[FigID] = FigClass(datas, **kwargs)
if (DEBUG):
print(INFO+"SERVER: I created the requested Figure")
except:
except Exception as e:
if (DEBUG):
print(WARN+"SERVER: I could not create the requested Figure.")
print(SPCE+"SERVER: I tried: "+str(FigClass.__name__)+'('+str(datas)+', '+str(kwargs)+')')
return Status(False, "I could not create the requested Figure. I tried: "+str(FigClass.__name__)+'('+str(datas)+', '+str(kwargs)+')')
print(SPCE+"SERVER: Exception details where:",e.message, e.args )
return Status(False, "I could not create the requested Figure. I tried: "+str(FigClass.__name__)+'('+str(datas)+', '+str(kwargs)+')'+" Exception details where:"+str(e.message)+str(e.args))
if FigID in G_FIGURES :
return Status(True,"SERVER: I created the requested Figure with following instructions"+str(FigClass.__name__)+str(datas)+'('+str(args)+', '+str(kwargs)+')')
return False #should never get here
def treatUpdateSyncFigure(content) :
pass
def treatSyncFigFormatRawData(content):
def treatUpdateSyncFigure(self,content) :
pass
def treatSyncFigFormatRawData(self,figID):
# Identify the figure
fig = G_FIGURES.get(figID,None)
if fig is None :
if DEBUG:
print(WARN+"The figure ID: "+figID+" does not exist.")
return Status(False,"The figure ID: "+figID+" does not exist.")
elif isinstance(fig,MyFig) :
if DEBUG :
print('Figure ',figID,' found in database')
# Format the rawdata
try:
fig.formatRawData()
except Exception as e:
if DEBUG:
print(WARN+"I couldn't format the rawdata.")
print(SPCE+"SERVER: Exception details where:",e.message, e.args )
return Status(False,"I couldn't format the rawdata. Exception details where:",e.message, e.args)
# compose the answer
datas = ()
for ax in fig.get_axes():
# ax.data is any user defined object
# ax.packFormattedData returns it's string representation
# to be unpacked by ax.unpackFormattedData
# datas.append(ax.packFormattedData(ax.data))
datas = datas + (ax.data,)
answer = Answer(datas)
# Send the packed Formatted data
status = self.send(answer)
# If failed
if not status:
print('sending answer to request SYNCFIGFORMATRAWDATA failed')
# Wait for the client receipt
status = self.waitForReceipt(conn)
return Status(True,'round trip complet')
def send(self,sig):
# pickel the signal
# send the str
wf = self.server.socket.makefile(mode='wb')
if debug:
print('sending ',type(sig),' with content \"',sig.content,'\"')
try :
pickle.dump(sig,wf)
except Exception as e:
if DEBUG:
print(SPCE+"SERVER: Exception details where:",e.message, e.args )
return False
wf.close()
return True
def waitForSignal(self):
# wait for signal
# unpickel
rf = self.server.socket.makefile(mode='rb')
try :
response = pickle.load(rf)
if DEBUG and isinstance(response,Signal):
print('CLIENT Received: {} with content \"{}\"'.format(type(response),response.content))
except EOFError :
print('no answer received - or connection closed unexpectedly')
response = None
except Exception as e:
print('unknown error while waiting for response')
print(SPCE+"SERVER: Exception details where:",e.message, e.args )
response = None
rf.close()
if isinstance(response,Signal) :
return response
def treatSig(self,sig):
if isinstance(sig,Query) :
if sig.queryType == sig.READDATA :
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment