Ejemplo n.º 1
0
    class __CalculatedParams:

        params = ConfParams()
        user = ThingBoardUser()
        dt2 = 1 / 6000
        TMS_DL = float(params.getParam("INITIAL_TMS_DL"))
        CFT = 0

        TCC_MODE = params.getParam("TCC_MODE")
        TCC = float(params.getParam("INITIAL_TCC"))
        alpha0 = int(params.getParam("IIR_Alfa"))
        dict_Tcycle_A_2_by_sensor_id = {}
        dict_Tcharge_by_sensor_id = {}
        timer = None
        plc_client = None
        if len(params.getParam("PLC_HOST")) > 1:
            plc_client = ModbusTcpClient(params.getParam("PLC_HOST"))

        # after 30 seconds, "hello, world" will be printed
        # a time counter will be more than “TMS” or the time counter will be more than 5 sec

        def init_timer(self):
            # print("init_timer:"+str(self.TMS))
            min_interval = min(5.0, float(self.TMS_DL))
            self.timer = threading.Timer(min_interval, self.timerFunction)
            self.timer.start()

        def timerFunction(self):
            self.submit_CFT_and_TCC()
            # print("sent by Timer, TMS:"+str(self.TMS))

        def set_param(self, sensor_id, param_name, value):
            if self.timer == None:
                self.init_timer()

            if (not param_name):
                return

            if (param_name == "Tcycle_A_2"):
                self.process_Tcycle_A_2(sensor_id, value)

            elif (param_name == "Tcharge"):
                self.process_Tcharge(sensor_id, value)

            elif (param_name == "TBagSpacing"):
                self.submit_parameter("TBS", 0.01 * value, 3)

            elif (param_name == "ChBHight"):
                self.submit_parameter("ABH", 0.1 * value, 4)

            elif (param_name == "Tbaglength"):
                self.submit_parameter("TBL", 0.01 * value, 5)

        def submit_parameter(self, out_param_name, value, plc_reg_address=None):
            ts = {"ts": int(round(time.time() * 1000))}

            # if start_new_data:
            data = []

            new_obj_to_send = {"ts": ts["ts"], "values": {}}

            # Lior process out_param_name ,value
            # Change - Start
            attr_to_send = calculate_info(out_param_name, value)
            #print(value_storage)
            #print(attr_to_send)
            self.user.send_attributes("PLC", attr_to_send)
            
            # new_obj_to_send["values"][out_param_name] = value
            new_obj_to_send["values"][out_param_name] = add_color_digit(value, out_param_name)
            # Change - End

            data.append(new_obj_to_send)
            value = int(value * pow(2, 9))
            try:
                try:
                    if not self.plc_client == None:
                        result = self.plc_client.write_registers(plc_reg_address, [value], unit=0X01)
                        print(out_param_name + " Sent to PLC : " + str(value))
                        self.sendIsAlive()
                except Exception as e:
                    print("error sending data to PLC :  " + str(e))

                self.user.send_telemetry("PLC", data, False, None, None)

            except Exception as e:
                print("error sending data to Things Board :  " + str(e))
                # self.generalLogger.error("error sending data serv " + str(e))

        def process_Tcycle_A_2(self, sensor_id, value):
            self.dict_Tcycle_A_2_by_sensor_id[sensor_id] = value
            if (len(self.dict_Tcycle_A_2_by_sensor_id) == 3 and len(self.dict_Tcharge_by_sensor_id) == 3):
                self.submit_CFT_and_TCC()

        def process_Tcharge(self, sensor_id, value):
            self.dict_Tcharge_by_sensor_id[sensor_id] = value
            if (len(self.dict_Tcycle_A_2_by_sensor_id) == 3 and len(self.dict_Tcharge_by_sensor_id) == 3):
                self.submit_CFT_and_TCC()

        def sendIsAlive(self):
            data = {"ts": int(round(time.time() * 1000)), "values": {"is_alive": True}}
            jsonData = json.dumps(data)
            re = self.user.post(self.user.telemetry_url.format(self.user.access_token("MODBUS")), jsonData)

        def submit_CFT_and_TCC(self):
            if not self.timer == None:
                self.timer.cancel()

            if (len(self.dict_Tcycle_A_2_by_sensor_id) == 0 and len(self.dict_Tcharge_by_sensor_id) == 0):
                # print("no values to be sent by timer, init_timer")
                self.init_timer()
                return

            Nsyc = 0
            ATsycle = 0
            self.CFT = 0

            for value in self.dict_Tcycle_A_2_by_sensor_id.values():

                if (value > 2800 and value < 18000):
                    ATsycle += value
                    Nsyc += 1

            if Nsyc:
                ATsycle = ATsycle / Nsyc
                self.TMS_DL = (float(((10000 - (float(self.alpha0))) * (float(self.TMS_DL)) + (float(self.alpha0)) * (
                    float(ATsycle))) / 10000))
                # self.TMS = self.dt2*float(self.TMS_DL)

            Nsyc = 0
            Tcharge_values_list = []
            if self.TCC_MODE == '0':
                for value in self.dict_Tcharge_by_sensor_id.values():

                    if (value > 0 and value < self.TMS_DL):
                        Tcharge_values_list.append(int(value))
                    else:
                        Tcharge_values_list.append(0)

                if len(Tcharge_values_list) > 0:
                    self.TCC = self.dt2 * max(Tcharge_values_list)


            elif self.TCC_MODE == '1':
                self.TCC = 0
                for value in self.dict_Tcharge_by_sensor_id.values():

                    if (value > 0 and value < self.TMS_DL):
                        self.TCC += value
                        Nsyc += 1

                if Nsyc:
                    self.TCC = self.dt2 * self.TCC / Nsyc

            #             Mode 2: (Median(TCharge(1), TCharge(2), TCharge(3)))
            # If  0<TCharge(n)<( TMS_DL), Add TCharge(n) to a buffer
            # TCC = dt2*(median of the buffer)

            if self.TCC_MODE == '2':
                for value in self.dict_Tcharge_by_sensor_id.values():

                    if (value > 0 and value < self.TMS_DL):
                        Tcharge_values_list.append(int(value))

                if len(Tcharge_values_list) > 0:
                    self.TCC = self.dt2 * median(Tcharge_values_list)
                else:
                    self.TCC = 0




            elif self.TCC_MODE == '3':
                for value in self.dict_Tcharge_by_sensor_id.values():

                    if (value > 0 and value < self.TMS_DL):
                        Tcharge_values_list.append(int(value))
                    else:
                        Tcharge_values_list.append(0)

                if len(Tcharge_values_list) > 0:
                    value1 = max(Tcharge_values_list)

                    Tcharge_values_list.remove(value1)
                    if len(Tcharge_values_list) > 0:
                        value2 = max(Tcharge_values_list)
                        self.TCC = self.dt2 * (value1 + value2) / 2

                    else:
                        self.TCC = self.dt2 * value1
            if ATsycle > 0:
                self.CFT = self.dt2 * ATsycle - self.TCC;

            ts = {"ts": int(round(time.time() * 1000))}

            # if start_new_data:
            data = []

            new_obj_to_send = {"ts": ts["ts"], "values": {}}

            # Change - Start
            attr_to_send = calculate_info("CFT", self.CFT)
            #print(value_storage)
            #print(attr_to_send)
            self.user.send_attributes("PLC", attr_to_send)
            
            attr_to_send = calculate_info("TCC", self.TCC)
            #print(attr_to_send)
            self.user.send_attributes("PLC", attr_to_send)
            

            # new_obj_to_send["values"]["CFT"] = self.CFT
            new_obj_to_send["values"]["CFT"] = add_color_digit(self.CFT, "CFT")
            # new_obj_to_send["values"]["TCC"] = self.TCC
            new_obj_to_send["values"]["TCC"] = add_color_digit(self.TCC, "TCC")
            # Change - End

            data.append(new_obj_to_send)

            cftToSend = int(self.CFT * pow(2, 9))
            tccToSend = int(self.TCC * pow(2, 9))
            try:
                try:
                    if not self.plc_client == None:
                        result = self.plc_client.write_registers(1, [tccToSend], unit=0X01)
                        print("  TCC data sent to PLC :  " + str(tccToSend))
                        result = self.plc_client.write_registers(6, [cftToSend], unit=0X01)
                        print("  CFT data sent to PLC :  " + str(cftToSend))
                        result = self.plc_client.write_registers(9, [1], unit=0X01)
                        self.sendIsAlive()


                except Exception as e:
                    print("error sending data to PLC :  " + str(e))

                self.user.send_telemetry("PLC", data, False, None, None)

            except Exception as e:
                print("error sending data to Things Board :  " + str(e))
                # self.generalLogger.error("error sending data serv " + str(e))

            self.dict_Tcycle_A_2_by_sensor_id = {}
            self.dict_Tcharge_by_sensor_id = {}
            # self.timer = threading.Timer(min(5,int(self.TMS)), self.timerFunction)
            self.init_timer()
