feiyu02
2024-08-15 196bb14112448857a885e32dc4149e308e00b01a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package cn.flightfeather.supervision.bgtask
 
import cn.flightfeather.supervision.common.net.FumeHttpService
import cn.flightfeather.supervision.domain.entity.DeviceInfo
import cn.flightfeather.supervision.domain.entity.FumeMinuteValue
import cn.flightfeather.supervision.domain.enumeration.DistrictType
import cn.flightfeather.supervision.domain.enumeration.SceneType
import cn.flightfeather.supervision.domain.mapper.DeviceInfoMapper
import cn.flightfeather.supervision.domain.mapper.FumeMinuteValueMapper
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import tk.mybatis.mapper.entity.Example
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import kotlin.math.round
 
/**
 * 上传油烟监测数据
 */
@Component
class TaskPushFume(
    private val deviceInfoMapper: DeviceInfoMapper,
    private val fumeMinuteValueMapper: FumeMinuteValueMapper,
) : BaseTimingTask() {
 
    companion object {
        val LOGGER = LoggerFactory.getLogger(TaskPushFume::class.java)
 
        // 设备品牌
        const val ZQ = "zhuoquan"
        const val HZY = "hengzhiyuan"
        private val DEVICE_TYPE = listOf(ZQ, HZY)
    }
 
    // 设备信息缓存
    private val deviceCodeMap = mutableMapOf<String, MutableList<DeviceInfo?>>()
 
    override val period: Long
        get() = 1L
 
    override fun doTask(localtime: LocalDateTime) {
        //每10分钟计算一次平均值并上传
        if (!timeCheck(localtime)) return
 
        LOGGER.info("===========开始执行油烟数据上传任务===============")
        DEVICE_TYPE.forEach { type ->
            if (!deviceCodeMap.containsKey(type)) {
                deviceCodeMap[type] = mutableListOf()
            }
            val deviceCodeList = deviceCodeMap[type]!!
 
            //计算取值时间
            val endTime = localtime.minusMinutes(1).withSecond(59)
            val startTime = localtime.minusMinutes(10).withSecond(0)
 
            doTask(type, deviceCodeList, startTime, endTime)
        }
    }
 
    fun doTask(deviceType: String, deviceCodeList: MutableList<DeviceInfo?>, startTime: LocalDateTime, endTime:LocalDateTime) {
        // 刷新监测点编号
        refreshDeviceCode(deviceType, deviceCodeList)
        val p = getPostData(deviceType, deviceCodeList, startTime, endTime)
        upload(p.first, p.second, deviceType, startTime)
    }
 
    fun getPostData(
        deviceType: String,
        deviceCodeList: MutableList<DeviceInfo?>,
        startTime: LocalDateTime,
        endTime: LocalDateTime,
    ): Pair<FumeHttpService.PostData, List<FumeMinuteValue>> {
        //生成上传数据结构体
        val postData = FumeHttpService.PostData.newInstance(deviceType)
        val allData = mutableListOf<FumeMinuteValue>()
        deviceCodeList.forEach { d ->
            if (d == null) return@forEach
 
            //获取数据
            val dataList = fumeMinuteValueMapper.selectByExample(Example(FumeMinuteValue::class.java).apply {
                createCriteria().andEqualTo("mvStatCode", d.diCode)
                    .andBetween("mvCreateTime", startTime, endTime)
                and(createCriteria().orIsNull("mvUpload")
                    .orEqualTo("mvUpload", false))
            })
 
            // 每10分钟一组的数据集合
            val tempList = mutableListOf<FumeMinuteValue>()
            // 时间戳,代表某10分钟间隔
            var tempTag = ""
            var tagTime = startTime
            dataList.forEach {data ->
                val dataTime = LocalDateTime.ofInstant(data.mvCreateTime.toInstant(), ZoneId.systemDefault())
                val minute = dataTime.minute / 10
                val tag = dataTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:")) + minute + "0"
                if (tag != tempTag) {
                    tagTime = LocalDateTime.parse("${tag}:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
                    // 进行均值计算,生成上传数据对象
                    addPostData(deviceType, tempList, postData, allData, tagTime)
                    tempList.clear()
                    tempTag = tag
                }
                tempList.add(data)
            }
            if (tempList.isNotEmpty()) addPostData(deviceType, tempList, postData, allData, tagTime)
        }
 
        return postData to allData
    }
 
    fun addPostData(
        deviceType: String,
        tempList: List<FumeMinuteValue>,
        postData: FumeHttpService.PostData,
        allData: MutableList<FumeMinuteValue>,
        startTime: LocalDateTime,
    ) {
        if (tempList.isEmpty()) return
        //计算均值
        var count = 0
        var total = 0.0
        tempList.forEach {
            val fc = when (deviceType) {
                ZQ -> it.mvFumeConcentration
                HZY -> it.mvFumeConcentration2
                else -> it.mvFumeConcentration
            }
            total += fc
            if (fc != 0.0) {
                count++
            }
        }
        if (count == 0) {
            dataUpdate(tempList)
            return
        }
        val average = round(total / count * 100) / 100
 
        //均值等于0,不上报,直接更新上传状态
        if (average == 0.0) {
            dataUpdate(tempList)
            return
        }
 
        //生成上传数据结构体
        tempList.last().let {
            postData.data.add(FumeHttpService.FumeData(
                "${deviceType}_${it.mvStatCode}",
                startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
                0.0, average,
                if (it.mvFanStatus) 3 else 2,
                it.mvFanElectricity, 0,
                if (it.mvPurifierStatus) 3 else 2,
                it.mvPurifierElectricity, 0,
                0, 0.0
            ))
        }
 
        allData.addAll(tempList)
    }
 
    fun upload(
        postData: FumeHttpService.PostData,
        allData: List<FumeMinuteValue>,
        deviceType: String,
        localtime: LocalDateTime,
    ) {
        if (postData.data.isEmpty()) return
 
        //上传数据并更新数据状态
        LOGGER.info("===========数据采样时间:$localtime")
        postData.data.forEach {
            LOGGER.info("${it.equipmentShowId}   **   ${it.dataTime}")
        }
        LOGGER.info("=================================")
        FumeHttpService.uploadData(postData)?.run {
            LOGGER.info(this.toString())
            if (this["code"].asInt == 0 && this["data"].asInt > 0) {
                dataUpdate(allData)
            }
            LOGGER.info("===========${deviceType}油烟数据上传完成============")
        }
    }
 
 
    /**
     * 上传时间点检查,确定当前是否应该上传数据
     */
    fun timeCheck(localtime: LocalDateTime): Boolean {
        val min = localtime.minute
        return (min == 0 || min == 10 || min == 20 || min == 30 || min == 40 || min == 50)
    }
 
    /**
     * 刷新监测点编号
     */
    @Synchronized
    private fun refreshDeviceCode(deviceType: String, deviceCodeList: MutableList<DeviceInfo?>) {
        val now = LocalDateTime.now()
        if (deviceCodeList.isEmpty() || (now.hour == 0 && now.minute <= period)) {
            deviceCodeList.clear()
            deviceInfoMapper.selectByExample(Example(DeviceInfo::class.java).apply {
                createCriteria().andEqualTo("diProvinceCode", "31")
                    .andEqualTo("diCityCode", "3100")
                    .andEqualTo("diDistrictCode", DistrictType.XuHui.code)
                    .andEqualTo("diSceneTypeId", SceneType.Restaurant.value)
                    .andEqualTo("diDeviceTypeId", 1)
                    .andEqualTo("diSupplier", deviceType)
                    .andEqualTo("diOnline", true)
            }).let { deviceCodeList.addAll(it) }
        }
    }
 
    /**
     * 更新数据状态
     */
    private fun dataUpdate(dataList: List<FumeMinuteValue>) {
        dataList.forEach {
            it.mvUpload = true
            fumeMinuteValueMapper.updateByPrimaryKey(it)
        }
    }
}