Возникли проблемы с реализацией таймера в Киви - PullRequest
0 голосов
/ 07 марта 2019

Я пытаюсь создать приложение киви.Приложение работает следующим образом:

  1. Я посылаю количество секунд, в течение которых мой таймер должен работать через MQTT, по теме 'tafelxuren' (x - это число от 1 до 8).
  2. После отправки количества секунд, которое я хочу, чтобы оно длилось, я отправляю в команду 'tafelxstart' вторую команду MQTT (x - число от 1 до 8) с командой 'start'.
  3. Послеотправив команду запуска, мой таймер начинает работать.

enter image description here

Под моим таймером у меня есть 3 кнопки, пауза, возобновление и остановка.Хотя запуск и приостановка таймера работает с помощью команд MQTT, я не могу заставить свою кнопку возобновить работу должным образом, если после нажатия кнопки паузы осталось 26 секунд, я хочу, чтобы мой таймер возобновил работу с этой точки.Вместо этого он начинается снова с начала

Мой main.py:

import os
if os.name == 'posix':
    os.environ['KIVY_GL_BACKEND'] = 'gl'
import kivy, time,threading
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ObjectProperty
from kivy.clock import Clock
from kivy.config import Config
import paho.mqtt.client as mqtt
Config.set('graphics', 'fullscreen', 'auto')
import paho.mqtt.publish as publish
import paho.mqtt.subscribe as subscribe
import config

# lege MQTT-client instantie
client = None
# De topics die gebruikt worden
ingesteldetijd = [config.timeTopics['tafel1'],config.timeTopics['tafel2'],config.timeTopics['tafel3'],config.timeTopics['tafel4'],config.timeTopics['tafel5'],config.timeTopics['tafel6'],config.timeTopics['tafel7'],config.timeTopics['tafel8']]
ingesteldetijdTopics = [config.tim1, config.tim2, config.tim3, config.tim4, config.tim5, config.tim6, config.tim7, config.tim8]

starttopics = [config.startTopics['tafel1'],config.startTopics['tafel2'],config.startTopics['tafel3'],config.startTopics['tafel4'],config.startTopics['tafel5'],config.startTopics['tafel6'],config.startTopics['tafel7'],config.startTopics['tafel8']]
def on_connect(client,userdata,flags,rc):
        '''
        This function gets triggered when MQTT is connected succesfully
        '''
        if(rc == 0):
            print("[INFO   ] [MQTT        ] MQTT connected to broker "+config.settings['broker']+".")
            client.subscribe('#')
            ##################################### ingestelde tijd subscriptions #####################################
            for x in range(0,8):
                client.subscribe(ingesteldetijd[x])
                print('[INFO   ] [MQTT        ] Subscribed to '+ingesteldetijd[x])
            ##################################### ingestelde tijd subscriptions #####################################

            ##################################### start topic subscriptions #####################################
            for x in range(0,8):
                client.subscribe(starttopics[x])
                print('[INFO   ] [MQTT        ] Subscribed to '+starttopics[x])
            ##################################### start topic subscriptions #####################################
        else:
            print("MQTT connection to broker "+config.settings['broker']+"failed.")


def on_message(client,userdata,msg):
    '''
    If there's a message received on one of the topics, the messages gets handled here.
    '''
    ################################## tijd instellen topic ##################################
    if msg.topic == 'tafel1uren':
        config.tim1 = int(msg.payload.decode('utf-8'))
    if msg.topic == 'tafel2uren':
        config.tim2 = int(msg.payload.decode('utf-8'))
    if msg.topic == 'tafel3uren':
        config.tim3 = int(msg.payload.decode('utf-8'))
    if msg.topic == 'tafel4uren':
        config.tim4 = int(msg.payload.decode('utf-8'))
    if msg.topic == 'tafel5uren':
        config.tim5 = int(msg.payload.decode('utf-8'))
    if msg.topic == 'tafel6uren':
        config.tim6 = int(msg.payload.decode('utf-8'))
    if msg.topic == 'tafel7uren':
        config.tim7 = int(msg.payload.decode('utf-8'))
    if msg.topic == 'tafel8uren':
        config.tim8 = int(msg.payload.decode('utf-8'))
    ################################## tijd instellen topic ##################################

    if msg.topic == config.startTopics['tafel1']:
        if msg.payload.decode('utf-8') == 'start':
            config.tb1start = True
        if msg.payload.decode('utf-8') == 'stop':
            config.tb1start = False
    if msg.topic == config.startTopics['tafel2']:
        if msg.payload.decode('utf-8') == 'start':
            config.tb2start = True
        if msg.payload.decode('utf-8') == 'stop':
            config.tb2start = False
    if msg.topic == config.startTopics['tafel3']:
        if msg.payload.decode('utf-8') == 'start':
            config.tb3start = True
        if msg.payload.decode('utf-8') == 'stop':
            config.tb3start = False
    if msg.topic == config.startTopics['tafel4']:
        if msg.payload.decode('utf-8') == 'start':
            config.tb4start = True
        if msg.payload.decode('utf-8') == 'stop':
            config.tb4start = False
    if msg.topic == config.startTopics['tafel5']:
        if msg.payload.decode('utf-8') == 'start':
            config.tb5start = True
        if msg.payload.decode('utf-8') == 'stop':
            config.tb5start = False
    if msg.topic == config.startTopics['tafel6']:
        if msg.payload.decode('utf-8') == 'start':
            config.tb6start = True
        if msg.payload.decode('utf-8') == 'stop':
            config.tb6start = False
    if msg.topic == config.startTopics['tafel7']:
        if msg.payload.decode('utf-8') == 'start':
            config.tb7start = True
        if msg.payload.decode('utf-8') == 'stop':
            config.tb7start = False
    if msg.topic == config.startTopics['tafel8']:
        if msg.payload.decode('utf-8') == 'start':
            config.tb8start = True
        if msg.payload.decode('utf-8') == 'stop':
            config.tb8start = False

