def main(): client = Redis(host="127.0.0.1", db=2) bot = QQ() if True: # if not reload_login_state(client, bot): ok, message = bot.login_by_qrcode() if not ok: logging("Login failed: %s", message) return try: bot_handler = MsgHandler(bot) while True: time.sleep(0.5) try: new_msg = bot.check_msg() print "message: ", new_msg except socket.timeout as ex: logging.warning("check msg timeout, retrying... %s", ex) continue if new_msg is not None: bot_handler.handle(new_msg) except KeyboardInterrupt: logging.info("Stop Bot. Logout.") finally: dump_login_state(client, bot) logging.info("Dump login state... OK")
def toBeCH(self): listNodeNoCH = [] for i in range(len(self.network)): NodeCH = False for j in range(len(self.clusterH)): if self.network[i][0][0] == self.clusterH[j][0]: NodeCH = True if NodeCH == False and self.alive(self.network[i][0][0]) == 1: listNodeNoCH.append(self.network[i]) if len(listNodeNoCH) == 0: listNodeNoCH = copy.deepcopy(self.network) self.clusterH[:] = [] print('lisnoch') print(listNodeNoCH) e = listNodeNoCH[0][0][1] print("ener", e) coorCH = listNodeNoCH[0][0][2] for i in range(len(listNodeNoCH)): if listNodeNoCH[i][0][1] >= e: self.adrrCH = listNodeNoCH[i][0][0] e = listNodeNoCH[i][0][1] coorCH = listNodeNoCH[i][0][2] self.clusterH.append([self.adrrCH, e]) print(self.clusterH) msgHandler = MsgHandler() print(coorCH) msgCH = msgHandler.Encode_CH_Change_Msg(self.adrrCH, e, coorCH) print("New Cluster Head :", self.adrrCH, e) return self.adrrCH, msgCH
def __init__(self, host, socket, addr): asyncore.dispatcher.__init__(self, socket) self.host = host self.unit_id = "unknown" self.msgHandler = MsgHandler() self.outbox = collections.deque() self.last_write = time.time()
def receive(self,addr_source, port_source): code=0 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((addr_source, port_source)) s.setblocking(0) msgHandler=MsgHandler() #a=time.time() #time.sleep(5) #b=time.time() #print b-a lastSend=time.time() start_time=lastSend number_node_activated=0 while True: try: #time.sleep(1) #print str(time.time()-lastSend) if (time.time()-lastSend)>COMMUNICATION_TIMEOUT and self.HasInit==True and lastSend!=start_time: print 'lost connection with cluster head for : ' + str(time.time()-lastSend) self.Change_to_spare_CH() print 'change to spare cluster head: '+ str(self.clusterHead) msg=msgHandler.Encode_CH_Change_Msg(self.clusterHead[0],self.clusterHead[1],self.clusterHead[2]) for eachNode in self.network: code=self.send(eachNode[0], PORT, msg) lastSend=time.time() print 'Reset lastSend time: ' +str (lastSend) data, addr = s.recvfrom(1024) #print 'received' + data type_msg=msgHandler.Decode(data) if type_msg==1: temp,code=msgHandler.Decode_CH_Change_Msg(data) if code==0: self.clusterHead=temp self.RefreshNetwork(temp) print '******************************' print 'received: ' + str(temp) print 'CH changed:' print self.clusterHead else: print "error in decoding CH change msg." elif type_msg==2: temp,code=msgHandler.Decode_List_Info_Msg(data) if code==0: self.network=temp self.clusterHead=temp[0] lastSend=time.time() print 'Received network info: ' print str(self.network) print ' ' else:
def init(self): self.handler = MsgHandler() self.ttsPlayer = TtsPlayer() self.speechProcess = SpeechProcess() self.serverProcess = ServerProcess() ret = self.ttsPlayer.init() if ret: self.ttsPlayer.speak("你好,我是歐拉蜜", None) ret = self.speechProcess.init(self.handler) if ret: ret = self.serverProcess.init(self.handler) return ret
def setUp(self): self.valid_buff = bytearray.fromhex( "404039003247512d313630313030383803201000010f0000002d0703110f1b390703110f1b030c549e3d0c2aec200200000000000034080d0a" ) self.invalid_buff = bytearray.fromhex("404036") self.msgHandler = MsgHandler() self.valid_unit_id = "unknown" self.valid_box = collections.deque() host = Mock() socket = Mock() addr = Mock() self.client = Client(host, socket, addr)
def receive(self, addr_source, port_source): print 'thread start' code = 0 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((addr_source, port_source)) msgHandler = MsgHandler() while True: data, addr = s.recvfrom(1024) print 'received' + data type_msg = msgHandler.Decode(data) if type_msg == 1: temp, code = msgHandler.Decode_CH_Change_Msg(data) if code == 0: self.clusterHead = temp self.RefreshNetwork(temp) print 'CH changed:' + self.clusterHead else: print "error in decoding CH change msg." elif type_msg == 2: temp, code = msgHandler.Decode_List_Info_Msg(data) if code == 0: self.network = temp print self.network else: print "error in decoding list of info msg" elif type_msg == 3: temp, code = msgHandler.Decode_Info_Msg(data) if code == 0: print '-----------------3.--------' Ischanged = self.RefreshNode(temp) print temp print Ischanged else: print 'Error in decoding info msg' elif type_msg == 4: temp, code = msgHandler.Decode_Sensor_Data(data) if code == 0: self.allSensorData = self.allSensorData + temp with self.networkLock: for i in range(len(self.network)): if self.network[i][0][0] == self.addrCH: self.network[i][0][3] = time.time() print temp else: print 'Error in decoding sensor data' elif type_msg == 0: print 'error in decode message'
def init(self): self.handler = MsgHandler() self.ttsPlayer = TtsPlayer() self.speechProcess = SpeechProcess() ret = self.ttsPlayer.init() if ret: ret = self.speechProcess.init(self.handler) while not self.speechProcess.check_connectivity( 'http://www.google.com.tw'): self.ttsPlayer.speak("網路連線中", None) time.sleep(3) nliResult = self.speechProcess.nlp.getNliResult("你好") self.ttsPlayer.speak("你好,我是歐拉蜜", None) return ret
def initReceive(self): code=0 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(('', PORT)) msgHandler=MsgHandler() while True: data, addr = s.recvfrom(1024) #print 'received' + data type_msg=msgHandler.Decode(data) if type_msg==1: temp,code=msgHandler.Decode_CH_Change_Msg(data) if code==0: judge = self.calculateCoor(temp[2], self.coordinate) if judge: self.clusterHead=temp self.RefreshNetwork(temp) print '******************************' print 'Received: CH change message: ' + str(temp) else: newInfo = [self.addr, self.energy, self.coor] self.clusterHead = newInfo self.RefreshNetwork(newInfo) print '******************************' print 'Received: CH change message: ' + str(newInfo) print ' ' print 'CH is changed to: ' + str(self.clusterHead) print ' ' else: print "Error in decoding CH change msg." print ' ' s.close() break elif type_msg==5: addr_des,code=msgHandler.Decode_Broadcast_msg(data) if code==0: print '******************************' print 'Received broadcast from:' + addr_des print 'Own address' + self.addr msg=msgHandler.Encode_Info_Msg(self.addr,self.energy,self.coordinate) IsSent = self.send(addr_des, PORT,msg) else: print 'Error in decoding broadcast message.' print ' ' return code
def run(socket, instances, access_rights, coder): print("ClientManager starting..") msg_handler = MsgHandler(instances) while True: try: print("Waiting msg") received_msg = get_msg(socket, coder) print("Received request '" + str(list(received_msg.keys())[0]) + "' from " + str(socket)) msg_for_client = msg_handler.handle(received_msg, access_rights) # print("Msg for client " + str(msg_for_client)) header, body = build_response(msg_for_client, coder) send_msg(socket, header, body) except ConnectionAbortedError: print("Connection lost with " + str(socket)) raise ConnectionAbortedError except Exception as e: print("An error has occurred " + str(e)) msg = build_response(instances, error_msg("ServerError", str(e))) send_msg(socket, *msg) pass
handler = logging.handlers.RotatingFileHandler(WXLOG_FILE, maxBytes = 1024*1024, backupCount = 5) # 实例化handler fmt = '%(asctime)s <%(filename)s><%(lineno)d>: [%(levelname)s] - %(message)s' handler2 = logging.handlers.RotatingFileHandler(MOLOG_FILE, maxBytes = 1024*1024, backupCount = 5) # 实例化handler formatter = logging.Formatter(fmt) # handler.setFormatter(formatter) # handler2.setFormatter(formatter) logger = logging.getLogger('wx') # logger.addHandler(handler) logger.setLevel(logging.DEBUG) logger1 = logging.getLogger('monitor') # logger1.addHandler(handler2) logger1.setLevel(logging.DEBUG) with aiohttp.ClientSession() as client, aiohttp.ClientSession() as rclient: wx = Wechat(client) robot = RobotEngine(rclient, config.apikey) msg = MsgHandler(wx, robot) god = Monitor(wx) tasks = [ wx.sync() , wx.sendmsg() , wx.updategroupinfo() , msg.msgloop() , god.monitor() ] asyncio.get_event_loop().run_until_complete(asyncio.wait(tasks))
if __name__ == '__main__': base = BaseStation() choseCH = time.time() s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: thread.start_new_thread(base.receive, ( '', 14800, )) except: print 'no' time.sleep(1) msgHandler = MsgHandler() msg = msgHandler.Encode_Info_Msg('12', 100, [3, 5]) try: s.sendto(msg, ('127.0.0.1', 14800)) print 'sent:' + msg except: print 'no send' '''finally: s.close()''' msg = msgHandler.Encode_Info_Msg('1', 110, [2, 8]) try: s.sendto(msg, ('127.0.0.1', 14800)) print 'sent:' + msg except: print 'no send'
# -*- coding: utf-8 -*-
if __name__ == '__main__': buff = [] BS = Base_Station() #timerSendMsg = threading.Timer() #buffSize = 10 # for the cluster head beginTime = time.time() timerUpdateHead = time.time() lastSend = time.time() CH_start = 0 # 1: Yes ; 0: No HOST='' try: thread.start_new_thread(BS.receive,(HOST,BS_port,)) except: print 'Thread Create Failed.' MS_Handler=MsgHandler() while (1): pass # judge if current node is cluster node '''if (node.clusterHead[0] == node.addr): if not CH_start: CH_start = 1 timerUpdateHead = time.time() lastSend = time.time() # receive the fake data from sensor if (node.allSensorData!=""): buff.append(node.allSensorData) node.allSensorData = "" #for nodeInfo in node.network:
def receive(self,addr_source, port_source): code=0 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((addr_source, port_source)) msgHandler=MsgHandler() while True: data, addr = s.recvfrom(1024) #print 'received' + data type_msg=msgHandler.Decode(data) if type_msg==1: temp,code=msgHandler.Decode_CH_Change_Msg(data) if code==0: judge = self.calculateCoor(temp[2], self.coordinate) if judge: self.clusterHead=temp self.RefreshNetwork(temp) print '******************************' print 'Received: CH change message: ' + str(temp) else: newInfo = [self.addr, self.energy, self.coor] self.clusterHead = newInfo self.RefreshNetwork(newInfo) print '******************************' print 'Received: CH change message: ' + str(newInfo) print ' ' print 'CH is changed to: ' + str(self.clusterHead) print ' ' else: print "Error in decoding CH change msg." print ' ' elif type_msg==2: temp,code=msgHandler.Decode_List_Info_Msg(data) if code==0: self.network=temp print 'Received: ' + addr_source print self.network else: print "error in decoding list of info msg" elif type_msg==3: temp,code=msgHandler.Decode_Info_Msg(data) if code==0: Ischanged=self.RefreshNetwork(temp) print '******************************' #print temp[0] print 'Received Info msg from: ' + str(temp[0]) print ' ' #print temp #print Ischanged else: print 'Error in decoding info msg' print ' ' elif type_msg==4: temp,code=msgHandler.Decode_Sensor_Data(data) if code==0: self.allSensorData=self.allSensorData+temp print '******************************' print 'Received sensor data: ' + str(temp) print ' ' else: print 'Error in decoding sensor data' print ' ' #TODO: boradcast response elif type_msg==5: addr_des,code=msgHandler.Decode_Broadcast_msg(data) if code==0: print '******************************' print 'Received broadcast from:' + addr_des print ' ' msg=msgHandler.Encode_Info_Msg(self.addr,self.energy,self.coordinate) IsSent = self.send(addr_des, PORT, msg) #print 'IsSent; ' + str(IsSent) else: print 'Error in decoding broadcast message.' print ' ' elif type_msg==0: print 'Error in decode message: ' + data print ' ' #analyze data # connect to the speicified address and port # receive message # analyze message # store important information into the msg # return action status code # 0: success # 1: fail return code