Beispiel #1
0
    def intervalScheduler(self):

        countdown = self.interval / self.tick

        while True:

            bExit = self.blockAndWait()

            if bExit:
                return

            countdown -= 1

            if countdown <= 0:
                countdown = self.interval / self.tick
                recordDone = Record(
                    data=None,
                    message='>Trigger<   ProcHdl::{:04d}'.format(
                        self.config['Identifier']))
                self.return_queue.put(recordDone)
            else:

                # calculate remaining time
                guitext = GuiCMD(self.remainingTime(countdown=countdown))
                self.return_queue.put(guitext)
Beispiel #2
0
    def atSpecificTime(self):

        ############################
        #     At specific time     #
        ############################

        if not self.activeDays:
            return

        nState = 0

        while True:

            if nState == 0:  # Init: Get the day offset

                dayOffset = self.getDayOffset(self.activeDays, self.specTime)

                nState = 1
                continue

            elif nState == 1:  # Init: Calculate timedelta

                delta_t = datetime.combine(date.today(),
                                           self.specTime) - datetime.now()
                delta_t = delta_t + timedelta(days=dayOffset)
                nState = 2
                continue

            elif nState == 2:  # Init: Prepare countdown and tick

                countdown = delta_t.seconds + (delta_t.days * 86400)
                self.tick = 1
                nState = 3
                continue

            elif nState == 3:  # Wait for the start

                if countdown <= 0:

                    recordDone = Record(
                        data=None,
                        message='>Trigger<   ProcHdl::{:04d}'.format(
                            self.config['Identifier']))
                    self.return_queue.put(recordDone)
                    nState = 0  # Go to interval mode
                else:

                    # calculate remaining time
                    guitext = GuiCMD(self.remainingTime(countdown=countdown))
                    self.return_queue.put(guitext)

                countdown -= 1

            bExit = self.blockAndWait()

            if bExit:
                return
Beispiel #3
0
 def message(update, context):
     context.bot.send_message(chat_id=update.effective_chat.id,
                              text='Message received')
     guitext = GuiCMD('Message received from: {}, MsgId.: {:d}'.format(
         update.message.from_user.first_name,
         update.message.message_id))
     self.return_queue.put(guitext)
     record = Record(
         update.message,
         'Message received from: {}, MsgId.: {:d}'.format(
             update.message.from_user.first_name,
             update.message.message_id))
     self.return_queue.put(record)
Beispiel #4
0
    def execute(self):


        #####################################
        #                                   #
        #     REFERENCE IMPLEMENTATION      #
        #                                   #
        #####################################


        cmd = None
        cnt = 0

        #####################################
        #                                   #
        #     Start of the infinite loop    #
        #                                   #
        #####################################

        # The example executes an infinite loop till it's receives a stop command
        while(True):

            # Example code: Do something
            cnt+=1

            try:
                # Block for 1 second and wait for incoming commands 
                cmd = self.cmd_queue.get(block=True, timeout=1)
            except queue.Empty:
                pass

            if isinstance(cmd, ProcCMD) and cmd.bStop:
                # Stop command received, exit
                return



            # Example Code: Send status text to GUI every timeout interval
            guitext = GuiCMD('cnt: {}'.format(cnt))
            self.return_queue.put(guitext)


            # Example code: Send data to element output every 5 x timeout
            if cnt % 5 == 0:
                # Recors(data, message)
                recordDone = Record(cnt, 'ID: 0x{:08x} - Sending value of cnt: {}'.format(self.id, cnt))     
                self.return_queue.put(recordDone)
Beispiel #5
0
    def execute(self):

        #####################################
        #                                   #
        #     REFERENCE IMPLEMENTATION      #
        #                                   #
        #####################################

        cmd = None
        cnt = 0

        #####################################
        #                                   #
        #     Start of the infinite loop    #
        #                                   #
        #####################################

        # The example executes an infinite loop till it's receives a stop command
        while (True):

            # Example code: Do something

            try:
                # Block for 1 second and wait for incoming commands
                cmd = self.cmd_queue.get(block=True, timeout=1)
            except queue.Empty:
                pass

            if isinstance(cmd, ProcCMD):
                if cmd.bStop:
                    # Stop command received, exit
                    return
                else:
                    # Example Code: Send number of received data packets to GUI
                    cnt += 1
                    guitext = GuiCMD('Data received: {}'.format(cnt))
                    self.return_queue.put(guitext)
                    cmd.data += 1

                    # Example Code: Increment received data by one and forward it to subsequent elements
                    recordDone = Record(
                        cmd.data, 'Sending value of cnt: {}'.format(cmd.data))
                    self.return_queue.put(recordDone)

                    cmd = None