class CrudeTimerGrid(GridLayout):
    _python_access = ObjectProperty(None)
    time = NumericProperty(0)
    def __init__(self,**kwargs):
        super(CrudeTimerGrid,self).__init__(**kwargs)
        self.runningTimer = 0
        Clock.schedule_interval(self.load_times,1)
        Clock.schedule_interval(self.start,1)

    def load_times(self, *_):
        tafelobjecten = self.parent.parent.ids
        for x in range(0,8):
            if list(tafelobjecten.values())[x] == self:
                if str(list(tafelobjecten.keys())[x]) == 'tafel1':
                    self.time = config.tim1
                if str(list(tafelobjecten.keys())[x]) == 'tafel2':
                    self.time = config.tim2
                if str(list(tafelobjecten.keys())[x]) == 'tafel3':
                    self.time = config.tim3
                if str(list(tafelobjecten.keys())[x]) == 'tafel4':
                    self.time = config.tim4
                if str(list(tafelobjecten.keys())[x]) == 'tafel5':
                    self.time = config.tim5
                if str(list(tafelobjecten.keys())[x]) == 'tafel6':
                    self.time = config.tim6
                if str(list(tafelobjecten.keys())[x]) == 'tafel7':
                    self.time = config.tim7
                if str(list(tafelobjecten.keys())[x]) == 'tafel8':
                    self.time = config.tim8

    def start(self, *_):
        tafelobjecten = self.parent.parent.ids
        self.runningTimer = self.time
        for x in range(0,8):
            if list(tafelobjecten.values())[x] == self:
                if str(list(tafelobjecten.keys())[x]) == 'tafel1':
                    #self.time = config.tim1
                    if config.tb1start == True:
                        if(self.runningTimer > 0):
                            Clock.schedule_interval(self.tick,1)
                elif str(list(tafelobjecten.keys())[x]) == 'tafel2':
                    #self.time = config.tim2
                    if config.tb2start == True:
                        if(self.runningTimer > 0):
                            Clock.schedule_interval(self.tick,1)
                elif str(list(tafelobjecten.keys())[x]) == 'tafel3':
                    #self.time = config.tim3
                    if config.tb3start == True:
                        if(self.runningTimer > 0):
                            Clock.schedule_interval(self.tick,1)
                elif str(list(tafelobjecten.keys())[x]) == 'tafel4':
                    #self.time = config.tim4
                    if config.tb4start == True:
                        if(self.runningTimer > 0):
                            Clock.schedule_interval(self.tick,1)
                elif str(list(tafelobjecten.keys())[x]) == 'tafel5':
                    #self.time = config.tim5
                    if config.tb5start == True:
                        if(self.runningTimer > 0):
                            Clock.schedule_interval(self.tick,1)
                elif str(list(tafelobjecten.keys())[x]) == 'tafel6':
                    #self.time = config.tim6
                    if config.tb6start == True:
                        if(self.runningTimer > 0):
                            Clock.schedule_interval(self.tick,1)
                elif str(list(tafelobjecten.keys())[x]) == 'tafel7':
                    #self.time = config.tim7
                    if config.tb7start == True:
                        if(self.runningTimer > 0):
                            Clock.schedule_interval(self.tick,1)
                elif str(list(tafelobjecten.keys())[x]) == 'tafel8':
                    #self.time = config.tim8
                    if config.tb8start == True:
                        if(self.runningTimer > 0):
                            Clock.schedule_interval(self.tick,1)

    def pause(self):
        tafelobjecten = self.parent.parent.ids
        for x in range(0,8):
            if list(tafelobjecten.values())[x] == self:
                if str(list(tafelobjecten.keys())[x]) == 'tafel1':
                    config.tb1start = False
                    Clock.unschedule(self.tick)
                if str(list(tafelobjecten.keys())[x]) == 'tafel2':
                    config.tb2start = False
                    Clock.unschedule(self.tick)
                if str(list(tafelobjecten.keys())[x]) == 'tafel3':
                    config.tb3start = False
                    Clock.unschedule(self.tick)
                if str(list(tafelobjecten.keys())[x]) == 'tafel4':
                    config.tb4start = False
                    Clock.unschedule(self.tick)
                if str(list(tafelobjecten.keys())[x]) == 'tafel5':
                    config.tb5start = False
                    Clock.unschedule(self.tick)
                if str(list(tafelobjecten.keys())[x]) == 'tafel6':
                    config.tb6start = False
                    Clock.unschedule(self.tick)
                if str(list(tafelobjecten.keys())[x]) == 'tafel7':
                    config.tb7start = False
                    Clock.unschedule(self.tick)
                if str(list(tafelobjecten.keys())[x]) == 'tafel8':
                    config.tb8start = False
                    Clock.unschedule(self.tick)


    def resume(self, *_):
        tafelobjecten = self.parent.parent.ids
        for x in range(0,8):
            if list(tafelobjecten.values())[x] == self:
                if str(list(tafelobjecten.keys())[x]) == 'tafel1':
                    config.tb1start = True
                    Clock.schedule_interval(self.tick,1)
                if str(list(tafelobjecten.keys())[x]) == 'tafel2':
                    config.tb2start = True
                    Clock.schedule_interval(self.tick,1)
                if str(list(tafelobjecten.keys())[x]) == 'tafel3':
                    config.tb3start = True
                    Clock.schedule_interval(self.tick,1)
                if str(list(tafelobjecten.keys())[x]) == 'tafel4':
                    config.tb4start = True
                    Clock.schedule_interval(self.tick,1)
                if str(list(tafelobjecten.keys())[x]) == 'tafel5':
                    config.tb5start = True
                    Clock.schedule_interval(self.tick,1)
                if str(list(tafelobjecten.keys())[x]) == 'tafel6':
                    config.tb6start = True
                    Clock.schedule_interval(self.tick,1)
                if str(list(tafelobjecten.keys())[x]) == 'tafel7':
                    config.tb7start = True
                    Clock.schedule_interval(self.tick,1)
                if str(list(tafelobjecten.keys())[x]) == 'tafel8':
                    config.tb8start = True
                    Clock.schedule_interval(self.tick,1)        #pass

    def stop(self, *_):
        #TODO: implement stop button
        pass

    def tick(self, *_):
        tafelobjecten = self.parent.parent.ids
        if self.runningTimer > 0:
            self.runningTimer -= 1
            # publish de juiste tafel topic met de waarde van de restrerende tijd
            for x in range(0,8):
                if list(tafelobjecten.values())[x] == self:
                    client.publish(topic = str(list(tafelobjecten.keys())[x]), payload = str(self.runningTimer))
                    self.ids.Changelabel.text = str(time.strftime('%H:%M:%S',time.gmtime(self.runningTimer)))
        else:
            pass

