Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove trash collector functionality #6

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
node_modules
package-lock.json
.env
template.env
dist
32 changes: 30 additions & 2 deletions dist/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.globalEventEmitter = void 0;
const express_1 = __importDefault(require("express"));
const body_parser_1 = __importDefault(require("body-parser"));
const mongoose_1 = __importDefault(require("mongoose"));
const dotenv = require('dotenv');
const http_1 = __importDefault(require("http"));
const socket_io_1 = require("socket.io");
const events_1 = require("events");
const auth_1 = __importDefault(require("./routes/auth"));
const city_1 = __importDefault(require("./routes/city"));
const project_1 = __importDefault(require("./routes/project"));
Expand All @@ -15,18 +19,42 @@ const sensor_1 = __importDefault(require("./routes/sensor"));
const trashCollector_1 = __importDefault(require("./routes/trashCollector"));
const noise_1 = __importDefault(require("./routes/noise"));
const history_1 = __importDefault(require("./routes/history"));
const mqttClient_1 = require("./mqttClient");
const mqtt = require('mqtt');
const app = (0, express_1.default)();
const PORT = process.env.PORT || 5001;
dotenv.config();
// import './mqttClient';
const server = http_1.default.createServer(app);
const io = new socket_io_1.Server(server, {
cors: {
origin: '*',
}
});
// Create a global event emitter
exports.globalEventEmitter = new events_1.EventEmitter();
// Initialize WebSocket
io.on('connection', (socket) => {
console.log('New client connected');
socket.on('disconnect', () => {
console.log('Client disconnected');
});
});
// Listen for MQTT messages
exports.globalEventEmitter.on('mqttMessage', (topic, message) => {
io.emit('newData', { topic, message });
});
// Initialize MQTT handler
(0, mqttClient_1.initializeMQTT)(exports.globalEventEmitter);
// Middleware
app.use(body_parser_1.default.json());
// Update CORS policy to whitelist every client domain
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') {
return res.sendStatus(204); // Stop further processing for preflight
}
next();
});
app.use('/api/v1/auth', auth_1.default);
Expand All @@ -47,6 +75,6 @@ app.get('/', (req, res) => {
res.send('Hello World with from TinyAIoT');
});
// Start the server
app.listen(PORT, () => {
server.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
30 changes: 15 additions & 15 deletions dist/controllers/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,22 +51,22 @@ exports.loginUser = loginUser;
const signupUser = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
console.log('Coming inside signup ====>');
const { role, email, password, projects, preferences } = req.body;
const currentUserId = req.user.id; // Assuming user ID is attached to the request by auth middleware
const currentUserRole = req.user.role; // Assuming user role is attached to the request by auth middleware
// const currentUserId = req.user.id; // Assuming user ID is attached to the request by auth middleware
// const currentUserRole = req.user.role; // Assuming user role is attached to the request by auth middleware
try {
// Check if the current user has the right to create the specified role
if (currentUserRole === 'ADMIN' && role !== 'USER') {
return res
.status(403)
.json({ message: 'Admins can only create user type users.' });
}
if (currentUserRole === 'SUPERADMIN' && role === 'SUPERADMIN') {
return res
.status(403)
.json({ message: 'Cannot create another SUPERADMIN.' });
}
console.log('Current User Id =>', currentUserId);
console.log('Current User Role =>', currentUserRole);
// // Check if the current user has the right to create the specified role
// if (currentUserRole === 'ADMIN' && role !== 'USER') {
// return res
// .status(403)
// .json({ message: 'Admins can only create user type users.' });
// }
// if (currentUserRole === 'SUPERADMIN' && role === 'SUPERADMIN') {
// return res
// .status(403)
// .json({ message: 'Cannot create another SUPERADMIN.' });
// }
// console.log('Current User Id =>', currentUserId);
// console.log('Current User Role =>', currentUserRole);
// Validate email uniqueness
const existingUser = yield user_1.User.findOne({ email });
if (existingUser) {
Expand Down
6 changes: 2 additions & 4 deletions dist/controllers/history.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,16 @@ const history_1 = require("../models/history");
// Define the route controller function to handle posting history data
const postHistory = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
try {
// const fillLevelSensorId = '668e6979f3b1e021dfba6aed';
// const batteryLevelSensorId = '668e69a3f3b1e021dfba6af3';
// const noiseSensorId = '668e6b79e921750c7a2fe08d';
const noiseSensorId = '668e6b79e921750c7a2fe08d';
// const noiseSensor = await Sensor.findOne({ _id: noiseSensorId });
// for (const data of noiseData) {
// if (data.noise_level !== undefined) {
// console.log('Coming inside noise level ===>');
// if (noiseSensor) {
// const newHistory = new History({
// sensor: noiseSensor._id,
// measureType: 'noise_level',
// measurement: data.noise_level,
// noisePrediction: data.value,
// });
// await newHistory.save();
// noiseSensor.history.push(newHistory._id);
Expand Down
55 changes: 52 additions & 3 deletions dist/controllers/noise.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getNoiseSensorHistoryBySensorId = exports.addNoiseHistory = void 0;
exports.anySample = exports.getNoiseSensorHistoryBySensorId = exports.addNoiseHistory = void 0;
const history_1 = require("../models/history");
const sensor_1 = require("../models/sensor");
const project_1 = require("../models/project");
const mqtt_1 = require("../utils/mqtt");
const addNoiseHistory = (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
try {
const { projectId, sensorId, prediction, value } = req.body;
// For now always send the projectId as 6681292999d92893669ea287
// For now always send the sensorId as "668945bfbc487cfc392c0068"
// For now always send the projectId as 668e605974f99f35291be526
// For now always send the sensorId as 668e92ca094613ff3bade435
// Check if the project exists
const project = yield project_1.Project.findById(projectId);
if (!project) {
Expand Down Expand Up @@ -67,3 +68,51 @@ const getNoiseSensorHistoryBySensorId = (req, res, next) => __awaiter(void 0, vo
}
});
exports.getNoiseSensorHistoryBySensorId = getNoiseSensorHistoryBySensorId;
const anySample = (req, res, next) => {
try {
const testMessage = `{
"end_device_ids": {
"device_id": "trash-bin-01",
"application_ids": {
"application_id": "tinyaiot-project-seminar"
},
"dev_eui": "9876B6FFFE12FD2D",
"join_eui": "0000000000000000"
},
"correlation_ids": [
"as:up:01J1WZCHYT2RYVV9P3KDP3GGKC",
"rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:0c89dab4-4185-43b8-ab1f-78608a201e6b"
],
"received_at": "2024-07-03T18:58:21.774534711Z",
"uplink_message": {
"f_port": 1,
"frm_payload": "PA/CAQ==",
"rx_metadata": [
{
"gateway_ids": {
"gateway_id": "test"
},
"rssi": -110,
"channel_rssi": -110,
"snr": 4.2
}
],
"settings": {
"data_rate": {
"lora": {
"bandwidth": 125000,
"spreading_factor": 7
}
},
"frequency": "868000000"
}
},
"simulated": true
}`;
const { batteryLevel, fillLevel, signalLevel } = (0, mqtt_1.mqttTrashParser)(JSON.parse(testMessage));
console.log(batteryLevel, fillLevel, signalLevel);
return res.status(200).json({ message: 'Success' });
}
catch (error) { }
};
exports.anySample = anySample;
5 changes: 4 additions & 1 deletion dist/controllers/sensor.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ exports.postNoiseSensor = exports.postSensor = exports.getSensorById = exports.g
const trashbin_1 = require("../models/trashbin");
const project_1 = require("../models/project");
const sensor_1 = require("../models/sensor");
const mqttClient_1 = require("../mqttClient");
const getAllSensors = (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
try {
// Implement logic to get all sensors
Expand Down Expand Up @@ -43,7 +44,7 @@ const getSensorById = (req, res, next) => __awaiter(void 0, void 0, void 0, func
exports.getSensorById = getSensorById;
const postSensor = (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
try {
const { trashbinID, measureType, applianceType } = req.body;
const { trashbinID, measureType, applianceType, ttnDeviceName } = req.body;
const userID = req.user.id;
const userRole = req.user.role;
if (!trashbinID && applianceType === 'trashbin') {
Expand Down Expand Up @@ -74,11 +75,13 @@ const postSensor = (req, res, next) => __awaiter(void 0, void 0, void 0, functio
trashbin: trashbinID,
measureType,
applianceType,
ttnDeviceName,
});
yield newSensor.save();
// Push the new sensor ID into the trashbin.sensors array
trashbin.sensors.push(newSensor._id);
yield trashbin.save();
(0, mqttClient_1.subscribeSensor)(ttnDeviceName);
return res
.status(200)
.json({ message: 'Sensor created successfully', newSensor });
Expand Down
43 changes: 42 additions & 1 deletion dist/controllers/trashCollector.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,16 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.testHistory = exports.getTrashbinsAssignedToTrashCollector = exports.createTrashCollector = exports.assignTrashbinsToTrashCollector = void 0;
exports.testHistory = exports.getTrashbinsAssignedToTrashCollector = exports.createTrashCollector = exports.getTrashCollector = exports.assignTrashbinsToTrashCollector = void 0;
const trashbin_1 = require("../models/trashbin");
const trashcollector_1 = require("../models/trashcollector");
const mqtt_1 = require("../utils/mqtt");
const project_1 = require("../models/project");
const mongoose_1 = __importDefault(require("mongoose"));
const assignTrashbinsToTrashCollector = (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
try {
const userRole = req.user.role;
Expand Down Expand Up @@ -65,6 +70,42 @@ const assignTrashbinsToTrashCollector = (req, res, next) => __awaiter(void 0, vo
}
});
exports.assignTrashbinsToTrashCollector = assignTrashbinsToTrashCollector;
const getTrashCollector = (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
try {
const projectQuery = req.query.project;
let trashcollectors;
let count;
if (projectQuery) {
// Check if the projectQuery is a valid ObjectId
if (mongoose_1.default.Types.ObjectId.isValid(projectQuery)) {
trashcollectors = yield trashcollector_1.TrashCollector.find({ project: projectQuery })
.populate('assignee')
.populate('project');
}
else {
// If not a valid ObjectId, assume it's an identifier
const project = yield project_1.Project.findOne({ identifier: projectQuery });
if (project) {
trashcollectors = yield trashcollector_1.TrashCollector.find({ project: project._id })
.populate('assignee')
.populate('project');
}
else {
return res.status(404).json({ message: 'Project not found' });
}
}
}
else {
trashcollectors = yield trashcollector_1.TrashCollector.find();
}
count = trashcollectors.length;
return res.status(200).json({ count, trashcollectors });
}
catch (error) {
res.status(500).json({ message: error.message });
}
});
exports.getTrashCollector = getTrashCollector;
const createTrashCollector = (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
try {
const userRole = req.user.role;
Expand Down
2 changes: 1 addition & 1 deletion dist/models/history.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const historySchema = new Schema({
},
measureType: {
type: String,
enum: ['fill_level', 'battery_level', 'noise_level'],
enum: ['fill_level', 'battery_level', 'noise_level', 'signal_level'],
required: true,
},
noisePrediction: {
Expand Down
6 changes: 5 additions & 1 deletion dist/models/sensor.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const sensorSchema = new Schema({
},
measureType: {
type: String,
enum: ['fill_level', 'battery_level', 'noise_level'],
enum: ['fill_level', 'battery_level', 'noise_level', 'signal_level'],
required: true,
},
unit: {
Expand All @@ -38,6 +38,10 @@ const sensorSchema = new Schema({
default: '',
},
],
ttnDeviceName: {
type: String,
required: true,
}
}, {
timestamps: true,
});
Expand Down
Loading