mac
2024-06-24 24a59bc611c38ec3c01987cd5bb33984aa9731b2
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
package com.hdl.photovoltaic.ui;
 
 
import android.os.Bundle;
import android.os.Process;
import android.os.SystemClock;
import android.text.TextUtils;
 
 
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hdl.linkpm.sdk.core.exception.HDLException;
import com.hdl.linkpm.sdk.home.type.HomeType;
import com.hdl.photovoltaic.HDLApp;
import com.hdl.photovoltaic.R;
import com.hdl.photovoltaic.base.CustomBaseActivity;
import com.hdl.photovoltaic.bean.MqttInfo;
import com.hdl.photovoltaic.config.ConstantManage;
import com.hdl.photovoltaic.config.UserConfigManage;
import com.hdl.photovoltaic.databinding.ActivityCpowerStationBinding;
import com.hdl.photovoltaic.enums.NetworkType;
import com.hdl.photovoltaic.listener.CloudCallBeak;
import com.hdl.photovoltaic.other.HdlDeviceLogic;
import com.hdl.photovoltaic.other.HdlLogLogic;
import com.hdl.photovoltaic.other.HdlMqttLogic;
import com.hdl.photovoltaic.other.HdlOtaLogic;
import com.hdl.photovoltaic.other.HdlResidenceLogic;
import com.hdl.photovoltaic.other.HdlThreadLogic;
import com.hdl.photovoltaic.other.HdlUniLogic;
import com.hdl.photovoltaic.ui.bean.DeviceRemoteInfo;
import com.hdl.photovoltaic.ui.bean.HouseIdBean;
import com.hdl.photovoltaic.ui.bean.OidBean;
import com.hdl.photovoltaic.uni.HDLUniMP;
import com.hdl.photovoltaic.uni.HDLUniMPSDKManager;
import com.hdl.photovoltaic.utils.AppManagerUtils;
import com.hdl.sdk.link.HDLLinkLocalSdk;
import com.hdl.sdk.link.common.event.EventListener;
import com.hdl.sdk.link.core.bean.LinkResponse;
import com.hdl.sdk.link.core.bean.ModbusResponse;
import com.hdl.sdk.link.core.bean.eventbus.BaseEventBus;
import com.hdl.sdk.link.core.bean.gateway.GatewayBean;
import com.hdl.sdk.link.core.config.HDLLinkConfig;
import com.hdl.sdk.link.core.utils.mqtt.MqttRecvClient;
 
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
 
import java.lang.reflect.Type;
import java.util.List;
 
import cn.jpush.android.api.JPushInterface;
 
/**
 * C端-电站界面
 */
public class CPowerStationActivity extends CustomBaseActivity {
 
    private ActivityCpowerStationBinding viewBinding;
 
    private EventListener allTopicsListener;
    private int backPressTimes;
 
    @Override
    public Object getContentView() {
        viewBinding = ActivityCpowerStationBinding.inflate(getLayoutInflater());
        return viewBinding.getRoot();
    }
 
    @Override
    public void onBindView(Bundle savedInstanceState) {
        setNotificationBarBackgroundColor(CustomColor.white);
        setStatusBarTextColor();
        //C端启动App自动打开小程序电站详情界面
        startAppAutomaticallyOpenUni();
        //注册监听
        this.registerAllTopicsListener();
        //初始化mqtt客户端
        this.initMqttClient();
        //上传极光注册ID到云端
        this.pushTokens();
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        //启动页与mainActivity样式一样,这样启动页和mainActivity看上去是一个界面,目的是为了mainActivity遮住下一页;
//        AppManagerUtils.getAppManager().finishActivity(StartActivity.class);
//        this.portConflictDialog();
    }
 
