# Path: conpot/utils/networking.py
# def str_to_bytes(x):
#     return x if isinstance(x, bytes) else str(x).encode("ascii")


from struct import pack, unpack
from conpot.protocols.s7comm.exceptions import ParseException
from conpot.utils.networking import str_to_bytes
import struct
# This implementation of the S7 protocol is highly inspired
# by the amazing plcscan work by the ScadaStrangeLove group.
# https://code.google.com/p/plcscan/source/browse/trunk/s7.py



class COTP(object):
    def __init__(self, tpdu_type=0, opt_field=0, payload="", trailer=""):
        self.tpdu_type = tpdu_type
        self.opt_field = opt_field
        self.payload = payload
        self.trailer = trailer

        if self.tpdu_type == 240:
            self.packet_length = 2
        else:
            self.packet_length = 1 + len(self.payload)

            # COTP BASE PACKET FORMAT:
            # -------------------------------------
            #           1 byte      LENGTH (=n + 1)
            #           1 byte      TPDU TYPE
            #           1 byte      OPT FIELD (optional!), bitmask!
            #           n bytes     TPDU PAYLOAD
            #           x bytes     TRAILER (optional!), most probably containing S7.

    def pack(self):
        if self.tpdu_type == 0xF0:
            return (
                pack("!BBB", self.packet_length, self.tpdu_type, self.opt_field)

# Path: conpot/utils/networking.py
# def str_to_bytes(x):
#     return x if isinstance(x, bytes) else str(x).encode("ascii")


# Path: conpot/protocols/s7comm/cotp.py
from struct import pack, unpack
from conpot.protocols.s7comm.exceptions import ParseException
from conpot.utils.networking import str_to_bytes
import struct

# This implementation of the S7 protocol is highly inspired
# by the amazing plcscan work by the ScadaStrangeLove group.
# https://code.google.com/p/plcscan/source/browse/trunk/s7.py



class COTP(object):
    def __init__(self, tpdu_type=0, opt_field=0, payload="", trailer=""):
        self.tpdu_type = tpdu_type
        self.opt_field = opt_field
        self.payload = payload
        self.trailer = trailer

        if self.tpdu_type == 240:
            self.packet_length = 2
        else:
            self.packet_length = 1 + len(self.payload)

            # COTP BASE PACKET FORMAT:
            # -------------------------------------
            #           1 byte      LENGTH (=n + 1)
            #           1 byte      TPDU TYPE
            #           1 byte      OPT FIELD (optional!), bitmask!
            #           n bytes     TPDU PAYLOAD
            #           x bytes     TRAILER (optional!), most probably containing S7.

    def pack(self):
        if self.tpdu_type == 0xF0:
            return (
                pack("!BBB", self.packet_length, self.tpdu_type, self.opt_field)

                + str_to_bytes(self.payload)