California
Posts: 181
Joined: Sat Jun 06, 2015 2:33 pm

Threading problems

Thu Dec 05, 2019 8:26 am

Hello, I want to have three diferent threads working independet of each other but without succes so far. Below is a test code where first thread is digital clock which take care for providing time variables which are used in second thread which trigers some actions depending on time. In test we have a five second time sleep. The last thread is so called watch dog pulse which controlls digital output (LED) to get squere pulse every half second. So when time sleep is active, digital output shoul flash every half second but this doesn't happend.
Thanks in advance, Vlado

Code: Select all

# -*- coding: utf-8 -*-
import gui_47
import sys
import os
import datetime
from slaves import *
from dig_izhodi import *


from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import QTimer
import time
import threading

init_serial()
tm_mesec = 0
tm_dan = 0
tm_ura = 0
tm_minuta = 0
tm_sekunda = 0


def digitalna_ura():
    global tm_mesec
    global tm_dan
    global tm_ura
    global tm_minuta
    global tm_sekunda

    now = datetime.datetime.now()
    master.URA.setText(now.strftime("%H" + ":" + "%M" + ":" + "%S"))
    
    tm_mesec = time.localtime().tm_mon
    tm_dan = time.localtime().tm_mday
    tm_ura = time.localtime().tm_hour
    tm_minuta = time.localtime().tm_min
    tm_sekunda = time.localtime().tm_sec

    
def aktivnosti_po_uri():
    if ((master.rs485_komunikacija() == 1) and (watch_dog() == 1)):
        if tm_sekunda == 35:
            time.sleep(5)
            print("5 sekund")

def watch_dog_pulse():
    dig_out_13()

def trigering():
    digitalna_ura()
    aktivnosti_po_uri()
    watch_dog_pulse()
    
    

if __name__ == "__main__":

    app = QtGui.QApplication(sys.argv)

    gui_master = gui_47.QtGui.QTabWidget()
    master = gui_47.Ui_Izbira()
    master.setupUi(gui_master)
 
    timer = QTimer()
    timer.timeout.connect(trigering)  
    timer.start(500)

    t1= threading.Thread(target=digitalna_ura, args=())
    t2= threading.Thread(target=aktivnosti_po_uri, args=())
    t3= threading.Thread(target=watch_dog_pulse, args=())

    t1.start()
    t2.start()
    t3.start()

    t1.join()
    t2.join()
    t3.join()


    gui_master.show()
    sys.exit(app.exec_())



User avatar
Paeryn
Posts: 2779
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: Threading problems

Thu Dec 05, 2019 6:00 pm

From your code the three threads t1, t2 and t3 which run the functions digitalna_ura(), aktivnosti_po_uri() and watch_dog_pulse() respectively are one-shot deals as the functions do one thing and end (I'm not totally sure about the third thread as it just calls another function which I presume is from one of the imported modules, but as soon as that function ends then so does thread). Your code backs that up as you start all three then join all three before you show gui_master (threads only join when they have ended).

You are using QTimer to call triggering() every 0.5 seconds (I think QTimer.start() is in milliseconds). Since this function calls the three functions digitalna_ura(), aktivnosti_po_uri() and watch_dog_pulse() sequentially then they will run sequentially and in the same thread (which I assume will be the same thread as the GUI's event loop is running in, i.e. your main program's thread). I'm not sure what QTimer does if the function it calls hasn't finished when the next timeout is due.
Last edited by Paeryn on Thu Dec 05, 2019 6:10 pm, edited 1 time in total.
She who travels light — forgot something.

User avatar
paddyg
Posts: 2460
Joined: Sat Jan 28, 2012 11:57 am
Location: UK

Re: Threading problems

Thu Dec 05, 2019 6:10 pm

As Paeryn says none of those threaded functions have while loops so they will just run then stop. Is that what you intend? Normally the threaded functions would be started then loop in the background doing something.
also https://groups.google.com/forum/?hl=en-GB&fromgroups=#!forum/pi3d

California
Posts: 181
Joined: Sat Jun 06, 2015 2:33 pm

Re: Threading problems

Thu Dec 05, 2019 9:29 pm

Thanks both of you for the respond.
Function "digitalna_ura()" provides time variables which are used later in function "aktivnosti_po_uri()" to triger some communication activities (for test only time.sleep for 5 seconds). And yes, it is tigered with QTimer every second. Third function controll digital output - in normal operation we got there puls per second which goes to the hardware watchdog circuit (for safety reason).
So in this case of test example I would like to achive normal pulses every second from third function even when time.sleep in second function is active. How to achive this with while loop is very big question for me.

Regards,

User avatar
paddyg
Posts: 2460
Joined: Sat Jan 28, 2012 11:57 am
Location: UK

Re: Threading problems

Fri Dec 06, 2019 12:00 am

Hi, this is a stripped back threading with while loops. Fairly ugly code with globals and copy pasted stuff that needs DRYing, but hopefully clear what's going on. You could use the QT timer to run a function to set the boolean trigger variables rather than a threaded loop. That wouldn't need to be in a thread as it will be very fast (already threaded on the QT side).

I've switched to using boolean globals rather than time variables as that seemed more logical to me i.e. one control and other functions not needing to check the time. Also safer to check that time.time() is after the next trigger rather than number of seconds == 35

Code: Select all

import time
import threading

T_2 = 5
T_3 = 1

def f1():
    global next_f2, trigger_2, next_f3, trigger_3
    while True:
        if time.time() > next_f2:
            trigger_2 = True
            next_f2 += T_2
        if time.time() > next_f3:
            trigger_3 = True
            next_f3 += T_3
        time.sleep(0.1) # depends on resolution of timing required

def f2():
    global trigger_2
    while True:
        if trigger_2:
            print("f2 triggered", time.time())
            trigger_2 = False
        time.sleep(0.1)

def f3():
    global trigger_3
    while True:
        if trigger_3:
            print("f3 triggered", time.time())
            trigger_3 = False
        time.sleep(0.1)

next_f2 = time.time() + T_2
trigger_2 = False
next_f3 = time.time() + T_3
trigger_3 = False

t1 = threading.Thread(target=f1)
t2 = threading.Thread(target=f2)
t3 = threading.Thread(target=f3)
t1.start()
t2.start()
t3.start()

while True:
    time.sleep(10.0)
Also see https://www.raspberrypi.org/forums/view ... p#p1572495 recent thread about timing and drift using loops like this. It has a more generalized function that wraps the threading nicely.
also https://groups.google.com/forum/?hl=en-GB&fromgroups=#!forum/pi3d

California
Posts: 181
Joined: Sat Jun 06, 2015 2:33 pm

Re: Threading problems

Fri Dec 06, 2019 11:15 am

Thanks. Very helpful piece of the code. Let me implement your idea into my code.

Regards

California
Posts: 181
Joined: Sat Jun 06, 2015 2:33 pm

Re: Threading problems

Sat Dec 07, 2019 7:22 am

It works now, but I got warning message: "QPixmap: It is not safe to use pixmaps outside the GUI thread".
What does it mean? How to avoid it?

User avatar
paddyg
Posts: 2460
Joined: Sat Jan 28, 2012 11:57 am
Location: UK

Re: Threading problems

Sat Dec 07, 2019 8:38 am

Some modules have functionality that has to run in the main thread of the process that started the program. For instance in pi3d the calls to external OpenGL DLLs can't be offloaded into spawned threads. So when it needs to be run at the same time as Qt or Flask etc it either has to be run as a different process using multiprocessing (which has similarities with threading) or else use the Qt loop hooks instead of threading. i.e. in your code you could just set the Qt timer to run the functions when you want them run (and don't make them loop but don't put them in threads) That would seem to be the simplest way to do what you want.

It's quite hard to give specific help without knowing what your two imports gui_47 and dig_izhodi do and by importing * you make it hard guess where any of the imported tokens came from!
also https://groups.google.com/forum/?hl=en-GB&fromgroups=#!forum/pi3d

Paul Hutch
Posts: 430
Joined: Fri Aug 25, 2017 2:58 pm
Location: Blackstone River Valley, MA, USA
Contact: Website

Re: Threading problems

Sat Dec 07, 2019 12:56 pm

California wrote:
Sat Dec 07, 2019 7:22 am
It works now, but I got warning message: "QPixmap: It is not safe to use pixmaps outside the GUI thread".
What does it mean? How to avoid it?
This post and the other thread it links to explain the warning pretty well.
https://stackoverflow.com/questions/502 ... gui-thread

California
Posts: 181
Joined: Sat Jun 06, 2015 2:33 pm

Re: Threading problems

Sat Dec 07, 2019 1:42 pm

Thanks for your responds. This warning appears only with the last release of the Raspbian, no warnings with Jessie.

California
Posts: 181
Joined: Sat Jun 06, 2015 2:33 pm

Re: Threading problems

Sat Dec 07, 2019 2:32 pm

Code so far, it needs harware to run it. In python 2.7 version it includes also graphs, writteing and reading into-from xls files and more.

main.py:

Code: Select all

# -*- coding: utf-8 -*-
import gui_47
import sys
import os
import datetime
from slaves import *
from dig_izhodi import *


from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import QTimer
import time
import threading

init_serial()
tm_mesec = 0
tm_dan = 0
tm_ura = 0
tm_minuta = 0
tm_sekunda = 0
rs485_flag = 1


def rpi_reboot():
    os.system('sudo shutdown -r now')

def digitalna_ura():
    global tm_mesec
    global tm_dan
    global tm_ura
    global tm_minuta
    global tm_sekunda

    now = datetime.datetime.now()
    master.URA.setText(now.strftime("%H" + ":" + "%M" + ":" + "%S"))
    
    tm_mesec = time.localtime().tm_mon
    tm_dan = time.localtime().tm_mday
    tm_ura = time.localtime().tm_hour
    tm_minuta = time.localtime().tm_min
    tm_sekunda = time.localtime().tm_sec

def set_rs485_flag():
    global rs485_flag
    if master.rs485_komunikacija() == 1:
        rs485_flag = 1
    else:
        rs485_flag = 0
    
def aktivnosti_po_uri():
    global rs485_flag
    if master.rs485_komunikacija() == 1:
        rs485_flag = 1
        if watch_dog() == 1:       
            if (tm_sekunda == 2 or tm_sekunda == 12
                or tm_sekunda == 22 or tm_sekunda == 32
                or tm_sekunda == 42 or tm_sekunda == 52):            
                master.read_DS18B20()
            #    master.read_SHT11()                                                        # Hladilnica
            #    master.command_210_read_UPS()
                #if master.read_190_allowed() == 1:
                    #master.read_PCF8583()
                    

            if tm_sekunda == 29:                                             # Citanje temperatur
                master.read_slave_160()

            if tm_sekunda == 35:
                time.sleep(5)
                print("5 sekund")

#            if (tm_sekunda == 9 or tm_sekunda == 39):
#                master.read_slave_190()

#            if tm_sekunda == 27:
#                master.read_slave_210()

#            if tm_sekunda == 19:
#                master.read_slave_220()
#                master.read_slave_230()
#                master.read_slave_240()


    else:
        rs485_flag = 0

    master.pushButton_Nastavi_zac_ogr_Zgoraj.clicked.connect(master.set_time_zgoraj)
    master.pushButton_Nastavi_zac_ogr_Spodaj.clicked.connect(master.set_time_spodaj)
    master.checkBox_Up_5_6.clicked.connect(master.up_5_6_OnOff)
    master.pushButton_SetTime.clicked.connect(master.set_time_190)
    master.pushButton_SetTime.released.connect(master.flag_190_clear)
    master.Ogrevanje_izven_sezone.clicked.connect(master.vklop_izklop_ogrevanje)
    master.set_160.pressed.connect(master.set_slave_160)
    master.set_160.released.connect(master.flag_160_clear)
 #   master.Button_UPS_10s_test.clicked.connect(master.command_210_UPS_test_10s)
 #   master.Button_Start_Test_Power_Off.clicked.connect(master.command_210_power_OFF)
 #   master.Button_Stop_Test_Power_On.clicked.connect(master.command_210_power_ON)
 #   master.Set_220.clicked.connect(master.set_slave_220)
 

#------------------------------------------------------------------------------
def watch_dog_pulse():
    global rs485_flag
    if rs485_flag == 1:
        dig_out_13()

def prozenje():
    t1= threading.Thread(target=digitalna_ura)
    #t2= threading.Thread(target=set_rs485_flag)
    t2= threading.Thread(target=aktivnosti_po_uri)
    t3= threading.Thread(target=watch_dog_pulse)

    t1.start()
    t2.start()
    t3.start()
    #t4.start()

    
    

if __name__ == "__main__":

    app = QtGui.QApplication(sys.argv)

    gui_master = gui_47.QtGui.QTabWidget()
    master = gui_47.Ui_Izbira()
    master.setupUi(gui_master)

# Timer - Triger na eno sekundo  
    timer = QTimer()
    timer.timeout.connect(prozenje)  # triga spremembe na uri
    timer.start(1000)

    


    gui_master.show()
    sys.exit(app.exec_())




dig_izhodi.py:

Code: Select all

"""
pin 1  3,3V
pin 4  5V
pin 6  GND
pin 7  DI shut down
pin 8  Tx
pin 10 Rx
pin 13 DO watch dog
pin 15 DO CPU cooler
pin 31 DI kill application
pin 37 DI WatchDog - omogoceno branje slejvov ob log 1
"""

import RPi.GPIO as GPIO
from subprocess import call
import os
from sys import exit

#import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)                            # Stevilka dejanskega pina se uporabi v kodi
GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)  # Set up pin 7 as an input
GPIO.setup(13, GPIO.OUT)                            # WatchDog
GPIO.setup(15,GPIO.OUT)                             # CPU cooler
GPIO.setup(37, GPIO.IN, pull_up_down=GPIO.PUD_UP)   # signal iz 74123
GPIO.setup(31, GPIO.IN, pull_up_down=GPIO.PUD_UP)   # zaustavitev aplikacije s tipko