Ejemplo n.º 2
0
        2 is normal priority.  Default sets the priority of the current
        python process but can take any valid process ID. """
        
   
    
#     priorityclasses = [win32process.IDLE_PRIORITY_CLASS,
#                        win32process.BELOW_NORMAL_PRIORITY_CLASS,
#                        win32process.NORMAL_PRIORITY_CLASS,
#                        win32process.ABOVE_NORMAL_PRIORITY_CLASS,
#                        win32process.HIGH_PRIORITY_CLASS,
#                        win32process.REALTIME_PRIORITY_CLASS]
#     if pid == None:
pid = win32api.GetCurrentProcessId()
handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
win32process.SetPriorityClass(handle, win32process.REALTIME_PRIORITY_CLASS)
params=ConfParams()
#system( params.getParam("GATEWAY_NAME"))

load = True
printError = True

while load:

    try:
        from Cmd.CmdControler import CmdControler 
        from TcpServer import TcpServSensor
        from TcpServer import TcpServPLC
    
        load = False
        print("\n\n------------start---------------")
Ejemplo n.º 3
0
class SensorDataProcess:
    headersProcess = None
    connection_terminated = False
    all_data = None
    algo_8_ts_diff_list = []
    last_algo_8_ts = 0
    algo_8_data = {}
    first_time_ind = True
    collect_calibration = False
    calibration_list = []
    mean_med_vel = 0
    params = ConfParams()

    def __init__(self):
        self.headersProcess = ProcessHeaders()
        self.all_data = []

    @property
    def id_sensor(self):
        return self.headersProcess.headers[self.headersProcess.ID_SENSOR_INDEX]

    def get_list_params(self):
        try:
            data_type_as_number = TypeData(self.headersProcess.headers[
                self.headersProcess.TYPE_DATA]).value

            #case it's algo_2_demo
            if (data_type_as_number == 25):
                data_type_as_number = 6

            #return algoParams.paramsOut[data_type_as_number - 2]
            return algoParams.paramsOut[str(data_type_as_number)]
        except Exception as e:
            return []
            print(
                str(self.headers) + '\n' +
                '-------------------------------------------------------------'
            )

    def get_data_as_decimals(self, value_number_of_byte):
        all_valus = ''

        start_range = 0
        end_range = self.headersProcess.len_data
        if self.headersProcess.is_debuge_buffer:
            print(" debug buffer index " + str(self.headersProcess.data[0]))
            start_range = 1
            end_range = self.headersProcess.len_data - 1

        for i in range(start_range, end_range, value_number_of_byte):

            #if i==0 and  self.headersProcess.is_debuge_buffer:
            #    print(" debug buffer index " +str(self.headersProcess.data[i]))

            if value_number_of_byte == 2:
                value = int.from_bytes(
                    #   self.headersProcess.data[i:i + 2], byteorder="big", signed=True)
                    self.headersProcess.data[i:i + 2],
                    byteorder="big",
                    signed=False)
            else:
                value = int(self.headersProcess.data[i])

            all_valus += ',' + str(value)

        all_valus = "response of command index: " + all_valus.replace(
            ",", '', 1)
        if not self.headersProcess.is_debuge_buffer:
            all_valus = all_valus.replace(",", ' Data : ', 1)

        return all_valus

    def process_data(self, start_timer=None) -> (str, dict):
        #time.sleep(1)
        plcCalculatedParams = PlcCalculatedParams()
        ts = {"ts": int(round(time.time() * 1000))}

        # if start_new_data:
        self.all_data = []
        global first_time_ind
        distance_factor = float(self.params.getParam("ALGO_8_DISTANCE_FACTOR"))
        id_socket = self.id_sensor

        # increment = 1 if self.headersProcess.type_data == "plc_data" else 2

        list_params = self.get_list_params(
        ) if self.headersProcess.is_plc_data else None
        iParam = 0
        new_obj_to_send = {"ts": ts["ts"], "values": {}}
        self.algo_8_data["TS"] = ts["ts"]
        if (self.headersProcess.isRawData):
            new_obj_to_send = ''

        if self.headersProcess.type_data == 'algo_8':
            try:
                #AccDistHigh is multiplied by distance_factor
                type_data = list_params[
                    0] if list_params else self.headersProcess.type_data
                value = int.from_bytes(self.headersProcess.data[0:4],
                                       byteorder="big",
                                       signed=True)
                new_obj_to_send["values"][type_data] = value * distance_factor
                #algo_8_data["TS"] = int(round(time.time() * 1000))
                self.algo_8_data[type_data] = value * distance_factor

                type_data = list_params[
                    1] if list_params else self.headersProcess.type_data
                value = int.from_bytes(self.headersProcess.data[4:6],
                                       byteorder="big",
                                       signed=True)
                new_obj_to_send["values"][type_data] = value
                self.algo_8_data[type_data] = value

                type_data = list_params[
                    2] if list_params else self.headersProcess.type_data
                value = int.from_bytes(self.headersProcess.data[6:10],
                                       byteorder="big",
                                       signed=True)
                new_obj_to_send["values"][type_data] = value
                self.algo_8_data[type_data] = value

                type_data = list_params[
                    3] if list_params else self.headersProcess.type_data
                value = int.from_bytes(self.headersProcess.data[10:11],
                                       byteorder="big",
                                       signed=True)
                new_obj_to_send["values"][type_data] = value
                self.algo_8_data[type_data] = value

                type_data = list_params[
                    4] if list_params else self.headersProcess.type_data
                value = int.from_bytes(self.headersProcess.data[11:15],
                                       byteorder="big",
                                       signed=True)
                new_obj_to_send["values"][type_data] = value
                self.algo_8_data[type_data] = value

                type_data = list_params[
                    5] if list_params else self.headersProcess.type_data
                value = int.from_bytes(self.headersProcess.data[15:19],
                                       byteorder="big",
                                       signed=True)
                new_obj_to_send["values"][type_data] = value
                self.algo_8_data[type_data] = value

                if SensorDataProcess.collect_calibration:
                    SensorDataProcess.calibration_list.append(
                        self.algo_8_data["MedVel"])
                    print(self.calibration_list)
                    if len(SensorDataProcess.calibration_list) > 5:
                        SensorDataProcess.mean_med_vel = sum(
                            SensorDataProcess.calibration_list) / len(
                                SensorDataProcess.calibration_list)
                        print(SensorDataProcess.mean_med_vel)
                        SensorDataProcess.collect_calibration = False
                        SensorDataProcess.calibration_list = []

            except Exception as e:
                print("Error params" + str(self.headersProcess.headers))

            ts_diff = ts["ts"] - SensorDataProcess.last_algo_8_ts
            #print("ts", ts["ts"])
            #print("last_algo_8_ts", SensorDataProcess.last_algo_8_ts)
            #print("ts_diff", ts_diff)
            new_obj_to_send["values"]["ts_diff"] = ts_diff
            SensorDataProcess.last_algo_8_ts = ts["ts"]

            if len(self.algo_8_ts_diff_list) > 99:
                self.algo_8_ts_diff_list.pop(0)
            self.algo_8_ts_diff_list.append(ts_diff)
            #print(self.algo_8_ts_diff_list)
            ts_diff_avg = round(
                sum(self.algo_8_ts_diff_list) / len(self.algo_8_ts_diff_list))
            new_obj_to_send["values"]["ts_diff_avg"] = ts_diff_avg
            #Delete first value in run
            #print("first_time_ind ", SensorDataProcess.first_time_ind)
            if SensorDataProcess.first_time_ind:
                self.algo_8_ts_diff_list.pop(0)
                SensorDataProcess.first_time_ind = False

        else:
            for i in range(0, self.headersProcess.len_data, 2):

                try:
                    type_data = list_params[
                        iParam] if list_params else self.headersProcess.type_data

                    #print("type_data :" + str(type_data))
                    iParam = iParam + 1
                except Exception as e:
                    print("Error params" + str(self.headersProcess.headers))
                value = int.from_bytes(self.headersProcess.data[i:i + 2],
                                       byteorder="big",
                                       signed=True)
                #print(type_data+" : "+str(value))
                # if not Algo Params with no values *"-1")
                if (self.headersProcess.isRawData):
                    new_obj_to_send += str(self.headersProcess.id_sensor
                                           ) + ',' + str(value) + ',\n'

                elif (not (self.headersProcess.is_plc_data and value == -1)):
                    new_obj_to_send["values"][type_data] = value
                    plcCalculatedParams.set_param(id_socket, type_data, value)

        self.all_data.append(new_obj_to_send)

        return id_socket, self.all_data
Ejemplo n.º 4
0
    class __ThingBoardUser:
        params = ConfParams()
        telemetry_url = '/api/v1/{}/telemetry'
        attributes_url = '/api/v1/{}/attributes'
        port = params.getParam("TB_PORT")

        host = 'http://localhost'

        user = {"username": "******", "password": "******"}

        token = "Bearer "

        refreshToken = ""

        headers = {}
        logger_v = logging.getLogger('rawData_V_logger')
        handler = RotatingFileHandler('./Recorded_Raw_Data/rawData_V.log',
                                      maxBytes=20000000,
                                      backupCount=200)
        formatter = logging.Formatter('%(message)s')
        handler.setFormatter(formatter)

        logger_v.addHandler(handler)
        logger_v.setLevel(logging.DEBUG)

        logger_d = logging.getLogger('rawData_D_logger')
        handler = RotatingFileHandler('./Recorded_Raw_Data/rawData_D.log',
                                      maxBytes=20000000,
                                      backupCount=200)

        handler.setFormatter(formatter)

        logger_d.addHandler(handler)
        logger_d.setLevel(logging.DEBUG)

        binLoggers = {}

        @staticmethod
        def access_token(id_device):
            return str(id_device) + '_prex'

        def __init__(self):
            self.login()

        def set_headers(self, header_key, header_value):
            self.headers[header_key] = header_value

        def login(self, refresh=None):

            self.token = "Bearer "
            url = '/api/auth/login' if not refresh else '/api/auth/token'

            body = json.dumps(self.user) if not refresh else json.dumps(
                {"refreshToken": self.refreshToken})

            re = self.post(url, body)
            #http://localhost:8080/deviceGroups/c19f6a00-e2a6-11ea-9233-194f88fa09ad
            if re.status_code == 200:
                re = json.loads(re.text)
                self.refreshToken = re.get("refreshToken")
                self.token += re.get("token")
                self.set_headers('X-Authorization', self.token)

        def get(self, path):

            re = requests.get(url=self.get_url(path), headers=self.headers)
            if re.status_code == 401 and json.loads(
                    re.text).get("message") == "Token has expired":
                self.login(True)
                self.get(path)
            return re

        def post(self, path, body):
            return requests.post(url=self.get_url(path), data=body)

        def get_url(self, path):
            return self.host + ":" + self.port + path

        def get_bin_filename(self, basename):
            # append year and week number to basename ]_[year]_[month][day]_[h]_[m][s].bin
            return '{}_{}.bin'.format( \
                 basename, time.strftime('%Y_%m_%d_%H_%M_%S'))

        def send_attributes(self, id_device, data):
            try:
                jsonData = json.dumps(data)
                # print(jsonData)
                re = self.post(
                    self.attributes_url.format(self.access_token(id_device)),
                    jsonData)
                # print("url: ",re.status_code)
                # print("Sending attributes data succeeded: "+str(jsonData))

            except requests.exceptions.RequestException as e:
                print(e)
                return False

        def send_telemetry(self,
                           id_device,
                           data,
                           isRawData,
                           binData,
                           rawDataType,
                           send_keep_alive=False):
            #fi = ""
            #type_data = ""
            i = data[0]
            #             for i in data:
            #                 for j in i["values"]:
            #                     fi +=  str(id_device)+','+str(i["values"][j]) + ',\n'
            #                     if not type_data:
            #                         type_data = j
            # print(self.all_data)

            if (isRawData):
                if (rawDataType == "velocity"):
                    self.logger_v.debug(i)
                else:
                    self.logger_d.debug(i)

                id_deviceStr = str(id_device)

                binLoggerSize = 0
                binLogger = self.binLoggers.get(rawDataType + id_deviceStr)

                if (binLogger != None):
                    binLoggerSize = os.path.getsize(binLogger.name)

                if (binLogger == None or binLoggerSize > 2000000):
                    # #RD[SN]_[year]_[month][day]_[h]_[m][s].bi
                    if (binLoggerSize > 2000000):
                        binLogger.close()

                    binLogger = open(
                        self.get_bin_filename('./Recorded_Raw_Data/RD_' +
                                              rawDataType + '_' +
                                              id_deviceStr), 'ba')

                    #binLogger = RotatingBinaryFileBuff)r('./Recorded_Raw_Data/RD_'+rawDataType+'_'+id_deviceStr)
                    self.binLoggers[rawDataType + id_deviceStr] = binLogger

                binLogger.write(binData)
                binLogger.flush()
                if send_keep_alive:
                    data = {
                        "ts": int(round(time.time() * 1000)),
                        "values": {
                            "is_alive": True
                        }
                    }
                    jsonData = json.dumps(data)
                    re = self.post(
                        self.telemetry_url.format(
                            self.access_token(id_device)), jsonData)

                print(self.telemetry_url.format(self.access_token(id_device)))
                print("Sending telemetry data succeeded: " + str(jsonData))
                print(re)

            try:
                if (not isRawData):
                    # print("Wait for the data to be uploaded")
                    jsonData = json.dumps(i)
                    #      jsonData= jsonData[3:len(jsonData)]

                    re = self.post(
                        self.telemetry_url.format(
                            self.access_token(id_device)), jsonData)
                    #print("Sending data succeeded: "+str(jsonData))
            except requests.exceptions.RequestException as e:
                print(e)
                return False

                if (not isRawData):
                    if re.status_code != 200:
                        print("error sending data", re.reason)
                        return False
            # for i in data:
            #     i = json.dumps(i).encode()
            #     try:
            #         re = self.post(self.telemetry_url.format(self.access_token(id_device)), i)
            #     except requests.exceptions.RequestException as e:
            #         print(e)
            #         return False
            #     if re.status_code != 200:
            #         print("error sending data", re)
            #         return False
            # print("sending data complet")

        def __str__(self):
            return repr(self)
Ejemplo n.º 5
0
from properties.PropertiesReader import ConfParams

params = ConfParams()

print(params.getParam("GATEWAY_NAME"))
Ejemplo n.º 6
0
    class __TcpServer:
        params = ConfParams()
        get_status = b'\x12\x01\x01'

        begin_of_packet = b'UUUU'
        user = ThingBoardUser()

        plcCalculatedParams = PlcCalculatedParams()
        function_process_data_to_view = None
        update_conected_sensors = None
        update_cmd_view = None
        bind_ip = '0.0.0.0'
        bind_port = int(params.getParam("GATEWAY_PORT"))
        dict_allSensor_by_id = {}
        # dict_allSockets_by_sensor_id={}
        prevPacket = None
        prevPacketType = None
        errorLoggers = {}
        lastPackets = {}
        lostPacketsCounter = {}
        nextDeviceIdIndexToProcess = 0
        generalLogger = None
        do_update_sensor_server_print_Consol = False
        threadData = threading.local()
        #dataPerSensor={}
        dataPerSensor = defaultdict(dict)

        def getLogger(self, sensor_id):
            logger = None
            if (sensor_id in self.errorLoggers):
                logger = self.errorLoggers[sensor_id]

            if (logger != None):
                return logger
            logger = logging.getLogger(sensor_id)
            handler = RotatingFileHandler('../logs/' + sensor_id + '.log',
                                          maxBytes=20000000,
                                          backupCount=20)
            formatter = logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            handler.setFormatter(formatter)

            logger.addHandler(handler)
            logger.setLevel(logging.DEBUG)
            self.errorLoggers[sensor_id] = logger
            return logger

        def update_sensors_server(self, sensor_id, key, value):
            if key == "get_debug_buffer":

                self.dataPerSensor[sensor_id]["get_debug_buffer"] = value

            elif key == "update_view_with_first_raw_data_packet":
                #self.dataPerSensor[sensor_id]="update_view_with_first_raw_data_packet"
                self.dataPerSensor[sensor_id][
                    "update_view_with_first_raw_data_packet"] = value
                #self.threadData.update_view_with_first_raw_data_packet=value
            elif key == "print_incoming_packets_info_to_console":
                self.do_update_sensor_server_print_Consol = value
            else:
                self.dataPerSensor[sensor_id][key] = value

        def recv_data(self, client_socket, processData):
            #value=client_socket.recv(100)
            #print("first 100 bytes : ", str(value))
            global prevPacket
            global prevPacketType

            value = None
            foundPacketPrefix = False
            # value=client_socket.recv(2000)
            # print("out of reading sync , next 2000: ", value )
            #value=client_socket.recv(20000)
            #in case out of reading sync, clearing the socket buffer
            outOfReadingSync = ''
            while (not foundPacketPrefix):
                while (value != b'U'):
                    if (value != None):
                        outOfReadingSync = outOfReadingSync + str(value)

                    value = client_socket.recv(1)
                    #if(value== b''):
                    #processData.connection_terminated=True
                    #return
                    #print("out of reading sync , next 200: ", str(value))
                value = client_socket.recv(4)
                #if(value== b''):
                #processData.connection_terminated=True
                #return
                if (value == self.begin_of_packet):
                    foundPacketPrefix = True
                    if (outOfReadingSync != ''
                            and self.do_update_sensor_server_print_Consol):
                        print("out of reading sync"
                              )  #: ", str(outOfReadingSync))
                    outOfReadingSync = ''

                else:
                    value = None

            value = client_socket.recv(
                processData.headersProcess.LENGTH_HEADERS)
            #print("headers : ", str(value))
            value_length = len(value)
            while value_length < processData.headersProcess.LENGTH_HEADERS:
                self.generalLogger.warn(
                    "in value.length < processData.headersProcess.len_data loop , length requred"
                    + str(processData.headersProcess.LENGTH_HEADERS) +
                    " and , value " + str(value))

                value += client_socket.recv(
                    processData.headersProcess.LENGTH_HEADERS - value_length)
                value_length = len(value)

            #if(value== b''):
            #processData.connection_terminated=True
            #return

            valueAll = value
            processData.headersProcess.headers = value
            #print("headers : ", str(value))

            value = client_socket.recv(processData.headersProcess.len_data)
            value_length = len(value)
            while value_length < processData.headersProcess.len_data:
                if self.do_update_sensor_server_print_Consol:
                    self.generalLogger.warning(
                        "in value.length < processData.headersProcess.len_data loop , length requred"
                        + str(processData.headersProcess.len_data) +
                        " and , value " + str(value))
                value += client_socket.recv(
                    processData.headersProcess.len_data - value_length)
                value_length = len(value)

            # if(value== b''):
            #   processData.connection_terminated=True
            #   return

            processData.headersProcess.data = value

            valueAll = valueAll + value
            if processData.headersProcess.isRawData == True:
                print("Raw Data :" + str(value))
            logger = self.getLogger(str(processData.headersProcess.headers[0]))

            if self.do_update_sensor_server_print_Consol:
                print(
                    "PfS :" + str(processData.headersProcess.headers[0]) +
                    " ,SqN : " + str(processData.headersProcess.headers[4]) +
                    " ,Packet Type :", processData.headersProcess.type_data)

            if (processData.headersProcess.is_debuge_buffer):
                print("packet data: " + processData.get_data_as_decimals(2))

            if processData.headersProcess.is_vz_param:

                index = str(processData.headersProcess.data[0])
                #print('\nReceived index:', index)
                #print(self.dataPerSensor['command'])
                param_type = int(self.dataPerSensor['command'][index])
                #print('param_type: ', param_type)
                #print('Received data bytes ', str(processData.headersProcess.data))

                if param_type == 1:  # boolean
                    value = struct.unpack('<4B',
                                          processData.headersProcess.data[1:])
                elif param_type == 2:  # uint
                    (value, ) = struct.unpack(
                        '<I', processData.headersProcess.data[1:])
                elif param_type == 3:  # int
                    (value, ) = struct.unpack(
                        '<i', processData.headersProcess.data[1:])
                elif param_type == 4:  # flout (double)
                    (value, ) = struct.unpack(
                        '<f', processData.headersProcess.data[1:])
                else:
                    value = struct.unpack('<4B',
                                          processData.headersProcess.data[1:])
                    #value = processData.headersProcess.data[1:]
                    #value = processData.get_data_as_decimals(1)

                print("packet data: response of command index: ", index,
                      " Data:  ", str(value), '\n')

            #PfS :1, SqN: 42, id_sensor: 1
            if (processData.headersProcess.headers[0] > 13
                    or processData.headersProcess.headers[0] < 0):
                msg = "sensor ID " + str(
                    processData.headersProcess.headers[0]
                ) + " is not valid, packet content: :" + str(valueAll)
                print(msg)
                self.generalLogger.error(msg)
                raise Exception(msg)

            lastPacket = None
            sSensorID = str(processData.headersProcess.headers[0])
            if (sSensorID in self.lastPackets):
                lastPacket = self.lastPackets[sSensorID]

            if (lastPacket != None):
                currentSeqNumber = processData.headersProcess.headers[4]

                lastPackeSeqNumber = lastPacket.headersProcess.headers[4]
                if (currentSeqNumber != (lastPackeSeqNumber + 1)
                        and currentSeqNumber != 0
                        and lastPackeSeqNumber != 255):
                    lostCounter = 0
                    if (sSensorID in self.lostPacketsCounter):
                        lostCounter = self.lostPacketsCounter[sSensorID]

                    lostCounter = lostCounter + (currentSeqNumber -
                                                 lastPackeSeqNumber)
                    self.lostPacketsCounter[sSensorID] = lostCounter

                    logger.error("lost packets , current seq id  : " +
                                 str(currentSeqNumber) + ' , prev seq ID : ' +
                                 str(lastPackeSeqNumber))
                    logger.error("lost packets Counter : " + str(lostCounter))
                    logger.error("current packet content  : " + str(valueAll))
                    logger.error("prev packet content  : " +
                                 str(processData.headersProcess.headers) +
                                 str(processData.headersProcess.data))

            #valdation of algo_2_demo , value --8
            if (processData.headersProcess.headers[3] == 25
                    and processData.headersProcess.data[1] != 8):
                logger.error(
                    "validation of algo_2_demo value==8 failed, actual value : "
                    + processData.headersProcess.data[1])
                logger.error(" packet content  : " + str(valueAll))

            self.lastPackets[sSensorID] = processData
            #print("current Packet data length :", str(processData.headersProcess.len_data))
            #print("current Packet input   :",  valueAll )
            prevPacket = valueAll
            prevPacketType = processData.headersProcess.type_data

            sensor_id = str(processData.headersProcess.headers[0])

            if sensor_id in self.dataPerSensor and "update_view_with_first_raw_data_packet" in self.dataPerSensor[
                    sensor_id] and self.dataPerSensor[sensor_id][
                        "update_view_with_first_raw_data_packet"] == True:  #and processData.headersProcess.type_data in ['velocity','distance']   :
                self.update_cmd_view("raw_data_packet", valueAll)
                self.dataPerSensor[sensor_id][
                    "update_view_with_first_raw_data_packet"] = False

        def handle_client_connection(self, client_socket):

            self.threadData.update_view_with_first_raw_data_packet = False
            time.sleep(5)

            client_socket.send(self.get_status)

            while True:
                try:
                    processData = SensorDataProcess()
                    self.recv_data(client_socket, processData)
                    if (processData.connection_terminated):
                        temp_id = None
                        temp_id = processData.headersProcess.id_sensor
                        if id == None:
                            temp_id = ""
                        print("connection is terminated " + str(temp_id))
                        self.generalLogger.error("connection is terminated " +
                                                 str(temp_id))
                        if (temp_id != ""
                                and temp_id in self.dict_allSensor_by_id):
                            del self.dict_allSensor_by_id[temp_id]
                            self.update_conected_sensors(
                                self.dict_allSensor_by_id)
                        return

                    ts = {"ts": int(round(time.time() * 1000))}
                    #                 if(processData.headersProcess.id_sensor in  self.dict_allSensor_by_id):
                    #                     del   self.dict_allSockets_by_sensor_id[self.dict_allSensor_by_id[processData.headersProcess.id_sensor]]
                    self.dict_allSensor_by_id[
                        processData.headersProcess.id_sensor] = client_socket
                    #  self.dict_allSockets_by_sensor_id[client_socket] = processData.headersProcess.id_sensor
                    self.update_conected_sensors(self.dict_allSensor_by_id)
                    if (processData.headersProcess.is_debuge_buffer
                            or processData.headersProcess.is_vz_param):
                        continue
                    if processData.headersProcess.is_plc_data or processData.headersProcess.isRawData:  #or self.headersProcess.type_data == "end_of_pac":

                        id_socket, data = processData.process_data(ts)

                        try:

                            do_send_is_alive_ping = (
                                processData.headersProcess.isRawData and
                                processData.headersProcess.pack_seq_number %
                                100 == 0)
                            self.user.send_telemetry(
                                id_socket, data,
                                processData.headersProcess.isRawData,
                                processData.headersProcess.data,
                                processData.headersProcess.type_data,
                                do_send_is_alive_ping)

                        except Exception as e:
                            print("error sending data serv " + str(e))
                            self.generalLogger.error(
                                "error sending data serv " + str(e))
                    else:
                        fer = self.function_process_data_to_view(processData)

                except Exception as e:
                    #ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
                    msg = str(e)
                    print("general error " + msg)
                    self.generalLogger.error(msg)

                    print(traceback.format_exc())

                    self.generalLogger.error(
                        "general error " + str(e) +
                        " processData.headersProcess._headers:  " +
                        str(processData.headersProcess._headers))
                    self.generalLogger.error(
                        "general error   processData.headersProcess._headers:  "
                        + str(processData.headersProcess._headers))
                    self.generalLogger.error(
                        "general error  processData.headersProcess._headers:  "
                        + str(processData.headersProcess.data))
                    self.generalLogger.error(traceback.format_exc())
                    if ("closed" in msg):
                        return

#
#         def handle_client_connections(self):
#
#
#
#             while True:
#                 sensor_ids=self.dict_allSensor_by_id.keys()
#                 for sensor_id in sensor_ids:
#                     try:
#                         client_socket=self.dict_allSensor_by_id[sensor_id]
#                         self.handle_client_connection(client_socket)
#                     except Exception as e:
#                         print("error sending data serv" + str(e))
#                         self.generalLogger.error("error sending data serv" + str(e))

        def send_to_sensor(self, ids_sensor: list, data: str):
            #             if read_sensor_raw_data_in_secods:
            #                 for i in ids_sensor:
            #                     if i not in self.list_sensors_send_coomend_read_raw_data:
            #                         self.list_sensors_send_coomend_read_raw_data[i] = read_sensor_raw_data_in_secods
            for i in ids_sensor:
                if i not in self.dict_allSensor_by_id:
                    return 'error id sensor ' + str(i)
                try:
                    print("send to sensor " + str(i) + " : " + str(data))
                    self.dict_allSensor_by_id.get(i).send(data)
                except Exception as e:
                    print(e)
                    self.generalLogger.error("error sending data sensor" +
                                             str(e))
            return ''

        def run(self):
            if (self.generalLogger == None):
                self.generalLogger = self.getLogger('generalSensorsGateway')

            server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            #server = socket.socket(socket.AF_INET, socket.SOCK_RAW )

            server.bind((self.bind_ip, self.bind_port))
            server.listen(8)  # max backlog of connections
            #   print('Listening on {}:{}'.format(self.bind_ip, self.bind_port))
            while True:
                print('Waiting for Sensors connection')
                client_sock, address = server.accept()
                client_sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF,
                                       10000)
                print('Accepted connection from {}:{}'.format(
                    address[0], address[1]))
                client_handler = threading.Thread(
                    target=self.handle_client_connection, args=(client_sock, ))
                client_handler.start()
Ejemplo n.º 7
0
    class __TcpServer:
        params = ConfParams()
        #         get_status = b'\x12\x01\x01'
        #
        #         begin_of_packet =b'UUUUU'
        #user = ThingBoardUser()

        #
        #         function_process_data_to_view = None
        update_conected_plc = None
        plc_host = params.getParam("PLC_HOST")

        plc_socket = None

        # 192.168.1.22:502
        #PLC Mod Bus Regs 40001-40100
        #         dict_allSensor_by_id = {}
        #         prevPacket=None
        #         prevPacketType=None
        logger = None
        plc_client = None

        def __init__(self):
            if (self.logger == None):
                self.createLogger('generalPLCgateway')
            if len(self.plc_host) > 1:
                plc_client = ModbusTcpClient(self.plc_host)
            try:
                if len(self.plc_host) > 1:
                    result = plc_client.read_holding_registers(0, 5, unit=0X01)
                    if len(result.registers) == 5:
                        print("Gateway connected succesfully to PLC : " +
                              str(result))
                #self.update_conected_plc(self.plc_host)

                else:
                    print("connection is terminated ")
                    self.logger.error("connection is terminated ")
            except Exception as e:
                print("error sending data to PLC " + str(e))
                self.logger.error("error sending data to PLC " + str(e))

        def recv_data(self, client_socket, processData):
            #             value=client_socket.recv(100)
            #             print("first 100 bytes : ", str(value))

            value = client_socket.recv(20)
            if (value == b''):
                self.plc_socket = None
                processData.connection_terminated = True
                return

            print("received from PLC :", str(value))
            self.send_to_plc(value)
#             #in case out of reading sync, clearing the socket buffer
#             while(value!=self.begin_of_packet):
#                 print("out of reading sync, clearing the socket buffer")
#                 socketIsNoEmpty=True
#                 while(socketIsNoEmpty):
#                     print("read 10000")
#                     value=client_socket.recv(1024)
#                     if(len(value)<1024):
#                         socketIsNoEmpty=False
#                 value=client_socket.recv( processData.headersProcess.LENGTH_PACKET_PREFIX)
#
#
#             value=client_socket.recv( processData.headersProcess.LENGTH_HEADERS)
#             valueAll=value
#             processData.headersProcess.headers = value
#             #print("hearers : ", str(value))
#
#             value = client_socket.recv(processData.headersProcess.len_data)
#             processData.headersProcess.data =  value
#             valueAll=valueAll+value;
# #
# #             if(processData.headersProcess.headers[0]>8 or processData.headersProcess.headers[0]<1):
# #                 print("sensor ID not valid "+str(processData.headersProcess.headers[0]) + '\n' + '--- ')
# #
# #                 print("previous packet: ", str(prevPacket))
# #                 print("previous packet Type: ",prevPacketType)
# #                 print("current packet: ", str(valueAll))
#             print("current Packet Type :", processData.headersProcess.type_data)
#             print("current Packet data length :", str(processData.headersProcess.len_data))
#             prevPacket=valueAll
#             prevPacketType=processData.headersProcess.type_data

        def handle_client_connection(self, client_socket):

            self.plc_socket = client_socket

            time.sleep(5)

            #client_socket.send(self.get_status)

            while True:
                processData = SensorDataProcess()
                self.recv_data(client_socket, processData)
                if (processData.connection_terminated):
                    print("connection is terminated ")
                    self.logger.error("connection is terminated ")
                    self.update_conected_plc("")
                    return
            # ts = {"ts":SensorDataProcess.current_milli_time()}
            #self.dict_allSensor_by_id[processData.headersProcess.id_sensor] = client_socket
#                 self.update_conected_sensors(self.dict_allSensor_by_id)
#
#                 if processData.headersProcess.is_plc_data or processData.headersProcess.isRawData :#or self.headersProcess.type_data == "end_of_pac":
#
#                     id_socket, data = processData.process_data(ts)
#
#
#
#                     try:
#                         self.user.send_telemetry(id_socket, data, processData.headersProcess.isRawData )
#
#                     except Exception as e:
#                         print("error sending data serv" + str(e))
#                 else:
#                     fer = self.function_process_data_to_view(processData)
#

#         def send_to_sensor(self, ids_sensor: list, data: str ):
# #             if read_sensor_raw_data_in_secods:
# #                 for i in ids_sensor:
# #                     if i not in self.list_sensors_send_coomend_read_raw_data:
# #                         self.list_sensors_send_coomend_read_raw_data[i] = read_sensor_raw_data_in_secods
#             for i in ids_sensor:
#                 if i not in self.dict_allSensor_by_id:
#                     return 'error id sensor ' + str(i)
#                 try:
#                     self.dict_allSensor_by_id.get(i).send(data)
#                 except Exception as e:
#                     print(e)
#             return ''

        def createLogger(self, loggerName):

            self.logger = logging.getLogger(loggerName)
            handler = RotatingFileHandler('../logs/' + loggerName + '.log',
                                          maxBytes=20000000,
                                          backupCount=20)
            formatter = logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            handler.setFormatter(formatter)

            self.logger.addHandler(handler)
            self.logger.setLevel(logging.DEBUG)

        def send_to_plc(self, data: str):
            #             if read_sensor_raw_data_in_secods:
            #                 for i in ids_sensor:
            #                     if i not in self.list_sensors_send_coomend_read_raw_data:
            #                         self.list_sensors_send_coomend_read_raw_data[i] = read_sensor_raw_data_in_secods

            try:
                result = self.plc_client.write_registers(0, [300, 305],
                                                         unit=0X01)
                print(str(result))
            except Exception as e:
                print("error sending data to PLC " + str(e))
                self.logger.error("error sending data to PLC " + str(e))
Ejemplo n.º 8
0
class CmdView:
    #seconds_of_last_raw_data: Entry
    password: Entry
    SSId: Entry
    init_sensor: BooleanVar
    update_sensor_BIST: BooleanVar
    transmitting_row_data: BooleanVar
    pointer_leaser: BooleanVar
    handle_data_send = None

    update_sensors_server = None
    params = ConfParams()

    entries = []

    algo_select = ""
    plc_mode_select = ""

    container = None
    master = tk.Tk()
    canvas = None
    scrollable_frame = None

    algo_params = algoParams()

    algoritem_options = algo_params.algoritem_options

    plc_mode_options = "a"
    raw_data_type = algo_params.raw_data_type

    fildes_by_algo = algo_params.params_logic

    check_box_text_and_value = {
        # "rtc": {
        #     "text": "update RTC",
        #     "value": tk.IntVar(),
        # },
        "pointer_leaser": {
            "text": "EU HW:Turn ON Laser pointer",
            "value": tk.IntVar(),
        },
        "transmited_to_gatway": {
            "text": "WI-FI:Transmit PLC parameters",
            "value": tk.IntVar()
        },
        # "init_sensor":{
        #     "text": "init sensor",
        #     "value": tk.IntVar(),
        # },
        # "sensor_bist": {
        #     "text": "update sensor BIST",
        #     "value": tk.IntVar(),
        # } ,
        "transmited_row_data": {
            "text": "WI-FI:Transmit Raw DATA",
            "value": tk.IntVar(),
        },  #enablerawdatatouart/disablerawdatatouart
        "print_row_data_to_uart": {
            "text": "UART:Transmit Raw DATA",
            "value": tk.IntVar(),
        },
        "print_row_data_to_uart_every_minute": {
            "text": "UART:Tr. Raw DATA every minute",
            "value": tk.IntVar(),
        },
        "print_incoming_packets_info_to_console": {
            "text": "Console: Print incoming packets",
            "value": tk.IntVar(),
        }
    }

    error_label = None

    updateRTC = None

    id_sensor = [0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13]

    params_input_element = []

    check_box_element = []

    prev_algo_select = ""

    port = ""

    ip_server = ""

    id_sensor_field: IntVar

    data = {}

    select_all = 0

    sensor_select = None

    list_bist = ["normal", "saw", "sinus"]

    option_element = None
    command_file = None

    e1 = None

    cal_fac1 = 0
    vt_cal_fac = 0

    def __init__(self, handle_data, update_sensors_server):
        self.handle_data_send = handle_data
        self.update_sensors_server = update_sensors_server
        self.init_view()

    def update_conected_sensors(self, conected_sensors):
        self.connected_sensors_lab.configure(
            text="connected sensors: " +
            str(conected_sensors.keys()).replace("dict_keys", ""))

    def update_conected_plc(self, conected_plc):
        self.connected_plc_lab.configure(text="connected PLC: " +
                                         str(conected_plc))

    def add_bool_to_sender_data(self, file, value):
        if file == "print_incoming_packets_info_to_console":
            self.update_sensors_server(
                "na", "print_incoming_packets_info_to_console",
                bool(value.get()))
        else:
            self.data[file] = value.get()
        # print(self.data)

    def send_cmd(self, addlData=None):
        error_message = None
        if not addlData:
            addlData = {}
        try:
            self.data["id"] = self.sensor_select.get(
            ) if not self.select_all else 'all'

            if ("get_debug_buffer" in addlData):
                self.data["get_debug_buffer"] = addlData["get_debug_buffer"]
                print(self.data)
                return self.handle_data_send(self.data, False, error_message)

            if self.password.get():
                self.data["network_password"] = self.password.get()

            if self.SSId.get():
                self.data["network_name"] = self.SSId.get()

            if self.id_sensor_field.get():
                self.data["id_sensor"] = int(self.id_sensor_field.get())

            if self.sensor_bist.get():
                self.data["sensor_bist"] = self.list_bist.index(
                    self.sensor_bist.get())

            if self.port.get():
                self.data["network_port"] = self.port.get()

    #         if self.seconds_of_last_raw_data.get():
    #             self.data["get_raw_data"] = int(self.seconds_of_last_raw_data.get())

            if self.ip_server.get():
                self.data["network_server_ip"] = self.ip_server.get()

    #at embedded :  {Algo_2=2,Algo_3_4=3,Algo_5=4,No_Algo=5};
            if self.algo_select.get():
                #self.data["algo_selected"] = self.algoritem_options.index(self.algo_select.get())+2
                self.data["algo_selected"] = self.algoritem_options[
                    self.algo_select.get()]
                #if(self.data["algo_selected"]>2):
                #    self.data["algo_selected"] =  self.data["algo_selected"]+1

                self.data["params"] = []

                for entryIndex in range(len(self.entries)):
                    value = ''
                    if (isinstance(self.entries[entryIndex], Entry)):
                        value = self.entries[entryIndex].get()
                    else:
                        value = self.raw_data_type.index(
                            self.entries[entryIndex].get()) + 1

                    self.data["params"].append(value)

            for key in addlData:
                self.data[key] = addlData[key]

        except Exception as e:
            msg = str(e)
            print("general error " + msg)
            error_message = "Error while parsing GUI parameters, please verify values are not missing or not correct"

        print(self.data)
        return self.handle_data_send(self.data, False, error_message)

    def set_ids(self):
        self.option_element.pack_forget(
        ) if self.select_all else self.option_element.pack(
            side=tk.RIGHT, expand=tk.YES, fill=tk.X)

    def show_error(self, message):
        self.error_label.config(text=message)

    def clear_params_list(self):
        self.entries = []
        for i in self.params_input_element:
            i.pack_forget()

        if self.data.get("params"):
            del self.data["params"]

    def set_params(self):

        self.clear_params_list()
        #index=self.algoritem_options.index(self.algo_select.get())
        key = self.algoritem_options[self.algo_select.get()]
        #if(index>0):
        #    index=index+1
        fildes = self.fildes_by_algo[str(key)]

        #No Algo
        #if (index == 3):
        if (key == 5):
            self.set_row_data_options()
            return

        #algo_2_demo
        #elif (index == 4):
        elif (key == 6):
            return

        self.option_element.pack_forget()
        for field in range(len(fildes)):
            row = tk.Frame(self.master)
            lab = tk.Label(row, width=15, text=fildes[field], anchor='w')
            ent = tk.Entry(row)
            row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
            lab.pack(side=tk.LEFT)
            ent.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X)
            self.params_input_element.append(row)
            self.params_input_element.append(lab)
            self.params_input_element.append(ent)
            self.entries.append(ent)

    def set_row_data_options(self):

        row = tk.Frame(self.master)
        self.select_row_data_options = tk.StringVar(row)
        # row = tk.Frame(row)
        lab = tk.Label(row,
                       width=15,
                       text="choosing row data type",
                       anchor='w')
        self.row_data_options_list = tk.OptionMenu(
            row, self.select_row_data_options, *self.raw_data_type)
        row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
        lab.pack(side=tk.LEFT)
        self.row_data_options_list.pack(side=tk.RIGHT,
                                        expand=tk.YES,
                                        fill=tk.X)

        self.params_input_element.append(row)
        self.params_input_element.append(lab)
        self.params_input_element.append(self.row_data_options_list)
        self.entries.append(self.select_row_data_options)

    def get_status(self):
        idS = self.sensor_select.get() if not self.select_all else 'all'
        # self.data["id"] = self.sensor_select.get() if not self.select_all.get() else 'all'
        self.clear_all()
        self.data["id"] = idS
        self.data["status"] = True
        self.handle_data_send(self.data)
        self.data = {}

    def reset_device(self, ids=None):
        if (not ids):
            idS = self.sensor_select.get() if not self.select_all else 'all'
        # self.data["id"] = self.sensor_select.get() if not self.select_all.get() else 'all'
        self.clear_all()
        self.data["id"] = idS
        self.data["reset_eu"] = True
        self.handle_data_send(self.data)
        self.data = {}

    def get_command_file(self):

        if not self.sensor_select.get() and not self.select_all:
            self.show_error('you must select sensor')
            return

        idS = self.sensor_select.get() if not self.select_all else 'all'

        #self.clear_all()

        command_file = self.params.getParam(
            "COMMAND_FILE_PATH"
        )  #C:/Users/USER/Desktop/Manual/requirements.txt
        # Using readlines()
        print("open file : " + command_file)
        file1 = open(command_file, 'r')
        Lines = file1.readlines()
        file1.close()

        for line in Lines:

            print("process line : " + str(line))
            write_command_length = None
            self.data["id"] = idS

            if line[0] == "R":
                splitted = line.split(",")
                #skip 4th number
                line = ",".join(splitted[:4]) + "," + splitted[5]
                line = "R26,06," + line.replace("R", "27", 1)
                indx = int(splitted[1])
                param_type = splitted[4].strip()
                #store param_type by index to be used on reply
                self.update_sensors_server("command", str(indx), param_type)

            elif line[0] == "r":
                splitted = line.split(",")
                #skip 4th number
                line = ",".join(splitted[:4]) + "," + splitted[5]
                line = "R26,06," + line.replace("r", "27", 1)
                indx = int(splitted[1])
                param_type = splitted[4].strip()
                self.update_sensors_server("command", str(indx), param_type)

            elif line[0] == "W":

                write_command_length = line.count(',') + 2
                splitted = line.split(",")
                #skip 3rd number
                line = ",".join(splitted[:3]) + "," + ",".join(splitted[4:])
                line = "W26," + str(write_command_length) + "," + line.replace(
                    "W", "26", 1)

            elif line[0] == "w":

                write_command_length = line.count(',') + 2
                splited = line.split(",")
                #skip 3rd number
                line = ",".join(splitted[:3]) + "," + ",".join(splitted[4:])
                line = "W26," + str(write_command_length) + "," + line.replace(
                    "w", "26", 1)

            print("Sent line is ", line)
            self.data["command"] = line
            self.data["send_command"] = True
            self.handle_data_send(self.data)
            self.data = {}

    def update_plc_device(self):

        # self.data["id"] = self.sensor_select.get() if not self.select_all.get() else 'all'
        # self.clear_all()
        #             Buffer[0] = module address                            (0x01);
        #             Buffer[1] = function                                  (0x03 '03' Read Multiple Registers); //write 16(decimal)
        #             Buffer[2] = Register Address High Byte                (0x038 - add 14468);
        #             Buffer[3] = Register Address Low Byte                 (0x084 - add 14468);
        #             Buffer[4] = number of word(16 bit) to return MSB      (0x00);
        #             Buffer[5] = number of word(16 bit) to return LSB      (0x02 - 2 word to return);
        #             Buffer[6] = CRC LOW BYTE                              (0x89);
        #             Buffer[7] = CRC HIGH BYTE                             (0x42);

        pass
        #self.data["module address"] = 1
        #self.data["function"] = 3
        # self.data["Register Address"] =14468

        # self.data["plc data"] =2

        #self.handle_data_send(self.data,True)
        # self.data = {}

#     def cb(self, event):
#         print ("variable is"+ self.var.get())
#         self.add_bool_to_sender_data(self.field_text, self.value)

    def set_check_box_view(self):

        for key, field in self.check_box_text_and_value.items():
            row = tk.Frame(self.master)
            # self.check_box_text_and_value[field]["value"] = tk.Variable()
            field["value"].set(0)
            #              c = Checkbutton(
            #             master, text="Enable Tab",
            #             variable=self.var,
            #             command=self.cb)
            c = tk.Checkbutton(
                row,
                text=field["text"],
                variable=field["value"],
                command=lambda field_text=key, value=field[
                    "value"]: self.add_bool_to_sender_data(field_text, value))
            #tk.Button(row, text='Apply', command=lambda field_text=key, value=field["value"]: self.add_bool_to_sender_data(field_text, value)).pack(side=tk.RIGHT, padx=3, pady=3)
            row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
            c.pack(side=tk.LEFT)

    def get_last_raw_data(self):
        idS = self.sensor_select.get() if not self.select_all else 'all'
        # self.data["id"] = self.sensor_select.get() if not self.select_all.get() else 'all'
        self.clear_all()
        self.data["id"] = idS
        self.data["get_raw_data"] = True
        self.handle_data_send(self.data)
        self.data = {}

    def clear_all(self):
        self.data = {}
        for field in self.check_box_text_and_value:
            self.check_box_text_and_value[field]["value"].set(0)

        self.algo_select.set("")
        self.clear_params_list()
        self.SSId.delete(0, 'end')
        self.password.delete(0, 'end')
        self.port.delete(0, 'end')
        self.ip_server.delete(0, 'end')
        self.sensor_select.set("")
        self.select_all = 0
        self.id_sensor_field.set("")
        self.sensor_bist.set("")

        #self.seconds_of_last_raw_data.delete(0, 'end')
        self.set_ids()

    def init_view(self):

        master = self.master
        master.title(
            self.params.getParam("GATEWAY_NAME") + ' , v:' +
            self.params.getParam("VERSION"))

        # Change - Start
        tabControl = ttk.Notebook(master)

        tab1 = ttk.Frame(tabControl)
        tab2 = ttk.Frame(tabControl)
        tab3 = ttk.Frame(tabControl)

        tabControl.add(tab1, text='Main')
        tabControl.add(tab2, text='Config')
        tabControl.add(tab3, text='Calibration')

        tabControl.pack(expand=1, fill="both")
        # Change - End

        #container = ttk.Frame(master)
        self.canvas = tk.Canvas(tab1)
        canvas = self.canvas
        # scrollbar = ttk.Scrollbar(master, orient="vertical", command=canvas.yview)
        scrollbar = ttk.Scrollbar(tab1,
                                  orient="vertical",
                                  command=canvas.yview)
        self.scrollable_frame = ttk.Frame(canvas)
        scrollable_frame = self.scrollable_frame

        #         scrollable_frame.bind(
        #             "<Configure>",
        #             lambda e: canvas.configure(
        #                 scrollregion=canvas.bbox("all")
        #                 )
        #             )

        self.master = scrollable_frame
        master = self.master

        canvas.create_window((0, 0),
                             window=scrollable_frame,
                             anchor="nw",
                             tags="my_tag")

        canvas.configure(yscrollcommand=scrollbar.set)

        scrollable_frame.bind("<Configure>", self.OnFrameConfigure)

        self.sensor_select = tk.StringVar()
        row = ttk.Frame(self.scrollable_frame)
        lab = tk.Label(row, width=15, text="select Sensor", anchor='w')
        self.option_element = tk.OptionMenu(row, self.sensor_select,
                                            *self.id_sensor)
        c = tk.Checkbutton(row,
                           width=15,
                           text="select all Sensors",
                           variable=self.select_all,
                           command=self.set_ids)

        row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
        lab.pack(side=tk.LEFT)
        self.option_element.pack(side=tk.LEFT, expand=tk.YES, fill=tk.X)
        c.pack()

        self.set_check_box_view()

        row = ttk.Frame(scrollable_frame)
        lab = tk.Label(row, text="WIFI", anchor='w')
        self.SSId = tk.Entry(row)
        self.password = tk.Entry(row)

        lab.pack(side=tk.LEFT)
        self.SSId.pack(side=tk.LEFT, expand=tk.YES)
        self.password.pack(side=tk.LEFT, expand=tk.YES)

        self.port = tk.Entry(row)
        self.ip_server = tk.Entry(row)
        row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)

        self.port.pack(side=tk.LEFT, expand=tk.YES)
        self.ip_server.pack(side=tk.LEFT, expand=tk.YES)
        #
        #         row = ttk.Frame(scrollable_frame)
        #         lab = tk.Label(row, text="Write bytes to vz sensor", anchor='w')
        #         self.byte_to_sensor = tk.Entry(row)
        #         row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
        #         lab.pack(side=tk.LEFT)
        #         self.byte_to_sensor.pack(fill=tk.X, expand=tk.YES)

        #         row = tk.Frame(self.master)
        #         lab = tk.Label(row, text="Get the latest data in seconds", anchor='w')
        #         self.seconds_of_last_raw_data = tk.Entry(row)
        #         row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
        #         lab.pack(side=tk.LEFT)
        #         self.seconds_of_last_raw_data.pack(fill=tk.X, expand=tk.YES)

        self.id_sensor_field = tk.StringVar(row)
        row = ttk.Frame(scrollable_frame)
        lab = tk.Label(row, width=15, text="Write EU ID:", anchor='w')
        op = tk.OptionMenu(row, self.id_sensor_field, *self.id_sensor)

        lab.pack(side=tk.LEFT)
        op.pack(side=tk.LEFT, expand=tk.YES, fill=tk.X)

        self.sensor_bist = tk.StringVar(row)

        lab = tk.Label(row, width=15, text="Sensor BIST", anchor='w')
        op = tk.OptionMenu(row, self.sensor_bist, *self.list_bist)
        row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
        lab.pack(side=tk.LEFT)
        op.pack(side=tk.LEFT, expand=tk.YES, fill=tk.X)

        self.algo_select = tk.StringVar()
        row = ttk.Frame(scrollable_frame)
        lab = tk.Label(row, width=15, text="select algo", anchor='w')
        op = tk.OptionMenu(row,
                           self.algo_select,
                           *self.algoritem_options,
                           command=lambda _: self.set_params())
        row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
        lab.pack(side=tk.LEFT)
        op.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X)

        self.plc_mode_select = tk.StringVar()
        row = ttk.Frame(scrollable_frame)
        lab = tk.Label(row, width=15, text="PLC Mode", anchor='w')
        op = tk.OptionMenu(row,
                           self.plc_mode_select,
                           *self.plc_mode_options,
                           command=lambda _: self.update_plc_device())
        row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
        lab.pack(side=tk.LEFT)
        op.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X)

        self.error_label = tk.Label(master, fg="red")
        self.error_label.pack(padx=5, pady=5)

        row = ttk.Frame(scrollable_frame)
        self.connected_sensors_lab = tk.Label(row,
                                              text="connected sensors",
                                              anchor='w')
        row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
        self.connected_sensors_lab.pack(side=tk.LEFT)

        row = ttk.Frame(scrollable_frame)
        self.connected_plc_lab = tk.Label(row,
                                          text="connected PLC: ",
                                          anchor='w')
        row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
        self.connected_plc_lab.pack(side=tk.LEFT)

        tk.Button(master,
                  text='Get DB',
                  command=self.get_debugge_buffer_packet).pack(side=tk.RIGHT,
                                                               padx=8,
                                                               pady=8)

        tk.Button(master, text='VZWrite ',
                  command=self.get_command_file).pack(side=tk.RIGHT,
                                                      padx=8,
                                                      pady=8)

        tk.Button(master, text='RD Packet',
                  command=self.get_row_data_packet).pack(side=tk.RIGHT,
                                                         padx=8,
                                                         pady=8)

        tk.Button(master, text='Status',
                  command=self.get_status).pack(side=tk.RIGHT, padx=8, pady=8)

        tk.Button(master, text='Reset',
                  command=self.reset_device).pack(side=tk.RIGHT,
                                                  padx=8,
                                                  pady=8)

        tk.Button(master, text='Clear',
                  command=self.clear_all).pack(side=tk.RIGHT, padx=8, pady=8)

        tk.Button(master, text='SEND',
                  command=self.send_cmd).pack(side=tk.RIGHT, padx=8, pady=8)

        # Change - Start
        string_vars = {}
        # the fields must match the saved_config dictionary
        params = {
            'FWI': 'FWI (Former Wear Indication)',
            'TCC': 'TCC (Time of Charge Compaction)',
            'PSD': 'PSD (Product in Seal Detection)',
            'TBS': 'TBS (Time of Bag Spacing)',
            'ABH': 'ABH (Average Bag Height)',
            'TBL': 'TBL (Time of Bag Length)',
            'CFT': 'CFT (Chips Fall Time)',
            'JCT': 'JCT (Jaws Cycle Time)'
        }

        def send_params():
            return_map = {
                'FIRST_SHIFT': (start_1st_shift.get(), end_1st_shift.get()),
                'SECOND_SHIFT': (start_2nd_shift.get(), end_2nd_shift.get()),
                'N': n.get()
            }

            for token in params.keys():
                return_map[token] = []
                for place in range(5):
                    return_map[token].append(string_vars[token][place].get())

            #print(return_map)

            with open('config.txt', 'w') as outfile:
                json.dump(return_map, outfile)

            params_to_send = {
                "START_FIRST_SHIFT": start_1st_shift.get(),
                "END_FIRST_SHIFT": end_1st_shift.get(),
                "START_SECOND_SHIFT": start_2nd_shift.get(),
                "END_SECOND_SHIFT": end_2nd_shift.get(),
                "LAST_N": n.get()
            }
            user = ThingBoardUser()
            user.send_attributes("PLC", params_to_send)

        # To Do - add validation
        def valid_time():
            return True

        def prepare_second_table_row(token, desc):
            row = tk.Frame(tab2)
            row.pack(fill=tk.X)

            string_vars[token] = []
            for i in range(5):
                string_vars[token].append(tk.StringVar())

            row_label = tk.Label(row, text=desc, width=30)
            string_vars[token][0].set(saved_config[token][0])
            column_1 = Entry(row, textvariable=string_vars[token][0], width=20)
            string_vars[token][1].set(saved_config[token][1])
            column_2 = Entry(row, textvariable=string_vars[token][1], width=20)
            string_vars[token][2].set(saved_config[token][2])
            column_3 = Entry(row, textvariable=string_vars[token][2], width=20)
            string_vars[token][3].set(saved_config[token][3])
            column_4 = Entry(row, textvariable=string_vars[token][3], width=20)
            string_vars[token][4].set(saved_config[token][4])
            column_sensor = Entry(row,
                                  textvariable=string_vars[token][4],
                                  width=20)

            row_label.pack(side=tk.LEFT)
            tk.Label(row, width=2, bg="red").pack(side=tk.LEFT)
            column_1.pack(side=tk.LEFT)
            tk.Label(row, width=2, bg="yellow").pack(side=tk.LEFT)
            column_2.pack(side=tk.LEFT)
            tk.Label(row, width=2, bg="LimeGreen").pack(side=tk.LEFT)
            column_3.pack(side=tk.LEFT)
            tk.Label(row, width=2, bg="yellow").pack(side=tk.LEFT)
            column_4.pack(side=tk.LEFT)
            tk.Label(row, width=2, bg="red").pack(side=tk.LEFT)
            column_sensor.pack(side=tk.LEFT)

        def calibration_step_1():
            self.vt_cal_fac = 50
            self.cal_fac = 1
            cal_fac_du2m_s = 2**8 * 1000 * self.cal_fac / self.vt_cal_fac
            self.data["algo_selected"] = self.algoritem_options["algo_8"]
            self.data["id"] = self.sensor_select.get(
            ) if not self.select_all else 'all'
            self.data["params"] = []
            print("cal_fac_du2m_s ", cal_fac_du2m_s)
            self.data["params"].append(cal_fac_du2m_s)
            print("self.data ", self.data)
            self.send_cmd()
            time.sleep(5)

            ref_val = 100
            SensorDataProcess.collect_calibration = True

            def step_1_function():
                print("in Calibration 1")
                message_var.set("Wait a minute to continue")
                mean_val = SensorDataProcess.mean_med_vel
                self.cal_fac1 = mean_val / ref_val
                print("cal_fac1: ", self.cal_fac1)
                message_var.set(
                    "The first test is completed, set the machine to the next velocity and run the second test."
                )
                button_2['state'] = 'normal'
                button_1['state'] = 'disabled'

            t = threading.Timer(6 * 10, step_1_function)
            t.start()

        def calibration_step_2():
            ref_val = 200

            SensorDataProcess.collect_calibration = True

            def step_2_function():
                print("in Calibration 2")
                message_var.set("Wait a minute for result")
                mean_val = SensorDataProcess.mean_med_vel
                cal_fac2 = mean_val / ref_val
                cal_fac = (self.cal_fac1 + cal_fac2) / 2
                print("self.cal_fac1: ", self.cal_fac1)
                print("cal_fac2: ", cal_fac2)
                print("cal_fac: ", cal_fac)
                if cal_fac > 0 and abs(self.cal_fac1 -
                                       cal_fac2) / cal_fac < 0.1:
                    cal_fac_du2m_s = 2**8 * 1000 * cal_fac / self.vt_cal_fac
                    message_var.set(
                        "The second test is completed, the Calibration Constant is calculated! \n Calibration Constant = "
                        + str(cal_fac_du2m_s))
                    self.data["algo_selected"] = self.algoritem_options[
                        "algo_8"]
                    self.data["id"] = self.sensor_select.get(
                    ) if not self.select_all else 'all'
                    self.data["params"] = []
                    self.data["params"].append(cal_fac_du2m_s)
                    self.send_cmd()
                else:
                    message_var.set(
                        "Calculation error: The 'angle factor' of the first and the second runs are not equal!"
                    )

                button_1['state'] = 'normal'

            t = threading.Timer(6 * 10, step_2_function)
            t.start()

        # Display configuration part of form
        try:
            with open('config.txt', 'r') as infile:
                saved_config = json.load(infile)
        except Exception:
            saved_config = {
                'FIRST_SHIFT': ('', ''),
                'SECOND_SHIFT': ('', ''),
                'N': '',
                'FWI': (0, 0, 0, 0, 'VZ4'),
                'TCC': (0, 0, 0, 0, 'VZ1,2,3'),
                'PSD': (0, 0, 0, 0, 'VZ5'),
                'TBS': (0, 0, 0, 0, 'VZ6'),
                'ABH': (0, 0, 0, 0, 'VZ6'),
                'TBL': (0, 0, 0, 0, 'VZ6'),
                'CFT': (0, 0, 0, 0, 'VZ1,2,3'),
                'JCT': (0, 0, 0, 0, 'VZ5')
            }
        #print(saved_config)

        # Configuration tab
        tk.Label(tab2, text="Shift change settings", bg="red").pack(fill=tk.X,
                                                                    pady=15)

        top_table = tk.Frame(tab2)
        top_table.pack()

        left_side = tk.Frame(top_table)
        left_side.pack(side=tk.LEFT)

        row11 = tk.Frame(left_side)
        start_1st_shift_label = tk.Label(row11,
                                         text="Start of first shift",
                                         width=30)
        start_1st_shift = Entry(row11,
                                width=20,
                                validate='key',
                                validatecommand=valid_time)
        start_1st_shift.insert(tk.END, saved_config["FIRST_SHIFT"][0])
        row11.pack(fill=tk.X)
        start_1st_shift_label.pack(side=tk.LEFT)
        start_1st_shift.pack(side=tk.LEFT)

        row12 = tk.Frame(left_side)
        end_1st_shift_label = tk.Label(row12,
                                       text="End of first shift",
                                       width=30)
        end_1st_shift = Entry(row12,
                              width=20,
                              validate='key',
                              validatecommand=valid_time)
        end_1st_shift.insert(tk.END, saved_config["FIRST_SHIFT"][1])
        row12.pack(fill=tk.X)
        end_1st_shift_label.pack(side=tk.LEFT)
        end_1st_shift.pack(side=tk.LEFT)

        row13 = tk.Frame(left_side)
        row13.pack(fill=tk.X)
        tk.Label(row13, text='', width=30).pack(side=tk.LEFT)
        Entry(row13, width=20, state='disabled').pack(side=tk.LEFT)

        row14 = tk.Frame(left_side)
        n_label = tk.Label(row14, text="N", width=30)
        n = Entry(row14, width=20)
        n.insert(tk.END, saved_config['N'])
        row14.pack(fill=tk.X)
        n_label.pack(side=tk.LEFT)
        n.pack(side=tk.LEFT)

        right_side = tk.Frame(top_table)
        right_side.pack(side=tk.LEFT)

        row21 = tk.Frame(right_side)
        start_2nd_shift_label = tk.Label(row21,
                                         text="Start of second shift",
                                         width=30)
        start_2nd_shift = Entry(row21,
                                width=20,
                                validate='key',
                                validatecommand=valid_time)
        start_2nd_shift.insert(tk.END, saved_config["SECOND_SHIFT"][0])
        row21.pack(fill=tk.X)
        start_2nd_shift_label.pack(side=tk.LEFT)
        start_2nd_shift.pack(side=tk.LEFT)

        row22 = tk.Frame(right_side)
        end_2nd_shift_label = tk.Label(row22,
                                       text="End of second shift",
                                       width=30)
        end_2nd_shift = Entry(row22,
                              width=20,
                              validate='key',
                              validatecommand=valid_time)
        end_2nd_shift.insert(tk.END, saved_config["SECOND_SHIFT"][1])
        row22.pack(fill=tk.X)
        end_2nd_shift_label.pack(side=tk.LEFT)
        end_2nd_shift.pack(side=tk.LEFT)

        row23 = tk.Frame(right_side)
        row23.pack(fill=tk.X)
        tk.Label(row23, text='', width=30).pack(side=tk.LEFT)
        Entry(row23, width=20, state='disabled').pack(side=tk.LEFT)

        row24 = tk.Frame(right_side)
        row24.pack(fill=tk.X)
        tk.Label(row24, text='', width=30).pack(side=tk.LEFT)
        Entry(row24, width=20, state='disabled').pack(side=tk.LEFT)

        tk.Label(tab2, text="Data ranges settings", bg="red").pack(fill=tk.X,
                                                                   pady=15)

        row0 = tk.Frame(tab2)
        header = tk.Label(row0,
                          text="Parameter name",
                          width=30,
                          bg="LightGray")
        header1 = tk.Label(row0, text="Limit 1", width=17, bg="LightGray")
        header2 = tk.Label(row0, text="Limit 2", width=17, bg="LightGray")
        header3 = tk.Label(row0, text="Limit 3", width=17, bg="LightGray")
        header4 = tk.Label(row0, text="Limit 4", width=16, bg="LightGray")
        header_sensor = tk.Label(row0,
                                 text="Sensor SN",
                                 width=17,
                                 bg="LightGray")

        row0.pack(fill=tk.X)

        header.pack(side=tk.LEFT)
        tk.Label(row0, width=2, bg="red").pack(side=tk.LEFT)
        header1.pack(side=tk.LEFT)
        tk.Label(row0, width=2, bg="yellow").pack(side=tk.LEFT)
        header2.pack(side=tk.LEFT)
        tk.Label(row0, width=2, bg="LimeGreen").pack(side=tk.LEFT)
        header3.pack(side=tk.LEFT)
        tk.Label(row0, width=2, bg="yellow").pack(side=tk.LEFT)
        header4.pack(side=tk.LEFT)
        tk.Label(row0, width=2, bg="red").pack(side=tk.LEFT)
        header_sensor.pack(side=tk.LEFT)

        for token, desc in params.items():
            prepare_second_table_row(token, desc)

        send = tk.Button(tab2, text="SEND", width=20, command=send_params)
        send.pack(pady=20)

        frame_1 = tk.Frame(tab3, borderwidth=1)
        frame_1.pack(anchor=tk.W)
        step_1 = tk.Label(
            frame_1,
            text=
            "Choose sensor ID on Main tab.\nStep 1: Set Machine to Velocity = 100 m/min and press ENTER, and run test 1: ",
            width=60,
            height=6,
            font=(None, 12),
            anchor=tk.W)
        step_1.pack(side=tk.LEFT)
        button_1 = tk.Button(frame_1,
                             text="Test 1",
                             width=10,
                             bd=2,
                             command=calibration_step_1)
        button_1.pack(side=tk.LEFT)
        frame_2 = tk.Frame(tab3, borderwidth=1)
        frame_2.pack(anchor=tk.W)
        step_2 = tk.Label(
            frame_2,
            text=
            "Step 2: Set Machine to Velocity = 200 m/min and press ENTER, and run test 2:",
            width=60,
            height=6,
            font=(None, 12),
            anchor=tk.W)
        step_2.pack(side=tk.LEFT, expand=True)
        button_2 = tk.Button(frame_2,
                             text="Test 2",
                             width=10,
                             bd=2,
                             state=tk.DISABLED,
                             command=calibration_step_2)
        button_2.pack(side=tk.LEFT)
        frame_3 = tk.Frame(tab3, borderwidth=1)
        frame_3.pack(anchor=tk.W)
        step_3 = tk.Label(
            frame_3,
            text="Step 3: Wait for calibration constant to be calculated.",
            width=60,
            height=6,
            font=(None, 12),
            anchor=tk.W)
        step_3.pack(fill=tk.X, expand=True, anchor="w")
        frame_4 = tk.Frame(tab3,
                           highlightbackground="gray",
                           highlightthickness=1,
                           width=600,
                           height=50)
        frame_4.pack(anchor=tk.W)
        frame_4.pack_propagate(False)
        message_var = tk.StringVar()
        label = tk.Label(frame_4, textvariable=message_var, font=(None, 12))

        # message_var.set("Hey!? How are you doing?")
        label.pack()

        # Change - End

        #dict:

        # tk.Button(master,
        #           text='get last raw data', command=self.get_last_raw_data).pack(side=tk.RIGHT, padx=8, pady=8)
        #container.pack()
        canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")

    def displayRawData(self, data):
        data_length = len(data)
        int_data = []
        for i in range(5, data_length, 2):
            value = int.from_bytes(data[i:i + 2], byteorder="big", signed=True)
            int_data.append(value)

        print("Raw Data Packet : " + str(int_data))
        #Display Data
        #messagebox.showinfo("Raw Data",str(data))

    def update_cmd_view(self, key, value):
        if key == "raw_data_packet":
            addData = {'transmited_row_data': 0}
            self.send_cmd(addData)
            self.displayRawData(value)

    #for Algo 5
    def get_row_data_packet(self):
        addData = {'transmited_row_data': 1}
        if not self.send_cmd(addData):
            self.update_sensors_server(
                str(self.data["id"]), "update_view_with_first_raw_data_packet",
                False)

        sensor_id = self.sensor_select.get() if not self.select_all else 'all'
        self.update_sensors_server(sensor_id,
                                   "update_view_with_first_raw_data_packet",
                                   True)

    def get_debugge_buffer_packet(self):

        # {'get_debug_buffer': DEBUG_BUFFER_TYPE}
        DEBUG_BUFFER_MODE = int(self.params.getParam("DEBUG_BUFFER_MODE"))
        addData = {'get_debug_buffer': DEBUG_BUFFER_MODE}
        self.send_cmd(addData)

#         if self.send_cmd(addData)==False:
#             self.update_sensors_server(str( self.data["id"]),"update_view_with_first_raw_data_packet",False)

    def OnFrameConfigure(self, event):
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

    @staticmethod
    def run():
        tk.mainloop()