Exemplo n.º 1
0
class TcpConnection(object):
    def __init__(self, loop, socket, peeraddr):
        self.loop_ = loop
        self.socket_ = Socket(socket)
        self.peeraddr_ = peeraddr
        self.events_ = Events(self.socket_.getSocketFd(), kEevntRead)
        self.handle_ = Handle(self.events_)
        self.recvBuffer_ = ''
        self.writeBuffer_ = ''
        self.messageCb_ = defMessageCallback

    def tcpConnectionHandRead(self, reventFd, reventMask):
        assert reventFd == self.socket_.getSocketFd()
        data = ''
        length = 30
        while True:
            try:
                data = self.socket_.recv(length)
            except error, e:
                if e.errno == errno.EAGAIN:
                    break
            if len(data) == 0:
                self.loop_.delHandle(self.handle_)
                self.recvBuffer_ = ''
                break
            else:
                self.recvBuffer_ += data
        if len(self.recvBuffer_) != 0:
            self.messageCb_(self, self.recvBuffer_)
            self.recvBuffer_ = ''
Exemplo n.º 2
0
 def __init__(self, loop, socket, peeraddr):
     self.loop_ = loop
     self.socket_ = Socket(socket)
     self.peeraddr_ = peeraddr
     self.events_ = Events(self.socket_.getSocketFd(), kEevntRead)
     self.handle_ = Handle(self.events_)
     self.recvBuffer_ = ''
     self.writeBuffer_ = ''
     self.messageCb_ = defMessageCallback
Exemplo n.º 3
0
 def __init__(self, loop):
     self.loop_ = loop
     self.serversd_ = Socket()
     self.serversd_.bind()
     self.serversd_.listen(100)
     self.conns_ = {}
     self.events_ = Events(self.serversd_.getSocketFd(), kEevntRead)
     self.handle_ = Handle(self.events_, self.serverReadCb)
     self.loop_.addHandle(self.handle_)
     self.messageCb_ = defMessageCallback
Exemplo n.º 4
0
 def create(self, gateType, mouseCords, screen):
     self.screen = screen
     self.type = gateType
     self.image, self.rect = load_image(os.getcwd()+"/switch0.bmp", -1)
     print("switch created, cords: ", self.rect.topleft)
     self.setCords(mouseCords[0], mouseCords[1])
     outSocket = Socket()
     outSocket.setType("out")
     outSocket.setGate(self)
     outSocket.setScreen(self.screen)
     outSocket.update()
     self.outSocket = outSocket
     print("switch created at ", mouseCords,
           " with outSocket at ", outSocket.rect.topleft)
Exemplo n.º 5
0
    def open(self):
        """
        Initializes sonar connection
        :return:
        """
        # Initialize the port
        if not self.conn:
            try:
                self.conn = Socket(self.port, self.baudrate)
            except OSError as e:
                raise SonarNotFound(self.port, e)

        rospy.loginfo("Initializing connection with firing mechanism on %s",
                      self.port)
        self.initialized = True
        self.read()
Exemplo n.º 6
0
    def __init__(self, optManager):
        self.optManager = optManager
        self.socket = Socket(optManager)
        self.id = randint(1, 100000)

        for i in range(0, 80):
            self.cases.append(["-1"])
Exemplo n.º 7
0
    def open(self):
        """
        Initializes connection
        :return:
        """
        # Initialize the port
        if not self.conn:
            try:
                self.conn = Socket(port=self.port, baudrate=self.baudrate)
                self.conn.conn.open()
            except OSError as e:
                raise SonarNotFound(self.port, e)

        rospy.loginfo("Initializing connection with depth board on %s",
                      self.port)
        self.initialized = True
 def run(self):
     app = Application()
     path = '/tmp/%s' % self.name
     if os.path.exists(path):
         os.remove(path)
     s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
     s.bind(path)
     s.listen(1)
     sockets = [s.fileno()]
     while self.running:
         r, w, e = select.select(sockets, [], [], 10)
         if len(r) == 0:
             continue
         if s.fileno() in r:
             conn, addr = s.accept()
             self.clients.append(Socket(conn))
             sockets.append(conn.fileno())
         for conn in self.clients:
             if conn.fileno() in r:
                 d = conn.read()
                 if conn.connected:
                     app.queue(self.cb, conn, d)
                 else:
                     sockets.remove(conn.fileno())
         self.clients[:] = [x for x in self.clients if x.connected]
     s.close()
Exemplo n.º 9
0
 def create(self, gateType, mouseCords,screen):
     self.screen = screen
     self.type = gateType
     self.image, self.rect = load_image(os.getcwd()+"/assets/switch0.bmp", -1)
     print "switch created, cords: ",self.rect.topleft
     self.setCords(mouseCords[0],mouseCords[1])
     outSocket = Socket()
     outSocket.setType("out")
     outSocket.setGate(self)
     outSocket.setScreen(self.screen)
     outSocket.update()
     self.outSocket = outSocket
     print "switch created at ", mouseCords," with outSocket at ", outSocket.rect.topleft
Exemplo n.º 10
0
 def connect(self, addr = '127.0.0.1', port = 4242) :
     try:
         self._server = Socket()
         statusCode = self._server.connect_ex((addr, port))
         if statusCode != 0 :
             raise statusCode
     except :
         self.connectLocalCamera()
Exemplo n.º 11
0
class TcpServer(object):
    def __init__(self, loop):
        self.loop_ = loop
        self.serversd_ = Socket()
        self.serversd_.bind()
        self.serversd_.listen(100)
        self.conns_ = {}
        self.events_ = Events(self.serversd_.getSocketFd(), kEevntRead)
        self.handle_ = Handle(self.events_, self.serverReadCb)
        self.loop_.addHandle(self.handle_)
        self.messageCb_ = defMessageCallback

    def initNewConn(self, acceptRet):
        print "initNewConn"
        client = acceptRet[0]
        peeraddr = acceptRet[1]

        conn = TcpConnection(self.loop_, client, peeraddr)
        conn.setMessageCallback(self.messageCb_)

        conn.connectionInit()

        self.conns_[client.fileno()] = conn

    def setMessageCallback(self, messagecb=defMessageCallback):
        self.messageCb_ = messagecb

    def serverReadCb(self, reventFd, reventMask):
        print "serverReadCb"
        assert reventFd == self.serversd_.getSocketFd()

        #(socket object, address info)
        newconn = self.serversd_.accept()
        self.initNewConn(newconn)
Exemplo n.º 12
0
class AbletonJS(ControlSurface):
    def __init__(self, c_instance):
        super(AbletonJS, self).__init__(c_instance)

        Socket.set_log(self.log_message)
        Socket.set_message(self.show_message)
        self.socket = Socket(self.command_handler)

        self.handlers = {
            "internal": Internal(c_instance, self.socket),
            "cue-point": CuePoint(c_instance, self.socket),
            "device": Device(c_instance, self.socket),
            "device-parameter": DeviceParameter(c_instance, self.socket),
            "scene": Scene(c_instance, self.socket),
            "song": Song(c_instance, self.socket),
            "song-view": SongView(c_instance, self.socket),
            "track": Track(c_instance, self.socket),
            "clip_slot": ClipSlot(c_instance, self.socket),
            "clip": Clip(c_instance, self.socket)
        }

        self.parse()

        self.socket.send("connect")

    def disconnect(self):
        self.log_message("Disconnecting")
        self.socket.send("disconnect")
        self.socket.shutdown()
        super(AbletonJS, self).disconnect()

    def parse(self):
        self.socket.process()
        self.schedule_message(1, self.parse)

    def command_handler(self, payload):
        self.log_message("Received command: " + str(payload))
        namespace = payload["ns"]

        if self.handlers.has_key(namespace):
            handler = self.handlers[namespace]
            handler.handle(payload)
        else:
            self.socket.send("error", "No handler for NS " + str(namespace))