def dig_out_13():
    GPIO.output(13, not GPIO.input(13))


def shutdown(pin):
    GPIO.cleanup()
    call(os.system('sudo poweroff'))


# wait for rising pulse from button press
#GPIO.setmode(GPIO.BOARD)  # Set pin numbering to board numbering
#GPIO.setup(7, GPIO.IN)  # Set up pin 7 as an input
GPIO.add_event_detect(7, GPIO.RISING, callback=shutdown, bouncetime=200)
# Set up an interrupt to look for button presses


# Return CPU temperature as float
def getCPUtemp():
    cTemp = os.popen('vcgencmd measure_temp').readline()
    return float(cTemp.replace("temp=","").replace("'C\n",""))


def set_cooler():
    CPU_temp = getCPUtemp()
    if CPU_temp > 45.0:
        GPIO.output(15, GPIO.HIGH)
    elif CPU_temp < 42.0:
        GPIO.output(15, GPIO.LOW)


def watch_dog():
    # optokopler skupaj z metodo tvori negiranje negiranja (1->0, 0->1)
    # log. 1 na vhodu optokoplerja da na njegovem izhodu log 0
    if (GPIO.input(37)):
    # log 0 na GPIO.INPUT(37) da na izhodu metode log 1
        wd_flag = 0
        #print (wd_flag)
    else:
        wd_flag = 1
        #print (wd_flag)
    return wd_flag


def kill_app():
    if (GPIO.input(31)):
        pass
    else:
        GPIO.cleanup()
        exit(0) # Successful exit application
slaves.py:

Code: Select all

import serial
import array
import struct
from time import sleep
from ctypes import *



maxReadCount=8
readBuffer = array.array('i')


ser = 0

#-----------------------------------------------------------------------
def init_serial():
    COMNUM = 2
    global ser
    ser = serial.Serial()
    
    #ser.port = "/dev/ttyUSB0"
    ser.port = "/dev/ttyAMA0"
    ser.baudrate = 19200
    ser.parity=serial.PARITY_NONE
    ser.stopbits=serial.STOPBITS_ONE
    ser.bytesize=serial.EIGHTBITS
    ser.timeout = 10
    ser.open()
#------------------------------------------------------------------------
def convert_MICROCHIP_32bit_to_float(x):
    if x == 0:
        x = 1231459733
    x_hex = format(x, 'x')
    bits = bin(int(x_hex, 16))[2:].zfill(len(x_hex) * 4)   
    i = 0
    val = "                                ".encode()
    b_s = list(val)
    for char in bits:
        current_bit = int(char)
        if current_bit == 1:
            if i < 8:
                b_s[i + 1] = "1"
            elif i == 8:
                b_s[0] = "1"
            else:
                b_s[i] = "1"
        else:
            if i < 8:
                b_s[i + 1] = "0"
            elif i == 8:
                b_s[0] = "0"
            else:
                b_s[i] = "0"
        i = i + 1   
    val = [int(i) for i in b_s]
    out = 0
    for bit in val:
        out = (out << 1) | bit   
    hex_val = hex(out) 
    def convert(s):
        i = int(s, 16)                   # convert from hex to a Python int
        cp = pointer(c_int(i))           # make this into a c integer
        fp = cast(cp, POINTER(c_float))  # cast the int pointer to a float pointer
        return fp.contents.value         # dereference the pointer, get the float    
    float_val = convert(hex_val)
    return float_val

#--------------------------------------------------------------------------
def crc_calc(start_, addr, datalen_, dat_0, dat_1, dat_2, stop_):
    crc = datalen_ ^ addr
    crc = crc ^ dat_0
    crc = crc ^ dat_1
    crc = crc ^ dat_2
    crc = 255 - crc
    if crc == start_ or crc == stop_:
        crc = crc + 1
    return crc
#--------------------------------------------------------------------------

#--------------------------------------------------------------------------
#-----------------------------Slave 190------------------------------------
def slave_read_PCF8583():
    start = 0x96
    address = 0xbe
    datalen = 0x83
    data_0 = 0xba
    data_1 = 0xbc
    data_2 = 0xba
    stop = 0xa9

    crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
    data = bytearray(
        [start, address, datalen, data_0, data_1, data_2, crc_, stop])
    ser.write(data)
    readBuffer = array.array('i')
    readCount = 0
    while readCount < maxReadCount:
        readBuffer.append(ord(ser.read(1)))
        readCount = readCount + 1

#-----------------------------------------------------------------------------
def read_time():

    start = 0x96
    address = 0xbe
    datalen = 0x83
    data_0 = 0xbb
    data_1 = 0xbc
    data_2 = 0
    stop = 0xa9

    crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
    data = bytearray(
        [start, address, datalen, data_0, data_1, data_2, crc_, stop])
    ser.write(data)
    readBuffer = array.array('i')
    readCount = 0
    while readCount < maxReadCount:
        readBuffer.append(ord(ser.read(1)))
        readCount = readCount + 1

    completeTransfer = 10
    allPackets = 0
    start = 0x96
    address = 0xbe
    datalen = 0x83
    data_0 = 0xbc
    data_1 = 0
    data_2 = 0
    stop = 0xa9

    while allPackets < completeTransfer:
        crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
        data = bytearray(
            [start, address, datalen, data_0, data_1, data_2, crc_, stop])
        ser.write(data)
        readBuffer = array.array('i')
        readCount = 0
        while readCount < maxReadCount:
            readBuffer.append(ord(ser.read(1)))
            readCount = readCount + 1

        i = 0
        while i < maxReadCount:
            val = (readBuffer[i])
            if i == 4:
                a = val
                if allPackets == 0:
                    year = int(a)
                if allPackets == 1:
                    month = int(a)
                if allPackets == 2:
                    day = int(a)
                if allPackets == 3:
                    hour = int(a)
                if allPackets == 4:
                    minuttes = int(a)
                if allPackets == 5:
                    seconds = int(a)
                if allPackets == 6:
                    week_day = int(a)
                if allPackets == 7:
                    up_6_7 = int(a)
                if allPackets == 8:
                    up = int(a)
                if allPackets == 9:
                    down = int(a)

            i = i + 1
        data_1 = data_1 + 1
        allPackets = allPackets + 1
    return year, month, day, hour, minuttes, seconds, week_day, up_6_7, up, down

#----------------------------------------------------------------------------
def check_heating():
    # funkcija preverja stanje omogočenosti ogrevanja na 190
    start = 0x96
    address = 0xbe
    datalen = 0x83
    data_0 = 0xba
    data_1 = 0xee
    data_2 = 0xba
    stop = 0xa9

    crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
    data = bytearray(
        [start, address, datalen, data_0, data_1, data_2, crc_, stop])
    ser.write(data)
    readBuffer = array.array('i')
    readCount = 0
    while readCount < maxReadCount:
        readBuffer.append(ord(ser.read(1)))
        readCount = readCount + 1
    i = 0
    while i < maxReadCount:
        val = (readBuffer[i])
        if i == 4:
            heating_situation = int(val)
        i = i + 1
    return heating_situation
#--------------------------------------------------------------------------
def set_time_zg(x):
    # funkcija omogoča nastavitev ure vklopa ogrevanja na 190 za zgoraj
    start = 0x96
    address = 0xbe
    datalen = 0x83
    data_0 = 0xba
    data_1 = x
    data_2 = 0xba
    stop = 0xa9

    crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
    data = bytearray(
        [start, address, datalen, data_0, data_1, data_2, crc_, stop])
    ser.write(data)
    readBuffer = array.array('i')
    readCount = 0
    while readCount < maxReadCount:
        readBuffer.append(ord(ser.read(1)))
        readCount = readCount + 1
    i = 0
    while i < maxReadCount:
        val = (readBuffer[i])
        if i == 4:
            heating_situation = int(val)
        i = i + 1
    return heating_situation
#------------------------------------------------------------------------
def set_time_sp(x):
    # funkcija omogoča nastavitev ure vklopa ogrevanja na 190 za spodaj
    start = 0x96
    address = 0xbe
    datalen = 0x83
    data_0 = 0xba
    data_1 = x
    data_2 = 0xba
    stop = 0xa9

    crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
    data = bytearray(
        [start, address, datalen, data_0, data_1, data_2, crc_, stop])
    ser.write(data)
    readBuffer = array.array('i')
    readCount = 0
    while readCount < maxReadCount:
        readBuffer.append(ord(ser.read(1)))
        readCount = readCount + 1
    i = 0
    while i < maxReadCount:
        val = (readBuffer[i])
        if i == 4:
            heating_situation = int(val)
        i = i + 1
    return heating_situation
#------------------------------------------------------------------------
def control_heating_5_6(x):
    # funkcija omogoča vklop in izklop ogrevanja na 190 od 5. do 6. ure zgoraj
    start = 0x96
    address = 0xbe
    datalen = 0x83
    data_0 = 0xba
    data_1 = x
    data_2 = 0xba
    stop = 0xa9

    crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
    data = bytearray(
        [start, address, datalen, data_0, data_1, data_2, crc_, stop])
    ser.write(data)
    readBuffer = array.array('i')
    readCount = 0
    while readCount < maxReadCount:
        readBuffer.append(ord(ser.read(1)))
        readCount = readCount + 1
    i = 0
    while i < maxReadCount:
        val = (readBuffer[i])
        if i == 4:
            heating_situation = int(val)
        i = i + 1
    return heating_situation
#-------------------------------------------------------------------------
def set_time(a, b, c, d, e, f, g, h, i, j):

    start = 0x96
    address = 0xbe
    datalen = 0x83
    data_0 = 0xbb
    data_1 = 0xbd
    data_2 = 0
    stop = 0xa9

    crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
    data = bytearray(
        [start, address, datalen, data_0, data_1, data_2, crc_, stop])
    ser.write(data)
    readBuffer = array.array('i')
    readCount = 0
    while readCount < maxReadCount:
        readBuffer.append(ord(ser.read(1)))
        readCount = readCount + 1

    completeTransfer = 10
    
    start = 0x96
    address = 0xbe
    datalen = 0x83
    data_0 = 0xbd
    data_1 = 0    # increment counter
    data_2 = 0    # data to slave
    stop = 0xa9

    allPackets = 0
    while allPackets < completeTransfer:
        if allPackets == 0:
            data_2 = a
        if allPackets == 1:
            data_2 = b
        if allPackets == 2:
            data_2 = c
        if allPackets == 3:
            data_2 = d
        if allPackets == 4:
            data_2 = e
        if allPackets == 5:
            data_2 = f
        if allPackets == 6:
            data_2 = g
        if allPackets == 7:
            data_2 = h
        if allPackets == 8:
            data_2 = i
        if allPackets == 9:
            data_2 = j

        crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
        data = bytearray(
            [start, address, datalen, data_0, data_1, data_2, crc_, stop])
        ser.write(data)
        readBuffer = array.array('i')
        readCount = 0
        while readCount < maxReadCount:
            readBuffer.append(ord(ser.read(1)))
            readCount = readCount + 1
            print (readCount)

        data_1 = data_1 + 1
        #print (data_1)
        allPackets = allPackets + 1
        #print ("---")
        #if allPackets == 10:
            #print ("exit")
