Skip to content
Permalink
Browse files
big commit.
  • Loading branch information
kailad committed Nov 30, 2019
1 parent 6600946 commit 04131760b7e195ef21f549819abf97ccabf4252f
Show file tree
Hide file tree
Showing 18 changed files with 1,870 additions and 149 deletions.
300 index.js
@@ -1,144 +1,178 @@
#!/usr/bin/env node
const Koa = require('koa');
const app = new Koa()

//Routes File

'use strict'

/* MODULE IMPORTS */
const Koa = require('koa')
const Router = require('koa-router')
const WebSocket = require('ws');
const mqtt = require('mqtt');
const json = require('koa-json');
const path = require('path');
const render = require('koa-ejs')
const router = Router();
const port = 9001


var LightOnOff = false;
var LightConnected = false;

render(app, {
root: path.join(__dirname, 'views'),
layout: 'layout',
viewExt: 'html',
cashe: false,
debug: false,
const views = require('koa-views')
const staticDir = require('koa-static')
const bodyParser = require('koa-bodyparser')
const koaBody = require('koa-body')({multipart: true, uploadDir: '.'})
const session = require('koa-session')
const alert = require('alert-node');

/* IMPORT CUSTOM MODULES */
const User = require('./modules/user')
const Lights = require('./modules/lights')

const app = new Koa()
const router = new Router()

/* CONFIGURING THE MIDDLEWARE */
app.keys = ['darkSecret']
app.use(staticDir('public'))
app.use(bodyParser())
app.use(session(app))
app.use(views(`${__dirname}/views`, { extension: 'handlebars' }, {map: { handlebars: 'handlebars' }}))

const defaultPort = 8080
const port = process.env.PORT || defaultPort
const dbName = 'website.db'

let user

/**
* The secure home page.
*
* @name Home Page
* @route {GET} /
* @authentication This route requires cookie-based authentication.
*/
router.get('/', async ctx => {
try {
if(ctx.session.authorised !== true) return ctx.redirect('/login?msg=you need to log in')
const data = {}
if(ctx.query.msg) data.msg = ctx.query.msg
await ctx.render('index')
} catch(err) {
await ctx.render('error', {message: err.message})
}
})

/**
* The user registration page.
*
* @name Register Page
* @route {GET} /register
*/
router.get('/register', async ctx => await ctx.render('register'))
router.get('/lights', async ctx => await ctx.render('lights'))


router.get('/FrontLightON', koaBody, async ctx => {
try {
const lights = await new Lights(dbName)
await lights.frontOn()
alert('front light is on')
await ctx.render('lights')
}
catch(err) {
await ctx.render('error', {message: err.message})
}
})

router.get('/FrontLightOFF', koaBody, async ctx => {
try {
const lights = await new Lights(dbName)
await lights.frontOff()
alert('front light is off')
await ctx.render('lights')
}
catch(err) {
await ctx.render('error', {message: err.message})
}
})

router.get('/InsideLightOFF', koaBody, async ctx => {
try {
const lights = await new Lights(dbName)
await lights.insideOff()
alert('inside light is off')
await ctx.render('lights')
}
catch(err) {
await ctx.render('error', {message: err.message})
}
})

router.get('/InsideLightON', koaBody, async ctx => {
try {
const lights = await new Lights(dbName)
await lights.insideOn()
alert('inside light is on')
await ctx.render('lights')
}
catch(err) {
await ctx.render('error', {message: err.message})
}
})

const wss = new WebSocket.Server({
port: 3000,
perMessageDeflate: {
zlibDeflateOptions: {
// See zlib defaults.
chunkSize: 1024,
memLevel: 7,
level: 3
},
zlibInflateOptions: {
chunkSize: 10 * 1024
},
// Other options settable:
clientNoContextTakeover: true, // Defaults to negotiated value.
serverNoContextTakeover: true, // Defaults to negotiated value.
serverMaxWindowBits: 10, // Defaults to negotiated value.
// Below options specified as default values.
concurrencyLimit: 10, // Limits zlib concurrency for perf.
threshold: 1024 // Size (in bytes) below which messages
// should not be compressed.
}
});

router.post('/ExteriorLightOnOff', onoff);

router.get('/Lights', async ctx =>{
await ctx.render('lights');
if (LightConnected == false){
LightConnected = true;
const connection = new WebSocket('ws://localhost:3000')
wss.on('connection', function connection(ws) {
const client = mqtt.connect('mqtt.coventry.ac.uk', {
host: 'mqtt.coventry.ac.uk',
protocol: 'mqtts',
username: '302CEM',
password: 'n3fXXFZrjw',
port: 8883,
})

client.on('connect', function () {
client.subscribe('302CEM/Team2/kailad', function (err) {
if (!err){
client.publish('302CEM/Team2/kailad', 'Subbed')
}
})
})
});
}
else {
}
router.post('/MontionSensor', async ctx => {
try {
const body = ctx.request.body
console.log(body.Sensor)
const lights = await new Lights(dbName)
await lights.sensor(body.Sensor)
alert('Sensor set')
await ctx.render('lights')
}
catch(err) {
await ctx.render('error', {message: err.message})
}
})

async function onoff(ctx) {
const connection = new WebSocket('ws://localhost:3000')
wss.on('connection', function connection(ws) {
const client = mqtt.connect('mqtt.coventry.ac.uk', {
host: 'mqtt.coventry.ac.uk',
protocol: 'mqtts',
username: '302CEM',
password: 'n3fXXFZrjw',
port: 8883,
})

if (LightOnOff == false){
client.on('connect', function () {
client.subscribe('302CEM/Team2/kailad', function (err) {
if (!err){
LightOnOff = true;
client.publish('302CEM/Team2/kailad', 'Turn on the Exterior Light')
}
})
})
}
else if (LightOnOff == true){
client.on('connect', function () {
client.subscribe('302CEM/Team2/kailad', function (err) {
if (!err){
LightOnOff = false;
client.publish('302CEM/Team2/kailad', 'Turn off the Exterior Light')
}
})
})
}
});
ctx.redirect('/lights')
}
router.get ('/temperature', async ctx =>{
await ctx.render('temperature');
const connection = new WebSocket('ws://localhost:3000')
wss.on('connection', function connection(ws) {
const client = mqtt.connect('mqtt.coventry.ac.uk', {
host: 'mqtt.coventry.ac.uk',
protocol: 'mqtts',
username: '302CEM',
password: 'n3fXXFZrjw',
port: 8883,
})

client.on('connect', function () {
client.subscribe('302CEM/Team2/temp01', function (err) {
if (!err){
client.publish('302CEM/Team2/temp01', 'subbed')
}
})
})

client.on('message', function(topic, message, packet){
ws.send(`${message}`)
})
});
/**
* The script to process new user registrations.
*
* @name Register Script
* @route {POST} /register
*/
router.post('/register', koaBody, async ctx => {
try {
// extract the data from the request
const body = ctx.request.body
console.log(body)
// call the functions in the module
user = await new User(dbName)
await user.register(body.user, body.pass)
// await user.uploadPicture(path, type)
// redirect to the home page
ctx.redirect(`/?msg=new user "${body.name}" added`)
} catch(err) {
await ctx.render('error', {message: err.message})
} finally {
user.tearDown()
}
})
app.use(json());
app.use(router.routes());
module.exports = app.listen(port, () => console.log(`listening on port ${port}`))

router.get('/login', async ctx => {
const data = {}
if(ctx.query.msg) data.msg = ctx.query.msg
if(ctx.query.user) data.user = ctx.query.user
await ctx.render('login', data)
})

//mosquitto_sub -v -h mqtt.coventry.ac.uk --cafile mqtt.crt -p 8883 -u 302CEM -P n3fXXFZrjw -t 302CEM/Team2/kailad
//mosquitto_pub -h mqtt.coventry.ac.uk -p 8883 --cafile mqtt.crt -u 302CEM -P n3fXXFZrjw -t 302CEM/Team2/kailad -m "why doesnt mqtt work?"
router.post('/login', async ctx => {
try {
const body = ctx.request.body
user = await new User(dbName)
await user.login(body.user, body.pass)
ctx.session.authorised = true
return ctx.redirect('/?msg=you are now logged in...')
} catch(err) {
await ctx.render('error', {message: err.message})
} finally {
user.tearDown()
}
})

router.get('/logout', async ctx => {
ctx.session.authorised = null
ctx.redirect('/?msg=you are now logged out')
})

app.use(router.routes())
module.exports = app.listen(port, async() => console.log(`listening on port ${port}`))

0 comments on commit 0413176

Please sign in to comment.