Exemplo n.º 13
0
def main():
    print("SysBot Corrupter " + ver + " by rydoginator")
    config = configparser.ConfigParser()
    if os.path.isfile('config.ini'):
        config.read('config.ini')
        ip = config['Server']['host']
        port = config['Server']['port']
        if not config['Misc'].getboolean('SkipMsg'):
            if BoolInput("Would you like to connect to " + ip + ":" +  port + "? y or n:"):
                if BoolInput("Would you like to skip this message in the future? y or n:"):
                    config['Misc']['SkipMsg'] = 'yes'
                else:
                    config['Misc']['SkipMsg'] = 'no'
            else:
                ip = input("Enter switch IP address:")
    else:
        ip = input("Enter switch IP address:")
    s = Socket()
    s.connect(ip, PORT)
    if s.connected:
        if not config['Misc'].getboolean('SkipMsg'):
            if BoolInput("Would you like to skip this message in the future? y or n:"):
                config['Misc']['SkipMsg'] = 'yes'
            else:
                config['Misc']['SkipMsg'] = 'no'
        config['Server']['host'] = ip
        config['Server']['port'] = str(PORT)
        with open('config.ini', 'w') as f:
            config.write(f)
        print("Press Ctrl+C to stop execution")
        print("Executing in...")
        for x in range(0,3):
            print(3 - x)
            time.sleep(1)
        offset = 0
        while True:
            value = s.readFloat(x * 4 + 0x0)
            if between(value, 1.0, 2.0):
                buf = struct.pack("f", value)
                print (offset + "->" + buf)
            print (str(offset) + "->" + str(value))
            offset = offset + 4
Exemplo n.º 14
0
    def __init__(self):

        self.mouse = []
        super().__init__()
        self.title()
        super().geometry("%dx%d+105+105" %(self.WIDTH, self.HEIGHT))
        super().configure(bg = self.BACKGROUND)
        super().title(self.TITLE)
        super().maxsize(self.WIDTH, self.HEIGHT)
        super().minsize(self.WIDTH, self.HEIGHT)

        super().bind("<Button-1>", self.click)  ### catchup the event of mouse clicked

        self.cv    = XCanvas(root  = self) #### initital Canvas
        self.debug = Debug(root = self, cord = self.FENS["comment"]) 
        self.db    = Database()
        
        self.btnCommOn = False  ### communication status with RaspBerryPi, TRUE or FALSE
        self.btnGpioOn = True   ### SIGNAL LEVEL (On or Off) to GPIO

        self.sock = Socket(callback = self.getResult)
        self.network = self.db.loadImage(file = "network")
        self.switch  = self.db.loadImages(files = ["swOff", "swOn"])
Exemplo n.º 15
0
    def update(self):
        current = datetime.now()

        if self.state == "OFF" and self.startTime != "N.A" and self.belueftung.state == "OFF":
            #not(self.isBetween(20, 32)) and self.state == "OFF" and self.belueftung.state == "OFF" and self.sensorTemp.getLastTemp() != -1:
            self.turnOn()
        elif isinstance(
                self.startTime, datetime) and current > datetime.combine(
                    current.today(),
                    Socket.addtoTime(self, self.startTime.strftime("%H:%M:%S"),
                                     "00:05:00").time()):
            #self.isBetween(25, 32) and self.state == "ON" or self.sensorTemp.getLastTemp() == -1 and self.state == "ON" or self.belueftung.state == "ON" and self.state == "ON":
            self.turnOff()
            self.startTime = "N.A"
        else:
            return False
Exemplo n.º 16
0
    def expand(self):

        import stat
        from BlockDevice import BlockDevice
        from CharacterDevice import CharacterDevice
        from File import File
        from Link import Link
        from NamedPipe import NamedPipe
        from Socket import Socket

        subdirectories = []

        import os
        children = os.listdir(self.fullname())

        for name in children:

            if self._children.has_key(name): continue

            pathname = os.path.join(self.fullname(), name)
            # PORTABILITY: lstat is unix only
            mode = os.lstat(pathname)[stat.ST_MODE]

            if stat.S_ISDIR(mode):
                node = Directory(name, self)
                subdirectories.append(node)
            elif stat.S_ISREG(mode):
                node = File(name, self)
            elif stat.S_ISLNK(mode):
                node = Link(name, self)
            elif stat.S_ISSOCK(mode):
                node = Socket(name, self)
            elif stat.S_ISFIFO(mode):
                node = NamedPipe(name, self)
            elif stat.S_ISCHR(mode):
                node = CharacterDevice(name, self)
            elif stat.S_ISBLK(mode):
                node = BlockDevice(name, self)
            else:
                Firewall.hit("unknown file type: mode=%x" % mode)

            self._children[node.name] = node

        self._subdirectories = subdirectories
        return subdirectories
Exemplo n.º 17
0
    def __init__(self, c_instance):
        super(AbletonJS, self).__init__(c_instance)

        Socket.set_log(self.log_message)
        Socket.set_message(self.show_message)
        self.socket = Socket(self.command_handler)

        self.handlers = {
            "internal": Internal(c_instance, self.socket),
            "cue-point": CuePoint(c_instance, self.socket),
            "device": Device(c_instance, self.socket),
            "device-parameter": DeviceParameter(c_instance, self.socket),
            "scene": Scene(c_instance, self.socket),
            "song": Song(c_instance, self.socket),
            "song-view": SongView(c_instance, self.socket),
            "track": Track(c_instance, self.socket),
            "clip_slot": ClipSlot(c_instance, self.socket),
        }

        self.parse()

        self.socket.send("connect")
Exemplo n.º 18
0
 def turnOff(self):
     self.state = "OFF"
     return Socket.turnOff(self, self.codeOff, 'Heizung aus')
Exemplo n.º 19
0
            logging.info('Video server will be stopped ("exit" message got)')
            client.close()
            stopped = True
            break
        else :
            logging.warning('Unknown request method "' + request + '" : connection closed')
            client.close()
            break
    logging.debug('Conection with client closed: addr=' + clientaddr)
    exit(0)



logging.info('Video server has been started')

server = Socket()
server.bind(('127.0.0.1', 4242))
server.listen(5)

camera = cv2.VideoCapture(0)


while not stopped:
    connection = server.tryaccept(3)
    if connection is None :
        continue
    client,addr = connection
    thread = threading.Thread(target=processConnection, args=(client, camera))
    thread.start()

#for thread in threading.enumerate() :
Exemplo n.º 20
0
            logging.info('Video server will be stopped ("exit" message got)')
            client.close()
            stopped = True
            break
        else:
            logging.warning('Unknown request method "' + request +
                            '" : connection closed')
            client.close()
            break
    logging.debug('Conection with client closed: addr=' + clientaddr)
    exit(0)