#------------------------------------------------------------------------------
def control_heating(x):
    # funkcija omogoča vklop in izklop ogrevanja na 190 izven sezone
    start = 0x96
    address = 0xbe
    datalen = 0x83
    data_0 = 0xba
    data_1 = x
    data_2 = 0xba
    stop = 0xa9

    crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
    data = bytearray(
        [start, address, datalen, data_0, data_1, data_2, crc_, stop])
    ser.write(data)
    readBuffer = array.array('i')
    readCount = 0
    while readCount < maxReadCount:
        readBuffer.append(ord(ser.read(1)))
        readCount = readCount + 1
    i = 0
    while i < maxReadCount:
        val = (readBuffer[i])
        if i == 4:
            heating_situation = int(val)
        i = i + 1
    return heating_situation            
#------------------------------------------------------------------------------
#---------------------------------Slave 160 -----------------------------------
def slave_read_DS18B20():
    start = 0x96
    address = 0xa0
    datalen = 0x83
    data_0 = 0xba
    data_1 = 0xbc  # komanda
    data_2 = 0xba
    stop = 0xa9

    crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
    data = bytearray(
        [start, address, datalen, data_0, data_1, data_2, crc_, stop])
    ser.write(data)
    readBuffer = array.array('i')
    readCount = 0
    while readCount < maxReadCount:
        readBuffer.append(ord(ser.read(1)))
        readCount = readCount + 1
        
#------------------------------------------------------------------------------
def read_temp():
    #sleep(1.00)   # Master pocaka 1 sekundo pred prenosom temperatur
    start = 0x96
    address = 0xa0
    datalen = 0x83
    data_0 = 0xbb
    data_1 = 0xbc
    data_2 = 0
    stop = 0xa9

    crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
    data = bytearray(
        [start, address, datalen, data_0, data_1, data_2, crc_, stop])
    ser.write(data)
    readBuffer = array.array('i')
    readCount = 0
    while readCount < maxReadCount:
        readBuffer.append(ord(ser.read(1)))
        readCount = readCount + 1

    completeTransfer = 37
    allPackets = 0
    start = 0x96
    address = 0xa0
    datalen = 0x83
    data_0 = 0xbc
    data_1 = 0
    data_2 = 0
    stop = 0xa9

    while allPackets < completeTransfer:
        crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
        data = bytearray(
            [start, address, datalen, data_0, data_1, data_2, crc_, stop])
        ser.write(data)
        readBuffer = array.array('i')
        readCount = 0

        while readCount < maxReadCount:
            readBuffer.append(ord(ser.read(1)))
            readCount = readCount + 1
            

        ii = 0
        #print (ii)
        while ii < maxReadCount:
            val = (readBuffer[ii])
            if ii == 4:
                a = val
                if allPackets == 0:
                    ZG = int(a)
                if allPackets == 1:
                    ZG = ZG + (int(a) << 8)
                if allPackets == 2:
                    ZG = ZG + (int(a) << 16)
                if allPackets == 3:
                    ZG = ZG + (int(a) << 24)
                   

                if allPackets == 4:
                    SP = int(a)
                if allPackets == 5:
                    SP = SP + (int(a) << 8)
                if allPackets == 6:
                    SP = SP + (int(a) << 16)
                if allPackets == 7:
                    SP = SP + (int(a) << 24)
                   

                if allPackets == 8:
                    BO = int(a)
                if allPackets == 9:
                    BO = BO + (int(a) << 8)
                if allPackets == 10:
                    BO = BO + (int(a) << 16)
                if allPackets == 11:
                    BO = BO + (int(a) << 24)
                    

                if allPackets == 12:
                    SO = int(a)
                if allPackets == 13:
                    SO = SO + (int(a) << 8)
                if allPackets == 14:
                    SO = SO + (int(a) << 16)
                if allPackets == 15:
                    SO = SO + (int(a) << 24)
                    

                if allPackets == 16:
                    PE = int(a)
                if allPackets == 17:
                    PE = PE + (int(a) << 8)
                if allPackets == 18:
                    PE = PE + (int(a) << 16)
                if allPackets == 19:
                    PE = PE + (int(a) << 24)
                    

                if allPackets == 20:
                    ZU = int(a)
                if allPackets == 21:
                    ZU = ZU + (int(a) << 8)
                if allPackets == 22:
                    ZU = ZU + (int(a) << 16)
                if allPackets == 23:
                    ZU = ZU + (int(a) << 24)
                    

                if allPackets == 24:
                    SZ = int(a)
                if allPackets == 25:
                    SZ = SZ + (int(a) << 8)
                if allPackets == 26:
                    SZ = SZ + (int(a) << 16)
                if allPackets == 27:
                    SZ = SZ + (int(a) << 24)
                    

                if allPackets == 28:
                    SS = int(a)
                if allPackets == 29:
                    SS = SS + (int(a) << 8)
                if allPackets == 30:
                    SS = SS + (int(a) << 16)
                if allPackets == 31:
                    SS = SS + (int(a) << 24)
                    

                if allPackets == 32:
                    OUT = int(a)
                    
                    
                if allPackets == 33:
                    PEd = int(a)
                if allPackets == 34:
                    PEd = PEd + (int(a) << 8)
                if allPackets == 35:
                    PEd = PEd + (int(a) << 16)
                if allPackets == 36:
                    PEd = PEd + (int(a) << 24)
                    

            ii = ii + 1
            #print(ii)
        data_1 = data_1 + 1
        allPackets = allPackets + 1
    a = convert_MICROCHIP_32bit_to_float(ZG)
    b = convert_MICROCHIP_32bit_to_float(SP)
    c = convert_MICROCHIP_32bit_to_float(BO)
    d = convert_MICROCHIP_32bit_to_float(SO)
    e = convert_MICROCHIP_32bit_to_float(PE)
    f = convert_MICROCHIP_32bit_to_float(ZU)
    g = convert_MICROCHIP_32bit_to_float(SZ)
    h = convert_MICROCHIP_32bit_to_float(SS)
    i = OUT
    j = convert_MICROCHIP_32bit_to_float(PEd)

    return a, b, c, d, e, f, g, h, i, j

#-------------------------------------------------------------------------------
def convert_byte_to_bin_out(x):
    bits = format(x, '08b')
    i = 0
    val = list("        ")

    
    for char in bits:
        current_bit = int(char)
        if current_bit == 1:
            val[i] = 1
        else:
            val[i] = 2
        i = i + 1
  

    if val[2] == 1:
        pec = 1
    else:
        pec = 0

    if val[3] == 1:
        sonce = 1
    else:
        sonce = 0

    if val[4] == 1:
        bojler = 1
    else:
        bojler = 0

    if val[5] == 1:
        spodaj = 1
    else:
        spodaj = 0

    if val[6] == 1:
        zgoraj = 1
    else:
        zgoraj = 0

    if val[7] == 1:
        crpalka = 1
    else:
        crpalka = 0

    return crpalka, zgoraj, spodaj, bojler, sonce, pec
#-------------------------------------------------------------------------------
def convert_long_to_bytes(i):
    i = i % 4294967296
    n4 = i % 256
    i = i / 256
    n3 = i % 256
    i = i / 256
    n2 = i % 256
    n1 = i / 256
    return (n1, n2, n3, n4)

def convert_int_to_bytes(x):
    y = x.to_bytes(4,"big",signed=False)
    z = [int(i) for i in y]
    return z
#-------------------------------------------------------------------------------
def convert_float_to_MICROCHIP_32bit(x):
    x_IEEE = struct.pack(">f", x).hex()
    bits = bin(int(x_IEEE, 16))[2:].zfill(len(x_IEEE) * 4)
    i = 0
    val = "                                ".encode()
    b_s = list(val)
    for char in bits:
        current_bit = int(char)
        if current_bit == 1:
            if (i > 0) and (i < 9):
                b_s[i - 1] = "1"
            elif i == 0:
                b_s[8] = "1"
            else:
                b_s[i] = "1"
        else:
            if (i > 0) and (i < 9):
                b_s[i - 1] = "0"
            elif i == 0:
                b_s[8] = "0"
            else:
                b_s[i] = "0"
        i = i + 1
    bin_val = [int(i) for i in b_s]
    out = 0
    for bit in bin_val:
        out = (out << 1) | bit
    hex_val = hex(out)
    bytes_val = convert_int_to_bytes(out)
    return bytes_val
#-------------------------------------------------------------------------------
def set_temp(x, y):
    # Komanda za vpis setpointa
    start = 0x96
    address = 0xa0
    datalen = 0x83
    data_0 = 0xbb
    data_1 = 0xbd
    data_2 = 0
    stop = 0xa9

    crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
    data = bytearray(
        [start, address, datalen, data_0, data_1, data_2, crc_, stop])
    ser.write(data)
    readBuffer = array.array('i')
    readCount = 0
    while readCount < maxReadCount:
        readBuffer.append(ord(ser.read(1)))
        readCount = readCount + 1
    #print ("komanda za vpis setpointa")
    
    # Komanda za prenos podatkov iz masterja k slejvu
    #SZ = 25.4
    #SS = 20.8
    completeTransfer = 37  # prej 33
    allPackets = 0
    start = 0x96
    address = 0xa0
    datalen = 0x83
    data_0 = 0xbd
    data_1 = 0
    data_2 = 0
    stop = 0xa9
    j = 0

    while allPackets < completeTransfer:
        if j < 28:
            ax = convert_float_to_MICROCHIP_32bit(x)
        else:
            ax = convert_float_to_MICROCHIP_32bit(y)

        if (j == 24):
            data_2 = ax[3]  # LSB
        elif (j == 25):
            data_2 = ax[2]
        elif (j == 26):
            data_2 = ax[1]
        elif (j == 27):
            data_2 = ax[0]  # MSB
        elif (j == 28):
            data_2 = ax[3]  # LSB
        elif (j == 29):
            data_2 = ax[2]
        elif (j == 30):
            data_2 = ax[1]
        elif (j == 31):
            data_2 = ax[0]  # MSB
        else:
            data_2 = 0
        crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
        data = bytearray(
            [start, address, datalen, data_0, data_1, data_2, crc_, stop])
        ser.write(data)
        readBuffer = array.array('i')
        readCount = 0

        while readCount < maxReadCount:
            readBuffer.append(ord(ser.read(1)))
            readCount = readCount + 1

        i = 0
        while i < maxReadCount:
            val = (readBuffer[i])
            if i == 4:
                a = val
                if allPackets == 0:
                    ZG = int(a)
                if allPackets == 1:
                    ZG = ZG + (int(a) << 8)
                if allPackets == 2:
                    ZG = ZG + (int(a) << 16)
                if allPackets == 3:
                    ZG = ZG + (int(a) << 24)

            i = i + 1
        data_1 = data_1 + 1
        allPackets = allPackets + 1
        j = j + 1
#-------------------------------------------------------------------------------
#--------------------------Slave 200--------------------------------------------
def read_poraba():

    start = 0x96
    address = 0xc8
    datalen = 0x83
    data_0 = 0xbb
    data_1 = 0xbc
    data_2 = 0
    stop = 0xa9

    crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
    data = bytearray(
        [start, address, datalen, data_0, data_1, data_2, crc_, stop])
    ser.write(data)
    readBuffer = array.array('i')
    readCount = 0

    while readCount < maxReadCount:
        readBuffer.append(ord(ser.read(1)))
        readCount = readCount + 1

    #sleep(0.06)
    completeTransfer = 12
    allPackets = 0
    start = 0x96
    address = 0xc8
    datalen = 0x83
    data_0 = 0xbc
    data_1 = 0
    data_2 = 0
    stop = 0xa9

    while allPackets < completeTransfer:
        crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
        data = bytearray(
            [start, address, datalen, data_0, data_1, data_2, crc_, stop])
        ser.write(data)
        readBuffer = array.array('i')
        readCount = 0

        while readCount < maxReadCount:
            readBuffer.append(ord(ser.read(1)))
            readCount = readCount + 1

        i = 0
        while i < maxReadCount:
            val = (readBuffer[i])
            if i == 4:
                a = val
                if allPackets == 0:
                    kWh = int(a)
                if allPackets == 1:
                    kWh = kWh + (int(a) << 8)
                if allPackets == 2:
                    kWh = kWh + (int(a) << 16)
                if allPackets == 3:
                    kWh = kWh + (int(a) << 24)
                    print (kWh)

                if allPackets == 4:
                    m3v = int(a)
                if allPackets == 5:
                    m3v = m3v + (int(a) << 8)
                if allPackets == 6:
                    m3v = m3v + (int(a) << 16)
                if allPackets == 7:
                    m3v = m3v + (int(a) << 24)

                if allPackets == 8:
                    m3p = int(a)
                if allPackets == 9:
                    m3p = m3p + (int(a) << 8)
                if allPackets == 10:
                    m3p = m3p + (int(a) << 16)
                if allPackets == 11:
                    m3p = m3p + (int(a) << 24)

            i = i + 1
        data_1 = data_1 + 1
        allPackets = allPackets + 1

    a = convert_MICROCHIP_32bit_to_float(kWh)
    b = convert_MICROCHIP_32bit_to_float(m3v)
    c = convert_MICROCHIP_32bit_to_float(m3p)
    return a, b, c