class Main(GridLayout):
    pass

class CrudeTimerApp(App):
    pass

if __name__ == '__main__':  
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.username_pw_set(config.settings['username'], config.settings['password'])
    client.connect(config.settings['broker'])
    t = threading.Thread(target=client.loop_start())
    t.daemon = True
    t.start()
    CrudeTimerApp().run()

Мой файл .kv:

#:kivy 1.10.1
################################### Widget template ##########################################
<CrudeTimerGrid>:
    _python_access: Changelabel
    id: timer
    rows: 4
    BoxLayout:
        size_hint_y: 0.15
        orientation: 'horizontal'
        canvas.before:
            Color:
                rgba: .5, .5, .5, 1
            Line:
                width: 2
                rectangle: self.x, self.y, self.width, self.height
        Label:
            font_size: 20
            text: 'Restrerende tijd:'
            canvas.before:
                Color:
                    rgba: .5, .5, .5, 1
                Line:
                    width: 2
                    rectangle: self.x, self.y, self.width, self.height
        Label:
            font_size: 20
            id: Changelabel
            canvas.before:
                Color:
                    rgba: .5, .5, .5, 1
                Line:
                    width: 2
                    rectangle: self.x, self.y, self.width, self.height
    BoxLayout:
        size_hint_y: 0.15
        orientation: 'horizontal'
        canvas.before:
            Color:
                rgba: .5, .5, .5, 1
            Line:
                width: 2
                rectangle: self.x, self.y, self.width, self.height
        Label:
            font_size: 20
            text: 'Pauzetijd:'
            canvas.before:
                Color:
                    rgba: .5, .5, .5, 1
                Line:
                    width: 2
                    rectangle: self.x, self.y, self.width, self.height
        Label:
            font_size: 20
            text: '00'
            canvas.before:
                Color:
                    rgba: .5, .5, .5, 1
                Line:
                    width: 2
                    rectangle: self.x, self.y, self.width, self.height
    BoxLayout:
        size_hint_y: 0.2
        canvas.before:
            Color:
                rgba: .5, .5, .5, 1
            Line:
                width: 2
                rectangle: self.x, self.y, self.width, self.height
        Button:
            text: "Pauze"
            on_press: timer.pause()
        Button:
            text: "Hervatten"
            on_press: timer.resume()
        Button:
            text: "Stoppen"
            #on_press: timer.reset()
    Label:
        text: ''
