On only for X hours a day

Unless someone has a better option. I am trying to create a smart app that will allow a switch to be on for only X hours in a day. My use case is I use a smart remote for my TV and when my son place PS4 it turns a virtual switch on and I want to keep track of how long it has been on. Even if he turns it on and off a few times and then turn it off ones that threshold has been. The issue is I can’t think of a good way to calculate how long it has been on in seconds so I can subtract it from daily allowance. I have tried saving “new Date()” the subtracting it from current date with no luck. Does anyone have any recommendations?

Perhaps parental control in PS4 is an option you can look at…

If not, only option I can think of is webcore.

Parental control options

Settings available vary depending on the country or region, or the status of your child’s account. For details, visit the customer support website for your country or region.

Play Time

You can see how long your children play on your PS4™ system or limit when and how long they can play. These settings apply to children who are members of your family. Play time is the amount of time your child is logged in to your PS4™ system, even if games or applications are not running.

To check or restrict play time, you need to set a time zone for each child. Play time is reset at midnight in the time zone you set. Select (Settings) > [Parental Controls/Family Management] > [Family Management], and then follow the on-screen instructions to enter your sign-in information.

Select a user from the screen that appears, and then select [Time Zone].

To check your child’s total play time for the day and see information for each child, select: (Settings) > [Parental Controls/Family Management] > [Family Management].

Children can see how much play time they have on the following screens:

  • Login screen
  • Upper right of the home screen
  • Quick menu (Settings) > [Parental Controls/Family Management] > [Play Time for Today]

To restrict play time, select (Settings) > [Parental Controls/Family Management], and then choose restrictions you want to apply to that user.

To change play time for today, extend or shorten your child’s play time on the day they play. Select [Restrict] to set when and how long your child is allowed to play each day. When the set play time ends, a pop-up notification appears repeatedly on the screen to let your child know that they’re out of play time. The PS4™ system can also automatically log your child out when play time ends. The default setting is [Notify Only]. You can set the same play times for every day, or set specific restrictions for each day of the week.

Wow I was over thinking this. Thanks jkp that should work for the PS4. I still however would like to know if anyone has a recommendation for keeping track of how long the switch is on because now I am thinking I may want to use this to turn off the TV all together after a set amount of time. Here is what I got so far.

state.offTimer = 60

def remoteSwitchHandler(evt) {
    log.debug "Switch evt: ($evt.value)"
    if (evt.value == "on") {
        state.startTime = now()
        log.debug "Switch on: offTimer($state.offTimer)"
        if (state.offTimer > 0) {
            log.debug "Waiting to turn off switch"
            runIn(state.offTimer, turnOff)
		}
        else {
        	runIn(30, turnOff)
        }
    }
    else {
    	unsubscribe(turnOff)
        if (state.startTime == null) {
        	state.startTime = now()
        }
        def diffTimeUsed = now() - state.startTime
        def diffTimeUsedSec = Math.round(diffTimeUsed / 1000)
        log.debug "Switch off: diffTimeUsedSec($diffTimeUsedSec)"
        state.offTimer = state.offTime - diffTimeUsedSec
        log.debug "Switch off: offTimer($state.offTimer)"

    }
}

Hello @jamesbc619,

Perhaps you could try using the SmartApp SDK, below is a similar example where the configuration helps you to:

  1. Select a device to receive its events and send commands to it.
  2. Set the time expiration (in seconds).
  3. See the remaining time (in seconds).
  4. When an event is received:
    a. ON: Start the timer.
    b. OFF: Pause the timer.
  5. When the time expires, turn off the device.
const express = require('express');
const SmartApp = require('@smartthings/smartapp');
const bodyParser = require('body-parser');
const Timer = require('easytimer.js').Timer;
 
const server = express();
server.use(bodyParser.json());
 
const app = new SmartApp();
 
let timeLeft=0;
let timer = null;
 
/* Defines the SmartApp */
app.configureI18n()
    .page('mainPage', (context, page, configData) => {
        page.section('switchDev', section => {
            section.deviceSetting('switchD').capabilities(['switch']).required(true).permissions('rx');
        });
        page.section('preferences', (section) => {
            section.numberSetting('aftertime').defaultValue("0");
        });
        page.section('remaining', (section) => {
            section.paragraphSetting('remainingT').text(`${timeLeft}`).description("seconds");
        });
    })
    .updated(async (context, updateData) => {
        await context.api.subscriptions.unsubscribeAll();
        return Promise.all([
            context.api.subscriptions.subscribeToDevices(context.config.switchD, 'switch', 'switch.on', 'switchOnEventHandler'),
            context.api.subscriptions.subscribeToDevices(context.config.switchD, 'switch', 'switch.off', 'switchOffEventHandler')
        ]);
    })
    .subscribedEventHandler('switchOnEventHandler', (context, deviceEvent) => {
        timeLeft=context.configNumberValue('aftertime');
        timer = new Timer();
        timer.start({precision: 'seconds'});
        timer.addEventListener('secondsUpdated', function (e) {
            timeLeft--;
            if(timeLeft==0){
                return context.api.devices.sendCommands(context.config.switchD, "switch", "off")
            }
        });
    })
    .subscribedEventHandler('switchOffEventHandler', (context, deviceEvent) => {
        timer.pause();
    });
 
server.post('/', async (req, res) => {
    app.handleHttpCallback(req, res);
});
 
 
/* Starts the server */
let port = 3000;
server.listen(port, () =>
  console.log(`Server is up and running on port ${port}`)
);

For more information see the sample of a Simple SmartApp and the settings type of the SmartApp SDK .

Let me know if you have any doubts.