#-------------------------------------------------------------------------------
#---------------------Slave 210-------------------------------------------------
#-------------komanda za IZKLOP mreze---------------------------------------
def start_UPS_test():
    start = 0x96
    address = 0xd2
    datalen = 0x83
    data_0 = 0xba
    data_1 = 0xbd     # komanda
    data_2 = 0xba
    stop = 0xa9

    crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
    data = bytearray(
        [start, address, datalen, data_0, data_1, data_2, crc_, stop])
    ser.write(data)
    readBuffer = array.array('i')
    readCount = 0
    while readCount < maxReadCount:
        readBuffer.append(ord(ser.read(1)))
        readCount = readCount + 1
    i = 0
    while i < maxReadCount:
        val = (readBuffer[i])
        if i == 4:
            power_situation = int(val)
        i = i + 1
    return power_situation
#------------komanda za VKLOP mreze---------------------------------- 
def stop_UPS_test():
    start = 0x96
    address = 0xd2
    datalen = 0x83
    data_0 = 0xba
    data_1 = 0xdb     # komanda
    data_2 = 0xba
    stop = 0xa9

    crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
    data = bytearray(
        [start, address, datalen, data_0, data_1, data_2, crc_, stop])
    ser.write(data)
    readBuffer = array.array('i')
    readCount = 0
    while readCount < maxReadCount:
        readBuffer.append(ord(ser.read(1)))
        readCount = readCount + 1
    i = 0
    while i < maxReadCount:
        val = (readBuffer[i])
        if i == 4:
            power_situation = int(val)
        i = i + 1
    return power_situation
#------------------------------------------------------------------------
def UPS_test_10s():  # Test UPS for 10s
    start = 0x96
    address = 0xd2
    datalen = 0x83
    data_0 = 0xba
    data_1 = 0xab     # komanda
    data_2 = 0xba
    stop = 0xa9

    crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
    data = bytearray(
        [start, address, datalen, data_0, data_1, data_2, crc_, stop])
    ser.write(data)
    readBuffer = array.array('i')
    readCount = 0
    while readCount < maxReadCount:
        readBuffer.append(ord(ser.read(1)))
        readCount = readCount + 1
    
#------------------------------------------------------------------------
def slave_210_read_UPS():  # RS232 read (SoftUART)
    start = 0x96
    address = 0xd2
    datalen = 0x83
    data_0 = 0xba
    data_1 = 0xba     # komanda
    data_2 = 0xba
    stop = 0xa9

    crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
    data = bytearray(
        [start, address, datalen, data_0, data_1, data_2, crc_, stop])
    ser.write(data)
    readBuffer = array.array('i')
    readCount = 0
    while readCount < maxReadCount:
        readBuffer.append(ord(ser.read(1)))
        readCount = readCount + 1
#--------------------------------------------------------------------------    
def read_210():
    start=0x96
    address=0xd2
    datalen=0x83
    stop=0xa9
    data_0=0xbb
    data_1=0xbc
    data_2=0

    crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
    data = bytearray([start, address, datalen, data_0, data_1, data_2, crc_, stop])    
    ser.write(data)
    readBuffer = array.array('i')
    readCount=0
    while readCount < maxReadCount:
        readBuffer.append(ord(ser.read(1)))
        readCount=readCount+1            

    completeTransfer=34
    allPackets=0
    start=0x96
    address=0xd2
    datalen=0x83
    stop=0xa9
    data_0=0xbc
    data_1=0
    data_2=0
    while allPackets < completeTransfer:
        crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
        data = bytearray([start, address, datalen, data_0, data_1, data_2, crc_, stop])
        ser.write(data)
        readBuffer = array.array('i')
        readCount=0
        while readCount < maxReadCount:
            readBuffer.append(ord(ser.read(1)))
            readCount=readCount+1
   
        i=0
        while i < maxReadCount:
            val=(readBuffer[i])
            if i == 4:    
                a=val
                if allPackets == 0:
                    Uin = int(a)
                if allPackets == 1:
                    Uin = Uin + (int(a) << 8)
                if allPackets == 2:
                    Uin = Uin + (int(a) << 16)
                if allPackets == 3:
                    Uin = Uin + (int(a) << 24)

                if allPackets == 4:
                    Uf = int(a)
                if allPackets == 5:
                    Uf = Uf + (int(a) << 8)
                if allPackets == 6:
                    Uf = Uf + (int(a) << 16)
                if allPackets == 7:
                    Uf = Uf + (int(a) << 24)

                if allPackets == 8:
                    Uout = int(a)
                if allPackets == 9:
                    Uout = Uout + (int(a) << 8)
                if allPackets == 10:
                    Uout = Uout + (int(a) << 16)
                if allPackets == 11:
                    Uout = Uout + (int(a) << 24)    
                    
                if allPackets == 12:
                    Imax = int(a)
                if allPackets == 13:
                    Imax = Imax + (int(a) << 8)
                    
                if allPackets == 14:
                    Freq = int(a)
                if allPackets == 15:
                    Freq = Freq + (int(a) << 8)
                if allPackets == 16:
                    Freq = Freq + (int(a) << 16)
                if allPackets == 17:
                    Freq = Freq + (int(a) << 24)
                    
                if allPackets == 18:
                    Ubat = int(a)
                if allPackets == 19:
                    Ubat = Ubat + (int(a) << 8)
                if allPackets == 20:
                    Ubat = Ubat + (int(a) << 16)
                if allPackets == 21:
                    Ubat = Ubat + (int(a) << 24)
                    
                if allPackets == 22:
                    Temp = int(a)
                if allPackets == 23:
                    Temp = Temp + (int(a) << 8)
                if allPackets == 24:
                    Temp = Temp + (int(a) << 16)
                if allPackets == 25:
                    Temp = Temp + (int(a) << 24)
                    
                if allPackets == 26:
                    Status_7 = int(a)  

                if allPackets == 27:
                    Status_6 = int(a)

                if allPackets == 28:
                    Status_5 = int(a)

                if allPackets == 29:
                    Status_4 = int(a)

                if allPackets == 30:
                    Status_3 = int(a)

                if allPackets == 31:
                    Status_2 = int(a)

                if allPackets == 32:
                    Status_1 = int(a)

                if allPackets == 33:
                    Status_0 = int(a)    
   
                    
            i=i+1
        data_1=data_1+1
        allPackets=allPackets+1
    a = convert_MICROCHIP_32bit_to_float(Uin)
    b = convert_MICROCHIP_32bit_to_float(Uf)
    c = convert_MICROCHIP_32bit_to_float(Uout)
    d = Imax
    e = convert_MICROCHIP_32bit_to_float(Freq)
    f = convert_MICROCHIP_32bit_to_float(Ubat)
    g = convert_MICROCHIP_32bit_to_float(Temp)
    h = Status_7
    i = Status_6
    j = Status_5
    k = Status_4
    l = Status_3
    m = Status_2
    n = Status_1
    o = Status_0
    
    return a, b, c, d, e, f, g, h, i, j, k, l, m, n, o

#-------------------------------------------------------------------------------        
#----------------------slave 220 -----------------------------------------------
def convert_byte_to_bin_out_2(x):

    bits = format(x, '08b')
    i = 0
    val = list("        ")
    for char in bits:
        current_bit = int(char)
        if current_bit == 1:
            val[i] = 1
        else:
            val[i] = 2
        i = i + 1

    if val[5] == 1:
        kompresor = 1
    else:
        kompresor = 0

    if val[6] == 1:
        vlazilec = 1
    else:
        vlazilec = 0

    if val[7] == 1:
        ventilator = 1
    else:
        ventilator = 0

    return ventilator, vlazilec, kompresor
#-------------------------------------------------------------------------------
def slave_read_SHT11():
    start = 0x96
    address = 0xdc
    datalen = 0x83
    data_0 = 0xba
    data_1 = 0xbc
    data_2 = 0xba
    stop = 0xa9

    crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
    data = bytearray(
        [start, address, datalen, data_0, data_1, data_2, crc_, stop])
    ser.write(data)
    readBuffer = array.array('i')
    readCount = 0

    while readCount < maxReadCount:
        readBuffer.append(ord(ser.read(1)))
        readCount = readCount + 1    
#-------------------------------------------------------------------------------
def read_hladilnica():
    #sleep(0.32)
    start = 0x96
    address = 0xdc
    datalen = 0x83
    data_0 = 0xbb
    data_1 = 0xbc
    data_2 = 0
    stop = 0xa9

    crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
    data = bytearray(
        [start, address, datalen, data_0, data_1, data_2, crc_, stop])
    ser.write(data)
    readBuffer = array.array('i')
    readCount = 0

    while readCount < maxReadCount:
        readBuffer.append(ord(ser.read(1)))
        readCount = readCount + 1
        #print readBuffer

    completeTransfer = 11
    allPackets = 0
    start = 0x96
    address = 0xdc
    datalen = 0x83
    data_0 = 0xbc
    data_1 = 0
    data_2 = 0
    stop = 0xa9

    while allPackets < completeTransfer:
        crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
        data = bytearray(
            [start, address, datalen, data_0, data_1, data_2, crc_, stop])
        ser.write(data)
        readBuffer = array.array('i')
        readCount = 0

        while readCount < maxReadCount:
            readBuffer.append(ord(ser.read(1)))
            readCount = readCount + 1
            #print readBuffer

        i = 0
        while i < maxReadCount:
            val = (readBuffer[i])
            if i == 4:
                a = val
                if allPackets == 0:
                    HT = int(a)
                if allPackets == 1:
                    HT = HT + (int(a) << 8)
                if allPackets == 2:
                    HT = HT + (int(a) << 16)
                if allPackets == 3:
                    HT = HT + (int(a) << 24)

                if allPackets == 4:
                    HV = int(a)
                if allPackets == 5:
                    HV = HV + (int(a) << 8)
                if allPackets == 6:
                    HV = HV + (int(a) << 16)
                if allPackets == 7:
                    HV = HV + (int(a) << 24)

                if allPackets == 8:
                    ST = int(a)
                if allPackets == 9:
                    SV = int(a)
                if allPackets == 10:
                    OUT = int(a)
            i = i + 1
        data_1 = data_1 + 1
        allPackets = allPackets + 1
    a = convert_MICROCHIP_32bit_to_float(HT)
    b = convert_MICROCHIP_32bit_to_float(HV)
    return a, b, ST, SV, OUT
#-------------------------------------------------------------------------------
def set_hladilnica(ht, hv, ht_set, hv_set, h_out):
    # Komanda za vpis setpointa
    start = 0x96
    address = 0xdc
    datalen = 0x83
    data_0 = 0xbb
    data_1 = 0xbd
    data_2 = 0
    stop = 0xa9

    crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
    data = bytearray(
        [start, address, datalen, data_0, data_1, data_2, crc_, stop])
    ser.write(data)
    readBuffer = array.array('i')
    readCount = 0
    while readCount < maxReadCount:
        readBuffer.append(ord(ser.read(1)))
        readCount = readCount + 1

    # Komanda za prenos podatkov iz masterja k slejvu
    completeTransfer = 11
    allPackets = 0
    start = 0x96
    address = 0xdc
    datalen = 0x83
    data_0 = 0xbd
    data_1 = 0
    data_2 = 0
    stop = 0xa9
    j = 0
