Пример #1
0
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")
Пример #2
0
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")
Пример #3
0
    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
Пример #4
0
 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()
Пример #5
0
    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)
Пример #6
0
    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
Пример #7
0
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
Пример #8
0
    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
Пример #9
0
    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 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:
Пример #11
0
    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
Пример #12
0
    def __init__(self, name=None, comPkg=None):
        gLog.print("Throttle {0}: initializing".format(name))

        assert isinstance(name, str)

        assert isinstance(comPkg, CommunicationsPackage)
        inQu = comPkg.inQu
        inQuNum = comPkg.inQuNum
        outQu = comPkg.outQu

        assert isinstance(inQu, multiprocessing.queues.Queue)
        assert inQuNum >= 0
        assert isinstance(outQu, multiprocessing.queues.Queue)

        self.name = name
        self.virtSlot = None
        self.direction = kForward
        self.lights = kOff
        self.horn = kOff
        self.bell = kOff
        self.mute = kOff
        self.F5 = 0  # Flip this to close next turnout
        self.F6 = 0  # Flip this ot throw next turnout
        self.msgHandler = MsgHandler(name=self.name, comPkg=comPkg)
Пример #13
0
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'
Пример #14
0
class Throttle(object):
    def __init__(self, name=None, comPkg=None):
        gLog.print("Throttle {0}: initializing".format(name))

        assert isinstance(name, str)

        assert isinstance(comPkg, CommunicationsPackage)
        inQu = comPkg.inQu
        inQuNum = comPkg.inQuNum
        outQu = comPkg.outQu

        assert isinstance(inQu, multiprocessing.queues.Queue)
        assert inQuNum >= 0
        assert isinstance(outQu, multiprocessing.queues.Queue)

        self.name = name
        self.virtSlot = None
        self.direction = kForward
        self.lights = kOff
        self.horn = kOff
        self.bell = kOff
        self.mute = kOff
        self.F5 = 0  # Flip this to close next turnout
        self.F6 = 0  # Flip this ot throw next turnout
        self.msgHandler = MsgHandler(name=self.name, comPkg=comPkg)

    def addInterest(self, interest):
        gLog.print("Throttle {0}: adding interest {1}".format(self.name, interest))
        assert interest in ControllerInMsgs
        self.msgHandler.addInterest(interest)

    def removeInterest(self, interest):
        gLog.print("Throttle {0}: removing interest {1}".format(self.name, interest))
        assert interest in ControllerInMsgs
        self.msgHandler.removeInterest(interest)

    def waitFor(self, msg):
        gLog.print("waitFor: msg = {0}".format(msg))
        assert isinstance(msg, tuple)
        return self.msgHandler.waitFor(msg)

    def close(self):
        gLog.print("Throttle {0}: closing".format(self.name))
        self.msgHandler.close()

    def getBlocking(self):
        msg = self.msgHandler.getBlocking()
        # gLog.print("Throttle {0}: getBlocking msg {1}".format(self.name, msg))
        return msg

    def getNonblocking(self):
        try:
            msg = self.msgHandler.getNonblocking()
            # gLog.print("Throttle {0}: getNonlocking msg {1}".format(self.name, msg))
            return msg
        except multiprocessing.queues.Empty:
            gLog.print("Throttle {0}: getNonlocking empty qu exception".format(self.name))
            raise multiprocessing.queues.Empty

    def put(self, msg):
        self.msgHandler.put(msg)

    def atSpeedGoTo(self, speed, destination, sensorsToExclude):
        self.addInterest(PutTrainPositionMsg)
        self.put(GetTrainPositionMsg(slot=self.virtSlot))
        done = False
        while not done:
            msg = self.waitFor(PutTrainPositionMsg(slot=self.virtSlot, sensors=[]))
            if msg.slot == self.virtSlot:
                self.removeInterest(PutTrainPositionMsg)
                done = True
        fromSensor = msg.sensors[0]
        preSensor = msg.sensors[1]
        path = self.getPath(kBreadthFirst, preSensor, fromSensor, destination, sensorsToExclude)
        self.setSpeed(speed)
        self.followSensorPath(path)

    def waitForTrainToReach(self, sensor):
        # Pre  train is moving
        # Post returns when train reaches the indicated sensor
        method = 1
        if method == 1:
            # Use train position to know when train has reached sensor
            self.addInterest(PutTrainPositionMsg)
            while True:
                msg = self.waitFor(PutTrainPositionMsg(slot=self.virtSlot, sensors=[]))
                if msg.sensors[1] == sensor:
                    break
            self.removeInterest(PutTrainPositionMsg)
        else:
            # Use sensor firing, which has the following defect:
            #   One doesn't know which train fired the sensor
            self.addInterest(PutSensorStateMsg)
            self.waitFor(PutSensorStateMsg(id=sensor, state=kSensorOpen))
            self.removeInterest(PutSensorStateMsg)

    def followCommandPath(self, path):
        """
        A command path is a list of tuples (sensor#, command)
        When the train reaches the sensor, the throttle executes the command.
        """
        previousSensor = 0
        for point in path:
            sensor = point[0]
            command = point[1]
            if sensor != previousSensor:
                previousSensor = sensor
                self.waitForTrainToReach(sensor)
            self.doCommand(command)

    def atSensorDoCommand(self, sensor, command):
        commandPath = [[sensor, command]]
        self.followCommandPath(commandPath)

    def atSensorDoCommands(self, sensor, commands):
        commandPath = []
        for command in commands:
            commandPath.append([sensor, command])
        self.followCommandPath(commandPath)

    def followSwitchPath(self, path):
        """
        A switch path is a list of triples (sensor#, switch#, direction)
        When the train reaches the sensor, the throttle moves the switch.
        """
        previousSensor = 0
        for point in path:
            sensor = point[0]
            switch = point[1]
            direction = point[2]
            if sensor != previousSensor:
                previousSensor = sensor
                self.waitForTrainToReach(sensor)
            self.moveSwitch(switch, direction)

    def followSensorPath(self, path):
        """
        A sensor path is a list or tuple of sensor numbers defining the path which a train
        desires to follow. As the train approaches section (i, i+1),  the throttle makes section (i+1, i+2)
        usable. To get things started, the throttle makes the section (0, 1) usable,
        where i indicates sensor i.
        """
        self.makeSectionUsable(path[0], path[1])
        for i in range(0, len(path) - 2):
            self.waitForTrainToReach(path[i])
            self.makeSectionUsable(path[i + 1], path[i + 2])

    ################################################################################

    def readLayout(self, fileName):
        gLog.print("Throttle {0}: sending DoReadLayoutMsg using file {1}".format(self.name, fileName))
        assert isinstance(fileName, str)
        self.addInterest(PutReadLayoutResponseMsg)
        self.put(DoReadLayoutMsg(fileName=fileName))
        msg = self.waitFor(PutReadLayoutResponseMsg(responseFlag=0, code=0))
        self.removeInterest(PutReadLayoutResponseMsg)
        sleep(3)
        return msg

    def initTrain(self, address, position):
        gLog.print("Throttle {0}: sending DoLocoInitMsg".format(self.name))
        assert 0 <= address <= 9999
        assert isinstance(position, list) or isinstance(position, tuple)
        self.put(DoLocoInitMsg(address=address, sensors=position))
        responseMsg = None
        if position:
            self.addInterest(PutInitOutcomeMsg)
            responseMsg = self.waitFor(PutInitOutcomeMsg(physAdd=address, physSlot=0, virtAdd=0, virtSlot=0))
            self.removeInterest(PutInitOutcomeMsg)
            if responseMsg.physSlot > 120:
                self.virtSlot = None
            else:
                self.virtSlot = responseMsg.virtSlot
        return responseMsg

    def getPath(self, pathKind, preSensor, fromSensor, toSensor, sensorsToExclude):
        gLog.print("Throttle {0}: sending GetPathMsg".format(self.name))
        self.addInterest(PutPathMsg)
        self.put(
            GetPathMsg(
                slot=self.virtSlot,
                pathKind=pathKind,
                preSensor=preSensor,
                fromSensor=fromSensor,
                toSensor=toSensor,
                sensorsToExclude=sensorsToExclude,
            )
        )
        msg = self.waitFor(PutPathMsg(sensors=[]))
        self.removeInterest(PutPathMsg)
        return msg.sensors

    def setVirtSlot(self, virtSlot):
        self.virtSlot = virtSlot

    def doFunction(self, func, *args):
        func(self, *args)

    def doCommand(self, command):
        if len(command) == 1:
            command[0](self)
        elif len(command) == 2:
            command[0](self, command[1])
        elif len(command) == 3:

            command[0](self, command[1], command[2])
        elif len(command) == 4:
            command[0](self, command[1], command[2], command[3])
        else:
            print("Command too long: {0}".format(command))

    def doCommands(self, commands):
        for command in commands:
            self.doCommand(command)

    def sendDirf(self):
        assert self.virtSlot is not None
        self.put(
            LocoDirfMsg(
                slot=self.virtSlot, direction=self.direction, lights=self.lights, horn=self.horn, bell=self.bell
            )
        )

    def sendSnd(self):
        assert self.virtSlot is not None
        self.put(LocoSndMsg(slot=self.virtSlot, mute=self.mute, F5=self.F5, F6=self.F6))

    def setSpeed(self, speed):
        assert self.virtSlot is not None
        assert speed >= 0
        self.put(LocoSpdMsg(slot=self.virtSlot, speed=speed))

    def setDirection(self, direction):
        assert direction == kForward or direction == kBackward
        self.direction = direction
        self.sendDirf()

    def setLights(self, onOff):
        assert onOff == kOn or onOff == kOff
        self.lights = onOff
        self.sendDirf()

    def setHorn(self, onOff):
        assert onOff == kOn or onOff == kOff
        self.horn = onOff
        self.sendDirf()

    def tootHorn(self):
        for i in range(3):
            self.setHorn(kOn)
            sleep(1)
            self.setHorn(kOff)
            if i != 2:
                sleep(0.2)

    def setBell(self, onOff):
        assert onOff == kOn or onOff == kOff
        self.bell = onOff
        self.sendDirf()

    def setMute(self, onOff):
        assert onOff == kOn or onOff == kOff
        self.mute = onOff
        self.sendSnd()

    def closeNextSwitch(self):
        if self.F5 == 0:
            self.F5 = 1
        else:
            self.F5 = 0
        self.sendSnd()

    def throwNextSwitch(self):
        if self.F6 == 0:
            self.F6 = 1
        else:
            self.F6 = 0
        self.sendSnd()

    def moveSwitch(self, sId, direction):
        assert sId > 0
        assert direction == kForward or direction == kBackward
        self.put(SwReqMsg(switch=sId, direction=direction))

    def pause(self, secs):
        sleep(secs)

    def makeSectionUsable(self, sensor1, sensor2):
        assert sensor1 > 0
        assert sensor2 > 0
        self.put(DoMakeSectionUsableMsg(sensor1=sensor1, sensor2=sensor2))
Пример #15
0
    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
    
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:
Пример #17
0
# -*- coding: utf-8 -*-
Пример #18
0
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))
Пример #19
0
        
    def selectNextHead(self):
        code=0
        try:
            self.network.sort(key= lambda x : x[1], reverse=True)
            self.clusterHead=self.network[0]
        except:
            code=1
        return code
    
    
if __name__ == '__main__':
    buff = []
    node = Node(1,'node1')
    MS_Handler=MsgHandler()
    print node.clusterHead
    node.send(BS_addr, BS_port, MS_Handler.Encode_Info_Msg(node.addr, node.energy, node.coordinate))
    node.initReceive()
    print node.clusterHead
    
    #timerSendMsg = threading.Timer()
    #buffSize = 10 # for the cluster head
    beginTime = time.time()
    timerUpdateHead = time.time()
    lastSend = time.time()
    sensorTime = time.time()

    CH_start = 0 # 1: Yes ;  0: No
    HOST=''
    try: