import BAC0
from models import Point, db
import time
from concurrent.futures import ThreadPoolExecutor
from tools import parse_bacnetName
def process_device(device, bacnet):
    controller = BAC0.device(device[0], device[1], bacnet)
    points_to_update = []
    points_to_create = []



    for point in controller.points:
        try:
            existing_point = Point.get(Point.bacnetName == point.properties.name)
            existing_point.value = point.value
            points_to_update.append(existing_point)
        except Point.DoesNotExist:
            new_point = {
                "name":parse_bacnetName(point.properties.name,device[0])['name'],
                "zone":parse_bacnetName(point.properties.name,device[0])['zone'],
                "prefix":parse_bacnetName(point.properties.name,device[0])['prefix'],
                'bacnetName':point.properties.name,
                'ip': device[0],
                'deviceId': device[1],
                'desc': point.properties.description,
                'value': point.value
            }
            points_to_create.append(new_point)

    # 批量更新
    if points_to_update:
        Point.bulk_update(points_to_update, fields=[Point.value])
    # 批量插入
    if points_to_create:
        Point.bulk_create([Point(**data) for data in points_to_create])

def periodic_fetch(interval):
    # 连接到网络
    bacnet = BAC0.lite(ip="192.168.1.97/24")
    while True:
        
        # 发现设备
        devices = bacnet.discover()

        with ThreadPoolExecutor() as executor:
            futures = [executor.submit(process_device, device, bacnet) for device in devices]
            for future in futures:
                future.result()

        time.sleep(interval)

if __name__ == "__main__":
    # 每隔 60 秒获取一次最新数据
    periodic_fetch(60)
    db.close()



