Open Source IoT Management System

Open Source IoT Management System! It includes a user authentication system, location monitoring, distance calculation, and service health monitoring. The system adopts a front-end and back-end separation architecture, with the back-end based on the Go language’s Gin/Fiber framework (high-performance web framework), the front-end built using Vue3 (reactive framework), and PostgreSQL (supporting complex queries and JSON fields) as the database, with Redis as the caching layer. The functional modules include: user authentication system, location monitoring, distance calculation, and service health monitoring.

Source code: https://www.gitpp.com/laoxiangjun/project0922-iot-manage-system

An open-source solution for an IoT management system based on your needs, including technical architecture, core functional module design, and typical application scenario implementation ideas:

1. Technical Stack Implementation

1. Back-end Architecture (Go Language)

// Example: Gin framework routing configuration
package main

import (
	"github.com/gin-gonic/gin"
	"your_project/auth"
	"your_project/location"
	"your_project/health"
)

func main() {
	r := gin.Default()

	// User authentication group
	authGroup := r.Group("/api/auth") {
		authGroup.POST("/login", auth.LoginHandler)
		authGroup.POST("/refresh", auth.RefreshToken)
	}

	// Device monitoring group (requires JWT verification)
	apiGroup := r.Group("/api")
	apiGroup.Use(auth.JWTAuthMiddleware()) {
		apiGroup.GET("/devices/:id/location", location.GetRealTimePosition)
		apiGroup.POST("/devices/distance", location.CalculateDistance)
		apiGroup.GET("/services/health", health.CheckServiceStatus)
	}

	r.Run(":8080")
}

Key Components:

  • Authentication Module: JWT + Redis for Token blacklist/refresh
  • Location Service: GeoHash algorithm for spatial data processing
  • Health Check: Prometheus metrics collection + Grafana visualization
  • Data Persistence: GORM for PostgreSQL operations (supports JSONB field storage for device metadata)

2. Front-end Architecture (Vue3 + TypeScript)

// Example: Location monitoring component
<template>
  <div class="location-dashboard">
    <LMap :center="center" :zoom="zoom">
      <LTileLayer :url="mapUrl"></LTileLayer>
      <LMarker
        v-for="device in devices"
        :key="device.id"
        :lat-lng="[device.lat, device.lng]"
      >
        <LPopup>
          <div>Device ID: {{ device.id }}</div>
          <div>Last Updated: {{ formatTime(device.updatedAt) }}</div>
        </LPopup>
      </LMarker>
    </LMap>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useDeviceStore } from '@/stores/device'
import { LMap, LTileLayer, LMarker, LPopup } from '@vue-leaflet/vue-leaflet'

const devices = ref([])
const center = ref([39.9042, 116.4074]) // Beijing coordinates
const zoom = ref(10)

onMounted(async () => {
  const store = useDeviceStore()
  devices.value = await store.fetchRealTimePositions()
})
</script>

Key Technologies:

  • Pinia state management
  • Leaflet map integration
  • ECharts data visualization
  • Axios interceptors for authentication handling

3. Database Design

-- Device table (supports multiple types of devices)
CREATE TABLE devices (
    id UUID PRIMARY KEY,
    type VARCHAR(20) NOT NULL CHECK (type IN ('truck', 'industrial', 'facility')),
    metadata JSONB,
    last_seen TIMESTAMP WITH TIME ZONE);

-- Location history table (optimized for time-series data)
CREATE TABLE location_history (
    id BIGSERIAL PRIMARY KEY,
    device_id UUID REFERENCES devices(id),
    coordinates GEOGRAPHY(Point, 4326),
    speed FLOAT,
    recorded_at TIMESTAMP WITH TIME ZONE DEFAULT NOW());

-- User permissions table (RBAC model)
CREATE TABLE roles (
    id SERIAL PRIMARY KEY,
    name VARCHAR(50) UNIQUE NOT NULL,
    permissions TEXT[] DEFAULT '{}');

Open Source IoT Management System

2. Core Functional Module Implementation

1. User Authentication System

  • Authentication Process:
    1. Username and password → JWT Token
    2. Refresh Token stored in Redis (TTL=7 days)
    3. Sensitive operations require two-factor verification (OTP)
  • Permission Control:
// Permission middleware example
func PermissionMiddleware(requiredPerms ...string) gin.HandlerFunc {
    return func(c *gin.Context) {
        claims := c.MustGet("claims").(*jwt.CustomClaims)
        userPerms := getUserPermissions(claims.UserID) // Query from database

        for _, perm := range requiredPerms {
            if !slices.Contains(userPerms, perm) {
                c.AbortWithStatusJSON(403, gin.H{"error": "forbidden"})
                return
            }
        }
        c.Next()
    }
}