################################### Widget template ##########################################

<Main@Widget>:
    rows: 2 # 2 rijen
    cols: 4 # 4 colums
    padding: 10 
    spacing: 10
    ################################### Tafel 1 ##########################################
    BoxLayout:
        canvas.before:
            Color:
                rgba: .5, .5, .5, 1
            Line:
                width: 2
                rectangle: self.x, self.y, self.width, self.height
        orientation: 'vertical'
        Label:
            size_hint_y: 0.15
            font_size: 25
            canvas.before:
                Color:
                    rgba: .5, .5, .5, 1
                Rectangle:
                    pos: self.pos
                    size: self.size
            text: 'Tafel 1'
        CrudeTimerGrid:
            id: tafel1
    ################################### Tafel 1 ##########################################

    ################################### Tafel 2 ##########################################
    BoxLayout:
        canvas.before:
            Color:
                rgba: .5, .5, .5, 1
            Line:
                width: 2
                rectangle: self.x, self.y, self.width, self.height
        orientation: 'vertical'
        Label:
            size_hint_y: 0.15
            font_size: 25
            canvas.before:
                Color:
                    rgba: .5, .5, .5, 1
                Rectangle:
                    pos: self.pos
                    size: self.size
            text: 'Tafel 2'
        CrudeTimerGrid:
            id: tafel2
    ################################### Tafel 2 ##########################################

    ################################### Tafel 3 ##########################################
    BoxLayout:
        canvas.before:
            Color:
                rgba: .5, .5, .5, 1
            Line:
                width: 2
                rectangle: self.x, self.y, self.width, self.height
        orientation: 'vertical'
        Label:
            size_hint_y: 0.15
            font_size: 25
            canvas.before:
                Color:
                    rgba: .5, .5, .5, 1
                Rectangle:
                    pos: self.pos
                    size: self.size
            text: 'Tafel 3'
        CrudeTimerGrid:
            id: tafel3
    ################################### Tafel 3 ##########################################

    ################################### Tafel 4 ##########################################
    BoxLayout:
        canvas.before:
            Color:
                rgba: .5, .5, .5, 1
            Line:
                width: 2
                rectangle: self.x, self.y, self.width, self.height
        orientation: 'vertical'
        Label:
            size_hint_y: 0.15
            font_size: 25
            canvas.before:
                Color:
                    rgba: .5, .5, .5, 1
                Rectangle:
                    pos: self.pos
                    size: self.size
            text: 'Tafel 4'
        CrudeTimerGrid:
            id: tafel4
    ################################### Tafel 4 ##########################################

    ################################### Tafel 5 ##########################################
    BoxLayout:
        canvas.before:
            Color:
                rgba: .5, .5, .5, 1
            Line:
                width: 2
                rectangle: self.x, self.y, self.width, self.height
        orientation: 'vertical'
        Label:
            size_hint_y: 0.15
            font_size: 25
            canvas.before:
                Color:
                    rgba: .5, .5, .5, 1
                Rectangle:
                    pos: self.pos
                    size: self.size
            text: 'Tafel 5'
        CrudeTimerGrid:
            id: tafel5
    ################################### Tafel 5 ##########################################

    ################################### Tafel 6 ##########################################
    BoxLayout:
        canvas.before:
            Color:
                rgba: .5, .5, .5, 1
            Line:
                width: 2
                rectangle: self.x, self.y, self.width, self.height
        orientation: 'vertical'
        Label:
            size_hint_y: 0.15
            font_size: 25
            canvas.before:
                Color:
                    rgba: .5, .5, .5, 1
                Rectangle:
                    pos: self.pos
                    size: self.size
            text: 'Tafel 6'
        CrudeTimerGrid:
            id: tafel6
    ################################### Tafel 6 ##########################################

    ################################### Tafel 7 ##########################################
    BoxLayout:
        canvas.before:
            Color:
                rgba: .5, .5, .5, 1
            Line:
                width: 2
                rectangle: self.x, self.y, self.width, self.height
        orientation: 'vertical'
        Label:
            size_hint_y: 0.15
            font_size: 25
            canvas.before:
                Color:
                    rgba: .5, .5, .5, 1
                Rectangle:
                    pos: self.pos
                    size: self.size
            text: 'Tafel 7'
        CrudeTimerGrid:
            id: tafel7
    ################################### Tafel 7 ##########################################

    ################################### Tafel 8 ##########################################
    BoxLayout:
        canvas.before:
            Color:
                rgba: .5, .5, .5, 1
            Line:
                width: 2
                rectangle: self.x, self.y, self.width, self.height
        orientation: 'vertical'
        Label:
            size_hint_y: 0.15
            font_size: 25
            canvas.before:
                Color:
                    rgba: .5, .5, .5, 1
                Rectangle:
                    pos: self.pos
                    size: self.size
            text: 'Tafel 8'
        CrudeTimerGrid:
            id: tafel8
    ################################### Tafel 8 ##########################################