logging.info('Video server has been started')

server = Socket()
server.bind(('127.0.0.1', 4242))
server.listen(5)

camera = cv2.VideoCapture(0)

while not stopped:
    connection = server.tryaccept(3)
    if connection is None:
        continue
    client, addr = connection
    thread = threading.Thread(target=processConnection, args=(client, camera))
    thread.start()

#for thread in threading.enumerate() :
#    if thread != threading.currentThread() :
Exemplo n.º 21
0
 def __init__(self):
     self.socket = Socket()
Exemplo n.º 22
0
user = raw_input("user ")
passwd = getpass("password ")

server_url = "http%s://%s:%s@%s:%s/" % ("", user, passwd, "127.0.0.1", 7227)
proxy = xmlrpclib.ServerProxy(server_url, allow_none=True)

bench(proxy.get_server_version)
bench(proxy.status_server)
bench(proxy.status_downloads)
#bench(proxy.get_queue)
#bench(proxy.get_collector)
print
try:

    # Make socket
    transport = Socket('localhost', 7228, False)

    # Buffering is critical. Raw sockets are very slow
    transport = TTransport.TBufferedTransport(transport)

    # Wrap in a protocol
    protocol = Protocol(transport)

    # Create a client to use the protocol encoder
    client = Pyload.Client(protocol)

    # Connect!
    transport.open()

    print "Login", client.login(user, passwd)
Exemplo n.º 23
0
 def create(self, gateType, mouseCords, screen):
     self.screen = screen
     self.type = gateType
     self.image, self.rect = load_image(os.getcwd()+"/bulb0.png", -1)
     print(self.type, " created, cords: ", self.rect.topleft)
     self.setCords(mouseCords[0], mouseCords[1])
     socket = Socket()
     socket.setType("in")
     socket.setGate(self)
     socket.setIndex(0)
     socket.setScreen(self.screen)
     socket.update()
     self.inSockets.append(socket)
Exemplo n.º 24
0
 def __init__(self):
     Socket.__init__(self, type=self.SOCK_STREAM)
     return
Exemplo n.º 25
0
 def __init__(self):
     Socket.__init__(self, type=self.SOCK_STREAM)
     return
Exemplo n.º 26
0
 def __init__(self, optManager):
     self.optManager = optManager
     self.socket = Socket(optManager)
Exemplo n.º 27
0
from flask import Flask, render_template, json, request
import pdb
import os
from Socket import Socket, ETHERNET_IP, WIFI_IP

app = Flask(__name__, static_url_path='')

S = Socket(ip="192.168.1.13")


@app.route('/<path:path>/css')
def send_js(path):
    return send_from_directory('css', path)


@app.route('/<path:path>/js')
def send_css(path):
    return send_from_directory('js', path)


@app.route('/hello')
def hello_world():
    return 'hello world'


@app.route('/')
def main():
    return render_template('index.html')


@app.route('/data', methods=['POST'])
Exemplo n.º 28
0
 def turnOff(self):
     self.state = "OFF"
     return Socket.turnOff(self, self.codeOff, 'Licht aus!')
Exemplo n.º 29
0
#### WHAT THE SCRIPT IS DOING:
# one port,one main thread
# if it receives "i wanna play" then it starts a new thread listenForNewTTTPlayers
# to create a game
# this thread runs a function that just keeps waiting until the main thread notifies it to take the other player

from Socket import Socket
import threading, random, json, Queue
from Games import Games

sock = Socket(5005)
games = Games(sock)  #global games object

newPlaysLock = threading.Lock()
newPlaysCV = threading.Condition(newPlaysLock)
newPlaysQ = Queue.Queue(
)  #a queue of dicts {username:username,addressPortTuple:addressportTuple}


def listenForNewPlays():  #{
    """
    listenForNewPlayers:
    accepts no parameters
    creates one "Games" object

    while True:
        keep waiting for something to appear on the newplaysQ
        take it from the queue and leave it to the games.play() method
    """
    while True:  #{
        with newPlaysCV:  #{
Exemplo n.º 30
0
 def create(self, gateType, mouseCords,screen):
     self.screen = screen
     self.type = gateType
     self.image, self.rect = load_image(os.getcwd()+"/bulb0.png", -1)
     print self.type," created, cords: ",self.rect.topleft
     self.setCords(mouseCords[0],mouseCords[1])
     socket = Socket()
     socket.setType("in")
     socket.setGate(self)
     socket.setIndex(0)
     socket.setScreen(self.screen)
     socket.update()
     self.inSockets.append(socket)