Beispiel #6
0
    def singleFireDelayed(self):

        ############################
        #   Single fire, delayed   #
        ############################

        countdown = self.interval / self.tick

        while countdown > 0:


            guitext = GuiCMD(self.remainingTime(countdown=countdown))
            self.return_queue.put(guitext)

            bExit = self.blockAndWait()

            if bExit:
                return

            countdown -= 1

        recordDone = Record(data=None, message='>Trigger<   ProcHdl::{:04d}'.format(self.config['Identifier']))     
        self.return_queue.put(recordDone)    
Beispiel #7
0
    def onEveryFullIntervalbetweenTimes(self):

        #########################################
        #  On every fullinterval between times  #
        #########################################

        if not self.activeDays:
            return

        if self.timebase == 'Seconds':
            self.tick = 0.2

        countdown = self.interval / self.tick  

        nState = 0
        
        while True:

            time = datetime.now().time()
            
            if nState == 0:     # Init: Get the day offset 
                
                dayOffset = self.getDayOffset(self.activeDays, self.stopTime)
                
                if dayOffset == 0 and time >= self.startTime:
                    nState = 2 # Go to interval mode
                else:
                    nState = 1

                continue

            elif nState == 1:   # Init: Calculate timedelta
                
                delta_t     = datetime.combine(date.today(), self.startTime) - datetime.now()
                delta_t     = delta_t + timedelta(days=dayOffset)      
                nState      = 2
                continue

            elif nState == 2: # Init: Prepare countdown and tick

                countdown   = delta_t.seconds + (delta_t.days * 86400)
                self.tick   = 1
                nState      = 3
                continue

            elif nState == 3:   # Wait for the start
                
                countdown -= 1

                if countdown <= 0:
                    nState = 4 # Go to interval mode
                else:

                    # calculate remaining time
                    guitext = GuiCMD(self.remainingTime(countdown=countdown))
                    self.return_queue.put(guitext)
                    
            elif nState == 4: # Init Interval Mode

                if self.timebase == 'Seconds':
                    nState = 50
                    # Helper value: Prevents that trigger is fired several times when
                    # countdown in decrement and the modulo condition is still valid
                    # Init with an 'invalid' value (according to the timebase)
                    lastFired = 61 
                elif self.timebase == 'Minutes':
                    nState = 60
                elif self.timebase == 'Hours':
                    nState = 70

                continue

            elif nState == 50: # Every full second: Init countdown
                  

                countdown -= (time.second % self.interval) / self.tick
                
                nState = 51
                continue
                
            elif nState == 51:    # Every full second

                countdown   -= 1


                if  time.second % self.interval == 0 and lastFired != time.second:
                    recordDone = Record(data=None, message='>Trigger<   ProcHdl::{:04d}'.format(self.config['Identifier']))    
                    self.return_queue.put(recordDone)
                    countdown = self.interval / self.tick
                    lastFired = time.second

                else:

                    # calculate remaining time
                    guitext = GuiCMD(self.remainingTime(countdown=countdown))
                    self.return_queue.put(guitext)

                if time >= self.stopTime:
                    
                    nState = 0
                    continue

            elif nState == 60: # Every full minutes: Init countdown
            
                # Calculate minutes
                fullMinutesInterval     = self.interval // 60
                passedMinutes           = time.minute % fullMinutesInterval
                countdown               -= (passedMinutes * 60 ) / self.tick

                # Calculate seconds
                countdown               -= time.second / self.tick            

                nState = 61
                continue


            elif nState == 61: # Every full minutes

                countdown -= 1

                if  time.minute % (self.interval / 60) == 0 and time.second == 0:
                    recordDone = Record(data=None, message='>Trigger<   ProcHdl::{:04d}'.format(self.config['Identifier']))   
                    self.return_queue.put(recordDone)
                    countdown = self.interval / self.tick

                else:

                    # calculate remaining time
                    guitext = GuiCMD(self.remainingTime(countdown=countdown))
                    self.return_queue.put(guitext)

                if time >= self.stopTime:
                    
                    nState = 0
                    continue


            elif nState == 70: # Every full hours: Init countdown
                        
                        
                # Calculate hours
                fullHoursInterval       = self.interval // 3600
                passedHours             = time.hour % fullHoursInterval
                countdown               -= (passedHours * 3600 )/ self.tick

                # Calculate minutes
                fullMinutesInterval     = self.interval // 60
                passedMinutes           = time.minute % fullMinutesInterval
                countdown               -= (passedMinutes * 60 )/ self.tick

                # Calculate seconds
                countdown               -= time.second / self.tick            

                nState = 71
                continue


            elif nState == 71: # Every full hours

                countdown -= 1

                if  time.minute % (self.interval / 60) == 0 and time.second == 0:
                    recordDone = Record(data=None, message='>Trigger<   ProcHdl::{:04d}'.format(self.config['Identifier']))   
                    self.return_queue.put(recordDone)
                    countdown = self.interval / self.tick

                else:

                    # calculate remaining time
                    guitext = GuiCMD(self.remainingTime(countdown=countdown))
                    self.return_queue.put(guitext) 

                if time >= self.stopTime:
                    
                    nState = 0
                    continue


            bExit = self.blockAndWait()

            if bExit:
                return
