Skip to content

Instantly share code, notes, and snippets.

@juliantheberge
Created April 17, 2018 03:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juliantheberge/b32661976c94fab9642ff7141a4f6180 to your computer and use it in GitHub Desktop.
Save juliantheberge/b32661976c94fab9642ff7141a4f6180 to your computer and use it in GitHub Desktop.
Autonomous Alarm Clock
export default class AlarmClock {
querySvc:QuerySvc;
dbInfo: pg.ConnectionConfig;
date:Date;
timeString:V.MilitaryTime;
maxRingTime: number;
maxSnooze: number;
constructor(dbInfo) {
this.dbInfo = dbInfo;
this.maxRingTime = 10;
}
// open pool separate from client and user login
init():Promise<QuerySvc> {
const pool = new pg.Pool(this.dbInfo)
pool.connect()
.then(client => {
this.querySvc = new QuerySvc(client)
return this.querySvc
})
.catch(e => e)
}
// loops through all saved alarms, there is no way this can scale
matchTime(alarms:R.AlarmDB[]) {
for (let i = 0; i < alarms.length; i++) {
// mostly for tracking purposes will probably change this
let time = alarms[i].time,
state = alarms[i].state,
title = alarms[i].title,
alarm = alarms[i].alarm_uuid,
user = alarms[i].user_uuid;
if (time === this.now()) {
// ringing
this.querySvc.updateAlarmState(['ringing', alarm])
} else if (state === 'ringing') {
// maximum ringing time has passed
if (TimeHelpers.parseStringTime(this.now()) > TimeHelpers.parseStringTime(time) + this.maxRingTime) {
this.querySvc.insertDismiss([alarm, user])
this.querySvc.updateAlarmState(['pending', alarm])
}
} else if (state === 'snoozing') {
console.log('state is snoozing', user, alarm)
this.snoozing(user, alarm)
} else {
// pending
}
}
}
// get time string
now() {
let date = new Date();
return date.toLocaleTimeString('en-Ud', { hour12: false });
}
// ticker for checking when alarms will match
start() {
this.init()
setInterval(() => {
this.querySvc.getAllActiveAlarms([])
.then(alarms => this.matchTime(alarms))
.catch(e => e)
}, 1000)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment