Add CRC to modbus frame (for RTU mode)

        :param frame: modbus RTU frame
        :type frame: str (Python2) or class bytes (Python3)
        :returns: modbus RTU frame with CRC
        :rtype: str (Python2) or class bytes (Python3)
541232
def _add_crc(self, frame):
        
        crc = struct.pack('<H', crc16(frame))
        return frame + crc
670961
def make_options_frame(self):
        
        self.tab_frame = ttk.Notebook(self.option_frame, width=800)
        self.tab_configure = tk.Frame(self.tab_frame)
        self.tab_classify = tk.Frame(self.tab_frame)
        self.make_configure_tab()
        self.make_classify_tab()

        self.tab_frame.add(self.tab_configure, text="Configure")
        self.tab_frame.add(self.tab_classify, text="Classify")
        self.tab_frame.pack(fill=tk.BOTH, expand=True)
110400
def s2i_frameid(x):
    
    try:
        return {
            "RT_CLASS_3": 0x0100,
            "RT_CLASS_1": 0x8000,
            "RT_CLASS_UDP": 0xC000,
            "FragmentationFrameID": 0xFF80,
        }[x]
    except KeyError:
        pass
    try:
        return next(key for key, value in six.iteritems(PNIO_FRAME_IDS)
                    if value == x)
    except StopIteration:
        pass
    return x
789690
def send(self, payload, opcode=ABNF.OPCODE_TEXT):
        

        frame = ABNF.create_frame(payload, opcode)
        return self.send_frame(frame)
38136
def next_frame_id(self):
        
        # Python 2/3 compatible way of converting 1 to "\x01" in py2 or b"\x01"
        # in py3.
        fid = bytes(bytearray((self._frame_id,)))
        self._frame_id += 1
        if self._frame_id > 0xFF:
            self._frame_id = 1
        try:
            del self._rx_frames[fid]
        except KeyError:
            pass
        return fid
1312284
def write_frame(self, frame_type, channel, payload):
        
        size = len(payload)
        self._write(pack('>BHI%dsB' % size,
            frame_type, channel, size, payload, 0xce))
197476
def crc16(frame):
    
    crc = 0xFFFF
    for index, item in enumerate(bytearray(frame)):
        next_byte = item
        crc ^= next_byte
        for i in range(8):
            lsb = crc & 1
            crc >>= 1
            if lsb:
                crc ^= 0xA001
    return crc
692455
function(path, options) {
    var modbus = this;

    // options
    options = options || {};

    // disable auto open, as we handle the open
    options.autoOpen = false;

    // internal buffer
    this._buffer = Buffer.from("");
    this._id = 0;
    this._cmd = 0;
    this._length = 0;

    // create the SerialPort
    this._client = new SerialPort(path, options);

    // register the port data event
    this._client.on("data", function(data) {

        // add new data to buffer
        modbus._buffer = Buffer.concat([modbus._buffer, data]);

        modbusSerialDebug({ action: "receive serial ascii port", data: data, buffer: modbus._buffer });
        modbusSerialDebug(JSON.stringify({ action: "receive serial ascii port strings", data: data, buffer: modbus._buffer }));

        // check buffer for start delimiter
        var sdIndex = modbus._buffer.indexOf(0x3A); // ascii for ':'
        if(sdIndex === -1) {
            // if not there, reset the buffer and return
            modbus._buffer = Buffer.from("");
            return;
        }
        // if there is data before the start delimiter, remove it
        if(sdIndex > 0) {
            modbus._buffer = modbus._buffer.slice(sdIndex);
        }
        // do we have the complete message (i.e. are the end delimiters there)
        if(modbus._buffer.includes("\r\n", 1, "ascii") === true) {
            // check there is no excess data after end delimiters
            var edIndex = modbus._buffer.indexOf(0x0A); // ascii for '\n'
            if(edIndex !== modbus._buffer.length - 1) {
                // if there is, remove it
                modbus._buffer = modbus._buffer.slice(0, edIndex + 1);
            }

            // we have what looks like a complete ascii encoded response message, so decode
            var _data = _asciiDecodeResponseBuffer(modbus._buffer);
            modbusSerialDebug({ action: "got EOM", data: _data, buffer: modbus._buffer });
            if(_data !== null) {

                // check if this is the data we are waiting for
                if (_checkData(modbus, _data)) {
                    modbusSerialDebug({ action: "emit data serial ascii port", data: data, buffer: modbus._buffer });
                    modbusSerialDebug(JSON.stringify({ action: "emit data serial ascii port strings", data: data, buffer: modbus._buffer }));
                    // emit a data signal
                    modbus.emit("data", _data);
                }
            }
            // reset the buffer now its been used
            modbus._buffer = Buffer.from("");
        } else {
            // otherwise just wait for more data to arrive
        }
    });

    /**
     * Check if port is open.
     *
     * @returns {boolean}
     */
    Object.defineProperty(this, "isOpen", {
        enumerable: true,
        get: function() {
            return this._client.isOpen;
        }
    });

    EventEmitter.call(this);
}
1359669
def to_frame(self, slot=SLOT.SCAN_MAP):
        
        payload = self.scanmap.ljust(64, b'\0')
        return yubikey_frame.YubiKeyFrame(command=slot, payload=payload)
957393
def get_current_frame():
    
    if hasattr(sys, "_getframe"):
        # noinspection PyProtectedMember
        return sys._getframe(1)
    try:
        raise ZeroDivisionError
    except ZeroDivisionError:
        return sys.exc_info()[2].tb_frame.f_back
866759
def __read_frame(self):
        

        if self.__frame_header_cache is None:
            _logger.debug("Reading frame header.")
            (length, frame_type) = struct.unpack('!II', self.__read(8))
            self.__frame_header_cache = (length, frame_type)
        else:
            (length, frame_type) = self.__frame_header_cache

        try:
            data = self.__read(length - 4)
        except errno.EAGAIN:
            self.__frame_header_cache = (length, frame_type)
            raise

        self.__frame_header_cache = None
        self.__process_message(frame_type, data)
305881
def add_frame(frame)
      raise ArgumentError, "Invalid argument 'frame'. Expected Frame, got #{frame.class}." unless frame.is_a?(Frame)
      # Do not add it again if the frame already belongs to this instance:
      @frames << frame unless @associated_frames[frame.uid]
      @associated_frames[frame.uid] = frame
    end
966229
def crc16(cmd, use_byte=False):
    
    crc = 0xFFFF

    # crc16 计算方法, 需要使用 byte
    if hasattr(cmd, 'encode'):
        cmd = bytes.fromhex(cmd)

    for _ in cmd:
        c = _ & 0x00FF
        crc ^= c
        for i in range(8):
            if crc & 0x0001 > 0:
                crc >>= 1
                crc ^= 0xA001
            else:
                crc >>= 1

    # modbus crc16计算时,需要高/低位倒置
    t = [(crc & 0x00FF), (crc >> 8 & 0xFF)]
    crc = '%02X%02X' % (t[0], t[1])
    if use_byte:
        crc = bytes.fromhex(crc)
    return crc
184208
def modflow_hob_to_instruction_file(hob_file):
    

    hob_df = pd.read_csv(hob_file,delim_whitespace=True,skiprows=1,
                         header=None,names=["simval","obsval","obsnme"])

    hob_df.loc[:,"obsnme"] = hob_df.obsnme.apply(str.lower)
    hob_df.loc[:,"ins_line"] = hob_df.obsnme.apply(lambda x:"l1 !{0:s}!".format(x))
    hob_df.loc[0,"ins_line"] = hob_df.loc[0,"ins_line"].replace('l1','l2')

    ins_file = hob_file + ".ins"
    f_ins = open(ins_file, 'w')
    f_ins.write("pif ~\n")
    f_ins.write(hob_df.loc[:,["ins_line"]].to_string(col_space=0,
                                                     columns=["ins_line"],
                                                     header=False,
                                                     index=False,
                                                     formatters=[SFMT]) + '\n')
    hob_df.loc[:,"weight"] = 1.0
    hob_df.loc[:,"obgnme"] = "obgnme"
    f_ins.close()
    return hob_df
444911
def _pdb_frame(self):
        """"""
        if self._pdb_obj is not None and self._pdb_obj.curframe is not None:
            return self._pdb_obj.curframe
1285361
def frame(*msgs):
    """"""
    res = io.BytesIO()
    for msg in msgs:
        res.write(msg)
    msg = res.getvalue()
    return pack('L', len(msg)) + msg
749364
def _send_mbus(self, frame):
        
        # for auto_open mode, check TCP and open if need
        if self.__auto_open and not self.is_open():
            self.open()
        # send request
        bytes_send = self._send(frame)
        if bytes_send:
            if self.__debug:
                self._pretty_dump('Tx', frame)
            return bytes_send
        else:
            return None