电信天翼物联网平台对接应用服务ctWing

1.创建账号

天翼平台

2.创建产品

344b131db6b0f290417baaea64345963.png

 

3.添加设备

4.在应用管理中新增应用

841fb60c7b34e2e665909da8843c864c.png

5.应用服务对接

SDK使用说明   中国电信物联网开放平台NB网关2.0API参考

收到平台推送过来的数据后,如果业务不复杂的话,推送频率不是特别高的话,可以直接进行业务处理,建议使用缓存机制,可以提高处理效率。正常情况下,直接处理即可

@Data
@ApiModel(value = "设备数据推送请求")
public class DevicePushRequest {
    @ApiModelProperty(name = "tenantId", value = "租户ID")
    private String tenantId;

    @ApiModelProperty(name = "productId", value = "产品ID")
    private String productId;

    @ApiModelProperty(name = "deviceId", value = "设备ID", required = true)
    private String deviceId;

    @ApiModelProperty(name = "messageType", value = "消息类型=dataReport")
    private String messageType;

    @ApiModelProperty(name = "IMEI", value = "NB终端设备识别号")
    private String IMEI;

    @ApiModelProperty(name = "IMSI", value = "NB终端sim卡标识")
    private String IMSI;

    @ApiModelProperty(name = "deviceType", value = "设备标识")
    private String deviceType;

    @ApiModelProperty(name = "topic", value = "数据上报主题")
    private String topic;

    @ApiModelProperty(name = "assocAssetId", value = "合作伙伴ID")
    private String assocAssetId;

    @ApiModelProperty(name = "timestamp", value = "时间戳", required = true)
    private long timestamp;

    @ApiModelProperty(name = "upPacketSN", value = "上行报文序号")
    private int upPacketSN;

    @ApiModelProperty(name = "upDataSN", value = "数据上报报文序号")
    private int upDataSN;

    @ApiModelProperty(name = "serviceId", value = "服务ID")
    private String serviceId;

    @ApiModelProperty(name = "protocol", value = "协议类型")
    private String protocol;

    @ApiModelProperty(name = "payload", value = "消息负载", required = true)
    private JSONObject payload;
}
@Data
public class CreateDevice {
    private String deviceName;
    private String deviceSn;
    private String imei;
    private String operator;
    private Integer productId;
    private CreateDeviceOther other;
}
@Data
public class CreateDeviceOther {
    private Integer autoObserver;
    private String imsi;
    private String pskValue;
}

 

@Data
public class DeviceCreateOnIotReq {

    private String deviceName;
    private String imei;
    private String imsi;

}
@Api(tags = "电信IoT应用模块")
@Slf4j
@RestController
@RequestMapping("api/ct_wing/v1")
public class CtWingController {

    @Autowired
    private CtWingService ctWingService;

    @ApiOperation("设备数据变化接收")
    @PostMapping("deviceDataChange")
    public JsonData deviceDataChangeReq(@ApiParam(value = "设备数据", required = true) @RequestBody JSONObject changeReq) {
        try {
            ctWingService.devicePushRecord(changeReq);
        } catch (Exception e) {
            log.error("deviceDataChangeReq()->error: {}", e.getMessage());
        }

        return JsonData.buildSuccess();
    }

    @ApiOperation(value = "Feign: 注册设备到IOT平台")
    @PostMapping(value = "/device/register")
    public JsonData registerDevice(@RequestBody DeviceCreateOnIotReq deviceCreateOnIotReq) {
        return ctWingService.createDevice(deviceCreateOnIotReq);
    }

    @ApiOperation(value = "Feign: 删除设备在IOT平台")
    @PostMapping(value = "/device/remove")
    public JsonData removeDevice(@RequestParam("deviceId") String deviceId) {
        return ctWingService.removeDevice(deviceId);
    }

}
/**
     * 设备推送数据
     * 1.结构化处理
     * 2.校验数据
     * 3.存储到redis中的list结构
     *
     * @param changeReq
     */
    @Override
    public void devicePushRecord(JSONObject changeReq) {
        if (changeReq != null) {
            String msgType = changeReq.getString("messageType");
            if (StringUtils.isNotBlank(msgType) && "dataReport".equals(msgType)) {
                DevicePushRequest devicePushRequest = null;
                try {
                    devicePushRequest = JSONObject.parseObject(changeReq.toJSONString(), DevicePushRequest.class);
                } catch (Exception e) {
                    log.error("devicePushRecord()->error: {}", e.getMessage());
                }

                if (devicePushRequest != null) {
                    // 获取设备实际上报的数据
                    String payload = devicePushRequest.getPayload().getString("APPdata");
                    if (StringUtils.isNotBlank(payload)) {
                        // 按协议校验
                        if (protoFactory.validateDevice(base64StrToHexStr(payload))) {
                            // 校验通过后存储到redis,从左边存值
                            redisTemplate.opsForList().leftPush(CacheConst.IOT_DEVICE_KEY, devicePushRequest);
                        }
                    } else {
                        log.error("devicePushRecord()->payload is null.");
                    }
                }
            }
        }
    }

    /**
     * 处理设备数据,支持不同的协议交互
     */
    @Override
    public void dealWithDeviceData() {
        devicePushRequests.clear();
        // 从右边取值,先进先出
        Object devicePushReq;
        while ((devicePushReq = redisTemplate.opsForList().rightPop(CacheConst.IOT_DEVICE_KEY)) != null) {
            devicePushRequests.add(devicePushReq);
        }

        for (Object obj : devicePushRequests) {
            protoFactory.dealWithDevice(JSONObject.parseObject(JSONObject.toJSONString(obj), DevicePushRequest.class));
        }
    }
