# Path: conpot/protocols/kamstrup_management/command_responder.py
# class CommandResponder(object):
#     COMMAND_NOT_FOUND = "\r\n" "? Command not found.\r\n" "Send 'H' for help.\r\n"
# 
#     def __init__(self):
#         self.commands = {
#             "!AC": commands.AccessControlCommand(),
#             "!AS": commands.AlarmServerCommand(),
#             "!GC": commands.GetConfigCommand(),
#             "!GV": commands.SoftwareVersionCommand(),
#             "!SA": commands.SetKap1Command(),
#             "!SB": commands.SetKap2Command(),
#             "!SC": commands.SetConfigCommand(),
#             "!SD": commands.SetDeviceNameCommand(),
#             "!SH": commands.SetLookupCommand(),
#             "!SI": commands.SetIPCommand(),
#             "!SK": commands.SetWatchdogCommand(),
#             "!SN": commands.SetNameserverCommand(),
#             "!SP": commands.SetPortsCommand(),
#             "!SS": commands.SetSerialCommand(),
#             "!RC": commands.RequestConnectCommand(),
#             "!RR": commands.RequestRestartCommand(),
#             "!WM": commands.WinkModuleCommand(),
#         }
# 
#         self.help_command = commands.HelpCommand(self.commands)
# 
#     def respond(self, request):
#         stripped_request = request.strip()
# 
#         if len(stripped_request) == 0:
#             return ""  # idle
# 
#         split_request = stripped_request.split(" ", 1)
#         command = split_request[0].upper()
# 
#         if len(command) > 3:
#             return self.COMMAND_NOT_FOUND
#         elif command.startswith("Q"):
#             return  # quit
# 
#         params = None
#         if len(split_request) > 1:
#             params = split_request[1]
# 
#         if command.startswith("H"):
#             return self.help_command.run(params)
#         if command.startswith("!"):
#             if command in list(self.commands.keys()):
#                 return self.commands[command].run(params)
# 
#         return self.COMMAND_NOT_FOUND
# 
# Path: conpot/core/protocol_wrapper.py
# def conpot_protocol(cls):
#     class Wrapper(object):
#         def __init__(self, *args, **kwargs):
#             self.wrapped = cls(*args, **kwargs)
#             self.cls = cls
#             if self.cls.__name__ not in "Proxy":
#                 if self.cls not in core_interface.protocols:
#                     core_interface.protocols[self.cls] = []
# 
#                 core_interface.protocols[self.cls].append(self.wrapped)
# 
#             self.__class__.__name__ = self.cls.__name__
# 
#         def __getattr__(self, name):
#             if name == "handle":
#                 # assuming that handle function from a class is only called when a client tries to connect with an
#                 # enabled protocol, update the last_active (last_attacked attribute)
#                 # FIXME: No handle function in HTTPServer
#                 core_interface.last_active = datetime.now().strftime(
#                     "%b %d %Y - %H:%M:%S"
#                 )
#             return self.wrapped.__getattribute__(name)
# 
#         def __repr__(self):
#             return self.wrapped.__repr__()
# 
#         __doc__ = cls.__doc__
#         __module__ = cls.__module__
# 
#     return Wrapper
# 
# Path: conpot/utils/networking.py
# def str_to_bytes(x):
#     return x if isinstance(x, bytes) else str(x).encode("ascii")


import logging
import socket
import gevent
import conpot.core as conpot_core
from gevent.server import StreamServer
from .command_responder import CommandResponder
from conpot.core.protocol_wrapper import conpot_protocol
from conpot.utils.networking import str_to_bytes

logger = logging.getLogger(__name__)