# spodnja koda od set_temp (160)   PAKET: TH(float), VH(float), setTH(byte), setVH(byte), OUT(byte)
    axt = convert_float_to_MICROCHIP_32bit(ht)
    axv = convert_float_to_MICROCHIP_32bit(hv)
    axst = ht_set
    axsv = hv_set
    axout = h_out
    while allPackets < completeTransfer:
        if (j == 0):
            data_2 = axt[3]  # LSB
        elif (j == 1):
            data_2 = axt[2]
        elif (j == 2):
            data_2 = axt[1]
        elif (j == 3):
            data_2 = axt[0]  # MSB
        elif (j == 4):
            data_2 = axv[3]  # LSB
        elif (j == 5):
            data_2 = axv[2]
        elif (j == 6):
            data_2 = axv[1]
        elif (j == 7):
            data_2 = axv[0]  # MSB
        elif (j == 8):
            data_2 = axst
        elif (j == 9):
            data_2 = axsv
        elif (j == 10):
            data_2 = axout
        else:
            data_2 = 0

        crc_ = crc_calc(start, address, datalen, data_0, data_1, data_2, stop)
        data = bytearray(
            [start, address, datalen, data_0, data_1, data_2, crc_, stop])
        ser.write(data)
        readBuffer = array.array('i')
        readCount = 0

        while readCount < maxReadCount:
            readBuffer.append(ord(ser.read(1)))
            readCount = readCount + 1

        i = 0
        while i < maxReadCount:
            val = (readBuffer[i])

            i = i + 1
        data_1 = data_1 + 1
        allPackets = allPackets + 1
        j = j + 1
#-------------------------------------------------------------------------------
#--------------------slave 230--------------------------------------------------
        

California
Posts: 181
Joined: Sat Jun 06, 2015 2:33 pm

Re: Threading problems

Sat Dec 07, 2019 2:40 pm

GUI modul. Becouse of the maximum characters number limit, some lines of the code are deleted, but all methods used in main program are there.

gui_47.py:

Code: Select all

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'Master_47.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!

from slaves import *
import time
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import pyqtSlot

temp_160 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]               # zg, sp, bo, so, pe_plin, zu, szg, ssp, out, pe_drva
global flag_160
flag_160 = 1
time_190 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]               # year, month, day, hour, minuttes, seconds, week_day, up_6_7, up, down
global flag_190
flag_190 = 1
time_flag = 0                                           # izvede samo enkrat na dan
zg_time = 0                                             # faktor za izracun obratovanja zgoraj
sp_time = 0                                             # faktor za izracun obratovanja spodaj
bo_time = 0                                             # faktor za izracun obratovanja bojler
poraba = [0, 0, 0]                                      # kWh, m3, m3   samo za slave 200
poraba_ = [0, 0, 0, 0, 0, 0, 0]                         # dan, ura, Tzu, kWh, L, m3, zg, sp, bo
ups_210 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # Uin, Ufault, Uout, Imax, Freq, Ubat, Temp, Status_7 - Status_0
hladilnica = [0, 0, 0, 0, 0]                            # HT, HV, ST, SV, OUT
vlaga = [0, 0]                                          # tmp, hum
tlak = [0, 0, 0]                                        # tmp, tlak, višina
poraba_buf_xls = [0, 0, 0, 0, 0, 0, 0]                  # zacasna spremenljivka za povprecje
ob_zagonu = 1                                           # branje xls fajla ob zagonu za grafe povprecja
ob_zagonu_ = 1                                          # branje xls fajla ob zagonu za grafe porabe



