Beispiel #1
0
    def _on_get_data(self, data: list):
        """
        传感器数据回调函数
        :param data: 数据
        :return:
        """
        # 每一次回调,每种类型的数据最多只取一次,防止出现抖动
        acc_data_found = False
        gyro_data_found = False
        ang_data_found = False
        for i in range(len(data) - 11):
            if not (data[i] == 0x55 and data[i + 1] & 0x50 == 0x50):
                continue
            if data[i] == 0x55 and data[i + 1] == 0x51 and sum(
                    data[i:i + 10]) & 255 == data[i + 10]:
                axl, axh, ayl, ayh, azl, azh, *_ = data[i + 2:i + 11]
                sensor_data = [
                    get_current_timestamp(),
                    (np.short((axh << 8) | axl)) / 32768 * 16 * 9.8,
                    (np.short((ayh << 8) | ayl)) / 32768 * 16 * 9.8,
                    (np.short((azh << 8) | azl)) / 32768 * 16 * 9.8
                ]
                if not acc_data_found:
                    acc_data_found = True
                    self.acc_to_display.append(sensor_data)
                    self.acc_to_detect_cycle.append(sensor_data)
            if data[i] == 0x55 and data[i + 1] == 0x52 and sum(
                    data[i:i + 10]) & 255 == data[i + 10]:
                wxl, wxh, wyl, wyh, wzl, wzh, *_ = data[i + 2:i + 11]
                sensor_data = [
                    get_current_timestamp(), (np.short(wxh << 8) | wxl) /
                    32768 * 2000 * (math.pi / 180),
                    (np.short(wyh << 8) | wyl) / 32768 * 2000 *
                    (math.pi / 180),
                    (np.short(wzh << 8) | wzl) / 32768 * 2000 * (math.pi / 180)
                ]
                if not gyro_data_found:
                    gyro_data_found = True
                    self.gyro_to_display.append(sensor_data)
                    self.gyro_to_detect_cycle.append(sensor_data)

            if data[i] == 0x55 and data[i + 1] == 0x53 and sum(
                    data[i:i + 10]) & 255 == data[i + 10]:
                rol, roh, pil, pih, yal, yah, *_ = data[i + 2:i + 11]
                sensor_data = [
                    get_current_timestamp(),
                    (np.short(roh << 8 | rol) / 32768 * 180),
                    (np.short(pih << 8 | pil) / 32768 * 180),
                    (np.short(yah << 8 | yal) / 32768 * 180)
                ]
                if not ang_data_found:
                    ang_data_found = True
                    self.ang_to_display.append(sensor_data)
                    self.ang_to_detect_cycle.append(sensor_data)
        self.fix_data_count()
def get_data_set_as_table(catalog_index=settings.DEFAULT_CATALOG_INDEX, skip_rows=0, sep=';', return_index=False, data=None, description=None):
    if (data is None) and (description is None):
        data, description = get_data_set(catalog_index, skip_rows, sep)
    else:
        data, description = data, description
    data_html = data.to_html()
    data_html = util_design.get_custom_table_header() + data_html[82:]
    if return_index:
        return data_html, description, get_current_timestamp(), list(data)
    else:
        return data_html, description, get_current_timestamp()
Beispiel #3
0
def make_question(title, message, image=""):
    result = {
        'id': generate_id(persistence.get_ids('question')),
        'submission_time': util.decode_time_for_human(util.get_current_timestamp()),
        'view_number': 0,
        'vote_number': 0,
        'title': title,
        'message': message,
        'image': image,
    }
    return result
Beispiel #4
0
 def firewall_simulator():
     while True:
         timestamp = util.get_current_timestamp()
         status = "BLOCK"
         interface = interfaces[randint(0, len(interfaces) - 1)]
         source_ip = firewall_ips[randint(0, len(firewall_ips) - 1)]
         destination_ip = my_ip
         log = " ".join(
             [timestamp, status, interface, source_ip, destination_ip])
         util.save_firewall_log(log)
         print(log)
         sleep(2)
Beispiel #5
0
    def __init__(self, sensor_data: Union[int, None] = None):
        """
        初始化
        :param sensor_data: 数据类型,0 - 9 表示使用data0中的数据进行模拟,"usb"表示usb数据,"socket"表示使用socket
        """
        # 传感器,用于实时数据
        self.sensor = None
        # 模拟数据
        self.sensor_data = sensor_data
        # 最多保存的数据点的个数
        self.ACC_POINT_COUNT = 400
        self.GYRO_POINT_COUNT = 400
        self.ANG_POINT_COUNT = 400
        # 原始数据,显示使用
        self.acc_to_display = []
        self.gyro_to_display = []
        self.ang_to_display = []
        # 用于检测步态的数据
        self.acc_to_detect_cycle = []
        self.gyro_to_detect_cycle = []
        self.ang_to_detect_cycle = []

        self.conn = None  # socket连接

        logger.info("是否使用实时数据:{0}".format(bool(sensor_data is None)))
        if type(sensor_data) == int and 0 <= sensor_data <= 9:
            assert sensor_data is None or 0 <= int(sensor_data) <= 9, "数据错误"
            self.last_data_index = 0  # 上一次载入的数据的index
            self.last_data_timestamp = None  # 传感器开始时间,用于模拟数据的时候读取数据
            self.acc_data_lines = None  # 模拟数据
            self.gyro_data_lines = None  # 模拟数据
            logger.info("载入data0加速度数据")
            self.acc_data_lines = load_data0_data(
                os.path.join(DATA_DIR, "data0",
                             "accData{0}.txt".format(sensor_data)))
            logger.info("载入data0陀螺仪数据")
            self.gyro_data_lines = load_data0_data(
                os.path.join(DATA_DIR, "data0",
                             "gyrData{0}.txt".format(sensor_data)))
            self.ang_data_lines = load_data0_data(
                os.path.join(DATA_DIR, "data0",
                             "angData{0}.txt".format(sensor_data)))
            self.last_data_timestamp = get_current_timestamp()
        elif sensor_data == "usb":
            self.set_handler()
        elif sensor_data == "socket":
            logger.info("使用socket数据")
            thread = threading.Thread(target=self._wait_socket_data)
            thread.start()
        else:
            raise Exception("错误的数据类型")
