def send(self, sock):
        """
        :param sock: a working UDP socket
        """
        if self.packed_data is None:
            self.build()
        if self.is_ready:
            try:
                broad_ip = None
                for iface in netifaces.interfaces():
                    try:
                        broad_ip = netifaces.ifaddresses(iface)[
                            netifaces.AF_INET][0]["broadcast"]
                        # cfg.log("Found a correct interface : " + str(iface))
                        break
                    except:
                        pass
                        # cfg.log("Not a correct interface : " + str(iface))
                if broad_ip is None:
                    raise Exception("No interface available !")
                if self.to_cuid != cfg.CUID_SERVER or self.to_cuid == cfg.CUID_BROASCAST:
                    sock.sendto(self.get_packed_data(),
                                (broad_ip, cfg.COMMUNICATION_PORT_DEVICE))
                if self.to_cuid == cfg.CUID_SERVER or self.to_cuid == cfg.CUID_BROASCAST:
                    sock.sendto(self.get_packed_data(),
                                (broad_ip, cfg.COMMUNICATION_PORT_SERVER))

                return True
            except Exception as e:
                cfg.warn("Network error : " + "".join(e.args))
            cfg.log("Sending : " +
                    utls.bytes_to_hex_string(self.get_packed_data()))
        else:
            cfg.warn("Packet is not ready !")
        return False