try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Izbira(object):
    def setupUi(self, Izbira):
        Izbira.setObjectName(_fromUtf8("Izbira"))
        Izbira.resize(892, 619)

        Izbira.setStyleSheet(_fromUtf8("background-color: rgb(200, 200, 200);"))
        self.col = QtGui.QColor(0, 0, 0)
        
        self.Datum_ura = QtGui.QWidget()
        self.Datum_ura.setObjectName(_fromUtf8("Datum_ura"))
        self.URA = QtGui.QLineEdit(self.Datum_ura)
        self.URA.setGeometry(QtCore.QRect(320, 180, 281, 71))
        font = QtGui.QFont()
        font.setPointSize(47)
        font.setBold(False)
        font.setItalic(True)
        font.setWeight(50)
        self.URA.setFont(font)
        self.URA.setObjectName(_fromUtf8("URA"))
        self.lineEdit_Year = QtGui.QLineEdit(self.Datum_ura)
        self.lineEdit_Year.setGeometry(QtCore.QRect(80, 340, 41, 33))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit_Year.setFont(font)
        self.lineEdit_Year.setObjectName(_fromUtf8("lineEdit_Year"))
        self.lineEdit_Month = QtGui.QLineEdit(self.Datum_ura)
        self.lineEdit_Month.setGeometry(QtCore.QRect(130, 340, 41, 33))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit_Month.setFont(font)
        self.lineEdit_Month.setObjectName(_fromUtf8("lineEdit_Month"))
        self.lineEdit_Day = QtGui.QLineEdit(self.Datum_ura)
        self.lineEdit_Day.setGeometry(QtCore.QRect(180, 340, 41, 33))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit_Day.setFont(font)
        self.lineEdit_Day.setObjectName(_fromUtf8("lineEdit_Day"))
        self.lineEdit_Hour = QtGui.QLineEdit(self.Datum_ura)
        self.lineEdit_Hour.setGeometry(QtCore.QRect(300, 340, 41, 33))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit_Hour.setFont(font)
        self.lineEdit_Hour.setObjectName(_fromUtf8("lineEdit_Hour"))
        self.lineEdit_Minutte = QtGui.QLineEdit(self.Datum_ura)
        self.lineEdit_Minutte.setGeometry(QtCore.QRect(350, 340, 41, 33))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit_Minutte.setFont(font)
        self.lineEdit_Minutte.setObjectName(_fromUtf8("lineEdit_Minutte"))
        self.lineEdit_Seconds = QtGui.QLineEdit(self.Datum_ura)
        self.lineEdit_Seconds.setGeometry(QtCore.QRect(400, 340, 41, 33))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit_Seconds.setFont(font)
        self.lineEdit_Seconds.setObjectName(_fromUtf8("lineEdit_Seconds"))
        self.lineEdit_WeekDay = QtGui.QLineEdit(self.Datum_ura)
        self.lineEdit_WeekDay.setGeometry(QtCore.QRect(570, 340, 111, 33))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit_WeekDay.setFont(font)
        self.lineEdit_WeekDay.setObjectName(_fromUtf8("lineEdit_WeekDay"))
        self.lineEdit_Up_day = QtGui.QLineEdit(self.Datum_ura)
        self.lineEdit_Up_day.setGeometry(QtCore.QRect(80, 420, 41, 33))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit_Up_day.setFont(font)
        self.lineEdit_Up_day.setObjectName(_fromUtf8("lineEdit_Up_day"))
        self.lineEdit_Down_day = QtGui.QLineEdit(self.Datum_ura)
        self.lineEdit_Down_day.setGeometry(QtCore.QRect(80, 470, 41, 33))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit_Down_day.setFont(font)
        self.lineEdit_Down_day.setObjectName(_fromUtf8("lineEdit_Down_day"))
        self.year = QtGui.QLabel(self.Datum_ura)
        self.year.setGeometry(QtCore.QRect(80, 310, 41, 21))
        self.year.setObjectName(_fromUtf8("year"))
        self.month = QtGui.QLabel(self.Datum_ura)
        self.month.setGeometry(QtCore.QRect(130, 310, 51, 21))
        self.month.setObjectName(_fromUtf8("month"))
        self.day = QtGui.QLabel(self.Datum_ura)
        self.day.setGeometry(QtCore.QRect(190, 310, 31, 21))
        self.day.setObjectName(_fromUtf8("day"))
        self.hour = QtGui.QLabel(self.Datum_ura)
        self.hour.setGeometry(QtCore.QRect(300, 310, 41, 21))
        self.hour.setObjectName(_fromUtf8("hour"))
        self.label = QtGui.QLabel(self.Datum_ura)
        self.label.setGeometry(QtCore.QRect(340, 310, 51, 21))
        self.label.setObjectName(_fromUtf8("label"))
        self.seconds = QtGui.QLabel(self.Datum_ura)
        self.seconds.setGeometry(QtCore.QRect(400, 310, 61, 21))
        self.seconds.setObjectName(_fromUtf8("seconds"))
        self.week_day = QtGui.QLabel(self.Datum_ura)
        self.week_day.setGeometry(QtCore.QRect(520, 310, 161, 21))
        self.week_day.setObjectName(_fromUtf8("week_day"))
        self.up_5_6 = QtGui.QLabel(self.Datum_ura)
        self.up_5_6.setGeometry(QtCore.QRect(740, 190, 81, 21))
        self.up_5_6.setObjectName(_fromUtf8("up_5_6"))
        self.pushButton_SetTime = QtGui.QPushButton(self.Datum_ura)
        self.pushButton_SetTime.setGeometry(QtCore.QRect(710, 420, 111, 81))
        self.pushButton_SetTime.setObjectName(_fromUtf8("pushButton_SetTime"))
        self.checkBox_Up_5_6 = QtGui.QCheckBox(self.Datum_ura)
        self.checkBox_Up_5_6.setGeometry(QtCore.QRect(710, 230, 111, 26))
        self.checkBox_Up_5_6.setObjectName(_fromUtf8("checkBox_Up_5_6"))
        self.checkBox_Read_190 = QtGui.QCheckBox(self.Datum_ura)
        self.checkBox_Read_190.setGeometry(QtCore.QRect(710, 340, 100, 26))
        self.checkBox_Read_190.setChecked(True)
        self.checkBox_Read_190.setTristate(False)
        self.checkBox_Read_190.setObjectName(_fromUtf8("checkBox_Read_190"))
        self.Zg_2 = QtGui.QLabel(self.Datum_ura)
        self.Zg_2.setGeometry(QtCore.QRect(110, 190, 71, 21))
        self.Zg_2.setObjectName(_fromUtf8("Zg_2"))
        self.Ogrevanje_sezona_aktivno = QtGui.QFrame(self.Datum_ura)
        self.Ogrevanje_sezona_aktivno.setGeometry(QtCore.QRect(80, 190, 21, 21))
        self.Ogrevanje_sezona_aktivno.setFrameShape(QtGui.QFrame.StyledPanel)
        self.Ogrevanje_sezona_aktivno.setFrameShadow(QtGui.QFrame.Raised)
        self.Ogrevanje_sezona_aktivno.setObjectName(_fromUtf8("Ogrevanje_sezona_aktivno"))
        self.Ogrevanje_izven_sezone = QtGui.QCheckBox(self.Datum_ura)
        self.Ogrevanje_izven_sezone.setGeometry(QtCore.QRect(80, 230, 141, 26))
        self.Ogrevanje_izven_sezone.setChecked(False)
        self.Ogrevanje_izven_sezone.setObjectName(_fromUtf8("Ogrevanje_izven_sezone"))
        self.pushButton_Nastavi_zac_ogr_Zgoraj = QtGui.QPushButton(self.Datum_ura)
        self.pushButton_Nastavi_zac_ogr_Zgoraj.setGeometry(QtCore.QRect(130, 420, 251, 31))
        self.pushButton_Nastavi_zac_ogr_Zgoraj.setObjectName(_fromUtf8("pushButton_Nastavi_zac_ogr_Zgoraj"))
        self.pushButton_Nastavi_zac_ogr_Spodaj = QtGui.QPushButton(self.Datum_ura)
        self.pushButton_Nastavi_zac_ogr_Spodaj.setGeometry(QtCore.QRect(130, 470, 251, 31))
        self.pushButton_Nastavi_zac_ogr_Spodaj.setObjectName(_fromUtf8("pushButton_Nastavi_zac_ogr_Spodaj"))
        self.Ogrevanje_zgoraj_5_6 = QtGui.QFrame(self.Datum_ura)
        self.Ogrevanje_zgoraj_5_6.setGeometry(QtCore.QRect(710, 190, 21, 21))
        self.Ogrevanje_zgoraj_5_6.setFrameShape(QtGui.QFrame.StyledPanel)
        self.Ogrevanje_zgoraj_5_6.setFrameShadow(QtGui.QFrame.Raised)
        self.Ogrevanje_zgoraj_5_6.setObjectName(_fromUtf8("Ogrevanje_zgoraj_5_6"))
        self.up_5_7 = QtGui.QLabel(self.Datum_ura)
        self.up_5_7.setGeometry(QtCore.QRect(630, 10, 191, 21))
        self.up_5_7.setObjectName(_fromUtf8("up_5_7"))
        self.lineEdit_WeekDay_SET = QtGui.QLineEdit(self.Datum_ura)
        self.lineEdit_WeekDay_SET.setGeometry(QtCore.QRect(520, 340, 41, 33))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit_WeekDay_SET.setFont(font)
        self.lineEdit_WeekDay_SET.setObjectName(_fromUtf8("lineEdit_WeekDay_SET"))
        self.checkBox_komunikacija = QtGui.QCheckBox(self.Datum_ura)
        self.checkBox_komunikacija.setGeometry(QtCore.QRect(80, 110, 181, 26))
        self.checkBox_komunikacija.setChecked(True)
        self.checkBox_komunikacija.setTristate(False)
        self.checkBox_komunikacija.setObjectName(_fromUtf8("checkBox_komunikacija"))
        self.RS485_komunikacija_aktivno = QtGui.QFrame(self.Datum_ura)
        self.RS485_komunikacija_aktivno.setGeometry(QtCore.QRect(280, 111, 541, 20))
        self.RS485_komunikacija_aktivno.setFrameShape(QtGui.QFrame.StyledPanel)
        self.RS485_komunikacija_aktivno.setFrameShadow(QtGui.QFrame.Raised)
        self.RS485_komunikacija_aktivno.setObjectName(_fromUtf8("RS485_komunikacija_aktivno"))
        Izbira.addTab(self.Datum_ura, _fromUtf8(""))
        self.UPS = QtGui.QWidget()
        self.UPS.setObjectName(_fromUtf8("UPS"))
        self.Uin_label = QtGui.QLabel(self.UPS)
        self.Uin_label.setGeometry(QtCore.QRect(90, 110, 31, 21))
        self.Uin_label.setObjectName(_fromUtf8("Uin_label"))
        self.Ufault_label = QtGui.QLabel(self.UPS)
        self.Ufault_label.setGeometry(QtCore.QRect(90, 160, 51, 21))
        self.Ufault_label.setObjectName(_fromUtf8("Ufault_label"))
        self.Uout_label = QtGui.QLabel(self.UPS)
        self.Uout_label.setGeometry(QtCore.QRect(90, 210, 41, 21))
        self.Uout_label.setObjectName(_fromUtf8("Uout_label"))
        self.Imax_label = QtGui.QLabel(self.UPS)
        self.Imax_label.setGeometry(QtCore.QRect(90, 260, 41, 21))
        self.Imax_label.setObjectName(_fromUtf8("Imax_label"))
        self.Freq_label = QtGui.QLabel(self.UPS)
        self.Freq_label.setGeometry(QtCore.QRect(90, 310, 41, 21))
        self.Freq_label.setObjectName(_fromUtf8("Freq_label"))
        self.Batt_label = QtGui.QLabel(self.UPS)
        self.Batt_label.setGeometry(QtCore.QRect(90, 360, 41, 21))
        self.Batt_label.setObjectName(_fromUtf8("Batt_label"))
        self.Temperature_label = QtGui.QLabel(self.UPS)
        self.Temperature_label.setGeometry(QtCore.QRect(90, 410, 41, 21))
        self.Temperature_label.setObjectName(_fromUtf8("Temperature_label"))
        self.UPS_power_fail = QtGui.QFrame(self.UPS)
        self.UPS_power_fail.setGeometry(QtCore.QRect(770, 60, 21, 21))
        self.UPS_power_fail.setFrameShape(QtGui.QFrame.StyledPanel)
        self.UPS_power_fail.setFrameShadow(QtGui.QFrame.Raised)
        self.UPS_power_fail.setObjectName(_fromUtf8("UPS_power_fail"))
        self.UPS_battery_low = QtGui.QFrame(self.UPS)
        self.UPS_battery_low.setGeometry(QtCore.QRect(770, 110, 21, 21))
        self.UPS_battery_low.setFrameShape(QtGui.QFrame.StyledPanel)
        self.UPS_battery_low.setFrameShadow(QtGui.QFrame.Raised)
        self.UPS_battery_low.setObjectName(_fromUtf8("UPS_battery_low"))
        self.UPS_bypass_boost = QtGui.QFrame(self.UPS)
        self.UPS_bypass_boost.setGeometry(QtCore.QRect(770, 160, 21, 21))
        self.UPS_bypass_boost.setFrameShape(QtGui.QFrame.StyledPanel)
        self.UPS_bypass_boost.setFrameShadow(QtGui.QFrame.Raised)
        self.UPS_bypass_boost.setObjectName(_fromUtf8("UPS_bypass_boost"))
        self.UPS_failed = QtGui.QFrame(self.UPS)
        self.UPS_failed.setGeometry(QtCore.QRect(770, 210, 21, 21))
        self.UPS_failed.setFrameShape(QtGui.QFrame.StyledPanel)
        self.UPS_failed.setFrameShadow(QtGui.QFrame.Raised)
        self.UPS_failed.setObjectName(_fromUtf8("UPS_failed"))
        self.UPS_type = QtGui.QFrame(self.UPS)
        self.UPS_type.setGeometry(QtCore.QRect(770, 260, 21, 21))
        self.UPS_type.setFrameShape(QtGui.QFrame.StyledPanel)
        self.UPS_type.setFrameShadow(QtGui.QFrame.Raised)
        self.UPS_type.setObjectName(_fromUtf8("UPS_type"))
        self.UPS_test = QtGui.QFrame(self.UPS)
        self.UPS_test.setGeometry(QtCore.QRect(770, 310, 21, 21))
        self.UPS_test.setFrameShape(QtGui.QFrame.StyledPanel)
        self.UPS_test.setFrameShadow(QtGui.QFrame.Raised)
        self.UPS_test.setObjectName(_fromUtf8("UPS_test"))
        self.UPS_shutdown = QtGui.QFrame(self.UPS)
        self.UPS_shutdown.setGeometry(QtCore.QRect(770, 360, 21, 21))
        self.UPS_shutdown.setFrameShape(QtGui.QFrame.StyledPanel)
        self.UPS_shutdown.setFrameShadow(QtGui.QFrame.Raised)
        self.UPS_shutdown.setObjectName(_fromUtf8("UPS_shutdown"))
        self.UPS_beeper = QtGui.QFrame(self.UPS)
        self.UPS_beeper.setGeometry(QtCore.QRect(770, 410, 21, 21))
        self.UPS_beeper.setFrameShape(QtGui.QFrame.StyledPanel)
        self.UPS_beeper.setFrameShadow(QtGui.QFrame.Raised)
        self.UPS_beeper.setObjectName(_fromUtf8("UPS_beeper"))
        self.UPS_power_fail_label = QtGui.QLabel(self.UPS)
        self.UPS_power_fail_label.setGeometry(QtCore.QRect(650, 60, 91, 21))
        self.UPS_power_fail_label.setObjectName(_fromUtf8("UPS_power_fail_label"))
        self.UPS_battery_low_label = QtGui.QLabel(self.UPS)
        self.UPS_battery_low_label.setGeometry(QtCore.QRect(650, 110, 91, 21))
        self.UPS_battery_low_label.setObjectName(_fromUtf8("UPS_battery_low_label"))
        self.UPS_bypass_boost_label = QtGui.QLabel(self.UPS)
        self.UPS_bypass_boost_label.setGeometry(QtCore.QRect(650, 160, 101, 21))
        self.UPS_bypass_boost_label.setObjectName(_fromUtf8("UPS_bypass_boost_label"))
        self.UPS_failed_label = QtGui.QLabel(self.UPS)
        self.UPS_failed_label.setGeometry(QtCore.QRect(650, 210, 101, 21))
        self.UPS_failed_label.setObjectName(_fromUtf8("UPS_failed_label"))
        self.UPS_type_label = QtGui.QLabel(self.UPS)
        self.UPS_type_label.setGeometry(QtCore.QRect(650, 260, 111, 21))
        self.UPS_type_label.setObjectName(_fromUtf8("UPS_type_label"))
        self.UPS_test_label = QtGui.QLabel(self.UPS)
        self.UPS_test_label.setGeometry(QtCore.QRect(650, 310, 61, 21))
        self.UPS_test_label.setObjectName(_fromUtf8("UPS_test_label"))
        self.UPS_shutdown_label = QtGui.QLabel(self.UPS)
        self.UPS_shutdown_label.setGeometry(QtCore.QRect(650, 360, 81, 21))
        self.UPS_shutdown_label.setObjectName(_fromUtf8("UPS_shutdown_label"))
        self.UPS_beeper_label = QtGui.QLabel(self.UPS)
        self.UPS_beeper_label.setGeometry(QtCore.QRect(650, 410, 81, 21))
        self.UPS_beeper_label.setObjectName(_fromUtf8("UPS_beeper_label"))
        self.lineEdit_UPS_Uin = QtGui.QLineEdit(self.UPS)
        self.lineEdit_UPS_Uin.setGeometry(QtCore.QRect(150, 100, 71, 33))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit_UPS_Uin.setFont(font)
        self.lineEdit_UPS_Uin.setObjectName(_fromUtf8("lineEdit_UPS_Uin"))
        self.lineEdit_UPS_Ufault = QtGui.QLineEdit(self.UPS)
        self.lineEdit_UPS_Ufault.setGeometry(QtCore.QRect(150, 150, 71, 33))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit_UPS_Ufault.setFont(font)
        self.lineEdit_UPS_Ufault.setObjectName(_fromUtf8("lineEdit_UPS_Ufault"))
        self.lineEdit_UPS_Uout = QtGui.QLineEdit(self.UPS)
        self.lineEdit_UPS_Uout.setGeometry(QtCore.QRect(150, 200, 71, 33))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit_UPS_Uout.setFont(font)
        self.lineEdit_UPS_Uout.setObjectName(_fromUtf8("lineEdit_UPS_Uout"))
        self.lineEdit_UPS_Imax = QtGui.QLineEdit(self.UPS)
        self.lineEdit_UPS_Imax.setGeometry(QtCore.QRect(150, 250, 71, 33))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit_UPS_Imax.setFont(font)
        self.lineEdit_UPS_Imax.setObjectName(_fromUtf8("lineEdit_UPS_Imax"))
        self.lineEdit_UPS_Freq = QtGui.QLineEdit(self.UPS)
        self.lineEdit_UPS_Freq.setGeometry(QtCore.QRect(150, 300, 71, 33))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit_UPS_Freq.setFont(font)
        self.lineEdit_UPS_Freq.setObjectName(_fromUtf8("lineEdit_UPS_Freq"))
        self.lineEdit_UPS_Batt = QtGui.QLineEdit(self.UPS)
        self.lineEdit_UPS_Batt.setGeometry(QtCore.QRect(150, 350, 71, 33))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit_UPS_Batt.setFont(font)
        self.lineEdit_UPS_Batt.setObjectName(_fromUtf8("lineEdit_UPS_Batt"))
        self.lineEdit_UPS_Temp = QtGui.QLineEdit(self.UPS)
        self.lineEdit_UPS_Temp.setGeometry(QtCore.QRect(150, 400, 71, 33))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit_UPS_Temp.setFont(font)
        self.lineEdit_UPS_Temp.setObjectName(_fromUtf8("lineEdit_UPS_Temp"))
        self.enota_zg_22 = QtGui.QLabel(self.UPS)
        self.enota_zg_22.setGeometry(QtCore.QRect(230, 400, 17, 37))
        self.enota_zg_22.setObjectName(_fromUtf8("enota_zg_22"))
        self.enota_zg_23 = QtGui.QLabel(self.UPS)
        self.enota_zg_23.setGeometry(QtCore.QRect(230, 350, 17, 37))
        self.enota_zg_23.setObjectName(_fromUtf8("enota_zg_23"))
        self.enota_zg_24 = QtGui.QLabel(self.UPS)
        self.enota_zg_24.setGeometry(QtCore.QRect(230, 300, 31, 37))
        self.enota_zg_24.setObjectName(_fromUtf8("enota_zg_24"))
        self.enota_zg_25 = QtGui.QLabel(self.UPS)
        self.enota_zg_25.setGeometry(QtCore.QRect(230, 250, 17, 37))
        self.enota_zg_25.setObjectName(_fromUtf8("enota_zg_25"))
        self.enota_zg_26 = QtGui.QLabel(self.UPS)
        self.enota_zg_26.setGeometry(QtCore.QRect(230, 200, 17, 37))
        self.enota_zg_26.setObjectName(_fromUtf8("enota_zg_26"))
        self.enota_zg_27 = QtGui.QLabel(self.UPS)
        self.enota_zg_27.setGeometry(QtCore.QRect(230, 150, 17, 37))
        self.enota_zg_27.setObjectName(_fromUtf8("enota_zg_27"))
        self.enota_zg_28 = QtGui.QLabel(self.UPS)
        self.enota_zg_28.setGeometry(QtCore.QRect(230, 100, 17, 37))
        self.enota_zg_28.setObjectName(_fromUtf8("enota_zg_28"))
        self.Graf_UPS_obremenitev = QtGui.QPushButton(self.UPS)
        self.Graf_UPS_obremenitev.setGeometry(QtCore.QRect(340, 250, 201, 31))
        self.Graf_UPS_obremenitev.setObjectName(_fromUtf8("Graf_UPS_obremenitev"))
        self.Graf_UPS_akomulator = QtGui.QPushButton(self.UPS)
        self.Graf_UPS_akomulator.setGeometry(QtCore.QRect(340, 350, 201, 31))
        self.Graf_UPS_akomulator.setObjectName(_fromUtf8("Graf_UPS_akomulator"))
        self.Graf_UPS_temperatura = QtGui.QPushButton(self.UPS)
        self.Graf_UPS_temperatura.setGeometry(QtCore.QRect(340, 400, 201, 31))
        self.Graf_UPS_temperatura.setObjectName(_fromUtf8("Graf_UPS_temperatura"))
        self.Button_UPS_10s_test = QtGui.QPushButton(self.UPS)
        self.Button_UPS_10s_test.setGeometry(QtCore.QRect(90, 510, 161, 31))
        self.Button_UPS_10s_test.setObjectName(_fromUtf8("Button_UPS_10s_test"))
        self.Button_Start_Test_Power_Off = QtGui.QPushButton(self.UPS)
        self.Button_Start_Test_Power_Off.setGeometry(QtCore.QRect(340, 510, 221, 31))
        self.Button_Start_Test_Power_Off.setObjectName(_fromUtf8("Button_Start_Test_Power_Off"))
        self.Button_Stop_Test_Power_On = QtGui.QPushButton(self.UPS)
        self.Button_Stop_Test_Power_On.setGeometry(QtCore.QRect(570, 510, 221, 31))
        self.Button_Stop_Test_Power_On.setObjectName(_fromUtf8("Button_Stop_Test_Power_On"))
        self.UPS_izpad_mreze_aktivno = QtGui.QFrame(self.UPS)
        self.UPS_izpad_mreze_aktivno.setGeometry(QtCore.QRect(340, 480, 451, 21))
        self.UPS_izpad_mreze_aktivno.setFrameShape(QtGui.QFrame.StyledPanel)
        self.UPS_izpad_mreze_aktivno.setFrameShadow(QtGui.QFrame.Raised)
        self.UPS_izpad_mreze_aktivno.setObjectName(_fromUtf8("UPS_izpad_mreze_aktivno"))
        Izbira.addTab(self.UPS, _fromUtf8(""))
        self.Ogrevanje = QtGui.QWidget()
        self.Ogrevanje.setObjectName(_fromUtf8("Ogrevanje"))
        self.Bojler_aktivno = QtGui.QFrame(self.Ogrevanje)
        self.Bojler_aktivno.setGeometry(QtCore.QRect(810, 210, 21, 21))
        self.Bojler_aktivno.setFrameShape(QtGui.QFrame.StyledPanel)
        self.Bojler_aktivno.setFrameShadow(QtGui.QFrame.Raised)
        self.Bojler_aktivno.setObjectName(_fromUtf8("Bojler_aktivno"))
        self.Cr = QtGui.QLabel(self.Ogrevanje)
        self.Cr.setGeometry(QtCore.QRect(720, 500, 61, 21))
        self.Cr.setObjectName(_fromUtf8("Cr"))
        self.set_160 = QtGui.QPushButton(self.Ogrevanje)        
        self.set_160.setGeometry(QtCore.QRect(460, 200, 151, 31))
        self.set_160.setObjectName(_fromUtf8("set_160"))
        
        