@conpot_protocol
class KamstrupManagementServer(object):
    def __init__(self, template, template_directory, args):
        self.command_responder = CommandResponder()
        self.banner = "\r\nWelcome...\r\nConnected to [{0}]\r\n"
        logger.info("Kamstrup management protocol server initialized.")
        self.server = None

    def handle(self, sock, address):
        session = conpot_core.get_session(
            "kamstrup_management_protocol",
            address[0],
            address[1],
            sock.getsockname()[0],
            sock.getsockname()[1],
        )
        logger.info(
            "New Kamstrup connection from %s:%s. (%s)",
            address[0],
            address[1],
            session.id,
        )
        session.add_event({"type": "NEW_CONNECTION"})

        try:
            sock.send(

# Path: conpot/protocols/kamstrup_management/command_responder.py
# class CommandResponder(object):
#     COMMAND_NOT_FOUND = "\r\n" "? Command not found.\r\n" "Send 'H' for help.\r\n"
# 
#     def __init__(self):
#         self.commands = {
#             "!AC": commands.AccessControlCommand(),
#             "!AS": commands.AlarmServerCommand(),
#             "!GC": commands.GetConfigCommand(),
#             "!GV": commands.SoftwareVersionCommand(),
#             "!SA": commands.SetKap1Command(),
#             "!SB": commands.SetKap2Command(),
#             "!SC": commands.SetConfigCommand(),
#             "!SD": commands.SetDeviceNameCommand(),
#             "!SH": commands.SetLookupCommand(),
#             "!SI": commands.SetIPCommand(),
#             "!SK": commands.SetWatchdogCommand(),
#             "!SN": commands.SetNameserverCommand(),
#             "!SP": commands.SetPortsCommand(),
#             "!SS": commands.SetSerialCommand(),
#             "!RC": commands.RequestConnectCommand(),
#             "!RR": commands.RequestRestartCommand(),
#             "!WM": commands.WinkModuleCommand(),
#         }
# 
#         self.help_command = commands.HelpCommand(self.commands)
# 
#     def respond(self, request):
#         stripped_request = request.strip()
# 
#         if len(stripped_request) == 0:
#             return ""  # idle
# 
#         split_request = stripped_request.split(" ", 1)
#         command = split_request[0].upper()
# 
#         if len(command) > 3:
#             return self.COMMAND_NOT_FOUND
#         elif command.startswith("Q"):
#             return  # quit
# 
#         params = None
#         if len(split_request) > 1:
#             params = split_request[1]
# 
#         if command.startswith("H"):
#             return self.help_command.run(params)
#         if command.startswith("!"):
#             if command in list(self.commands.keys()):
#                 return self.commands[command].run(params)
# 
#         return self.COMMAND_NOT_FOUND
# 
# Path: conpot/core/protocol_wrapper.py
# def conpot_protocol(cls):
#     class Wrapper(object):
#         def __init__(self, *args, **kwargs):
#             self.wrapped = cls(*args, **kwargs)
#             self.cls = cls
#             if self.cls.__name__ not in "Proxy":
#                 if self.cls not in core_interface.protocols:
#                     core_interface.protocols[self.cls] = []
# 
#                 core_interface.protocols[self.cls].append(self.wrapped)
# 
#             self.__class__.__name__ = self.cls.__name__
# 
#         def __getattr__(self, name):
#             if name == "handle":
#                 # assuming that handle function from a class is only called when a client tries to connect with an
#                 # enabled protocol, update the last_active (last_attacked attribute)
#                 # FIXME: No handle function in HTTPServer
#                 core_interface.last_active = datetime.now().strftime(
#                     "%b %d %Y - %H:%M:%S"
#                 )
#             return self.wrapped.__getattribute__(name)
# 
#         def __repr__(self):
#             return self.wrapped.__repr__()
# 
#         __doc__ = cls.__doc__
#         __module__ = cls.__module__
# 
#     return Wrapper
# 
# Path: conpot/utils/networking.py
# def str_to_bytes(x):
#     return x if isinstance(x, bytes) else str(x).encode("ascii")


# Path: conpot/protocols/kamstrup_management/kamstrup_management_server.py
import logging
import socket
import gevent
import conpot.core as conpot_core
from gevent.server import StreamServer
from .command_responder import CommandResponder
from conpot.core.protocol_wrapper import conpot_protocol
from conpot.utils.networking import str_to_bytes


logger = logging.getLogger(__name__)


@conpot_protocol
class KamstrupManagementServer(object):
    def __init__(self, template, template_directory, args):
        self.command_responder = CommandResponder()
        self.banner = "\r\nWelcome...\r\nConnected to [{0}]\r\n"
        logger.info("Kamstrup management protocol server initialized.")
        self.server = None

    def handle(self, sock, address):
        session = conpot_core.get_session(
            "kamstrup_management_protocol",
            address[0],
            address[1],
            sock.getsockname()[0],
            sock.getsockname()[1],
        )
        logger.info(
            "New Kamstrup connection from %s:%s. (%s)",
            address[0],
            address[1],
            session.id,
        )
        session.add_event({"type": "NEW_CONNECTION"})

        try:
            sock.send(

                str_to_bytes(