| config | ||
| iot-dashboard | ||
| middleware | ||
| routes | ||
| scripts | ||
| services | ||
| socket | ||
| utils | ||
| .gitignore | ||
| architecture.md | ||
| env.example | ||
| package-lock.json | ||
| package.json | ||
| README.md | ||
| server.js | ||
AI Agent Backend - IoT Dashboard
A comprehensive Node.js Express backend for IoT device management with AI-powered analytics, real-time streaming, self-healing capabilities, and intelligent suggestions.
Features
🔐 Authentication & Authorization
- JWT-based authentication with Redis session management
- Role-based access control (Admin, Operator, Viewer)
- Password hashing with bcrypt
- Rate limiting for security
📡 Real-time Data Streaming
- Apache StreamPipes integration for IoT data ingestion
- WebSocket support for real-time communication
- Kafka/MQTT support for message queuing
- Redis caching for high-performance data access
🤖 AI Agent Capabilities
- Intelligent anomaly detection
- Predictive maintenance suggestions
- Performance optimization recommendations
- Self-healing automation
- Machine learning model management
🚨 Alert Management
- Real-time alert generation
- Configurable alert rules and thresholds
- Multi-channel notifications (Email, SMS, WebSocket)
- Alert acknowledgment and resolution tracking
🔧 Self-Healing System
- Automated problem detection and resolution
- Device restart and configuration management
- Load balancing and circuit breaker patterns
- Maintenance scheduling
📊 Analytics & Insights
- Real-time dashboard metrics
- Performance analytics
- Device health monitoring
- Historical data analysis
📱 Notification System
- Multi-channel notifications (Email, SMS, In-app)
- Configurable notification preferences
- Notification history and status tracking
Tech Stack
- Runtime: Node.js 16+
- Framework: Express.js
- Database: MySQL 8.0+
- Cache: Redis 6.0+
- Authentication: JWT + bcrypt
- Real-time: Socket.IO
- Streaming: Apache StreamPipes, Kafka, MQTT
- Notifications: Nodemailer, Twilio
- Logging: Winston
- Validation: Express-validator
Prerequisites
- Node.js 16+
- MySQL 8.0+
- Redis 6.0+
- Apache StreamPipes (optional)
- Kafka (optional)
- MQTT Broker (optional)
Installation
-
Clone the repository
git clone <repository-url> cd ai-agent-backend -
Install dependencies
npm install -
Environment Configuration
cp env.example .envEdit
.envwith your configuration:# Database DB_HOST=localhost DB_PORT=3306 DB_USER=root DB_PASSWORD=your_password DB_NAME=ai_agent_iot # JWT JWT_SECRET=your_super_secret_jwt_key_here # Redis REDIS_HOST=localhost REDIS_PORT=6379 # StreamPipes STREAMPIPES_HOST=localhost STREAMPIPES_PORT=8080 STREAMPIPES_USERNAME=admin STREAMPIPES_PASSWORD=admin # Notifications SMTP_HOST=smtp.gmail.com SMTP_USER=your_email@gmail.com SMTP_PASS=your_app_password TWILIO_ACCOUNT_SID=your_twilio_account_sid TWILIO_AUTH_TOKEN=your_twilio_auth_token -
Database Setup
# Run migrations npm run migrate # Seed initial data (optional) npm run seed -
Start the server
# Development npm run dev # Production npm start
API Endpoints
Authentication
POST /api/auth/register- Register new userPOST /api/auth/login- User loginPOST /api/auth/logout- User logoutGET /api/auth/profile- Get user profilePUT /api/auth/profile- Update user profilePOST /api/auth/refresh- Refresh JWT token
Devices
GET /api/devices- Get all devicesGET /api/devices/:deviceId- Get device detailsPOST /api/devices- Create new devicePUT /api/devices/:deviceId- Update deviceDELETE /api/devices/:deviceId- Delete deviceGET /api/devices/:deviceId/data- Get device dataPOST /api/devices/:deviceId/command- Send command to deviceGET /api/devices/:deviceId/stats- Get device statistics
Alerts
GET /api/alerts- Get all alertsGET /api/alerts/:alertId- Get alert detailsPOST /api/alerts/:alertId/acknowledge- Acknowledge alertPOST /api/alerts/:alertId/resolve- Resolve alertGET /api/alerts/stats/overview- Get alert statistics
Analytics
GET /api/analytics/dashboard- Get dashboard overviewGET /api/analytics/performance- Get performance metrics
Healing
GET /api/healing- Get healing actions
Suggestions
GET /api/suggestions- Get AI suggestions
Notifications
GET /api/notifications- Get user notifications
StreamPipes
GET /api/streampipes/health- Check StreamPipes healthGET /api/streampipes/streams- Get data streams
WebSocket Events
Client to Server
subscribe_device- Subscribe to device updatesunsubscribe_device- Unsubscribe from device updatessubscribe_alerts- Subscribe to alertsunsubscribe_alerts- Unsubscribe from alertsdevice_control- Send device control commandacknowledge_alert- Acknowledge alert
Server to Client
device_data_update- Device data updatenew_alert- New alert notificationalert_acknowledged- Alert acknowledgedhealing_approved- Healing action approvedsuggestion_feedback_received- Suggestion feedbacknew_notification- New notificationdashboard_update- Dashboard update
Database Schema
Core Tables
users- User accounts and authenticationdevices- IoT device informationdevice_data- Raw device data storagealerts- Alert recordsnotifications- User notifications
AI & Analytics Tables
ai_suggestions- AI-generated suggestionsai_analysis_results- AI analysis resultshealing_actions- Self-healing actionsdevice_controls- Device control commands
Services Architecture
Core Services
- StreamPipesService - Handles Apache StreamPipes integration
- AIAgentService - Manages AI analysis and suggestions
- AlertService - Handles alert generation and management
- HealingService - Manages self-healing actions
- NotificationService - Handles multi-channel notifications
Configuration
- Database - MySQL connection and query management
- Redis - Caching and session management
- Logger - Structured logging with Winston
Development
Project Structure
├── config/ # Configuration files
├── middleware/ # Express middleware
├── routes/ # API route handlers
├── services/ # Business logic services
├── socket/ # WebSocket handlers
├── utils/ # Utility functions
├── scripts/ # Database scripts
├── logs/ # Application logs
├── server.js # Main application file
└── package.json # Dependencies and scripts
Available Scripts
npm start- Start production servernpm run dev- Start development server with nodemonnpm run migrate- Run database migrationsnpm run seed- Seed database with initial datanpm test- Run tests
Environment Variables
See env.example for all available configuration options.
Deployment
Production Setup
- Set
NODE_ENV=production - Configure production database and Redis
- Set up SSL certificates
- Configure reverse proxy (nginx)
- Set up process manager (PM2)
Docker Deployment
# Build image
docker build -t ai-agent-backend .
# Run container
docker run -p 5000:5000 --env-file .env ai-agent-backend
Monitoring & Logging
Health Checks
GET /health- Application health status- Service-specific health checks available
Logging
- Structured JSON logging
- Log rotation and archiving
- Different log levels (error, warn, info, debug)
Metrics
- Request/response metrics
- Database query performance
- Service health metrics
- Custom business metrics
Security
Authentication
- JWT tokens with configurable expiration
- Redis-based session management
- Password hashing with bcrypt
Authorization
- Role-based access control
- Route-level permissions
- Device-level access control
Security Headers
- Helmet.js for security headers
- CORS configuration
- Rate limiting
- Input validation
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
License
MIT License - see LICENSE file for details
Support
For support and questions:
- Create an issue in the repository
- Check the documentation
- Review the API examples
Roadmap
- Advanced ML model integration
- GraphQL API support
- Microservices architecture
- Kubernetes deployment
- Advanced analytics dashboard
- Mobile app support
- Multi-tenant support
- Advanced security features