#------------------------------------------------------------------------------
#---------------------------------Slave 190 -----------------------------------
    def rs485_komunikacija(self):
        if self.checkBox_komunikacija.checkState() == QtCore.Qt.Checked:
            rs485_flag = 1
        else:
            rs485_flag = 0
            
        if rs485_flag == 1:
            val = 255
        else:
            val = 0
        self.col.setGreen(val)
        self.RS485_komunikacija_aktivno.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())            
        return rs485_flag
    
    def read_PCF8583(self):
        command = slave_read_PCF8583()

    def read_190_allowed(self):
        if self.checkBox_Read_190.checkState() == QtCore.Qt.Checked:
            read_190_flag = 1
        else:
            read_190_flag = 0
        return read_190_flag

    def read_slave_190(self):
        timecomplete = read_time()
        global time_190
        time_190 = timecomplete
        self.lineEdit_Year.setText(str("%.0f" % timecomplete[0]))
        self.lineEdit_Month.setText(str("%.0f" % timecomplete[1]))
        self.lineEdit_Day.setText(str("%.0f" % timecomplete[2]))
        self.lineEdit_Hour.setText(str("%.0f" % timecomplete[3]))
        self.lineEdit_Minutte.setText(str("%.0f" % timecomplete[4]))
        self.lineEdit_Seconds.setText(str("%.0f" % timecomplete[5]))
        self.lineEdit_WeekDay_SET.setText(str("%.0f" % timecomplete[6]))

        if timecomplete[6] == 1:
            self.lineEdit_WeekDay.setText("Ponedeljek")
        elif timecomplete[6] == 2:
            self.lineEdit_WeekDay.setText("Torek")
        elif timecomplete[6] == 3:
            self.lineEdit_WeekDay.setText("Sreda")
        elif timecomplete[6] == 4:
            self.lineEdit_WeekDay.setText("Cetrtek")
        elif timecomplete[6] == 5:
            self.lineEdit_WeekDay.setText("Petek")
        elif timecomplete[6] == 6:
            self.lineEdit_WeekDay.setText("Sobota")
        elif timecomplete[6] == 7:
            self.lineEdit_WeekDay.setText("Nedelja")
        self.lineEdit_Up_day.setText(str("%.0f" % timecomplete[8]))
        self.lineEdit_Down_day.setText(str("%.0f" % (timecomplete[9] - 10)))
        ogrevanje = check_heating()
        if ogrevanje == 74:
            val = 255
        else:
            val = 0
        self.col.setGreen(val)
        self.Ogrevanje_sezona_aktivno.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

    def set_time_zgoraj(self, arg): 
        time_zg = int(self.lineEdit_Up_day.text())
        set_time_zg(time_zg)

    def set_time_spodaj(self, arg): #preveri vpis iz masterja (+10)
        time_sp = (int(self.lineEdit_Down_day.text()) + 10)
        set_time_sp(time_sp)

    def up_5_6_OnOff(self):
        if self.checkBox_Up_5_6.checkState() == QtCore.Qt.Checked:
            up_5_6 = 27
        else:
            up_5_6 = 26
        ogrevanje_5_6 = control_heating_5_6(up_5_6)

        if ogrevanje_5_6 == 27:
            val = 255
        else:
            val = 0

        self.col.setGreen(val)
        self.Ogrevanje_zgoraj_5_6.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

    def set_time_190(self):  # preveri za arg
        global flag_190
        num_year = int(self.lineEdit_Year.text())
        num_month = int(self.lineEdit_Month.text())
        num_day = int(self.lineEdit_Day.text())
        num_hour = int(self.lineEdit_Hour.text())
        num_min = int(self.lineEdit_Minutte.text())
        num_sec = int(self.lineEdit_Seconds.text())
        num_wekday = int(self.lineEdit_WeekDay_SET.text())
        num_up56 = 26
        num_up = int(self.lineEdit_Up_day.text())
        num_down = int(self.lineEdit_Down_day.text()) + 10
        if flag_190 == 1:     
            set_time(num_year, num_month, num_day, num_hour,
                num_min, num_sec, num_wekday, num_up56, num_up, num_down)
            flag_190 = 0
        #set_time(num_year, num_month, num_day, num_hour,
            #num_min, num_sec, num_wekday, num_up56, num_up, num_down)

    def flag_190_clear(self):
        global flag_190
        flag_190 = 1

    def vklop_izklop_ogrevanje(self):
        if self.Ogrevanje_izven_sezone.checkState() == QtCore.Qt.Checked:
            komanda = 241
        else:
            komanda = 31

        ogrevanje = control_heating(komanda)

        if ogrevanje == 74:
            val = 255
        else:
            val = 0

        self.col.setGreen(val)
        self.Ogrevanje_sezona_aktivno.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())
#--------------------------------------------------------------------------
#-----------------------------Slave 160 -----------------------------------
    def read_DS18B20(self):
        command = slave_read_DS18B20()

    def read_slave_160(self):
        temp = read_temp()
        global temp_160
        global zg_time
        global sp_time
        global bo_time
        temp_160 = temp
        self.lineEdit_ZG.setText(str("%.1f" % temp[0]))
        self.lineEdit_SP.setText(str("%.1f" % temp[1]))
        self.lineEdit_BO.setText(str("%.1f" % temp[2]))
        self.lineEdit_SO.setText(str("%.1f" % temp[3]))
        self.lineEdit_PE.setText(str("%.1f" % temp[4]))
        self.lineEdit_ZU.setText(str("%.1f" % temp[5]))
        self.lineEdit_SZgoraj.setText(str("%.2f" % temp[6]))
        self.lineEdit_SSpodaj.setText(str("%.2f" % temp[7]))
        a = convert_byte_to_bin_out(temp[8])
        self.lineEdit_PE_drva.setText(str("%.1f" % temp[9]))

        #print temp[8]

        if a[0] == 1:
            val = 255
        else:
            val = 0

        self.col.setGreen(val)
        self.Pec_aktivno.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

        if a[1] == 1:
            val = 255
        else:
            val = 0

        self.col.setGreen(val)
        self.Sonce_aktivno.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

        if a[2] == 1:
            val = 255
            bo_time = bo_time + 1
        else:
            val = 0

        self.col.setGreen(val)
        self.Bojler_aktivno.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

        if a[3] == 1:
            val = 255
            sp_time = sp_time + 1
        else:
            val = 0

        self.col.setGreen(val)
        self.Spodaj_aktivno.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

        if a[4] == 1:
            val = 255
            zg_time = zg_time + 1
        else:
            val = 0

        self.col.setGreen(val)
        self.Zgoraj_aktivno.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

        if a[5] == 1:
            val = 255
        else:
            val = 0

        self.col.setGreen(val)   # Pec na drva
        self.Crpalka_aktivno.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

    def set_slave_160(self):     # prej -- (self, arg)
        global flag_160
        num_zg = float(self.lineEdit_SZgoraj.text())
        num_sp = float(self.lineEdit_SSpodaj.text())
        if flag_160 == 1:     
            set_temp(num_zg, num_sp)
            flag_160 = 0
            
    def flag_160_clear(self):
        global flag_160
        flag_160 = 1

#-------------------------------------------------------------------------------
#----------------------------Slave 200------------------------------------------
    def read_slave_200(self):
        global poraba
        global poraba_
        poraba = read_poraba()
        poraba_[1] = poraba[0]
        poraba_[2] = poraba[1]
        poraba_[3] = poraba[2]
        self.lineEdit_Poraba_kWh.setText(str("%.3f" % poraba[0]))
        self.lineEdit_Poraba_m3.setText(str("%.3f" % poraba[1]))
        self.lineEdit_Poraba_m3_p.setText(str("%.3f" % poraba[2]))
#-------------------------------------------------------------------------------
#---------------------------Slave 210 ------------------------------------------
    def command_210_power_OFF(self):  # UPS_izpad_mreze_aktivno
        command = start_UPS_test()
        if command == 211:
            val = 255
        else:
            val = 0
        self.col.setGreen(val)
        self.UPS_izpad_mreze_aktivno.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

    def command_210_power_ON(self):
        command = stop_UPS_test()
        if command == 61:
            val = 0
        else:
            val = 255
        self.col.setGreen(val)
        self.UPS_izpad_mreze_aktivno.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

    def command_210_UPS_test_10s(self):
        command = UPS_test_10s()

    def command_210_read_UPS(self):
        command = slave_210_read_UPS()

    def read_slave_210(self):
        ups_complete = read_210()
        global ups_210
        ups_210 = ups_complete
        self.lineEdit_UPS_Uin.setText(str("%.1f" % ups_complete[0]))
        self.lineEdit_UPS_Ufault.setText(str("%.1f" % ups_complete[1]))
        self.lineEdit_UPS_Uout.setText(str("%.1f" % ups_complete[2]))
        self.lineEdit_UPS_Imax.setText(str("%.0f" % ups_complete[3]))
        self.lineEdit_UPS_Freq.setText(str("%.1f" % ups_complete[4]))
        self.lineEdit_UPS_Batt.setText(str("%.1f" % ups_complete[5]))
        self.lineEdit_UPS_Temp.setText(str("%.1f" % ups_complete[6]))
        
        if ups_complete[7] == 1:
            val = 255
        else:
            val = 0
        self.col.setGreen(val)
        self.UPS_power_fail.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

        if ups_complete[8] == 1:
            val = 255
        else:
            val = 0
        self.col.setGreen(val)
        self.UPS_battery_low.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

        if ups_complete[9] == 1:
            val = 255
        else:
            val = 0
        self.col.setGreen(val)
        self.UPS_bypass_boost.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

        if ups_complete[10] == 1:
            val = 255
        else:
            val = 0
        self.col.setGreen(val)
        self.UPS_failed.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

        if ups_complete[11] == 1:
            val = 255
        else:
            val = 0
        self.col.setGreen(val)
        self.UPS_type.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

        if ups_complete[12] == 1:
            val = 255
        else:
            val = 0
        self.col.setGreen(val)
        self.UPS_test.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

        if ups_complete[13] == 1:
            val = 255
        else:
            val = 0
        self.col.setGreen(val)
        self.UPS_shutdown.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

        if ups_complete[14] == 1:
            val = 255
        else:
            val = 0
        self.col.setGreen(val)
        self.UPS_beeper.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())