2. Location Monitoring System

  • Data Collection:
    • Device side: MQTT protocol reports coordinates
    • Server side: Kafka consumes location messages
    • Storage: TimescaleDB (PostgreSQL extension) optimized for time-series data
  • Distance Calculation:
// Haversine formula implementation
func CalculateDistance(lat1, lon1, lat2, lon2 float64) float64 {
    const R = 6371e3 // Earth radius (m)
    φ1 := lat1 * math.Pi / 180
    φ2 := lat2 * math.Pi / 180
    Δφ := (lat2 - lat1) * math.Pi / 180
    Δλ := (lon2 - lon1) * math.Pi / 180

    a := math.Sin(Δφ/2)*math.Sin(Δφ/2) +
        math.Cos(φ1)*math.Cos(φ2)*
            math.Sin(Δλ/2)*math.Sin(Δλ/2)
    c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a))

    return R * c
}

3. Service Health Monitoring

  • Monitoring Metrics:
    • Device online rate
    • Data reporting delay
    • Abnormal event frequency
  • Alert Rule Engine:
# Rule configuration example
rules:
  - name: "Device Offline Alert"
    condition: "last_seen < now() - interval '5 minutes'"
    severity: "warning"
    actions:
      - "send_email"
      - "log_to_s3"

3. Typical Application Scenario Implementation

1. Smart Logistics Implementation

// Transport task service
func CalculateETA(truckID string) (time.Duration, error) {
    // 1. Get current position
    currentPos, err := getLastPosition(truckID)
    if err != nil {
        return 0, err
    }

    // 2. Query route planning API
    route, err := callRoutingAPI(currentPos, destination)
    if err != nil {
        return 0, err
    }

    // 3. Adjust based on real-time traffic data
    trafficFactor := getTrafficFactor(route.Segments)
    return time.Duration(route.Duration * trafficFactor), nil
}

2. Industrial IoT Implementation

  • Predictive Maintenance:
    1. Vibration sensor data stream analysis
    2. LSTM neural network model training
    3. Remaining Useful Life (RUL) prediction
# Example: Using TensorFlow Lite for edge computing
import tflite_runtime.interpreter as tflite
interpreter = tflite.Interpreter(model_path="rul_model.tflite")
interpreter.allocate_tensors()  # Input sensor data
input_data = np.array([[0.12, 0.45, 0.78]], dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()  # Get prediction result
rul_prediction = interpreter.get_tensor(output_details[0]['index'])[0][0]

3. Smart City Implementation

  • Smart Trash Bin Monitoring:
    • Ultrasonic sensors detect fill levels
    • Solar-powered + LoRaWAN communication
    • Dynamic collection route planning
// Trash bin status report example
{
  "deviceId": "trash-bin-001",
  "fillLevel": 0.75,  // 0-1
  "location": {
    "type": "Point",
    "coordinates": [116.404, 39.915]
  },
  "timestamp": "2023-07-20T08:30:00Z"
}

Open Source IoT Management System

4. Open Source Project Recommendations

  1. Basic Framework Reference:
  2. Recommended Extension Components:
  3. Deployment Solutions:
    • Kubernetes cluster deployment
    • Prometheus + Grafana monitoring stack
    • CI/CD pipeline (GitHub Actions/GitLab CI)

5. Performance Optimization Recommendations

  1. Database Optimization:

    • Create spatial index for location_history table:
    CREATE INDEX idx_location_history_coordinates ON location_history USING GIST(coordinates);
  2. Cache Strategy:

    • Device status cache (Redis Hash):
    HMSET device:status:truck-001 "last_pos" "116.404,39.915" "speed" "60"
  3. Asynchronous Processing:

    • Use Go’s worker pool for position calculation:
    func worker(id int, jobs <-chan PositionJob, results chan<- PositionResult) {
        for j := range jobs {
            results <- calculateDistance(j)
        }
    }

This solution supports rapid expansion through modular design, and it is recommended to start developing the MVP version from the logistics tracking scenario, gradually improving the industrial equipment and urban facility management functions. All code is suggested to be open-sourced under the MIT license for community contribution and maintenance.

Source code: https://www.gitpp.com/laoxiangjun/project0922-iot-manage-system

Smart Logistics: Real-time tracking of truck locations, calculating transport distances and times. Industrial IoT: Monitoring equipment health status, preventive maintenance to reduce downtime. Smart City: Managing the operational status of public facilities (such as streetlights and trash bins).

Open Source IoT Management System

Thank you all for your attention ➕ sharing, thank you for the likes 👍 support ⬆️

Leave a Comment