<commit_before>"""
Module for reading out CO2Meter USB devices
via a hidraw device under Linux
"""
import sys
import fcntl
import threading
import weakref

CO2METER_CO2 = 0x50
CO2METER_TEMP = 0x42
CO2METER_HUM = 0x41
HIDIOCSFEATURE_9 = 0xC0094806


def _co2_worker(weak_self):
    """
    Worker thread that constantly reads from the usb device.
    """
    while True:
        self = weak_self()
        if self is None:
            break
        self._read_data()

        if not self._running:
            break
        del self


class CO2Meter:
    _key = [<KEY>]
    _device = ""
    _values = {}
    _file = ""
    _running = True
    _callback = None

    def __init__(self, device="/dev/hidraw0", callback=None):
        self._device = device
        self._callback = callback
        self._file = open(device, "a+b", 0)

        if sys.version_info >= (3,):
            set_report = [0] + self._key
            fcntl.ioctl(self._file, HIDIOCSFEATURE_9, bytearray(set_report))
        else:
            set_report_str = "\x00" + "".join(chr(e) for e in self._key)
            fcntl.ioctl(self._file, HIDIOCSFEATURE_9, set_report_str)

        thread = threading.Thread(target=_co2_worker, args=(weakref.ref(self),))
        thread.daemon = True
        thread.start()

    def _read_data(self):
        """
        Function that reads from the device, decodes it, validates the checksum
        and adds the data to the dict _values.
        Additionally calls the _callback if set
        """
        try:
            result = self._file.read(8)
            if sys.version_info >= (3,):
                data = list(result)
            else:
                data = list(ord(e) for e in result)

            decrypted = self._decrypt(data)
            if decrypted[4] != 0x0d or (sum(decrypted[:3]) & 0xff) != decrypted[3]:
                print(self._hd(data), " => ", self._hd(decrypted), "Checksum error")
            else:
                operation = decrypted[0]
                val = decrypted[1] << 8 | decrypted[2]
                self._values[operation] = self._convert_value(operation, val)
                if self._callback is not None:
                    if operation in {CO2METER_CO2, CO2METER_TEMP} or (operation == CO2METER_HUM and val != 0):
                        self._callback(sensor=operation, value=val)
        except:
            self._running = False

    def _decrypt(self, data):
        """
        The received data has some weak crypto that needs to be decoded first
        """
        cstate = [0x48, 0x74, 0x65, 0x6D, 0x70, 0x39, 0x39, 0x65]
        shuffle = [2, 4, 0, 7, 1, 6, 5, 3]

        phase1 = [0] * 8
        for i, j in enumerate(shuffle):
            phase1[j] = data[i]<commit_msg>Only decrypt when data seems encrypted<commit_after>"""
Module for reading out CO2Meter USB devices
via a hidraw device under Linux
"""
import sys
import fcntl
import threading
import weakref

CO2METER_CO2 = 0x50
CO2METER_TEMP = 0x42
CO2METER_HUM = 0x41
HIDIOCSFEATURE_9 = 0xC0094806


def _co2_worker(weak_self):
    """
    Worker thread that constantly reads from the usb device.
    """
    while True:
        self = weak_self()
        if self is None:
            break
        self._read_data()

        if not self._running:
            break
        del self


class CO2Meter:
    _key = [0xc4, 0xc6, 0xc0, 0x92, 0x40, 0x23, 0xdc, 0x96]
    _device = ""
    _values = {}
    _file = ""
    _running = True
    _callback = None

    def __init__(self, device="/dev/hidraw0", callback=None):
        self._device = device
        self._callback = callback
        self._file = open(device, "a+b", 0)

        if sys.version_info >= (3,):
            set_report = [0] + self._key
            fcntl.ioctl(self._file, HIDIOCSFEATURE_9, bytearray(set_report))
        else:
            set_report_str = "\x00" + "".join(chr(e) for e in self._key)
            fcntl.ioctl(self._file, HIDIOCSFEATURE_9, set_report_str)

        thread = threading.Thread(target=_co2_worker, args=(weakref.ref(self),))
        thread.daemon = True
        thread.start()

    def _read_data(self):
        """
        Function that reads from the device, decodes it, validates the checksum
        and adds the data to the dict _values.
        Additionally calls the _callback if set
        """
        try:
            result = self._file.read(8)
            if sys.version_info >= (3,):
                data = list(result)
            else:
                data = list(ord(e) for e in result)

            if data[4] != 0x0d:
                """ newer devices don't encrypt the data, if byte 4!=0x0d assume encrypted data """
                data = self._decrypt(data)
                
            if data[4] != 0x0d or (sum(data[:3]) & 0xff) != data[3]:
                print(self._hd(data), "Checksum error")
                return
            
            operation = data[0]
            val = data[1] << 8 | data[2]
            self._values[operation] = self._convert_value(operation, val)
            if self._callback is not None:
                if operation in {CO2METER_CO2, CO2METER_TEMP} or (operation == CO2METER_HUM and val != 0):
                    self._callback(sensor=operation, value=val)
        except:
            self._running = False

    def _decrypt(self, data):
        """
        The received data has some weak crypto that needs to be decoded first
        """
        cstate = [0x48, 0x74, 0x65, 0x6D, 0x70, 0x39, 0x39, 0x65]
        shuffle = [2, 4, 0, 7, 1, 6, 5, 3]

        phase1 = [0] * 8
        for i, j in enumerate(shuffle):
            phase1[j] = data[i]
{'fraction_non_alphanumeric': 0.10425191247109056, 'fraction_numerical': 0.03504714463618573, 'mean_word_length': 1.9220374220374221, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '443712', 'n_tokens_mistral': 1896, 'n_tokens_neox': 1781, 'n_words': 497}