#-------------------------------------------------------------------------------
#-------------------------slave 220---------------------------------------------
    def read_SHT11(self):
        command = slave_read_SHT11()

    def read_slave_220(self):
        global hladilnica
        hladilnica = read_hladilnica()

        self.lineEdit_Hladilnica_Temperatura.setText(str("%.2f" % hladilnica[0]))
        self.lineEdit_Hladilnica_Vlaga.setText(str("%.2f" % hladilnica[1]))
        self.lineEdit_Hladilnica_set_temp.setText(str("%.0f" % hladilnica[2]))
        #self.lineEdit_Hladilnica_set_temp.setText(str("%.1f" % (float(hladilnica[2] / 10))))
        self.lineEdit_Hladilnica_set_vlaga.setText(str("%.0f" % hladilnica[3]))
        a = convert_byte_to_bin_out_2(hladilnica[4])
        if a[0] == 1:
            val = 255
        else:
            val = 0
        self.col.setGreen(val)
        self.Hladilnica_kompresor_aktivno.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())
        if a[1] == 1:
            val = 255
        else:
            val = 0
        self.col.setGreen(val)
        self.Hladilnic_vlazilec_aktivno.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())
        if a[2] == 1:
            val = 255
        else:
            val = 0
        self.col.setGreen(val)
        self.Hladilnica_ventilator_aktivno.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())

    def set_slave_220(self, arg):
        num_ht = int(self.lineEdit_Hladilnica_set_temp.text())
        #num_ht = int(float(self.lineEdit_Hladilnica_set_temp.text()))
        num_hv = int(self.lineEdit_Hladilnica_set_vlaga.text())
        set_hladilnica(7.5, 75, num_ht, num_hv, 0)
#-------------------------------------------------------------------------------
#---------------slave 230-------------------------------------------------------

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    Izbira = QtGui.QTabWidget()
    ui = Ui_Izbira()
    ui.setupUi(Izbira)
    Izbira.show()
    sys.exit(app.exec_())



User avatar
paddyg
Posts: 2460
Joined: Sat Jan 28, 2012 11:57 am
Location: UK

Re: Threading problems

Sat Dec 07, 2019 4:44 pm

That's lots of code to look at - well I did ask for it ;) However I am more confused than ever. You still don't have any loops in your threaded functions so there seems very little benefit putting them in threads at all. Have you tried:

Code: Select all

def prozenje():
    digitalna_ura()
    aktivnosti_po_uri()
    watch_dog_pulse()
? And what was the result?

One issue might be the sleep or time of Qt function calls in aktivnosti_po_uri() which would delay the running of watch_dog_pulse(). But you could change the order you call the functions.

If you want to call the functions all at the same time, or at different frequencies then the logical way would be to use different QTimer objects (probably as singleShot in a recursive manner) so you could schedule a function to

Code: Select all

def read_ds18b20():
    if master.rs485_komunikacija() == 1 and watch_dog() == 1:
        master.read_DS18B20()
    QTimer.singleShot(10000, read_ds18b20) #10s delay subsequent times

QTimer.singleShot(2000, read_ds18b20) # 2s delay for first time
and similarly for your other funcs 29000->60000, 35000->60000 etc

Or is the problem that the GUI becomes unresponsive while the functions are running?
also https://groups.google.com/forum/?hl=en-GB&fromgroups=#!forum/pi3d

California
Posts: 181
Joined: Sat Jun 06, 2015 2:33 pm

Re: Threading problems

Sat Dec 07, 2019 5:43 pm

Somehow acidntly part code with "t1.join(), t2.join(), t3.join()" was removed and threading started to work, so I put your idea from yesterday on delay for some time.

User avatar
paddyg
Posts: 2460
Joined: Sat Jan 28, 2012 11:57 am
Location: UK

Re: Threading problems

Sat Dec 07, 2019 7:37 pm

Hi, Yes I just tested the idea of not putting the functions in Threads (pi3d_demos has an example using PyQt4 so I could add a time-wasting function very easily). The result is that the functions started by QTimer do block the execution of the main thread so that means that if you don't put the functions in threads you will get an unresponsive GUI if you include the time.sleep().
also https://groups.google.com/forum/?hl=en-GB&fromgroups=#!forum/pi3d

California
Posts: 181
Joined: Sat Jun 06, 2015 2:33 pm

Re: Threading problems

Tue Dec 10, 2019 9:25 am

Now I am the one to be confused ...
I did install python 3.7 idle and code posted above run in it without errors or warnings, running code in Thonny's editor stil give the same warnings as before.
Any explanation about it?

However, small example of threading was made by myself, which is not dependent on hardware, so you can take a look into it.
Again running in python idle gives no warnings, running in Thonny's editor gives warning as posted above.

Running code from terminal gives warnings aswell

main.py

Code: Select all

#
import gui
import sys
import time
import datetime
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import QTimer
import threading


tm_month = 0
tm_day = 0
tm_hour = 0
tm_minutte = 0
tm_second = 0
val_1 = 0
val_2 = 0

def digital_clock():
    global time
    global tm_month
    global tm_day
    global tm_hour
    global tm_minutte
    global tm_second

    now = datetime.datetime.now()
    master.Time.setText(now.strftime("%H" + ":" + "%M" + ":" + "%S"))
    
    tm_month = time.localtime().tm_mon
    tm_day = time.localtime().tm_mday
    tm_hour = time.localtime().tm_hour
    tm_minutte = time.localtime().tm_min
    tm_second = time.localtime().tm_sec

def time_dependent_activities():
    global val_1
    if (tm_second == 10 or tm_second == 20):
        val_1 = val_1 + 255
        if val_1 > 255:
            val_1 = 0
        master.col.setGreen(val_1)
        master.frame.setStyleSheet("QFrame { background-color: %s }" %
        master.col.name())
        time.sleep(5)
        
        
def watch_dog_pulse():
    global val_2
    val_2 = val_2 + 255
    if val_2 > 255:
        val_2 = 0
    master.col.setGreen(val_2)
    master.frame_2.setStyleSheet("QFrame { background-color: %s }" %
        master.col.name()) 
    
def trigering():
    t1= threading.Thread(target=digital_clock)
    t2= threading.Thread(target=time_dependent_activities)
    t3= threading.Thread(target=watch_dog_pulse)

    t1.start()
    t2.start()
    t3.start()

if __name__ == "__main__": 
    
    app = QtGui.QApplication(sys.argv)

    gui_master = gui.QtGui.QTabWidget()
    master = gui.Ui_Izbira()
    master.setupUi(gui_master)
    

    # Timer - Trigers updating of time label every second
    timer = QTimer()
    timer.timeout.connect(trigering)
    timer.start(1000)

    gui_master.show()
    sys.exit(app.exec_())
gui.py

Code: Select all

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'gui.ui'
#
# Created by: PyQt4 UI code generator 4.12.1
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui


try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Izbira(object):
    def setupUi(self, Izbira):
        Izbira.setObjectName(_fromUtf8("Izbira"))
        Izbira.resize(530, 363)

        Izbira.setStyleSheet(_fromUtf8("background-color: rgb(200, 200, 200);"))
        self.col = QtGui.QColor(0, 0, 0)
        
        Izbira.setWindowTitle(_fromUtf8(""))
        self.Mainpage = QtGui.QWidget()
        self.Mainpage.setObjectName(_fromUtf8("Mainpage"))
        self.Time = QtGui.QLineEdit(self.Mainpage)
        self.Time.setGeometry(QtCore.QRect(130, 20, 261, 71))
        font = QtGui.QFont()
        font.setPointSize(47)
        font.setBold(False)
        font.setItalic(True)
        font.setWeight(50)
        self.Time.setFont(font)
        self.Time.setObjectName(_fromUtf8("Time"))
        self.frame = QtGui.QFrame(self.Mainpage)
        self.frame.setGeometry(QtCore.QRect(130, 200, 41, 41))
        self.frame.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtGui.QFrame.Raised)
        self.frame.setObjectName(_fromUtf8("frame"))
        self.frame_2 = QtGui.QFrame(self.Mainpage)
        self.frame_2.setGeometry(QtCore.QRect(350, 200, 41, 41))
        self.frame_2.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame_2.setFrameShadow(QtGui.QFrame.Raised)
        self.frame_2.setObjectName(_fromUtf8("frame_2"))
        self.label = QtGui.QLabel(self.Mainpage)
        self.label.setGeometry(QtCore.QRect(130, 160, 68, 22))
        self.label.setObjectName(_fromUtf8("label"))
        self.label_2 = QtGui.QLabel(self.Mainpage)
        self.label_2.setGeometry(QtCore.QRect(330, 160, 68, 22))
        self.label_2.setObjectName(_fromUtf8("label_2"))
        Izbira.addTab(self.Mainpage, _fromUtf8(""))

        self.retranslateUi(Izbira)
        Izbira.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(Izbira)

    def retranslateUi(self, Izbira):
        self.label.setText(_translate("Izbira", "Thrade 2", None))
        self.label_2.setText(_translate("Izbira", "Thrade 3", None))
        Izbira.setTabText(Izbira.indexOf(self.Mainpage), _translate("Izbira", "Main page", None))


        
        

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    Izbira = QtGui.QTabWidget()
    ui = Ui_Izbira()
    ui.setupUi(Izbira)
    Izbira.show()
    sys.exit(app.exec_())


User avatar
paddyg
Posts: 2460
Joined: Sat Jan 28, 2012 11:57 am
Location: UK

Re: Threading problems

Tue Dec 10, 2019 11:37 pm

OK the best thing I can suggest is that you take all your gui modifying code out of threads. You can leave you structure in functions but move master refs to a new non threaded GUI function

Code: Select all

def time_dependent_activities():
    global val_1
    if (tm_second == 10 or tm_second == 20):
        val_1 = val_1 + 255
        if val_1 > 255:
            val_1 = 0
        time.sleep(5.0)
        
def watch_dog_pulse():
    global val_2
    val_2 = val_2 + 255
    if val_2 > 255:
        val_2 = 0

def redraw_gui():
    # NB this function shouldn't be put in a thread so don't have any code here that will cause a delay
    global val_1, val_2
    master.col.setGreen(val_1)
    master.frame.setStyleSheet("QFrame { background-color: %s }" %
                                    master.col.name())
    master.col.setGreen(val_2)
    master.frame_2.setStyleSheet("QFrame { background-color: %s }" %
                                    master.col.name()) 
    
def trigering():
    t1 = threading.Thread(target=digital_clock)
    t1.start()
    t2 = threading.Thread(target=time_dependent_activities)
    t2.start()
    t3 = threading.Thread(target=watch_dog_pulse)
    t3.start()
    redraw_gui()

I'm not sure about why you get errors sometimes and not others. IDLE doesn't really run python quite like the command line in a terminal so maybe there's a layer of filtering that hides or consumes the error messages.
also https://groups.google.com/forum/?hl=en-GB&fromgroups=#!forum/pi3d

California
Posts: 181
Joined: Sat Jun 06, 2015 2:33 pm

Re: Threading problems

Wed Dec 11, 2019 8:21 am

You are right, yesterday this exmple (with digital output for watchdog) was tested for hours and freezing of GUI was noticed after 3 hours, while digital output was stil in operation.
Thanks for your help, learned a lot ...

Regards, Vlado

California
Posts: 181
Joined: Sat Jun 06, 2015 2:33 pm

Re: Threading problems

Wed Dec 11, 2019 7:56 pm

Few more words ...
Running script all day long gives no errors, no warnings. Obviously this is right aproach to the programming of my application.
So once again, many thanks for helping and leading into right direction.

With best regards, Vlado

Return to “Python”