Beispiel #6
0
def make_answer(message, image, question_id, answer_id=None):
    if answer_id is None:
        id_ = generate_id(persistence.get_ids("answer"))
    else:
        id_ = answer_id
    result = {
        'id': id_,
        'submission_time': util.decode_time_for_human(util.get_current_timestamp()),
        'vote_number': 0,
        'message': message,
        'question_id': question_id,
        'image': image
    }
    return result
Beispiel #7
0
def make_comment(message, question_id, comment_id=None):
    if comment_id is None:
        id_ = generate_id(persistence.get_ids("comment"))
    else:
        id_ = comment_id
    result = {
        'id': id_,
        'submission_time': util.decode_time_for_human(util.get_current_timestamp()),
        'edited_count': 0,
        'message': message,
        'question_id': question_id,
        'answer_id': 0,
    }
    return result
Beispiel #8
0
def edit_question(cursor, dictionary):
    cursor.execute("""
                    UPDATE question
                    SET submission_time = '{submission_time}',
                        view_number = {view_number},
                        vote_number = {vote_number},
                        title = '{title}',
                        message = '{message}',
                        image = '{image}'
                    WHERE id = {id};
                   """.format(submission_time=util.decode_time_for_human(util.get_current_timestamp()),
                              view_number=dictionary['view_number'],
                              vote_number=dictionary['vote_number'],
                              title=dictionary['title'],
                              message=dictionary['message'],
                              image=dictionary['image'],
                              id=dictionary['id']
                              ))
Beispiel #9
0
    def _wait_socket_data(self):
        """
        起一个socket server等数据来
        :return:
        """
        def get_headers(data):
            """将请求头转换为字典"""
            header_dict = {}
            data = str(data, encoding="utf-8")

            header, body = data.split("\r\n\r\n", 1)
            header_list = header.split("\r\n")
            for i in range(0, len(header_list)):
                if i == 0:
                    if len(header_list[0].split(" ")) == 3:
                        header_dict['method'], header_dict['url'], header_dict[
                            'protocol'] = header_list[0].split(" ")
                else:
                    k, v = header_list[i].split(":", 1)
                    header_dict[k] = v.strip()
            return header_dict

        def get_data(info):
            logger.info(len(self.acc_to_display))
            payload_len = info[1] & 127
            if payload_len == 126:
                extend_payload_len = info[2:4]
                mask = info[4:8]
                decoded = info[8:]
            elif payload_len == 127:
                extend_payload_len = info[2:10]
                mask = info[10:14]
                decoded = info[14:]
            else:
                extend_payload_len = None
                mask = info[2:6]
                decoded = info[6:]

            bytes_list = bytearray()  # 这里我们使用字节将数据全部收集,再去字符串编码,这样不会导致中文乱码
            for i in range(len(decoded)):
                chunk = decoded[i] ^ mask[i % 4]  # 解码方式
                bytes_list.append(chunk)
            try:
                body = str(bytes_list, encoding='utf-8')
            except UnicodeDecodeError as err:
                logger.exception(err)
                return ""
            return body

        logger.info("等待连接")
        sock = socket.socket()
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(("0.0.0.0", 80))
        sock.listen(5)
        while True:
            # 等待用户连接
            self.conn, addr = sock.accept()
            logger.info("connect ")
            # 获取握手消息,magic string ,sha1加密
            # 发送给客户端
            # 握手消息
            data = self.conn.recv(8096)
            headers = get_headers(data)
            # 对请求头中的sec-websocket-key进行加密
            response_tpl = "HTTP/1.1 101 Switching Protocols\r\n" \
                           "Upgrade:websocket\r\n" \
                           "Connection: Upgrade\r\n" \
                           "Sec-WebSocket-Accept: %s\r\n" \
                           "WebSocket-Location: ws://%s%s\r\n\r\n"

            magic_string = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
            value = headers['Sec-WebSocket-Key'] + magic_string
            ac = base64.b64encode(hashlib.sha1(value.encode('utf-8')).digest())
            response_str = response_tpl % (ac.decode('utf-8'), headers['Host'],
                                           headers['url'])
            # 响应【握手】信息
            self.conn.send(bytes(response_str, encoding='utf-8'))
            # 可以进行通信
            while True:
                data = self.conn.recv(8096)
                data = get_data(data)
                if data:
                    logger.info(data)
                    try:
                        data = eval(data)
                    except Exception as err:
                        logger.exception(err)
                        continue
                    if data[0] == "acc":
                        data = [
                            get_current_timestamp(), data[1], data[2], data[3]
                        ]
                        self.acc_to_display.append(data)
                        self.acc_to_detect_cycle.append(data)
                    elif data[0] == "gyro":
                        data = [
                            get_current_timestamp(), data[1] * (math.pi / 180),
                            data[2] * (math.pi / 180),
                            data[3] * (math.pi / 180)
                        ]
                        self.gyro_to_display.append(data)
                        self.gyro_to_detect_cycle.append(data)
                    else:
                        raise Exception("错误的socket数据")
                self.fix_data_count()