예제 #2
0
파일: mydb.py 프로젝트: jplf/jplab
def main(argv):
    
    try:                                
        opts, args = getopt.getopt(argv, "hu:p:d:o:t:",
                        ["help", "user="******"password="******"db=", "operation=", "table="])
        
    except getopt.GetoptError:          
        usage()

    user     = config.user
    password = None
    op  = 'list_db'
    db  = config.db
    tbl = None
    
    for opt, val in opts:
        if opt in ('-h', '--help'):
            usage()
        elif opt in ('-u', '--user'):
            user = val
        elif opt in ('-p', '--password'):
            password = val
        elif opt in ('-d', '--db'):
            db = val
        elif opt in ('-o', '--operation'):
            op = val
        elif opt in ('-t', '--table'):
            tbl = val

    if user is None or password is None:
        usage()
        
    config.warn("Hi " + user)

    try:
        my_db = MySQLdb.connect(user=user, passwd=password,
                            unix_socket='/tmp/mysql.sock')

    except:
        print sys.exc_info()[1]
        sys.exit(1)
        
    global handle
    handle = my_db.cursor()
    
    if op == 'list_db':
        list_db()
        sys.exit(0)
        
    handle.execute('use ' + db)
    
    if op == 'list_tables':
        list_tables()
        
    elif op == 'dump_table':
        dump_table(tbl)
        
    else:
        usage()
    def __init__(self, guid, is_server=cfg.IS_SERVER, data_callback=None):
        """
        :param guid: the guid of the device
        """
        super(Communicator, self).__init__()

        # setting up
        self.data_callback = data_callback

        self.is_server = is_server
        self.global_uid = guid

        # setting network
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            port = cfg.COMMUNICATION_PORT_DEVICE
            if self.is_server:
                port = cfg.COMMUNICATION_PORT_SERVER
            self.sock.bind(('', port))
            self.address = self.sock.getsockname()
            cfg.log("Listening on" + str(self.address))
        except:
            cfg.warn("Socket setup error !")

        self.sender = Sender(self.sock)
        self.receiver = Receiver(lambda p: self.on_receive(p), self.sock)

        if self.is_server:
            self.communication_uid = cfg.CUID_SERVER
            # databases setup
            try:
                self.database = pymysql.connect(host=cfg.DB_IP,
                                                user=cfg.DB_USER,
                                                password=cfg.DB_PASS,
                                                db=cfg.DB_NAME,
                                                charset=cfg.DB_CHARSET)
            except pymysql.err.Error:
                cfg.warn("Database setup error !")

            # clean tables
            self.db_query("DELETE FROM " + cfg.TB_CONNECTIONS)
            self.db_query("DELETE FROM " + cfg.TB_SPECIFICATIONS)

            self.ready = True
        else:
            # connection setup if
            self.init_connection()
            self.ready = False
        """
        self.daemon = True
        # wait thread to stop before exiting program
        """

        while not self.is_ready():
            continue
 def reconstruct(self, raw_packet):
     cfg.log("Reading : " + utls.bytes_to_hex_string(raw_packet))
     try:
         self.set_to_cuid(int.from_bytes(raw_packet[:1], "big"))
         self.set_from_cuid(int.from_bytes(raw_packet[1:2], "big"))
         self.set_fonction_id(int.from_bytes(raw_packet[2:3], "big"))
         datlen = int.from_bytes(raw_packet[3:4], "big")
         self.set_data(raw_packet[4:4 + datlen])
         found_crc = int.from_bytes(raw_packet[4 + datlen:], "big")
         correct_crc = self.calculate_crc(raw_packet[:4 + datlen])
         if correct_crc != found_crc:
             cfg.warn("CRC Error : " + str(found_crc) + " != " +
                      str(correct_crc) + " !")
         else:
             cfg.log("CRC correct : " + str(found_crc))
     except:
         cfg.warn("Parse error...")
     return self
    def on_receive(self, packet):
        cfg.log(packet)
        if packet.get_to_cuid() == self.get_cuid() or packet.get_to_cuid(
        ) == cfg.CUID_BROASCAST:
            if packet.get_fonction_id() == cfg.FCT_INFO:
                # self.exec_callback(4, [packet.get_from_cuid(), packet.get_data()])
                print("Info : " + packet.get_data().decode("ascii"))
            elif packet.get_fonction_id() == cfg.FCT_IAMNEW and self.is_server:
                # I'M NEW
                other_guid = binascii.hexlify(
                    packet.get_data()).decode("ascii")
                cfg.log("I'M NEW : " + str(other_guid))
                # finding new CUID
                if self.database is not None:
                    self.db_query(
                        "DELETE FROM " + cfg.TB_CONNECTIONS + " WHERE GUID=%s",
                        (other_guid))
                    dat = self.db_query("SELECT CUID FROM " +
                                        cfg.TB_CONNECTIONS)
                    cfg.log("Already used CUIDs : " + str(dat))
                    is_ok = True
                    possible_cuid = 0
                    for possible_cuid in cfg.CUID_LIST_USABLE:
                        is_ok = True
                        for p in dat:
                            if possible_cuid in p:
                                is_ok = False
                        if is_ok:
                            break
                    if is_ok:
                        cfg.log("Found : " + str(possible_cuid))
                        # if CUID found -> register and send it
                        found_cuid = possible_cuid
                        self.db_query(
                            "INSERT INTO " + cfg.TB_CONNECTIONS +
                            " (GUID, CUID) VALUES (%s, %s)",
                            (other_guid, found_cuid))
                        # registered
                        self.send(
                            cfg.CUID_BROASCAST, cfg.FCT_YOURETHIS,
                            binascii.unhexlify(other_guid) +
                            found_cuid.to_bytes(1, "big"))
                        # sent
                    else:
                        cfg.warn("No usable CUID found !")
                else:
                    self.send(
                        cfg.CUID_BROASCAST, cfg.FCT_YOURETHIS,
                        binascii.unhexlify(other_guid) +
                        (2).to_bytes(1, "big"))
            elif packet.get_fonction_id(
            ) == cfg.FCT_YOURETHIS and not self.is_server:
                # YOU'RE THIS
                cfg.log(
                    "YOU'RE THIS " + utls.bytes_to_hex_string(
                        binascii.hexlify(packet.get_data()[:cfg.SIZE_GUID])) +
                    " - " + utls.bytes_to_hex_string(
                        binascii.hexlify(packet.get_data()[cfg.SIZE_GUID:])))
                cfg.log(
                    utls.bytes_to_hex_string(
                        binascii.hexlify(packet.get_data()[:cfg.SIZE_GUID])) +
                    " == " + self.get_guid() + " -> " + str(
                        utls.bytes_to_hex_string(
                            binascii.hexlify(packet.get_data()[:cfg.SIZE_GUID])
                        ) == self.get_guid()))
                if utls.bytes_to_hex_string(
                        binascii.hexlify(packet.get_data()
                                         [:cfg.SIZE_GUID])) == self.get_guid():
                    my_new_cuid = int.from_bytes(
                        packet.get_data()[cfg.SIZE_GUID:], "big")
                    cfg.log("YOU'RE THIS : " + str(my_new_cuid))
                    self.set_cuid(my_new_cuid)
                    # got new cuid
                    self.send(packet.get_from_cuid(), cfg.FCT_INFO, b'Hello !')
                self.ready = True
            elif packet.get_fonction_id(
            ) == cfg.FCT_GIVEDATA and self.is_server:
                # GIVE DATA
                cfg.log("Give DATA :" + str(packet))
                if self.db_query("SELECT inited FROM " + cfg.TB_CONNECTIONS +
                                 " WHERE cuid=" +
                                 str(packet.get_from_cuid()))[0][0] == 0:
                    cfg.log("Device not initialized !")
                    return

                vals = []
                for i in range(
                        self.db_query("SELECT numchan FROM " +
                                      cfg.TB_SPECIFICATIONS + " WHERE cuid=" +
                                      str(packet.get_from_cuid()))[0][0]):
                    vals.append(
                        int.from_bytes(
                            packet.get_data()[(i * cfg.DATA_VALUE_SIZE //
                                               8):((i + 1) *
                                                   cfg.DATA_VALUE_SIZE // 8)],
                            "big"))
                print(str(packet.get_from_cuid()) + " -> " + str(vals))
                if self.data_callback:
                    self.data_callback(packet.get_from_cuid(), vals)
            elif packet.get_fonction_id() == cfg.FCT_MYSPEC and self.is_server:
                # MY SPEC
                cfg.log("Give MYSPEC :" + str(packet))
                # | NCHAN | NLEN | DLEN | NAME   | DESC   |
                # | (8b)  | (8b) | (8b) | (NLENb)| (DLENb)|
                nchan = packet.get_data()[0]
                nlen = packet.get_data()[1]
                dlen = packet.get_data()[2]
                name = ""
                desc = ""
                for i in range(nlen):
                    name += chr(packet.get_data()[3 + i])
                for i in range(dlen):
                    desc += chr(packet.get_data()[3 + nlen + i])
                cfg.log(name + " - " + desc)
                self.db_query(
                    "UPDATE " + cfg.TB_CONNECTIONS +
                    " SET inited=%s WHERE CUID=%s",
                    (1, packet.get_from_cuid()))
                self.db_query(
                    "INSERT INTO " + cfg.TB_SPECIFICATIONS +
                    " (numchan,name,description,cuid) VALUE (%s,%s,%s,%s)",
                    (nchan, name, desc, packet.get_from_cuid()))
                cfg.log("DB Query finished !")
            elif packet.get_fonction_id() == cfg.FCT_GOODBYE:
                # GOODBYE
                cfg.log("Give GOODBYE :" + str(packet))
                if self.is_server:
                    self.db_query(
                        "DELETE FROM " + cfg.TB_CONNECTIONS + " WHERE CUID=%s",
                        (packet.get_from_cuid()))
                    self.db_query(
                        "DELETE FROM " + cfg.TB_SPECIFICATIONS +
                        " WHERE CUID=%s", (packet.get_from_cuid()))
                else:
                    # self.callbacks['stop']()
                    pass