Exemplo n.º 31
0
class AI():
    id = 0
    life = 10
    level = 1
    vision = 3
    freePlace = 0
    nbPlayer = []

    inventory = {"linemate": 0, "deraumere": 0, "sibur": 0, "mendiane": 0, "phiras": 0, "thystame": 0}
    cases = []
    listCommand = []
    broadcastMessage = []

    ignoreMessage = 0
    asking = 0
    firstAction = True
    firstReceive = True
    listChild = []

    def __init__(self, optManager):
        self.optManager = optManager
        self.socket = Socket(optManager)
        self.id = randint(1, 100000)

        for i in range(0, 80):
            self.cases.append(["-1"])

    def signalHandler(*args):
        for child in args[0].listChild:
            os.kill(child, signal.SIGTERM)
        sys.exit()

    def countNbPlayer(self, message):
        self.nbPlayer = counterPlayer

    def broadcastLevel(self):
        if self.listCommand == []:
            self.listCommand.append("broadcast " + self.optManager.nameEquip + " /l " + str(self.level))

    def broadcastMoveTo(self, message):
        orientation = int(message[0])
        walk = []

        if self.life < 10:
            return

        print ("ORIENTATION:", orientation)
        if orientation == 1:
            walk = ["avance"]
        elif orientation == 2:
            walk = ["avance", "gauche", "avance"]
        elif orientation == 3:
            walk = ["gauche", "avance"]
        elif orientation == 4:
            walk = ["gauche", "avance", "gauche", "avance"]
        elif orientation == 5:
            walk = ["gauche", "gauche", "avance"]
        elif orientation == 6:
            walk = ["droite", "avance", "droite", "avance"]
        elif orientation == 7:
            walk = ["droite", "avance"]
        elif orientation == 8:
            walk = ["avance", "droite", "avance"]

        walk.append("voir")
        for move in walk:
            Macro.CommandRef[move](self, True)

    def readBroadcast(self):
        idx = 0
        while idx < len(self.broadcastMessage):
            message = self.broadcastMessage[0]
            if message[1] == '/a':
                Macro.BroadcastRespRef[message[1]](self, message)
                self.broadcastMessage.pop(idx)
                idx = -1
            elif message[1] == '/l' and int(message[2]) != self.level:
                self.broadcastMessage.pop(idx)
                idx = -1
            idx += 1

        idx = 0

        print ("CAN I READ broadcast LEVEL ?", self.listCommand)
        if self.listCommand == []:
            if self.broadcastMessage != []:
                message = self.broadcastMessage[0]
                print ("|-^-| broadcast:", message)
                if message[1] != '/l':
                    Macro.BroadcastRespRef[message[1]](self, message)
                    self.broadcastMessage.pop(0)

            idxLast = -1
            i = 0
            while i < len(self.broadcastMessage):
                if self.broadcastMessage[i][1] == '/l':
                    idxLast = i
                i += 1

            if idxLast != -1:
                Macro.BroadcastRespRef["/l"](self, self.broadcastMessage[-1])

            idx = 0
            while idx < len(self.broadcastMessage):
                if self.broadcastMessage[idx][1] == '/l':
                    self.broadcastMessage.pop(idx)
                    idx = -1
                idx += 1

    def broadcastIncrease(self, message):
        myID = int(message[2])
        idAlly = int(message[3])
        if myID == self.id:
            for elem in self.nbPlayer:
                if elem == idAlly:
                    return
            self.nbPlayer.append(idAlly)
            print ("Increased PLAYER: ", idAlly)

    def broadcastRequest(self, message):
        self.socket.sendData("broadcast " + self.optManager.nameEquip + " /r " + str(self.id))
        self.listCommand.append("broadcast " + self.optManager.nameEquip + " /r " + str(self.id))

    def broadcastAnswer(self, message):
        self.listCommand.append("broadcast " + self.optManager.nameEquip + " /a " + message[2] + " " + str(self.id))
        self.socket.sendData("broadcast " + self.optManager.nameEquip + " /a " + message[2] + " " + str(self.id))

    def isRes(self, elem):
        if elem != "joueur" and elem != "" and elem != "-1" and elem != "nourriture":
            return True
        return False

    def isLevelComplete(self):
        levelRef = Macro.LevelRef[self.level]

        for elem in levelRef:
            if self.isRes(elem):
                if levelRef[elem] > self.inventory[elem]:
                    return False
        return True

    def putResOnCase(self, idx = 0):
        ressourceCase = dict(Macro.LevelRef[0])

        for elem in self.cases[0]:
            if self.life > 10:
                break
            if elem == "nourriture":
                self.funcPrend(idx, True)

        for elem in self.cases[0]:
            if self.isRes(elem):
                ressourceCase[elem] += 1
        for elem in ressourceCase:
            if elem != "joueur":
                if ressourceCase[elem] < Macro.LevelRef[self.level][elem]:
                    self.listCommand.append("pose " + elem + " " + str(0))

                    self.inventory[elem] -= 1
                    self.cases[0].append(elem)
                    return -1
                elif ressourceCase[elem] > Macro.LevelRef[self.level][elem]:
                    self.listCommand.append("prend " + elem + " " + str(0))
                    self.inventory[elem] += 1
                    self.cases[0].remove(elem)
                    return -1
        return 0

    def getCase(self, message):
        message = message.replace("{", "").replace("}", "")
        listCase = message.split(",")

        for idx, case in enumerate(listCase):
            self.cases[idx] = case[1:].split(" ")
        for command in self.listCommand:
            if command.find("prend") != -1:
                try:
                    info = command.split(" ")
                    self.cases[info[2]].remove(info[1])
                except:
                    eprint("ERROR DANS L ANTICIPATION PREND")
                    continue
            if command.find("pose") != -1:
                try:
                    info = command.split(" ")
                    self.cases[info[2]].append(info[1])
                except:
                    eprint("ERROR DANS L ANTICIPATION POSE")
                    continue

    def getCaseLevel(self):
        for idx, case in enumerate(self.cases):
            for elem in case:
                if self.isRes(elem):
                    ret = Macro.LevelRef[self.level][elem] - self.inventory[elem]
                    if ret > 0 and not "joueur" in case:
                        print ("Is there a player:", case)
                        return idx
        return -1

    def getCaseIncant(self):
        ret = (-1, -1)
        for idx, elem in enumerate(self.cases):
            nbAction = self.canIncant(idx)
            if nbAction != -1 and (nbAction < ret[1] or ret[1] == -1):
                ret = (idx, nbAction)
            if getIdxMax(self.vision) < idx:
                break
        if ret[0] == -1:
            return -1
        return ret[0]

    def canIncant(self, idx = 0):
        levelRef = dict(Macro.LevelRef[self.level])
        ressourceCase = dict(Macro.LevelRef[0])
        invRef = dict(self.inventory)

        if len(self.cases[idx]) > 0 and self.cases[idx][0] == "-1":
            return -1

        for elem in self.cases[idx]:
            if elem != "nourriture" and elem != "":
                ressourceCase[elem] += 1

        ret = 0
        for elem in ressourceCase:
            if ressourceCase[elem] > levelRef[elem] or ressourceCase[elem] < levelRef[elem]:
                ret = 1
        if ret == 0:
            return 0

        ret = 0
        tmpCase = dict(ressourceCase)
        for elem in ressourceCase:
            if elem != "nourriture" and elem != "joueur":
                tmpCase[elem] += invRef[elem]
                if tmpCase[elem] < levelRef[elem]:
                    ret = 1
        if ret == 1:
            return -1

        action = 0
        for elem in ressourceCase:
            if ressourceCase[elem] > levelRef[elem]:
                while ressourceCase[elem] > levelRef[elem]:
                    action += 1
                    ressourceCase[elem] -= 1
            elif ressourceCase[elem] > levelRef[elem]:
                while ressourceCase[elem] < levelRef[elem]:
                    action += 1
                    ressourceCase[elem] += 1
        if self.level == 1 and self.cases[idx].count("joueur") > 1:
            return -1
        elif self.level != 1 and self.cases[idx].count("joueur") > Macro.LevelRef[self.level]["joueur"]:
            return -1
        return action

    def funcDroite(self, broadcast = False):
        if broadcast is True:
            self.socket.sendData("droite")
            self.listCommand.append("droite")
            return
        self.listCommand.append("droite")

    def funcGauche(self, broadcast = False):
        if broadcast is True:
            self.socket.sendData("gauche")
            self.listCommand.append("gauche")
            return
        self.listCommand.append("gauche")

    def funcAvance(self, broadcast = False):
        if broadcast is True:
            self.socket.sendData("avance")
            self.listCommand.append("avance")
            return
        self.listCommand.append("avance")

    def funcVoir(self, broadcast = False):
        if broadcast is True:
            self.socket.sendData("voir")
            self.listCommand.append("voir")
            return
        self.listCommand.append("voir")

    def funcPrend(self, idx, food = False):
        case = self.cases[idx]

        if food is True:
            if "nourriture" in case:
                self.listCommand.append("prend nourriture " + str(idx))
                case.remove("nourriture")
            return

        for res in case:
            if self.isRes(res):
                if self.inventory[res] + 1 <= Macro.LevelRef[self.level][res]:
                    self.inventory[res] += 1
                    self.listCommand.append("prend " + res + " " + str(idx))
                    case.remove(res)
                else:
                    eprint("Doesn't need 'prend " + res + "'")

    def funcExpulse(self):
        self.listCommand.append("expulse")

    def funcIncantation(self, idx = 0):
        print ("Func incantation")
        if self.putResOnCase(idx) == -1:
            return
        self.listCommand.append("incantation")

    def connectNewPlayer(self):
        pid = os.fork()
        if pid == 0:
            FNULL = open(os.devnull, 'w')
            FTEST = open("test", "w+")
            self.listChild.append(subprocess.Popen("./zappy_ai " + " -n " + self.optManager.nameEquip + " -p " + str(self.optManager.port) + " -h " + self.optManager.host, stdout=FTEST, shell=True))
            sys.exit()

    def funcFork(self):
        self.listCommand.append("fork")

    def isRessource(self, ressource):
        for i in range(0, len(self.cases)):
            for res in self.cases[i]:
                if res == ressource:
                    return i
        return -1

    def blind(self):
        count = 0
        for i in range(0, getNbCaseLevel(self.vision)):
            for elem in self.cases[i]:
                if elem == "-1":
                    count += 1
        total = getNbCaseLevel(self.vision)

        if count / total >= 0.75:
            return True
        return False

    def moveTo(self, idx, simulate = False):
        caseTmp = list(self.cases[idx])
        walk = []
        count = 0
        if idx == 0:
            if simulate is True:
                return 0
            return

        for i, lineValues in enumerate(Macro.LineRef):
            if lineValues[0] <= idx <= lineValues[1]:
                count = i
                break
        for i in range(0, count + 1):
            walk.append("avance")

        line = Macro.LineRef[count]
        middle = (line[0] + line[1]) / 2
        if idx < middle:
            walk.append("gauche")
            while idx < middle:
                walk.append("avance")
                idx += 1
        elif idx > middle:
            walk.append("droite")
            while idx > middle:
                walk.append("avance")
                idx -= 1

        if simulate is True:
            return len(walk)

        if walk == []:
            return
        for move in walk:
            Macro.CommandRef[move](self)
        self.cases[0] = caseTmp

    def getCaseFood(self):
        for i in range(0, len(self.cases)):
            for res in self.cases[i]:
                if res == "nourriture":
                    return i
        return -1

    def needFork(self):
        if self.asking == 0:
            self.broadcastRequest("")
            self.asking = 1
            self.ownTimer = time.time()
        if time.time() - self.ownTimer >= 6.0:
            if self.asking == 1 and len(self.nbPlayer) < 8:
                if self.life > 10:
                    self.funcFork()
                    self.asking = 3

    def checkIncantPlayer(self, idx = 0):
        case = self.cases[idx]

        print ("NB player", case.count("joueur"))
        if case.count("joueur") == Macro.LevelRef[self.level]["joueur"]:
            return True

        if self.putResOnCase() == -1:
            return False

        print ("send broadcast /l")
        if case.count("joueur") < Macro.LevelRef[self.level]["joueur"] and self.life > 10:
            Macro.BroadcastRef["/l"](self)
        return False

    def chooseAnAction(self):
        print ("--- Vision ---")
        printList(self.vision, self.level, self.cases)
        print ("--------------")
        print ("--- Life:", self.life)
        print ("--- Free Place:", self.freePlace)
        print ("--- Inventory:", self.inventory)
        print ("--- Level Complete:", self.isLevelComplete())


        self.constructArmy()
        self.needFork()

        if self.canIncant() != -1 and self.life > 10:
            if self.checkIncantPlayer():
                self.funcIncantation()
            return

        if self.blind():
            self.funcVoir()
            return

        idx = self.getCaseFood()
        if self.life < 10 and idx != -1:
            print ("Get food:", idx)
            self.moveTo(idx)
            if self.checkIncantPlayer(idx):
                self.funcIncantation(idx)
            self.funcPrend(idx, True)
            return

        idx = self.getCaseIncant()
        if idx != -1 and self.life < 10:
            print ("Get incant Case:", idx)
            self.moveTo(idx)
            return

        idx = self.getCaseLevel()
        if idx != -1 and self.life < 10:
            print ("Get Res :", idx)
            self.moveTo(idx)
            self.funcPrend(idx, False)
            return

        idx = self.getCaseFood()
        if idx != -1:
            print ("Get food to stock:", idx)
            self.moveTo(idx)
            self.funcPrend(idx, True)
            return

        caseTmp = list(self.cases[2])
        self.moveTo(2)
        self.cases[0] = caseTmp

    def parseBroadcast(self, message):
        listMessage = message.split(",")
        orientation = listMessage[0].split(" ")[1]
        informations = listMessage[1].split(" ")

        final = []
        if informations[0] == self.optManager.nameEquip:
            final.append(orientation)
            final.extend(informations[1:])
            self.broadcastMessage.append(final)

    def updateInfo(self):
        self.listCommand.append("voir")
        self.listCommand.append("inventaire")
        self.listCommand.append("connect_nbr")

    def upStats(self):
        self.level += 1
        self.vision += 2
        print("STATS UPDATED")

    def receiveMessage(self, listMessage):
        message = listMessage[0]
        listMessage.pop(0)
        print ("<|", time.strftime("%H:%M:%S"), ":", message, " |>")
        print ("<|-", self.listCommand, "-|>")

        if message == "mort":
            sys.exit()

        if message.find("niveau actuel") != -1 and len(self.listCommand) > 0 and self.listCommand[0] != "incantation":
            self.upStats()
            message = ""
        if message.find("message") != -1:
            self.parseBroadcast(message)
            message = ""

        if message == "ok" or message == "ko":
            if message == "ko":
                eprint("-----Error ---")
                eprint(self.listCommand[0])
            if len(self.listCommand) > 0 and self.listCommand[0] != "voir" and (self.listCommand[0] != "incantation" or message == "ko"):
                self.listCommand.pop(0)
            message = ""

        if self.listCommand != [] and message != "":
            if self.listCommand[0] == "voir":
                self.getCase(message)
                self.listCommand.pop(0)
            elif self.listCommand[0] == "inventaire":
                self.life = int(message.replace("{", "").replace("}", "").split(",")[0].split(" ")[1])
                self.listCommand.pop(0)
            elif self.listCommand[0] == "connect_nbr":
                self.freePlace = int(message)
                self.listCommand.pop(0)
            elif self.listCommand[0] == "incantation":
                if message.find("niveau actuel") != -1:
                    self.upStats()
                    self.listCommand.pop(0)

    def constructArmy(self):
        while self.freePlace > 1:
            self.connectNewPlayer()
            self.freePlace -= 1

    def initData(self):
        self.socket.sendData("voir")
        self.listCommand.append("voir")
        self.socket.sendData("connect_nbr")
        self.listCommand.append("connect_nbr")

    def run(self):
        self.ownTimer = time.time()
        self.initData()

        signal.signal(signal.SIGINT, self.signalHandler)
        signal.signal(signal.SIGTERM, self.signalHandler)

        print ("----- My ID", self.id, "-----")
        while True:
            messages = self.socket.selectData()
            if messages != []:
                while messages != []:
                    self.receiveMessage(messages)
            if self.broadcastMessage != []:
                self.readBroadcast()
            if self.listCommand == []:
                self.chooseAnAction()
                self.updateInfo()
                print ("Actions:", self.listCommand)
                for command in self.listCommand:
                    if command.find("prend") != -1 or command.find("pose") != -1:
                        self.socket.sendData(command.split(" ")[0] + " " + command.split(" ")[1])
                    else:
                        self.socket.sendData(command)