    public void startAppAutomaticallyOpenUni() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(10);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //低于安卓14版本
                        if (android.os.Build.VERSION.SDK_INT < 34) {
                            startAppAutomaticallyOpenUni(false);
                        } else {
                            startAppAutomaticallyOpenUni(true);
                        }
                    }
                });
            }
        }).start();
    }
 
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMessage(BaseEventBus event) {
 
        if (event == null) {
            return;
        }
        if (TextUtils.isEmpty(event.getTopic())) {
            return;
        }
        //网关mqtt秘钥更新通知
        if (event.getTopic().contains("/custom/mqtt/secret/change")) {
            String[] topics = event.getTopic().split("/");
            //主题不符合规则不处理
            if (topics.length < 3) {
                return;
            }
            int index = -1;
            List<GatewayBean> list = HdlDeviceLogic.getInstance().getCurrentHomeGatewayList(UserConfigManage.getInstance().getHomeId());
            for (int i = 0; i < list.size(); i++) {
                GatewayBean gatewayBean = list.get(i);
                if (gatewayBean.getGatewayId().equals(topics[2])) {
                    index = i;
                    break;
                }
            }
            if (index > -1) {
                GatewayBean gatewayBean = list.get(index);
                HdlDeviceLogic.getInstance().getDeviceRemoteInfo(UserConfigManage.getInstance().getHomeId(), gatewayBean.getSpk(), gatewayBean.getDevice_mac(), new CloudCallBeak<DeviceRemoteInfo>() {
                    @Override
                    public void onSuccess(DeviceRemoteInfo deviceRemoteInfo) {
                        if (deviceRemoteInfo != null) {
                            //更新mqtt通讯的新秘钥
                            gatewayBean.setAesKey(deviceRemoteInfo.getSecret());
                            gatewayBean.setGatewayId(deviceRemoteInfo.getGatewayId());
                            //用之前的库,底层mqtt订阅,加解密会用到该参数;
                            HDLLinkConfig.getInstance().setAesKey(deviceRemoteInfo.getSecret());//设置mqtt通讯秘钥库
                            HDLLinkConfig.getInstance().setGatewayId(deviceRemoteInfo.getGatewayId());//设置GatewayId
                        }
                    }
 
                    @Override
                    public void onFailure(HDLException e) {
 
                    }
                });
            }
        } else if (event.getTopic().contains(HdlOtaLogic.localDownloadProgress)) {
            //下载云端驱动或者固件文件到本地,自己计算进度条上报到uni那边
            HDLUniMP.UniCallBackBaseBean uniCallBackBaseBean = new HDLUniMP.UniCallBackBaseBean();
            uniCallBackBaseBean.setType(event.getType());
            uniCallBackBaseBean.setData(event.getData());
            HdlUniLogic.getInstance().sendUni(HDLUniMP.UNI_EVENT_REPLY_OTA_MODEL, uniCallBackBaseBean);
            HdlLogLogic.print(event.getTopic() + new Gson().toJson(event.getData()), true);
        } else if (event.getTopic().contains(ConstantManage.network_change_post)) {
//            String wifi_ssid = WifiUtils.getInstance().getCurrentConnectWifiSsid();//获取WiFi的ssid需要位置权限的
            HdlLogLogic.print("监听网络状态--->" + event.getData().toString() + "(" + event.getType() + ")", true);
            //第一次启动App,以及切换网络的时候更新
            if (TextUtils.isEmpty(UserConfigManage.getInstance().getHomeId())) {
                return;
            }
            if (!event.getType().equals(NetworkType.no_network.toString())) {
//                AppManagerUtils.getAppManager().showLoading();
                HdlThreadLogic.runSubThread(new Runnable() {
                    @Override
                    public void run() {
                        //防止app启动的时候没有网络(app也登录不了),导致获取不了mqtt远程连接信息;
                        initMqttClient();
 
                        HdlDeviceLogic.getInstance().getCurrentHomeLocalAndCloudGatewayList(UserConfigManage.getInstance().getHomeId(), new CloudCallBeak<List<GatewayBean>>() {
                            @Override
                            public void onSuccess(List<GatewayBean> obj) {
//                                AppManagerUtils.getAppManager().hideLoading();
                            }
 
                            @Override
                            public void onFailure(HDLException e) {
//                                AppManagerUtils.getAppManager().hideLoading();
                            }
                        });
                    }
                });
            }
        } else if (event.getTopic().contains(HDLUniMP.UNI_EVENT_REPLY_OTHER_MODEL) && event.getType().contains(HDLUniMP.UNI_EVENT_REPLY_OTHER_BACK)) {
            //物理按键返回事件(包括左滑移除事件)
            killProcessApp();
        } else if (event.getTopic().contains(HDLUniMP.UNI_EVENT_REPLY_HOME_MODEL) && event.getType().contains(HDLUniMP.UNI_EVENT_REPLY_HOME_DEl)) {
            //C端电站详情里面删除后,会跑来这里;
            startAppAutomaticallyOpenUni(false);
        }
    }
 
 
    /**
     * C端启动App自动打开小程序电站详情界面
     */
    private void startAppAutomaticallyOpenUni(boolean delay) {
 
        if (delay) {
            SystemClock.sleep(2000);
        }
        List<HouseIdBean> HouseIdList = HdlResidenceLogic.getInstance().getHouseIdList();
        if (HouseIdList.size() == 0) {
            String path = HDLUniMP.UNI_EVENT_OPEN_HOME_Null_C;
            if (delay) {
                HdlUniLogic.getInstance().openUniMPDelay(path, null);
            } else {
                HdlUniLogic.getInstance().openUniMP(path, null);
            }
        } else {
            int select_home = 0;
            for (int i = 0; i < HouseIdList.size(); i++) {
                if (HouseIdList.get(i).getHomeId().equals(UserConfigManage.getInstance().getHomeId())) {
                    select_home = i;
                    break;
                }
            }
            HouseIdBean houseIdBean = HouseIdList.get(select_home);
            HdlResidenceLogic.getInstance().switchHouse(houseIdBean);
            String path = HDLUniMP.UNI_EVENT_OPEN_HOME_DETAILS_C + "?homeId=" + houseIdBean.getHomeId() + "&homeName=" + houseIdBean.getHomeName() + "&powerStationStatus=" + houseIdBean.getPowerStationStatus();
            if (delay) {
                HdlUniLogic.getInstance().openUniMPDelay(path, null);
            } else {
                HdlUniLogic.getInstance().openUniMP(path, null);
            }
        }
    }
 