Beispiel #8
0
    def onEveryFullInterval(self):
        
        ############################
        #  On every full interval  #
        ############################

        nState = 0

        if self.timebase == 'Seconds':
            nState = 10
            self.tick = 0.2
            # Helper value: Prevents that trigger is fired several times when
            # countdown in decrement and the modulo condition is still valid
            # Init with an 'invalid' value (according to the timebase)
            lastFired = 61 
        elif self.timebase == 'Minutes':
            nState = 20
        elif self.timebase == 'Hours':
            nState = 30


        # Countdown muss korrekt initialisiert werden
        countdown = self.interval / self.tick        

        while True:
        
            countdown   -= 1
            time        = datetime.now().time()

            if nState == 10:     # Every full second: Init countdown


                # passt
                #x = (self.interval / self.tick)
                #y = ((second % self.interval) / self.tick)
                countdown -= (time.second % self.interval) / self.tick
                
                nState = 11
                continue
        
            elif nState == 11:    # Every full second

                #countdown -= 1

                if  time.second % self.interval == 0 and lastFired != time.second:
                    recordDone = Record(data=None, message='>Trigger<   ProcHdl::{:04d}'.format(self.config['Identifier']))   
                    self.return_queue.put(recordDone)
                    countdown = self.interval / self.tick
                    lastFired = time.second

                else:

                    # calculate remaining time
                    guitext = GuiCMD(self.remainingTime(countdown=countdown))
                    self.return_queue.put(guitext)

            elif nState == 20: # Every full minutes: Init countdown

                
                
                # Calculate minutes
                fullMinutesInterval     = self.interval // 60
                passedMinutes           = time.minute % fullMinutesInterval
                countdown               -= (passedMinutes * 60 ) / self.tick

                # Calculate seconds
                countdown               -= time.second / self.tick            

                nState = 21
                continue


            elif nState == 21: # Every full minutes


                if  time.minute % (self.interval / 60) == 0 and time.second == 0:
                    recordDone = Record(data=None, message='>Trigger<   ProcHdl::{:04d}'.format(self.config['Identifier']))    
                    self.return_queue.put(recordDone)
                    countdown = self.interval / self.tick

                else:

                    # calculate remaining time
                    guitext = GuiCMD(self.remainingTime(countdown=countdown))
                    self.return_queue.put(guitext)


            elif nState == 30: # Every full hours: Init countdown
                
                
                # Calculate hours
                fullHoursInterval       = self.interval // 3600
                passedHours             = time.hour % fullHoursInterval
                countdown               -= (passedHours * 3600 )/ self.tick

                # Calculate minutes
                fullMinutesInterval     = self.interval // 60
                passedMinutes           = time.minute % fullMinutesInterval
                countdown               -= (passedMinutes * 60 )/ self.tick

                # Calculate seconds
                countdown               -= time.second / self.tick            

                nState = 21
                continue


            elif nState == 31: # Every full hours


                if  time.minute % (self.interval / 60) == 0 and time.second == 0:
                    recordDone = Record(data=None, message='>Trigger<   ProcHdl::{:04d}'.format(self.config['Identifier']))   
                    self.return_queue.put(recordDone)
                    countdown = self.interval / self.tick

                else:

                    # calculate remaining time
                    guitext = GuiCMD(self.remainingTime(countdown=countdown))
                    self.return_queue.put(guitext) 

            bExit = self.blockAndWait()

            if bExit:
                return