Exemplo n.º 32
0
class DepthInfo(QObject):
    """
    *DepthInfo* class for firing system driver
    """
    def __init__(self, port="/dev/ttyUSB0", baudrate=38400):
        """

        :param port:
        :param baudrate: Baud rate, 115200 by default (can be 9600-115200)
        """
        self.port = port
        self.baudrate = baudrate

        self.conn = None
        self.initialized = False
        self.configured = False

        # Create TransformStamped message
        self.transf = geometry_msgs.msg.TransformStamped()
        self.transf.header.frame_id = 'world'
        self.transf.child_frame_id = 'sonar'
        # Initialize values to publish
        self.transf.transform.translation.x = 0
        self.transf.transform.translation.y = 0
        self.transf.transform.translation.z = 0
        self.transf.transform.rotation.x = 0.0
        self.transf.transform.rotation.y = 0.0
        self.transf.transform.rotation.z = 0.0
        self.transf.transform.rotation.w = 1.0
        self.tfbroad = tf2_ros.TransformBroadcaster()

    def __enter__(self):
        """
        Initializes for first use
        """
        self.open()
        srv = Server(WinchConfig, self.config_callback)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        Cleans up
        :param exc_type:
        :param exc_val:
        :param exc_tb:
        :return:
        """
        self.close()
        rospy.loginfo("Closed depth reader on %s", self.port)

    def open(self):
        """
        Initializes connection
        :return:
        """
        # Initialize the port
        if not self.conn:
            try:
                self.conn = Socket(port=self.port, baudrate=self.baudrate)
                self.conn.conn.open()
            except OSError as e:
                raise SonarNotFound(self.port, e)

        rospy.loginfo("Initializing connection with depth board on %s",
                      self.port)
        self.initialized = True
        #self.read()

    def close(self):
        self.conn.close()

    def config_callback(self, config, level):
        rospy.loginfo(
            """Reconfigure request: {winch_port_baudrate}, {winch_port}""".
            format(**config))
        self.set_params(**config)
        return config

    def set_params(self,
                   winch_port_baudrate=None,
                   winch_port=None,
                   groups=None):
        self.port = winch_port
        self.baudrate = winch_port_baudrate
        self.close()
        self.conn = None
        self.open()
        #self.read()
        return self

    def send(self, message=None):
        self.conn.send(message)
        rospy.logdebug('%s sent', message)

    def read(self):
        """
        Receives information form port
        :return:
        """
        # send here something to verify sonar is connected?
        if not self.initialized:
            raise SonarNotConfigured(self.initialized)
        # Timeout count
        timeout_count = 0
        MAX_TIMEOUT_COUNT = 5

        # Scan until stopped
        self.preempted = False
        while not self.preempted:
            # Preempt on ROS shutdown
            if rospy.is_shutdown():
                self.preempt()
                return

            # Get the scan data
            try:
                data = self.get(wait=1)
                self.transf.header.stamp = rospy.Time.now()
                self.transf.transform.translation.z = data
                self.tfbroad.sendTransform(self.transf)
                timeout_count = 0
            except TimeoutError:
                timeout_count += 1
                rospy.logdebug("Timeout count: %d", timeout_count)
                if timeout_count >= MAX_TIMEOUT_COUNT:
                    timeout_count = 0
                rospy.sleep(0.5)
                # Try again
                continue

    def get(self, wait=2):
        """
        Sends command and returns reply
        :param message: Message to expect
        :param wait: Seconds to wait until received
        :return:
        """
        # Verify if sonar is initialized
        if not self.initialized:
            raise SonarNotConfigured

        #rospy.logdebug("Waiting for depth message")

        # Determine end time
        end = datetime.datetime.now() + datetime.timedelta(seconds=wait)

        # Wait until received
        while datetime.datetime.now() < end:
            try:
                reply = self.conn.conn.read(4)

                inhex = int(reply.encode('hex'), 16)

                return inhex
            except:
                break

        # Timeout
        rospy.logerr("Timed out before receiving depth message")
        raise TimeoutError()

    def preempt(self):
        """
        Preempts the process
        :return:
        """
        rospy.logwarn("Preempting depth reader process...")
        self.preempted = True
Exemplo n.º 33
0
class StreamReader :
    def __init__(self) :
        self._server = None
        self._capturedDevice = None
        pass

    def connect(self, addr = '127.0.0.1', port = 4242) :
        try:
            self._server = Socket()
            statusCode = self._server.connect_ex((addr, port))
            if statusCode != 0 :
                raise statusCode
        except :
            self.connectLocalCamera()

    def connectLocalCamera(self) :
        self.close()
        qem = QErrorMessage()
        qem.showMessage('Не удаётся подключиться к Raspberry Pi: Будет подключена локальная камера')
        qem.exec()
        self._capturedDevice = cv2.VideoCapture(0)    

    def releseLocalCamera(self) :
        self._capturedDevice.relese()
        self._capturedDevice = None

    def __del__(self) :
        self.close()

    def getFrame(self) :
        if self._server is not None :
            try: 
                return self._getFrameFromRemoteCamera() 
            except: 
                self.connectLocalCamera()

        if self._capturedDevice is not None :
            try: 
                return self._getFrameFromLocalCamera() 
            except: 
                raise CannotReadFrame
        raise CannotReadFrame


    def _getFrameFromRemoteCamera(self) :
        self._server.sendObject('get_frame')
        frame = self._server.recvObject()
        return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    def _getFrameFromLocalCamera(self) :
        retVal, frame = self._capturedDevice.read()
        if retVal == False :
            raise CannotReadFrame
        return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    def readable(self) :
        #заглушка
        return True

    def recvall(self, sock, size) :
        binary = sock.recv(size)
        diff = size - len(binary)
        while diff :
            buf = sock.recv(diff)
            diff = diff - len(buf)
            binary = binary + buf
        return binary

    def close(self) :
        if self._capturedDevice is not None :
            self._capturedDevice.release()
            self._capturedDevice = None
        if self._server is not None :
            try:
                #self._server.sendObject('close_conection')
                self._server.sendObject('exit')
                self._server.close()
            except:
                pass
            finally:
                self._server = None
Exemplo n.º 34
0
 def turnOn(self):
     self.state = "ON"
     Socket.turnOn(self, self.codeOn, 'Luefter an')
Exemplo n.º 35
0
    def create(self, gateType, mouseCords, screen):
        self.screen = screen
        self.type = gateType
        self.image, self.rect = load_image(
            os.getcwd() + "/" + gateType + '.png', -1)
        print(self.type, " created, cords: ", self.rect.topleft)
        self.setCords(mouseCords[0], mouseCords[1])
        if gateType == "not":  # for a not gate, we only create one input socket.
            socket1 = Socket()
            socket1.setType("in")
            socket1.setGate(self)
            socket1.setIndex(0)
            socket1.setScreen(self.screen)
            socket1.update()
            self.inSockets.append(socket1)

            outSocket = Socket()
            outSocket.setType("out")
            outSocket.setGate(self)
            outSocket.setScreen(self.screen)
            outSocket.update()
            self.outSocket = outSocket

        else:  # otherwise: two inputs, one output.
            socket1 = Socket()
            socket1.setType("in")
            socket1.setGate(self)
            socket1.setIndex(0)
            socket1.setScreen(self.screen)
            socket1.update()
            self.inSockets.append(socket1)

            socket2 = Socket()
            socket2.setType("in")
            socket2.setGate(self)
            socket2.setIndex(1)
            socket2.setScreen(self.screen)
            socket2.update()
            self.inSockets.append(socket2)

            outSocket = Socket()
            outSocket.setType("out")
            outSocket.setGate(self)
            outSocket.setScreen(self.screen)
            outSocket.update()
            self.outSocket = outSocket
Exemplo n.º 36
0
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#|R|a|s|p|b|e|r|r|y|P|i|.|c|o|m|.|t|w|
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# Copyright (c) 2018, raspberrypi.com.tw
# All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# test_lora_send.py
# The simple test program for lora module to send file
#
# Author : sosorry
# Date   : 10/03/2017
#

from Logger import Logger
from Socket import Socket
from LoRa import LoRa

rn = LoRa("RN2483")
socket=Socket(rn)
fd=socket.open("lena8rgb.jpg")
ack=socket.send_syn(fd)

while ack == True:
    ack = socket.send_data(fd)

socket.close()
Exemplo n.º 37
0
    def create(self, gateType, mouseCords,screen):
        self.screen = screen
        self.type = gateType
        self.image, self.rect = load_image(os.getcwd()+"/assets/"+gateType+'.png', -1)
        print self.type," created, cords: ",self.rect.topleft
        self.setCords(mouseCords[0],mouseCords[1])
        if gateType == "not": #for a not gate, we only create one input socket.
            socket1 = Socket()
            socket1.setType("in")
            socket1.setGate(self)
            socket1.setIndex(0)
            socket1.setScreen(self.screen)
            socket1.update()
            self.inSockets.append(socket1)

            outSocket = Socket()
            outSocket.setType("out")
            outSocket.setGate(self)
            outSocket.setScreen(self.screen)
            outSocket.update()
            self.outSocket = outSocket
            
        else:   #otherwise: two inputs, one output.
            socket1 = Socket()
            socket1.setType("in")
            socket1.setGate(self)
            socket1.setIndex(0)
            socket1.setScreen(self.screen)
            socket1.update()
            self.inSockets.append(socket1)

            socket2 = Socket()
            socket2.setType("in")
            socket2.setGate(self)
            socket2.setIndex(1)
            socket2.setScreen(self.screen)
            socket2.update()
            self.inSockets.append(socket2)

            outSocket = Socket()
            outSocket.setType("out")
            outSocket.setGate(self)
            outSocket.setScreen(self.screen)
            outSocket.update()
            self.outSocket = outSocket
Exemplo n.º 38
0
class Imap:

    def __init__(self, host, port, login, password):
        self._Socket = Socket(host, port)
        self.Host = host
        self.Port = int(port)
        self.Login = login
        self.Password = password

    def login(self):
        result_str = 'LOGIN {0} {1}'.format(self.Login, self.Password)
        self._Socket.send_msg(result_str)
        answer = self.get_answer().decode()
        if 'AUTHENTICATIONFAILED' in answer:
            raise Exception('Authentication failed')
        return self.get_answer()

    def select_folder(self, folder_name):
        self._Socket.send_msg('SELECT {}'.format(folder_name))
        return self.get_answer()

    def delete_folder(self, folder_name):
        self._Socket.send_msg('DELETE {}'.format(folder_name))

    def rename_folder(self, old_name, new_name):
        self._Socket.send_msg('RENAME {0} {1}'.format(old_name, new_name))

    def show_list_of_folders(self):
        self._Socket.send_msg('LIST "" *')
        return self.get_answer()

    def get_count_of_letters(self):
        raw_result = self.search_msg('all').decode().split('\n')
        result = []
        for item in raw_result:
            if '* SEARCH' in item:
                result = item.split(' ')
        result = result[-1].replace('\r', '')
        if result == 'SEARCH':
            return 0
        return result

    def parse_list_of_folders(self):
        result = []
        bytestr = self.show_list_of_folders().decode()
        splitted_str = bytestr.split('*')
        for item in splitted_str:
            if 'INBOX' in item:
                result.append(('Inbox', 'INBOX'))
                continue
            if 'All' in item:
                continue
            raw_name_of_folder = item[item.find('(') + 1:item.find(')')]
            raw_name_of_folder = raw_name_of_folder.replace(
                '\\HasNoChildren', '')
            raw_name_of_folder = raw_name_of_folder.replace(
                '\\HasChildren', '')
            raw_name_of_folder = raw_name_of_folder.replace(
                '\\Noselect', '')
            raw_name_of_folder = raw_name_of_folder.replace(
                '\\NoInferiors', '')
            name_of_folder =\
                raw_name_of_folder[raw_name_of_folder.find('\\') + 1:]
            if name_of_folder == '' or name_of_folder == ' ':
                continue
            id_of_folder = item[item.rfind(
                '"', 0, item.rfind('"')) + 1:item.rfind('"')]
            result.append(tuple([name_of_folder, id_of_folder]))
        return result

    def set_active(self, folder_name):
        self._Socket.send_msg('SUBCRIBE {}'.format(folder_name))

    def set_inactive(self, folder_name):
        self._Socket.send_msg('UNSUBCRIBE {}'.format(folder_name))

    def check_folder(self):
        self._Socket.send_msg('CHECK')
        return self.get_answer()

    def status_of_folder(self, folder_name, flags):
        self._Socket.send_msg('STATUS {0} ({1})'.format(folder_name, flags))
        return self.get_answer()

    def search_msg(self, flags):
        self._Socket.send_msg('SEARCH {}'.format(flags))
        return self.get_answer()

    def choose_msg(self, id, flags):
        self._Socket.send_msg('FETCH {0} {1}'.format(id, flags))
        return self.get_answer()

    def close_folder(self):
        self._Socket.send_msg('CLOSE')

    def get_answer(self):
        return self._Socket.get_answer()

    def logout(self):
        self._Socket.send_msg('LOGOUT')
Exemplo n.º 39
0
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# Copyright (c) 2018, raspberrypi.com.tw
# All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# test_lora_recv.py
# The simple test program for lora module to receive file
#
# Author : sosorry
# Date   : 10/03/2017
#
#!/usr/bin/python
# -*- coding: UTF-8 -*-

from Logger import Logger
from Socket import Socket
from LoRa import LoRa

rn = LoRa("RN2483")
socket = Socket(rn)

while True:
    data = socket.recv()

    if len(data) == 0:
        break;

socket.close()

Exemplo n.º 40
0
 def __init__(self, host, port, login, password):
     self._Socket = Socket(host, port)
     self.Host = host
     self.Port = int(port)
     self.Login = login
     self.Password = password
Exemplo n.º 41
0
 def turnOn(self):
     self.state = "ON"
     Socket.turnOn(self, self.codeOn, 'Licht an!')
Exemplo n.º 42
0
 def turnOff(self):
     self.state = "OFF"
     return Socket.turnOff(self, self.codeOff, 'Luefter aus')
Exemplo n.º 43
0
  passwd,
  "127.0.0.1",
  7227
)
proxy = xmlrpclib.ServerProxy(server_url, allow_none=True)

bench(proxy.get_server_version)
bench(proxy.status_server)
bench(proxy.status_downloads)
# bench(proxy.get_queue)
# bench(proxy.get_collector)
print
try:

    # Make socket
    transport = Socket('localhost', 7228, False)

    # Buffering is critical. Raw sockets are very slow
    transport = TTransport.TBufferedTransport(transport)

    # Wrap in a protocol
    protocol = Protocol(transport)

    # Create a client to use the protocol encoder
    client = Pyload.Client(protocol)

    # Connect!
    transport.open()

    print "Login", client.login(user, passwd)
Exemplo n.º 44
0
class AI():
    numClient = 0
    life = 10
    level = 1
    freePlace = 0
    inventory = {"linemate": 0, "deraumere": 0, "sibur": 0, "mendiane": 0, "phiras": 0, "thystame": 0}
    cases = [[], [], [], []]
    lastCommand = ""

    firstAction = True
    firstReceive = True

    def __init__(self, optManager):
        self.optManager = optManager
        self.socket = Socket(optManager)

    def isLevelComplete(self):
        levelRef = Macro.LevelRef[self.level]

        for elem in levelRef:
            if levelRef[elem] > self.inventory[elem]:
                return 0
        return 1

    def canIncant(self):
        levelRef = dict(Macro.LevelRef[self.level])
        ressourceCase = dict(Macro.LevelRef[0])
        invRef = dict(self.inventory)

        for elem in self.cases[0]:
            ressourceCase[elem] += 1

        for elem in invRef:
            if levelRef[elem] < invRef[elem]:
                invRef[elem] = levelRef[elem]

        for elem in ressourceCase:
            invRef[elem] += ressourceCase[elem]

        for elem in levelRef:
            if invRef[elem] > levelRef[elem] or invRef[elem] < levelRef[elem]:
                return 0

        return 1

    def putResOnCase(self):
        ressourceCase = dict(Macro.LevelRef[0])

        for elem in self.cases[0]:
            ressourceCase[elem] += 1
        for elem in ressourceCase:
            while ressourceCase[elem] < Macro.LevelRef[self.level]:
                self.socket.sendData("pose " + elem)
                message = ""
                while message == "":
                    message = self.socket.selectData()
                if message != "ok":
                    eprint("Error in put " + elem)
                ressourceCase[elem] += 1

    def createNeuralNetwork(self, load = False):
        listHidden1 = [Neuron("1", 6, load), Neuron("2", 6, load), Neuron("3", 6, load)]
        listHidden2 = [Neuron("4", 3, load), Neuron("5", 3, load)]
        listHidden3 = [Neuron("6", 2, load)]
        listNetwork = [NeuronLayer(listHidden1), NeuronLayer(listHidden2), NeuronLayer(listHidden3)]

        self.neuralNetwork = NeuralNetwork(listNetwork)

    def getCase(self, message):
        message = message.replace("{", "").replace("}", "")
        listCase = message.split(",")
        self.cases.append(listCase[0][1:].split(" "))
        self.cases.append(listCase[1][1:].split(" "))
        self.cases.append(listCase[2][1:].split(" "))
        self.cases.append(listCase[3][1:].split(" "))

    def getCaseLevel(self, idx):
        case = self.cases[idx]
        if len(case) > 0 and case[0] == "-1":
            return -1
        for elem in case:
            if elem != "nourriture" and elem != "joueur" and elem != '':
                ret = Macro.LevelRef[self.level][elem] - self.inventory[elem]
                if ret > 0:
                    return 1
        return 0

    def getCaseFood(self, idx):
        case = self.cases[idx]
        for elem in case:
            if elem == "nourriture":
                return 1
        return 0

    def getRangeAction(self, actionValue):
        last = 0.000
        for i in range(1, len(Macro.RangeRef)):
            #print (last, actionValue, Macro.RangeRef[i])
            if last <= actionValue < Macro.RangeRef[i]:
                return Macro.ActionRef[last]
            last = Macro.RangeRef[i]
        return ""

    def funcDroite(self):
        self.cases[1] = self.cases[3]
        self.cases[2] = ["-1"]
        self.cases[3] = ["-1"]
        self.socket.sendData("droite")
        self.lastCommand = "droite"

    def funcGauche(self):
        self.cases[3] = self.cases[1]
        self.cases[2] = ["-1"]
        self.cases[1] = ["-1"]
        self.socket.sendData("gauche")
        self.lastCommand = "gauche"

    def funcAvance(self):
        self.cases[0] = self.cases[2]
        self.cases[1] = ["-1"]
        self.cases[2] = ["-1"]
        self.cases[3] = ["-1"]
        self.socket.sendData("avance")
        self.lastCommand = "avance"

    def funcVoir(self):
        self.socket.sendData("voir")
        self.lastCommand = "voir"


    def funcPrend(self):
        case = self.cases[0]
        if len(case) > 0:
            self.socket.sendData("prend " + case[0])
            case.remove(case[0])
        else:
            eprint("Impossible to execute 'prend' ")
        self.lastCommand = "prend"

    def funcExpulse(self):
        print ("Expulse ?")
        self.lastCommand = "prend"

    def funcIncantation(self):
        self.putResOnCase()
        self.socket.sendData("incantation")
        self.lastCommand = "incantation"

    def funcFork(self):
        print ("fork")
        self.lastCommand = "fork"


    def chooseAnAction(self):
        inputs = []
        inputs.append(self.life)
        inputs.append(self.level)
        inputs.append(self.freePlace)

        inputs.append(self.getCaseLevel(0))
        inputs.append(self.getCaseLevel(1))
        inputs.append(self.getCaseLevel(2))
        inputs.append(self.getCaseLevel(3))

        inputs.append(self.getCaseFood(0))
        inputs.append(self.getCaseFood(1))
        inputs.append(self.getCaseFood(2))
        inputs.append(self.getCaseFood(3))

        inputs.append(self.isLevelComplete())
        inputs.append(self.canIncant())

        print ("INPUTS:", inputs)
        actionValue = self.neuralNetwork.update(inputs)[0]
        actionChoosen = self.getRangeAction(actionValue)
        if actionChoosen == "":
            eprint("Error in value of the neuralNetwork:", actionValue)
        print (actionValue, "--->", actionChoosen)
        command = input("Command:")
        if command == "quit":
            self.neuralNetwork.save()
            sys.exit()
        elif command == "learn":
            pass #learn it
        Macro.CommandRef[actionChoosen](self)

    def updateInfo(self):
        message = ""
        self.socket.sendData("inventaire")
        while message == "":
            message = self.socket.selectData()
        self.life = int(message.replace("{", "").replace("}", "").split(",")[0].split(" ")[1])

    def initData(self, message):
        # TODO receive "{xx,xx,,,,}\n9\r\n  with voir + connect_nbr CHANGE PARSING
        message = message.split("\n")
        self.getCase(message[0])
        self.freePlace = int(message[1])
        return False

    def receiveMessage(self, message):
        if self.firstReceive is True:
            self.firstReceive = self.initData(message)
        elif message == "mort":
            return
        if self.lastCommand != "":
            if self.lastCommand == "voir" and message[0] == "{":
                self.getCase(message)
            self.lastCommand = ""
        print (time.strftime("%H:%M:%S"), ":", message)

    def run(self):

        self.createNeuralNetwork(False)
        while True:
            message = self.socket.selectData()
            if message:
                self.receiveMessage(message)
            if self.firstAction is True:
                self.socket.sendData("voir")
                self.socket.sendData("connect_nbr")
                self.firstAction = False
            if self.lastCommand == "" and  self.firstReceive is False:
                self.updateInfo()
                self.chooseAnAction()

            message = ""