<commit_before>#!/usr/local/bin/python3

#Discover devices and update table

from zeroconf import Zeroconf, ServiceBrowser
import socket
import configparser
import xml.etree.cElementTree as ET
import os.path

class hazc_master:
#     global inst

    def __init__(self): #, ipaddr):
#         global instance
#         instance = self

        #ipaddr = 'localhost'
        self.version = "0.1"
        self.config = configparser.ConfigParser()
        self.config.read('config.ini')
        #self.ip = ipaddr
        self.MSGLEN = 1024
        self.END_OF_MSG = '*'

        self.xmlpath = self.config['discovery']['xml_location']
        self.checkXML()

#         self.xmlroot = ET.Element("root")

#         global inst
#         inst = self
        #init the XML file

    #start searching - THE method to run
    def detectDevices(self):
        self.zeroconf = Zeroconf()
        self.listener = hazcListener(self)
        self.browser = ServiceBrowser(self.zeroconf, self.config['global']['service_prefix'], self.listener)
        try:
            input("Press enter to exit...\n\n")
#             while(1):
                #loop
        finally:
            self.zeroconf.close()
#             self.webcontrol.close() #May not be neccesary

        #self.bindConnection() #option2

    def bindConnection(self):
        self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.webcontrol.bind(('localhost', 8796))
        self.webcontrol.listen(1)

#     TODO: send variable length packets
    def getInfo(self, ip):
        print("Getting info...")
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((ip,int(self.config['global']['port'])))

        attr = {}

        self.senddata(s, "version?")
        version = self.recvdata(s)
        attr['version'] = version

        self.senddata(s, "commands?")
        #retrieve commands as according to README
        commands = recvdata(s)
        #version 1 contains version? commands? status? shutdown!
        commandlist = self.parseconfigs(commands.split(';'))
        self.senddata(s, "status?")
        # control surfaces
        controls = list()

        attr['controls'] = controls

        s.shutdown(1)
        s.close()

        return attr

    def parseconfigs(self, cmdlist):
        confs = list()
        for str in cmdlist:
            if(str[0:4] is "set-"):
                confs.append(str[4:])
        return confs

    def fixmsglength(self, msg):
        if len(msg) < self.MSGLEN:
#             print("not long enough")
            while len(msg) < self.MSGLEN:
                msg+=self.END_OF_MSG
            return msg
        else:
#             print("too long")
            return msg[0:self.MSGLEN]

    def senddata(self, sock, msg):
        print(msg)
        bmsg = self.fixmsglength(msg).encode('utf-8')
        totalsent = 0
        while totalsent < self.MSGLEN:
#             print(totalsent)
#             print(msg)
            sent = sock.send(bmsg[totalsent:])
            if sent == 0:
                # closed
                raise RuntimeError("socket connection broken unexpectedly. Was trying:" + str(bmsg.decode('utf-8')))
            totalsent = totalsent + sent

    def recvdata(self, sock):
#         chunks = []
#         bytes_recd = 0
#         while bytes_recd < self.MSGLEN:
#             chunk = sock.recv(self.MSGLEN - bytes_recd)
#         if chunk == b'':
#             raise RuntimeError("Socket connection broken unexpectedly")
#         chunks.append(chunk)
#         bytes_recd += len(chunk)
#
#         msg = b''.join(chunks)

        msgbytes = sock.recv(self.MSGLEN)
        msgstr = msgbytes.decode('utf-8')
        rmsg = msg.strip(self.END_OF_MSG)
        print("->" + rmsg)
        return rmsg

    def checkXML(self): #see if XML exists, otherwise create it.
#         root = ET.Element("root")
        #if(not os.path.isfile(self.xmlpath)):
<commit_msg>new timestamp<commit_after>#!/usr/local/bin/python3

#Discover devices and update table

from zeroconf import Zeroconf, ServiceBrowser
import socket
import configparser
import xml.etree.cElementTree as ET
import os.path

class hazc_master:
#     global inst

    def __init__(self): #, ipaddr):
#         global instance
#         instance = self

        #ipaddr = 'localhost'
        self.version = "0.1"
        self.config = configparser.ConfigParser()
        self.config.read('config.ini')
        #self.ip = ipaddr
        self.MSGLEN = 1024
        self.END_OF_MSG = '*'

        self.xmlpath = self.config['discovery']['xml_location']
        self.checkXML()

#         self.xmlroot = ET.Element("root")

#         global inst
#         inst = self
        #init the XML file

    #start searching - THE method to run
    def detectDevices(self):
        self.zeroconf = Zeroconf()
        self.listener = hazcListener(self)
        self.browser = ServiceBrowser(self.zeroconf, self.config['global']['service_prefix'], self.listener)
        try:
            input("Press enter to exit...\n\n")
#             while(1):
                #loop
        finally:
            self.zeroconf.close()
#             self.webcontrol.close() #May not be neccesary

        #self.bindConnection() #option2

    def bindConnection(self):
        self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.webcontrol.bind(('localhost', 8796))
        self.webcontrol.listen(1)

#     TODO: send variable length packets
    def getInfo(self, ip):
        print("Getting info...")
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((ip,int(self.config['global']['port'])))

        attr = {}

        self.senddata(s, "version?")
        version = self.recvdata(s)
        attr['version'] = version

        self.senddata(s, "commands?")
        #retrieve commands as according to README
        commands = recvdata(s)
        #version 1 contains version? commands? status? shutdown!
        commandlist = self.parseconfigs(commands.split(';'))
        self.senddata(s, "status?")
        # control surfaces
        controls = list()

        attr['controls'] = controls

        s.shutdown(1)
        s.close()

        return attr

    def parseconfigs(self, cmdlist):
        confs = list()
        for str in cmdlist:
            if(str[0:4] is "set-"):
                confs.append(str[4:])
        return confs

    def fixmsglength(self, msg):
        if len(msg) < self.MSGLEN:
#             print("not long enough")
            while len(msg) < self.MSGLEN:
                msg+=self.END_OF_MSG
            return msg
        else:
#             print("too long")
            return msg[0:self.MSGLEN]

    def senddata(self, sock, msg):
        print(msg)
        bmsg = self.fixmsglength(msg).encode('utf-8')
        totalsent = 0
        while totalsent < self.MSGLEN:
#             print(totalsent)
#             print(msg)
            sent = sock.send(bmsg[totalsent:])
            if sent == 0:
                # closed
                raise RuntimeError("socket connection broken unexpectedly. Was trying:" + str(bmsg.decode('utf-8')))
            totalsent = totalsent + sent

    def recvdata(self, sock):
#         chunks = []
#         bytes_recd = 0
#         while bytes_recd < self.MSGLEN:
#             chunk = sock.recv(self.MSGLEN - bytes_recd)
#         if chunk == b'':
#             raise RuntimeError("Socket connection broken unexpectedly")
#         chunks.append(chunk)
#         bytes_recd += len(chunk)
#
#         msg = b''.join(chunks)


        msgbytes = sock.recv(self.MSGLEN)
        msgstr = msgbytes.decode('utf-8')
        rmsg = msg.strip(self.END_OF_MSG)
        print("->" + rmsg)
        return rmsg

    def checkXML(self): #see if XML exists, otherwise create it.
#         root = ET.Element("root")
        #if(not os.path.isfile(self.xmlpath)):

{'fraction_non_alphanumeric': 0.12108135550196726, 'fraction_numerical': 0.006599822312476203, 'mean_word_length': 1.983718288527073, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 10}, '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': '4067276', 'n_tokens_mistral': 2435, 'n_tokens_neox': 2351, 'n_words': 527}