dealDeviceLocation.py 6.21 KB
import logging
import pandas as pdas
import os
import chardet
from datetime import datetime, timezone
import re
import json

import openpyxl
from openpyxl import Workbook

from djcardrenewal.common.dbase.MysqlHelper import MysqlHelper
from djcardrenewal.common.dbase import DbConect
from djcardrenewal.common.sqlcontent import DjSql
from djcardrenewal.common.sqlcontent import CurMonthYzl
from djcardrenewal.common.string.StringBuilder import StringBuilder

import sys,traceback,Ice
Ice.loadSlice("--all -I.. djcardrenewal/supplychain/ice/bsd.ice")
Ice.loadSlice("--all -I.. djcardrenewal/supplychain/ice/Hdao_gps.ice")
Ice.loadSlice("--all -I.. --underscore djcardrenewal/supplychain/ice/district.ice")
Ice.loadSlice("--all -I.. --underscore djcardrenewal/supplychain/ice/ipoi.ice")
Ice.loadSlice("--all -I.. --underscore djcardrenewal/supplychain/ice/HDao_mile.ice")
import BaseStationData
import HDaoGps

print("sys config " + __name__)
log_name = './log/supplychain/dealDeviceLocationMain.log'
log_format = '[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]'
log_level = logging.DEBUG
log_mode = 'a'
logging.basicConfig(filename=log_name, format=log_format, level=log_level, filemode=log_mode)

class DealDeviceLocationMain:

    handleDescription = ''
    handleMonth = ''
    hmonth = ''
    module_file_path = ''
    defaultExportReleasePath = ''

    env_host = "192.168.5.26"

    def __init__(self, handle_month):
        logging.info("init construct bean")
        self.handleDescription = "---业务导出恒信数据---脚本执行..."
        self.handleMonth = handle_month
        self.hmonth = handle_month.replace('-', '')[2:6]

    def initCurrentMonthTable(self):
        logging.info("初始化:暂无操作")
        
    # 判断文件编码
    def detect_file_encoding(self, filename):
        with open(filename, 'rb') as f:
            content = f.read()
            result = chardet.detect(content)
            return result['encoding']

    def dealDeviceEndDateList(self):
        return True

    # 定义修改函数
    def modify_data(self, x):
        # 进行批量修改的逻辑
        if x is None:
            return x
        return x.replace("M{", "").replace("}", "")

    # 定义修改函数
    def modify_float_data(self, x):
        # 进行批量修改的逻辑
        if x is None:
            return 0
        current = str(x).replace("`", "").replace(' ', '')
        if current == '':
            return 0
        return current

    # 定义修改函数
    def dealSendDate(self, sendDate):
        # 去除字符串中的汉字
        sendDate = re.sub(r'[\u4e00-\u9fa5]', '', sendDate)

        # 进行批量修改的逻辑
        if ',' in sendDate:
            return sendDate.split(',')[0]
        
        if len(sendDate)<19:
            sendDate = sendDate + ' 00:00:00'
        return sendDate
    
    def getIceHdaoService(self):
        communicator = Ice.initialize(sys.argv)
        obj = communicator.stringToProxy(f'HDaoGpsSvc:default -h {self.env_host} -p 23470')
        obj.ice_ping()
        iceService = HDaoGps.DaoGpsServicePrx.checkedCast(obj)
        return iceService

    def getLatestGpsRecord(self, iceService, sn, type = 5):
        try:
            if not iceService:
                raise RuntimeError("Invalid proxy")
            req = HDaoGps.LatestGpsGetRequest()
            req.userID = int(sn)
            req.apType = type
            req.extraMapReq = 0

            rsp = iceService.getLatestGpsRecord(req)
            # print(rsp[1].record.gpsTime)
            # print(rsp)
            return rsp
        except:
            traceback.print_exc()
            return None

    # 定义修改函数
    def dealContentFile(self):
        # 1、读取文件内容
        deviceSourceFrame = pdas.read_excel(self.module_file_path)
        if deviceSourceFrame is None :
            logging.info("file is exception,please check")
            return
        
        # 2、loop 设备号,获取位置信息
        iceService = self.getIceHdaoService()
        for index,drow in deviceSourceFrame.iterrows():
            sn = drow.设备号
            # 组装位置信息
            gpsLocation = self.getLatestGpsRecord(iceService, sn, 5)
            if gpsLocation is not None and gpsLocation[1] is not None and gpsLocation[1].record.gpsTime>0:
                gpsTime = gpsLocation[1].record.gpsTime
                dt_object = datetime.fromtimestamp(gpsTime)
                # 格式化为字符串
                formatted_str = dt_object.strftime('%Y-%m-%d %H:%M:%S')
                logging.info('get gps time is:%s %s %s', sn, gpsTime, formatted_str)

                lngResult = gpsLocation[1].record.lng/1000000
                formatLng = "{:.6f}".format(lngResult)
                latResult = gpsLocation[1].record.lat/1000000
                formatLat = "{:.6f}".format(latResult)

                deviceSpeed = gpsLocation[1].record.speed
                deviceAlt = gpsLocation[1].record.alt
                deviceDir = gpsLocation[1].record.dir
            deviceSourceFrame.at[index, '经度'] = formatLat
            deviceSourceFrame.at[index, '纬度'] = formatLng
            deviceSourceFrame.at[index, '速度'] = deviceSpeed
            deviceSourceFrame.at[index, '海拔'] = deviceAlt
            deviceSourceFrame.at[index, 'gps时间'] = formatted_str
            deviceSourceFrame.at[index, '方向'] = deviceDir

        print('输出excel数据')
        # 输出数据到excel
        deviceSourceFrame.to_excel(f'{self.defaultExportReleasePath}', index=False)



if __name__ == "__main__":
    handle_month = '2021-2024'
    dedRes = False
    diRes = False
    urRes = False

    print('==========================根据设备SN获取设备位置信息==========================')

    
    #启动初始化
    dealMain = DealDeviceLocationMain(handle_month)
    logging.info("start handle" + dealMain.handleDescription + ' the month:' + dealMain.handleMonth)

    # 测试获取位置信息
    # dealMain.getLatestGpsRecord('561063062795826', 11)

    dealMain.module_file_path = 'D:/work_doc/dataexport/gpslocation/gpslocation20240410.xlsx'
    dealMain.defaultExportReleasePath = 'D:/work_doc/dataexport/gpslocation/gpslocation20240410-result.xlsx'

    dealMain.dealContentFile() 
    print('导出完成。')