Beispiel #9
0
    def intervalBetweenTimes(self):

        ############################
        #  Interval between times  #
        ############################

        if not self.activeDays:
            return

        nState = 0
        
        while True:
            
            if nState == 0:     # Init: Get the day offset 
                
                dayOffset = self.getDayOffset(self.activeDays, self.stopTime)
                
                if dayOffset == 0 and datetime.now().time() >= self.startTime:
                    nState = 2 # Go to interval mode
                else:
                    nState = 1

                continue

            elif nState == 1:   # Init: Calculate timedelta
                
                delta_t     = datetime.combine(date.today(), self.startTime) - datetime.now()
                delta_t     = delta_t + timedelta(days=dayOffset)      
                nState      = 2
                continue

            elif nState == 2: # Init: Prepare countdown and tick

                countdown   = delta_t.seconds + (delta_t.days * 86400)
                self.tick   = 1
                nState      = 3
                continue

            elif nState == 3:   # Wait for the start
                
                countdown -= 1

                if countdown <= 0:

                    recordDone = Record(data=None, message='>Trigger<   ProcHdl::{:04d}'.format(self.config['Identifier']))    
                    self.return_queue.put(recordDone)
                    nState = 4 # Go to interval mode
                else:

                    # calculate remaining time
                    guitext = GuiCMD(self.remainingTime(countdown=countdown))
                    self.return_queue.put(guitext)
                    
            elif nState == 4: # Init Interval Mode

                if self.timebase == 'Seconds':
                    self.tick = 0.2

                countdown = self.interval / self.tick

                nState = 5
                continue

            elif nState == 5: # Interval Mode

                countdown -= 1

                if countdown <= 0:
                    countdown = self.interval / self.tick
                    recordDone = Record(data=None, message='>Trigger<   ProcHdl::{:04d}'.format(self.config['Identifier']))  
                    self.return_queue.put(recordDone)
                else:

                    # calculate remaining time
                    guitext = GuiCMD(self.remainingTime(countdown=countdown))
                    self.return_queue.put(guitext)
                
                if datetime.now().time() >= self.stopTime:
                    
                    nState = 0
                    continue


            bExit = self.blockAndWait()

            if bExit:
                return
Beispiel #10
0
    def execute(self):

        #####################################
        #                                   #
        #     REFERENCE IMPLEMENTATION      #
        #                                   #
        #####################################

        cmd = None
        specificConfig = self.config.get('SpecificConfig')
        chat_ids = SetPersist('chat_ids')

        def getTargetState(no: int, btn: bool):

            btnText = 'Switch GPIO {} {}'.format(no, GPIO_State(not btn).name)
            cbData = '{}{}'.format(no, GPIO_State(not btn).name)
            return btnText, cbData

        self.gpio4_state = GPIO_State.Off.value
        self.gpio5_state = GPIO_State.Off.value

        btnText, cbData = getTargetState(4, self.gpio4_state)
        self.gpio4_button = InlineKeyboardButton(text=btnText,
                                                 callback_data=cbData)

        btnText, cbData = getTargetState(5, self.gpio5_state)
        self.gpio5_button = InlineKeyboardButton(text=btnText,
                                                 callback_data=cbData)

        self.keyboard = InlineKeyboardMarkup.from_column(
            [self.gpio4_button, self.gpio5_button])

        if not specificConfig:

            recordDone = Record(None, message='Config missing')
            self.return_queue.put(recordDone)
            return

        token = next(attr['Data'] for attr in specificConfig
                     if attr['Name'] == 'Token')

        if not token:
            recordDone = Record(None, message='Token missing')
            self.return_queue.put(recordDone)
            return

        updater = Updater(token=self.config['SpecificConfig'][0]['Data'],
                          use_context=True)

        dispatcher = updater.dispatcher

        def start(update: Update, context: CallbackContext):

            chat_ids.add(update.message.chat_id)

            context.bot.sendMessage(update.effective_chat.id,
                                    'Start remote control GPIO',
                                    reply_markup=self.keyboard)

        def unknown(update, context):
            context.bot.send_message(
                chat_id=update.effective_chat.id,
                text='Sorry, I didn\'t understand that command.')

        def message(update, context):
            context.bot.send_message(chat_id=update.effective_chat.id,
                                     text='Message received')

            msg = update.message.text

            record = Record(
                update.message,
                'Message received from: {}, MsgId.: {:d}'.format(
                    update.message.from_user.first_name,
                    update.message.message_id))
            self.return_queue.put(record)

        def callback(update: Update, context: CallbackContext):

            gpio_number = int(update.callback_query.data[0])

            gpio_state = update.callback_query.data[1:]
            gpio_state = GPIO_State[gpio_state].value

            btnText, cbData = getTargetState(gpio_number, gpio_state)

            if gpio_number == 4:
                self.gpio4_state = gpio_state
                self.gpio4_button = InlineKeyboardButton(text=btnText,
                                                         callback_data=cbData)
            elif gpio_number == 5:
                self.gpio5_state = gpio_state
                self.gpio5_button = InlineKeyboardButton(text=btnText,
                                                         callback_data=cbData)
            else:
                context.bot.sendMessage(
                    update.effective_chat.id,
                    'Unknown GPIO type in callback - doing nothing')
                return

            txt = 'GPIO {} set to {}'.format(gpio_number,
                                             GPIO_State(gpio_state).name)
            self.keyboard = InlineKeyboardMarkup.from_column(
                [self.gpio4_button, self.gpio5_button])

            context.bot.sendMessage(update.effective_chat.id,
                                    txt,
                                    reply_markup=self.keyboard)

        start_handler = CommandHandler('start', start)
        message_handler = MessageHandler(Filters.text & ~Filters.command,
                                         message)
        unknown_cmd_handler = MessageHandler(Filters.command, unknown)
        callback_handler = CallbackQueryHandler(callback)

        dispatcher.add_handler(start_handler)
        #dispatcher.add_handler(message_handler) # not necessary
        dispatcher.add_handler(unknown_cmd_handler)
        dispatcher.add_handler(callback_handler)

        updater.start_polling()

        while (updater.running):

            try:
                # Block for 1 second and wait for incoming commands
                cmd = self.cmd_queue.get(block=True, timeout=1)
            except queue.Empty:
                pass

            if isinstance(cmd, ProcCMD) and cmd.bStop:
                # Stop command received, exit
                updater.stop()

            elif isinstance(cmd, ProcCMD):

                guitext = GuiCMD("Sending data: " + str(cmd.data))
                self.return_queue.put(guitext)

                for chat_id in chat_ids:
                    try:
                        dispatcher.bot.send_message(chat_id=chat_id,
                                                    text=str(cmd.data))
                    except Exception as e:
                        logging.error(e)
                        chat_ids.discard(chat_id)
                        logging.warning('ChatId removed')

            cmd = None
