pmc a8add9dc6e
All checks were successful
Build and Deploy LTY / build-and-deploy (push) Successful in 29m50s
feat: update device interaction module
- Update apps, consumers, and serializers
- Add scheduler and tasks modules

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-27 18:03:08 +08:00

33 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import time
import logging
from django.core.cache import cache
logger = logging.getLogger(__name__)
# 超时阈值3分钟设备每2分钟上报一次留1分钟容差
DEVICE_OFFLINE_TIMEOUT = 180
def check_device_online_status():
"""
检查所有状态为 connected 的设备如果超过3分钟没有上报数据标记为离线。
由定时任务每60秒调用一次。
"""
from device_interaction.models import Device
connected_devices = Device.objects.filter(status='connected')
now = time.time()
offline_count = 0
for device in connected_devices:
last_seen = cache.get(f"device:last_seen:{device.mac_address}")
if last_seen is None or (now - float(last_seen)) > DEVICE_OFFLINE_TIMEOUT:
device.status = 'disconnected'
device.save(update_fields=['status'])
cache.delete(f"device:last_seen:{device.mac_address}")
offline_count += 1
logger.info(f"Device {device.mac_address} marked offline (timeout)")
if offline_count > 0:
logger.info(f"check_device_online_status: {offline_count} device(s) marked offline")