//    /**
//     * 物理按键返回事件(包括左滑移除事件)
//     */
//    @Override
//    public void onBackPressed() {
//        killProcessApp();
//        super.onBackPressed();
//    }
 
    private void killProcessApp() {
        //物理按键返回事件(包括左滑移除事件)
        if (AppManagerUtils.getAppManager().getActivitySize() <= 1) {
            if (backPressTimes == 0) {
                HdlThreadLogic.toast(_mActivity, R.string.kill_app);
                backPressTimes = 1;
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } finally {
                            backPressTimes = 0;
                        }
                    }
                }.start();
                return;
            } else {
                //关闭小程序
                if (null != HDLUniMPSDKManager.getInstance().getUniMP()) {
                    HDLUniMPSDKManager.getInstance().getUniMP().closeUniMP();
                }
                AppManagerUtils.getAppManager().finishAllActivity();
                Process.killProcess(Process.myPid());
            }
        }
    }
 
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        HdlUniLogic.getInstance().checkRemoveOtherUniMPEventCallBack();
        //移除监听
        HDLLinkLocalSdk.getInstance().removeAllTopicsListener(allTopicsListener);
    }
 
    /**
     * 上传极光注册ID到云端
     */
    private void pushTokens() {
        String registrationId_tag = "registrationID_" + UserConfigManage.getInstance().getUserId();
        String is_registrationID = HDLApp.getInstance().getKey(registrationId_tag);
        if (is_registrationID.equals("true")) {
            //上过就没有必要在上传啦
            return;
        }
 
        HdlThreadLogic.runSubThread(new Runnable() {
            @Override
            public void run() {
                String registrationID = JPushInterface.getRegistrationID(_mActivity);
                int addCount = 0;
                while (TextUtils.isEmpty(registrationID)) {
                    SystemClock.sleep(1000);//1s休眠
                    registrationID = JPushInterface.getRegistrationID(_mActivity);
                    addCount++;
                    if (addCount > 5) {
                        //5s超时
                        break;
                    }
                }
                if (!TextUtils.isEmpty(registrationID)) {
                    UserConfigManage.getInstance().setRegistrationID(registrationID);
                    UserConfigManage.getInstance().Save();
                    String finalRegistrationID = registrationID;
                    HdlResidenceLogic.getInstance().pushAdd(new CloudCallBeak<String>() {
                        @Override
                        public void onSuccess(String pushId) {
 
                            if (!TextUtils.isEmpty(pushId)) {
                                UserConfigManage.getInstance().setPushId(pushId);
                                UserConfigManage.getInstance().Save();
                            }
                            HDLApp.getInstance().setInfoMap(registrationId_tag, "true");//记录一下状态,后台杀死app会清空;
                            HdlLogLogic.print("C端--->添加极光ID到云端--->registrationID:" + UserConfigManage.getInstance().getUserName() + "--->" + finalRegistrationID, true);
 
                        }
 
                        @Override
                        public void onFailure(HDLException e) {
                            HDLApp.getInstance().setInfoMap(registrationId_tag, "false");//记录一下状态,后台杀死app会清空;
                            HdlLogLogic.print("C端--->添加极光ID到云端失败--->registrationID:" + UserConfigManage.getInstance().getUserName() + "--->" + finalRegistrationID, true);
                        }
                    });
 
                }
 
 
            }
        });
    }
 
    /**
     * 初始化mqtt客户端
     */
    public void initMqttClient() {
        //检查断开状态
        if (!MqttRecvClient.getInstance().isConnected()) {
            MqttRecvClient.getInstance().reConnect();
        }
        if (!MqttRecvClient.getInstance().isInit()) {
            HdlMqttLogic.getInstance().getMqttRemoteInfo(HomeType.A, new CloudCallBeak<MqttInfo>() {
                @Override
                public void onSuccess(MqttInfo info) {
                    if (info != null) {
                        MqttRecvClient.getInstance().setConnectParam(info.getUrl(), info.getClientId(), info.getUserName(), info.getPassWord());
                        MqttRecvClient.getInstance().connect();
                    }
                }
 
                @Override
                public void onFailure(HDLException e) {
                    HdlLogLogic.print("读取mqtt远程信息失败--->" + e.getMessage(), e.getCode(), true);
                }
            });
        }
    }
 
    /**
     * 注册所有主题数据的监听
     */
    private void registerAllTopicsListener() {
        allTopicsListener = new EventListener() {
            @Override
            public void onMessage(Object msg) {
 
                if (msg == null) {
                    return;
                }
                if (msg instanceof ModbusResponse) {
                    ModbusResponse response = (ModbusResponse) msg;
                    if (response.getTopic() == null) {
                        return;
                    }
                    HdlLogLogic.print("C端--->监听到Modbus数据--->" + new Gson().toJson(response), false);
//                    if (response.getTopic().endsWith("custom/native/inverter/up")) {
                    HDLUniMP.UniCallBackBaseBean uniCallBackBaseBean = new HDLUniMP.UniCallBackBaseBean();
                    uniCallBackBaseBean.setType(response.getTopic());
                    uniCallBackBaseBean.setData(response.getData());
//                    if (com.hdl.photovoltaic.ui.test.UniAppMqtt.getInstance().getUni()) {
//                        try {
//                            String t = String.format("AndroidToPC/%s/%s", System.currentTimeMillis(), HDLUniMP.UNI_EVENT_NOTIFICATION_DEVICE_MODEL);
//                            com.hdl.photovoltaic.ui.test.UniAppMqtt.getInstance().publish(t, JSONObject.toJSON(uniCallBackBaseBean).toString());
//                        } catch (Exception ignored) {
//                        }
//                    } else {
                    HdlUniLogic.getInstance().sendUni(HDLUniMP.UNI_EVENT_NOTIFICATION_DEVICE_MODEL, uniCallBackBaseBean);
//                    }
//                    }
 
                } else if (msg instanceof LinkResponse) {
                    LinkResponse linkResponse = (LinkResponse) msg;
                    if (linkResponse.getTopic() == null) {
                        return;
                    }
                    if (linkResponse.getTopic().endsWith("/ota/device/progress/up")) {
                        HDLUniMP.UniCallBackBaseBean uniCallBackBaseBean = new HDLUniMP.UniCallBackBaseBean();
                        uniCallBackBaseBean.setType(linkResponse.getTopic());
                        uniCallBackBaseBean.setData(linkResponse.getData());
                        HdlUniLogic.getInstance().sendUni(HDLUniMP.UNI_EVENT_REPLY_OTA_MODEL, uniCallBackBaseBean);
                        HdlLogLogic.print(linkResponse.getTopic() + new Gson().toJson(linkResponse.getData()), true);
                    } else if (linkResponse.getTopic().endsWith("/custom/device/list/upload")) {
                        //逆变器有新oid通知主题
                        if (linkResponse.getData() == null) {
                            HdlLogLogic.print("逆变器有新oid通知--->数据为空", false);
                            return;
                        }
                        try {
                            Gson gson = new Gson();
                            Type typeOfT = new TypeToken<List<OidBean>>() {
                            }.getType();
                            String json = gson.toJson(linkResponse.getData());
                            List<OidBean> oidList = gson.fromJson(json, typeOfT);
                            //增量增加add
                            HdlDeviceLogic.getInstance().updateOidAdd(UserConfigManage.getInstance().getHomeId(), oidList, null);
                        } catch (Exception ignored) {
                        }
 
 
                    }
                }
            }
        };
        HDLLinkLocalSdk.getInstance().registerAllTopicsListener(allTopicsListener);
    }
 
 
}