Main:

my config.py:

# MQTT broker settings.
settings = dict(
    broker = '172.16.24.128',
    username = 'pi',
    password = 'Piaservice123'
)

# start topics.
startTopics = dict(
    tafel1 = 'tafel1start',
    tafel2 = 'tafel2start',
    tafel3 = 'tafel3start',
    tafel4 = 'tafel4start',
    tafel5 = 'tafel5start',
    tafel6 = 'tafel6start',
    tafel7 = 'tafel7start',
    tafel8 = 'tafel8start'
)

# time in seconds topics.
timeTopics = dict(
    tafel1 = 'tafel1uren',
    tafel2 = 'tafel2uren',
    tafel3 = 'tafel3uren',
    tafel4 = 'tafel4uren',
    tafel5 = 'tafel5uren',
    tafel6 = 'tafel6uren',
    tafel7 = 'tafel7uren',
    tafel8 = 'tafel8uren'
)

# Currenttime topics.
currentTime = dict(
    tafel1 = 'tafel1',
    tafel2 = 'tafel2',
    tafel3 = 'tafel3',
    tafel4 = 'tafel4',
    tafel5 = 'tafel5',
    tafel6 = 'tafel6',
    tafel7 = 'tafel7',
    tafel8 = 'tafel8'
)

# Global timer vars
tim1 = 0
tim2 = 0
tim3 = 0
tim4 = 0
tim5 = 0
tim6 = 0
tim7 = 0
tim8 = 0

# startbooleans
tb1start = False
tb2start = False
tb3start = False
tb4start = False
tb5start = False
tb6start = False
tb7start = False
tb8start = False

Класс, в котором происходит вся магия, - это класс CrudeTimerGrid().Как я могу сделать так, чтобы мой таймер не сбрасывался каждый раз, когда я нажимаю на кнопку «Возобновить»?

Редактировать: удалось исправить мою проблему!Я сделал событие (self.event = Clock.schedule_interval(self.tick,1)) и имею 2 кнопки для паузы и возобновления.Я использую кнопку паузы (Clock.unschedule(self.event)), чтобы отменить планирование события, и кнопку возобновления (Clock.schedule_once(self.event)), чтобы перепланировать мой таймер.

1 Ответ

1 голос
/ 07 марта 2019

Вы не сможете отменить планирование события Kivy Clock с помощью Clock.unschedule(self.tick). Пожалуйста, обратитесь к примеру ниже.

Часы Kivy »Без планирования

Расписание

Заменить

Clock.schedule_interval(self.tick, 1)

с

self.event = Clock.schedule_interval(self.tick, 1)

запланированный

так что вы можете отменить планирование, используя либо

self.event.cancel()

или

Clock.unschedule(self.event)
...