Beispiel #11
0
    def execute(self):

        #####################################
        #                                   #
        #     REFERENCE IMPLEMENTATION      #
        #                                   #
        #####################################

        cmd = None
        specificConfig = self.config.get('SpecificConfig')
        chat_ids = ListPersist('chat_ids')

        if not specificConfig:

            recordDone = Record(None, message='Config missing')
            self.return_queue.put(recordDone)
            return

        token = next(attr['Data'] for attr in specificConfig
                     if attr['Name'] == 'Token')

        if not token:
            recordDone = Record(None, message='Token missing')
            self.return_queue.put(recordDone)
            return

        updater = Updater(token=self.config['SpecificConfig'][0]['Data'],
                          use_context=True)

        dispatcher = updater.dispatcher

        def start(update: Update, context: CallbackContext):

            chat_ids.append(update.message.chat_id)
            context.bot.send_message(
                chat_id=update.effective_chat.id,
                text="Hello, this chat ID is now registered for communication."
            )

        def unknown(update, context):
            context.bot.send_message(
                chat_id=update.effective_chat.id,
                text='Sorry, I didn\'t understand that command.')

        def message(update, context):
            context.bot.send_message(chat_id=update.effective_chat.id,
                                     text='Message received')
            guitext = GuiCMD('Message received from: {}, MsgId.: {:d}'.format(
                update.message.from_user.first_name,
                update.message.message_id))
            self.return_queue.put(guitext)
            record = Record(
                update.message,
                'Message received from: {}, MsgId.: {:d}'.format(
                    update.message.from_user.first_name,
                    update.message.message_id))
            self.return_queue.put(record)

        start_handler = CommandHandler('start', start)
        message_handler = MessageHandler(Filters.text & ~Filters.command,
                                         message)
        unknown_cmd_handler = MessageHandler(Filters.command, unknown)

        dispatcher.add_handler(start_handler)
        dispatcher.add_handler(
            message_handler)  # muss als letztes hinzugefügt werden
        dispatcher.add_handler(unknown_cmd_handler)

        updater.start_polling()

        while (updater.running):

            try:
                # Block for 1 second and wait for incoming commands
                cmd = self.cmd_queue.get(block=True, timeout=1)
            except queue.Empty:
                pass

            if isinstance(cmd, ProcCMD) and cmd.bStop:
                # Stop command received, exit
                updater.stop()

            elif isinstance(cmd, ProcCMD):

                guitext = GuiCMD("Sending data: " + str(cmd.data))
                self.return_queue.put(guitext)

                for chat_id in chat_ids:
                    try:
                        dispatcher.bot.send_message(chat_id=chat_id,
                                                    text=str(cmd.data))
                    except Exception as e:
                        logging.error(e)
                        chat_ids.remove(chat_id)
                        logging.warning('ChatId removed')

            cmd = None