/**
 * 处理设备数据的定时任务
 */
@Configuration
@EnableScheduling
public class DealWithDeviceTask implements SchedulingConfigurer {

    @Autowired
    private CtWingService ctWingService;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(() -> ctWingService.dealWithDeviceData(), triggerContext -> {
            String cron = "0/1 * * * * ?"; // 每1秒轮询一次
            return new CronTrigger(cron).nextExecutionTime(triggerContext);
        });
    }
}

 

/**
     * 设备注册
     */
    @Override
    public JsonData createDevice(DeviceCreateOnIotReq deviceCreateOnIotReq) {
        CreateDevice device = new CreateDevice();
        device.setDeviceName(deviceCreateOnIotReq.getDeviceName());
        device.setImei(deviceCreateOnIotReq.getImei());
        device.setOperator("wfzn");
        device.setProductId(productId);

        CreateDeviceOther other = new CreateDeviceOther();
        other.setAutoObserver(0);
        other.setImsi(deviceCreateOnIotReq.getImsi());

        device.setOther(other);

        //不支持通过imei查询设备,所以直接注册设备,通过应答来判断是否重复注册
        JsonData jsonData = new JsonData();
        try {
            CreateDeviceResponse deviceResponse;
            try {
                deviceResponse = createDeviceOnIot(device);
            } catch (Exception e) {
                return null;
            }
            jsonData = validateIotResponse(deviceResponse);
        } catch (Exception e) {
            JsonData.buildResult(BizCodeEnum.IOT_REGISTER_SAME);
        }

        return jsonData;
    }

    @Override
    public JsonData removeDevice(String deviceId) {
        JsonData jsonData = new JsonData();
        try {
            DeleteDeviceResponse deviceResponse = deleteDeviceOnIot(deviceId);
            jsonData = validateIotResponse(deviceResponse);
        } catch (Exception e) {
            JsonData.buildResult(BizCodeEnum.IOT_REGISTER_DELETE_FAIL);
        }

        return jsonData;
    }

    /**
     * 删除iot注册
     *
     * @param deviceId
     * @return
     */
    private DeleteDeviceResponse deleteDeviceOnIot(String deviceId) {
        AepDeviceManagementClient client = AepDeviceManagementClient.newClient()
                .appKey(appKey)
                .appSecret(appSecret)
                .build();

        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setParamMasterKey(masterKey);
        request.setParamDeviceIds(deviceId);
        request.setParamProductId(productId);

        DeleteDeviceResponse response = null;
        try {
            response = client.DeleteDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.shutdown();
        }

        return response;
    }

    /**
     * 校验Iot响应
     *
     * @param deviceResponse
     * @return
     * @throws UnsupportedEncodingException
     */
    private JsonData validateIotResponse(BaseApiResponse deviceResponse)  {
        String deviceId = null;
        if (deviceResponse.getStatusCode() == 200) {
            JSONObject body = JSONObject.parseObject(new String(deviceResponse.getBody(), StandardCharsets.UTF_8));

            if ("0".equals(body.get("code").toString())) {
                if (deviceResponse instanceof CreateDeviceResponse) {
                    deviceId = JSONObject.parseObject(body.get("result").toString()).get("deviceId").toString();
                    log.info("create iot device success: {}", deviceId);
                } else if (deviceResponse instanceof DeleteDeviceResponse) {
                    return JsonData.buildSuccess("success");
                }
            } else {
                return JsonData.buildError(body.get("msg").toString());
            }
        } else {
            return JsonData.buildError("StatusCode: " + deviceResponse.getStatusCode());
        }
        return JsonData.buildSuccess(deviceId);
    }

    /**
     * 注册设备到ctWing平台
     *
     * @param content
     * @return
     */
    private CreateDeviceResponse createDeviceOnIot(CreateDevice content) {
        AepDeviceManagementClient client = AepDeviceManagementClient.newClient()
                .appKey(appKey)
                .appSecret(appSecret)
                .build();

        CreateDeviceRequest request = new CreateDeviceRequest();
        request.setParamMasterKey(masterKey);
        request.setBody(JSONObject.toJSONBytes(content));

        CreateDeviceResponse response = null;
        try {
            response = client.CreateDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.shutdown();
        }

        return response;
    }

bd5f51de933ee324c38109028d3f83b2.png

对应产品和应用信息,去IOT平台创建的产品和应用里面看 

 

 

 

 

 

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值